#!/bin/bash

# Arguments
# $1 = pdb



nbad=$(awk '{if(length($5) > 1) print $0 }' $1 | wc -l)

if [[ $nbad -ne 0 ]]; then

	#cat $1 | awk 'BEGIN{FS="\t"}{ split($0, array, " "); a=substr(array[5],1,1); b=substr(array[5],2);  }'
	cat $1 | gawk 'BEGIN{FS="\t"}{ split($0, array, " "); if(array[5] ~ /([A-Z][0-9]+)/){ a=substr(array[5],1,1); b=substr(array[5],2); gsub(array[5], a" "b, $0); gsub(a" "b" ", a" "b, $0) ; print $0; }else{ print $0}}' > $1.temp.awk
	grep "ATOM\|HETATM" $1.temp.awk | awk '{ if(length($5)==1) updateName=$5;   if($1 == "ATOM" || $1 == "HETATM"){  print $0 > "chain"updateName".pdb";  }}' ;
	rm $1.temp.awk

else

	grep "ATOM\|HETATM" $1 | awk '{ if(length($5)==1) updateName=$5;   if($1 == "ATOM" || $1 == "HETATM"){  print $0 > "chain"updateName".pdb";  }}' ; 

fi

#grep "ATOM\|HETATM" $1 | awk '{ if(length($5)==1) updateName=$5;   if($1 == "ATOM" || $1 == "HETATM"){  print $0 > "chain"updateName".pdb";  }}' ; 
for i in chain* ; do echo "TER" >> $i ; echo "END" >> $i ; done
