#!/usr/bin/perl
#
# Cameron Mura, 05/10/2003.
# Perl script to split PDB file consisting of several models (e.g. from NMR) into separate files...
# only assumption is that individual structures begin with a "MODEL #" line, where # is an integer
# command-line syntax: 
# 	"> split_pdb_models.pl whatever.pdb"
#
#
my($pdb_file) = "";
my($global_count) = 0;
my($local_count) = 0;

chomp ($pdb_file = $ARGV[0]);
open (PDB, $pdb_file) || die "\nCannot open pdb_file '$pdb_file' or it doesn't exist.\n\n";

# assign basename for output files based on input PDB filename:
if ($pdb_file =~ /(\w+)\.(\w+)/) { $basename = $1."_" ; }
	else { $basename = $pdb_file."_"; }
print("\nOutput basename: $basename\n\n");


while (<PDB>)
{
	chomp($_);
	if ($_ =~ /^(MODEL)\s+(\d+)\s+/) { $global_count++; $local_count++; print "Writing out file \"$basename$global_count.pdb\"\n"; }
	if ($_ =~ /^(MODEL)\s+(\d+)\s+/ && $local_count > 1) { $local_count = 1; next; }
	if ($_ !~ /^(MODEL)/ && $local_count == 1 && $_ !~ /^(ENDMDL)/)
		{
		 open (OUTFILE, ">>$basename$global_count.pdb") || die "\nCannot open output PDB filename \"$basename$global_count.pdb\" for writing.\n\n";
		 print OUTFILE ("$_\n");
		 next;
		}
}	

exit;

