#!/usr/bin/perl -w

# 
# Usage:  pdbcat_1let.pl <in_stem> <in_start_no> <in_end_no> <in_step> <chain1_ter> <file_out> <model_start_no> <model_step>
#
#  Outpur <file_out>
#
#  This script reads a seies of pdb files in the amber dialect and rewrites them in standard pdb. 
#  Each file is converted to a model, all the models are concatenated into a single file. 
#  The output file has no header or END line.  This allows files to be concatenated, if necessary.
#  The names of the files to be read are assumed to have the form <in_stem>.#
#      <in_stem>         Constant part of the pdb file to be read (don't include dot)
#      <in_start_no>     The number of the first pdb file to be read
#      <in_end_no>       The number of the last  pdb file to be read
#      <in_step>         The step size between files to be read
#      <chain1_ter>      When this value is nonzero a TER line is inserted after this many lines. 
#                            A second TER line is added at the end of the model.
#                            For wild-type cx8 this is 1145. 
#                            For the mcx1 mutation this is 1143. 
#                            If this value is set to zero, no TER lines are written.
#      <file_out>        The name of the single output file.
#      <model_start_no>  The number of the first model 
#      <model_step>      The size of the step between model numbers.
#
#  Mike Bruist  February 27, 2008
#
#  March 27, 2008,       Modified to require ^ATOM on first line to be used for data collection.
#                        This allows PDB file to begin with any number of header lines.
#  June 7, 2008          Chnged script name in usage messages to pdbcat_1let.pl
#

if (@ARGV != 8) {
  die
  "1 Usage:  pdbcat_1let.pl <in_stem> <in_start_no> <in_end_no> <in_step> 
        <chain1_ter> <file_out> <model_start_no> <model_step>\n";
}     # end if (@ARGV

# collect arguments

$stem       = $ARGV[0];
$n          = $ARGV[1];
$fileEnd    = $ARGV[2];
$fileStep   = $ARGV[3];
$chain      = $ARGV[4];
$outFile    = $ARGV[5];
$m          = $ARGV[6];
$modelStep  = $ARGV[7];

open(OUT, ">$outFile") || die "2 Cannot create $outFile\n";

while ( $n <= $fileEnd ) {
  printf OUT "MODEL %8s \n", $m;
  open(PDB, $stem.".".$n) || die "3 Cannot open $stem",".$n\n";
  @pbd = <PDB>;

  $i=1;
  foreach (@pbd) {
    if (m/^ATOM/) {
      if ($i == $chain+1) {print OUT "TER \n"}
      $_ =~ s/DA[35] |DA  /  A /g;
      $_ =~ s/DC[35] |DC  /  C /g;
      $_ =~ s/DG[35] |DG  /  G /g;
      $_ =~ s/DT[35] |DT  /  T /g;
      print OUT $_;
      $i++;
    }         #  end if (m/^ATOM/)
  }   #  end foreach (@pbd)

  print OUT "TER\n";
  print OUT "ENDMDL \n";
  $n += $fileStep;
  $m += $modelStep;
}       #  end while
