#!/usr/bin/perl -w
if(!@ARGV) {
  print "USAGE $0 pdbList\n";
  exit(1);
}
open(IN, $ARGV[0]);

    open NOC, ">notCont.ls";
`mkdir oneChain`;

while (defined($line=<IN>)) {
    chomp($line);
    $pdbName = substr($line, 0,4);
    $pdbNameL = substr($line, 0,5);
    $pdbName =~ tr/A-Z/a-z/;
    $pdbNameL =~ tr/A-Z/a-z/;
	$pdbName =~ /^\w(\w{2})\w$/;
	if(-e "/cast/$1/$pdbName.pdb") {
	    `cp /cast/$1/$pdbName.pdb ./`;
	}
	else {
	    $pdbName =~ /^\w(\w{2})\w$/;
	    print "$1 $pdbName\n";
	    `wget ftp://ftp.rcsb.org/pub/pdb/data/structures/divided/pdb/$1/pdb$pdbName.ent.Z`;
	    `gzip -d pdb$pdbName.ent.Z`;
	    `mv -f pdb$pdbName.ent $pdbName.pdb`;
	}

#	create *.ab.pdb file and copy to oneChain

	$chainName= substr($line,4,1);
$chainName =~ tr/a-z/A-Z/;
	if($chainName eq "0"){
	    $chainName=" ";
	}

	if(-e "$pdbName.pdb"){
	    open PDB, "$pdbName.pdb";
	}
elsif(-e "/home/jinfeng/SharedData/pc90_res3.0/$pdbName.pdb"){
	open PDB, "/home/jinfeng/SharedData/pc90_res3.0/$pdbName.pdb";
	}
else {print "cannot open $pdbName.pdb\n"; next;}
	open OUT, ">$pdbNameL.ab.pdb";
	printf "$pdbNameL.ab.pdb\n";
	$isNC=1;
	$isStart=1;
	while(defined($line=<PDB>)){
	    if(substr($line,0,4) eq "ATOM"&& (substr($line,13,2) eq "CA" ||substr($line,13,2) eq "CB") && substr($line,21,1) eq $chainName){
		if(substr($line,16,4) =~ /[BCDE234][A-Z][A-Z][A-Z]/) {next;}
		else {
		    $resNum  = substr($line, 22,4); $resNum  =~ s/^\s+|\s+$//g;
		    if($isStart==1){
			$isStart=0;
			$prevNum=$resNum;
		    }
		    elsif(substr($line,13,2) eq "CA" && resNum!=($prevNum+1)){
			$isNC=0;
			$prevNum=$resNum;
		    }
		    else {$prevNum=$resNum;}
		    printf OUT "$line";
		}
	    }
	}

`mv $pdbNameL.ab.pdb oneChain`;
close(OUT);
close(PDB);
	if($isNC==0){
	    printf NOC "$pdbNameL\n";
	}
}
`mkdir wholePdb`;
`mv *.pdb wholePdb`;

