#!/bin/bash

for num in {1..200}
do
	#Check if the file already exists.
	if [ -f "complex.$num.fix.pdb" ];
	then rm "complex.$num.fix.pdb"	
	fi
	
	last_found=0
	molecule=0
	while read line         
			do         
				curr=${line:22:4}
				if [ $last_found -gt $curr ]
				then
					molecule=1
					last_found=$curr
					echo "TER" >> "complex.$num.fix.pdb"					
					echo "${line:0:21}B${line:22}" >> "complex.$num.fix.pdb"
				else
					last_found=$curr
					if [ $molecule -eq 0 ]
					then
						echo "$line" >> "complex.$num.fix.pdb"
					else
						echo "${line:0:21}B${line:22}" >> "complex.$num.fix.pdb"
					fi 
				fi
			
			done < "complex.$num.pdb"
#Now run HBPLUS and rename the output again
./hbplus "complex.$num.fix.pdb" -o

#Add Ter
	if [ -f "complex.$num.H.pdb" ];
	then rm "complex.$num.H.pdb"	
	fi
	last_found=0
	molecule=0
	while read line         
			do         
				curr=${line:22:4}
				if [ $last_found -gt $curr ]
				then
					molecule=1
					last_found=$curr
					echo "TER" >> "complex.$num.H.pdb"					
					echo "${line:0:21}B${line:22}" >> "complex.$num.H.pdb"
				else
					last_found=$curr
					if [ $molecule -eq 0 ]
					then
						echo "$line" >> "complex.$num.H.pdb"
					else
						echo "${line:0:21}B${line:22}" >> "complex.$num.H.pdb"
					fi 
				fi
			
			done < "complex.$num.fix.h"

done

#Finally, create the list and run Zrank
if [ -f "zrank_list.txt" ];
	then rm "zrank_list.txt"	
fi
for num in {1..200}
do

echo "complex.$num.H.pdb" >> "zrank_list.txt"

done

./zrank "zrank_list.txt"
for num in {1..200}
do

rm "complex.$num.H.pdb"
rm "complex.$num.fix.pdb"

done
