#!/usr/bin/perl
$offpam=$ARGV[0];$toppam=$ARGV[1];$unitcov=$ARGV[2];$pattern=$ARGV[3];
$inputoff=$ARGV[4];$inptop = $ARGV[5]; $outtop = $ARGV[6];
$tmpfile = "/tmp/temptop.$$"; $tmpfil2 = "/tmp/temptop2.$$";
system ("cp $inptop $tmpfile");
die "script will not overwrite existing output\n" if (-e $outtop);

#get potential from off file.
@off=split(',',$offpam);
$keyword=$off[0]; $offcol=substr $off[1],3;
$getpot=$keyword;
for ($n=2;$n<@off;$n++) { $getpot=$getpot.",".$off[$n]; }
@total=`offget_inter $inputoff $getpot`;

#transfer atoms types between gromacs and cryoff
print "Atom types are defined from [ $inputoff ] file.\n" if lc($pattern) eq "no";
if ($pattern =~ /type/i) {
  $ind1=index($pattern,"type");
  $typecov=1;
  $pat1=substr $pattern,$ind1; $pat1 =~ s/,|=/ /g; @file=split /\s+/,$pat1;
  open (PATF,$file[1]);
  while(<PATF>) { chomp; ($typ1,$typ2)=split; $typ{$typ1}=$typ2; }
  print "Atom types are defined from [ $file[1] ] file.\n";
} # read atom type from a file

# parameter position in top file
@top=split(',',$toppam);
$section=$top[0]; $pamcol=substr $top[1],3; 
$idx=0;
for ($n=2;$n<@top;$n++) {
  $top[$n]= substr $top[$n],2; @templn=split(/-/,$top[$n]);
  $templn[1]=$templn[0] unless $templn[1] > $templn[0];
  for ($j=$templn[0];$j<=$templn[1];$j++){ $ln[$idx]=$j; $idx++;"\n";}
}

#update top file.
$nterm=$idx;$idx=0;
for ($i=0;$i<$nterm;$i++) {
  $pamln=$ln[$i];
  $temp1=`topget_param_paramfile  $section $pamln 1  $inptop`;chomp($nam1=$temp1);$nam1=uc($typ{$nam1}) if $typecov == 1;#1st 
  $temp2=`topget_param_paramfile  $section $pamln 2  $inptop`;chomp($nam2=$temp2);$nam2=uc($typ{$nam2}) if $typecov == 1;#2nd 

  for ($j=0;$j<@total;$j++) {
    $str=$total[$j]; chomp($str); $str =~ s/^\s+|\s+$//g; @temp=split /\s+/,$str;
    if ( $nam1 eq  $temp[0] and $nam2 eq  $temp[1] or  $nam1 eq  $temp[1] and $nam2 eq  $temp[0]  ) {
      $pam=$temp[$offcol-1];$update=1;}
  } # get parameter

  if ($update) {
    $pam=sprintf("%.4f",$pam); 
    $pam=$pam*$unitcov;
    print "$nam1  $nam2  $pam \n";
    system("topupd_paramfile $section $pamln $pamcol $pam $tmpfile > $tmpfil2; mv $tmpfil2 $tmpfile");
    $idx++;$update=0;
  }
}
print "Update [ $idx  ] parameters for [ $section ].\n";
system ("mv $tmpfile $outtop");
