#!/usr/bin/perl -w
# Perl script to prepare PDB file for docking
# Version 2, Nov 2009

use strict;

if ($#ARGV  != 1) {
	print "prepare_pdbfile.pl <PDB> <RES_CHANGE>\n";
	print "\nPurpose: Prepare PDB file for rundockblaster\n";
	print "<PDB> is the input PDB file.\n";
	print "<RES_CHANGE> is a text file that modifies residue names. Format: Residue_number New_residue_name\n";
	print "Prints rec.pdb as output file.\n\n";
	exit;
}
# Variables. Needs cleanup.
# index
my $i=1;
my $j=0;
my $k=0;
# Hash 
my $residue;
my $state;
# PDB format
my $atomnumber;
my $atomtype;
my $resnumber;
my $restype;
my $x;
my $y;
my $z;

# Files
open (MATCH2,$ARGV[0]) || die "can't open pdb file\n";
open (COLORS,$ARGV[1]) || die "can't open ionization file\n";
open (PDBOUT,">colored.pdb") || die "can't open pdbout file\n";

# Read changes in residue names
my %hash = ();
while(<COLORS>) {
    ($residue,$state) = split(/\s/);
    chomp($state);
    $hash{$residue} = $state;
}

print "\nColor assignments:\n";
while(<MATCH2>) {
    if(/^ATOM/){
	# Extract data, format from pdb homepage. Safer than regexp.
	$atomnumber = substr $_,6,5;
	$atomtype = substr $_,12,4;
	$restype = substr $_,17,3;
	$resnumber = substr $_,22,4;
	$x = substr $_,30,8;
	$y = substr $_,38,8;
	$z = substr $_,46,8;
        
	# Remove spaces from residue number
	$resnumber =~ s/\s+//;         

     	# Set the residue number equal to the color
	if( defined $hash{$resnumber} ) {
		print "Residue number $resnumber has color $hash{$resnumber}\n";
		$resnumber = $hash{$resnumber};
		
	}

	# Print PDB file again
	printf PDBOUT "ATOM  $atomnumber $atomtype $restype  %4d    $x$y$z\n",$resnumber;
    }
}






