#!/usr/bin/perl


#Script que converte que arquivo xyz (saida do DICE) para o formato PDB.
#Evanildo Laceda Jr.
#Intituto de Fisica, USP, Brasil. 

###################################
#Ultima modificacao:  19/01/2012
##################################

@comand = @ARGV;

$help =grep(/-h/,@comand);



if ($help==1){

&intro();
exit;

}

&intro();

chomp($arquivo1 = @ARGV[0]);
print "\n# tipos de molecula [int]: ";
chomp($ntips=<STDIN>);


for ($i =1; $i<=$ntips; $i++){

print "\n# de moleculas tipo $i [int]: ";
chomp($nmtipo[$i]=<STDIN>);

print "# de atomos da molecula tipo $i [int]: ";
chomp($nat[$i]=<STDIN>);
$res[$i]="ML$i";
}





@arq1 = split(/\./,$arquivo1);
$ext=$arq1[1];

open(in,"<$arquivo1");

@linhas = <in>;



if ($ext eq "xyz") {

### INFORMACOES DE CABECARIO

chomp($ntotal=$linhas[0]);
$ntotal =~ s/ +//g;
@caixa =split(/=/,$linhas[1]);
chomp($caixa[1]);
#print "$caixa[1]\n";

###

$arquivo2 = $arq1[0]. ".pdb";

open(out,">$arquivo2");

print out "REMARK    GENERATED BY XYZ2PDB\n";
print out "CRYST1 $caixa[1]  90.00  90.00  90.00 P 1           1\n";
print out "MODEL 0\n";

$nres = 0;  #NUMERO DO RESIDUO
$k = 0;    #nUMERO DO ATOMO

for ($i=1; $i<=$ntips; $i++) {

$N[$i]=$nmtipo[$i]*$nat[$i];

}



for ($i =1; $i<=$ntips; $i++){

for ($j=1; $j<=$N[$i]; $j++) {


$k++;

if($j % $nat[$i] ==1){ $nres++;}

if ($j % $nat[$i] !=0){$nsym = $j % $nat[$i];}
else {$nsym = $nat[$i];}



@atom = split(/ +/,$linhas[$k+1]);
chomp(@atom);


$sym = $atom[1] . $nsym;
$x = $atom[2];
$y = $atom[3];
$z = $atom[4];

$fmt_pdb="%-6s%5d %-4s %3s  %4d    %8.3f%8.3f%8.3f  1.00 0.00\n";

printf out $fmt_pdb,ATOM,$k,$sym,$res[$i],$nres,$x,$y,$z;

    }
  }
}


print out "END\n";

print "\noutput:$arquivo2\n";

sub intro {
 print "------------------------------------\n";
 print "Dice2pdb\n";
 print "------------------------------------\n\n";
 
 print "command -> \$ dice2pdb [option] [file.xyz] \n\n";
 print "[options]  \n";
# print "none \t generate .xray file\n";
# print "-key \t generate .key file [tinker]\n";
# print "-itp \t generate .itp file [gromacs]\n";
 print "-h   \t help\n\n";
}

