
if [ $# != 2 ]; then
	echo "***ERROR*** Use: $0 <TABLE> <PQR>"
	exit -1
fi


PQR=$2
TABLE=$1

grep -v "REMARK" $PQR > $PQR.temp 

#awk '
#{
#	if(length($5 > 1)) print $5 
#} ' $PQR.temp




awk '


FNR==NR{
	equivalence[$1] = $2
	next
}

FNR!=NR{
	if(substr($3,1,1) == "H"){

		if(length($3) > 1){


			print $0, "H"
		}
	}else{

		print $0, equivalence[$3];



	}

}
' $TABLE $PQR.temp | sed 's/ \+/ /g' > $PQR.temp.bad

awk '
{
        x=$10;
        y=$11;
	z=$12;
        $10="";
	$11="";
	$12="";
	if(substr($0,1,3) != "TER" && substr($0,1,3) != "END") 
		printf("%s %.2f %.2f %s\n", $0, x, y, z)
	else
		print $0
}
' $PQR.temp.bad > $PQR.temp.format


awk '

NR==1{ x1=0; x2=0; x3=0; x4=0; x5=0; x6=0; x7=0; x8=0; x9=0; x10=0; x11=0; x12=0; x13=0; }

FNR==NR{
	if($1 == "ATOM" || $1 == "HETATM"){
	if(length($1) > x1) x1 = length($1);
	if(length($2) > x2) x2 = length($2);
	if(length($3) > x3) x3 = length($3);
	if(length($4) > x4) x4 = length($4);
	if(length($5) > x5) x5 = length($5);
	if(length($6) > x6) x6 = length($6);
	if(length($7) > x7) x7 = length($7);
	if(length($8) > x8) x8 = length($8);
	if(length($9) > x9) x9 = length($9);
	if(length($10) > x10) x10 = length($10);
	if(length($11) > x11) x11 = length($11);
	if(length($12) > x12) x12 = length($12);
	}

}


FNR!=NR{


	#total=length($1)+3+x1+2+x3+1+x4+1+x5+6+x7+1+x8+1+x9+1+x10+1+x11+2+x11;
	total=0;

	printf("%s", $1); total+=length($1);
	if($1=="ATOM") for(i=0; i<7-length($2); i++) { printf(" "); total+=1; }
	if($1=="HETATM") for(i=0; i<5-length($2); i++) { printf(" "); total+=1; }
	printf("%s", $2); total+=length($2);
	for(i=0; i<2; i++){ printf(" "); total+=1}
	printf("%s", $3); total+=length($3);
	for(i=0; i<4-length($3); i++){ printf(" "); total+=1;}
	printf("%s", $4); total+=length($4);
	for(i=0; i<1+x4-length($4); i++){ printf(" ");total+=1;}
	printf("%s", $5); total+=length($5);
	for(i=0; i<3-length($5); i++){ printf(" ");total+=1;}
	printf("%s", $6); total+=length($6);
	for(i=0; i<(13-length($7)-length($6)); i++){ printf(" "); total+=1;}
	printf("%s", $7); total+=length($7);
	for(i=0; i<8-length($8); i++){ printf(" ");total+=1;}
	printf("%s", $8); total+=length($8);
	for(i=0; i<8-length($9); i++){ printf(" ");total+=1;}
	printf("%s", $9); total+=length($9);
	for(i=0; i<6-length($10); i++){ printf(" ");total+=1;}
	printf("%s", $10); total+=length($10);
	for(i=0; i<5-length($11); i++){ printf(" ");total+=1;}
	printf("%s", $11); total+=length($11);
	for(i=0; i<79-total; i++) printf(" ");
	printf("%s", $12); total+=length($12);
	if(length($12) < x12){
		for(i=0; i<x12-length($12); i++){
		       	#printf(" ");
		}
	}
	printf("\n");




}

' $PQR.temp.format $PQR.temp.format




rm $PQR.temp
rm $PQR.temp.bad
rm $PQR.temp.format



