#!/bin/csh -f
# convert car file to pdb format

# CONECT records are generated if mdf file is present
# output can be read by xmol, rasmol, csed (cactvs)
# limitations: only H N C O S L (lone pair) atomic species are recognized

# uncomment if nawk needs to precede command line variables by -v
set var = #"-v"

if ($#argv != 1) then
	echo "usage:car2pdb.csh <car-file>"
	exit
endif

set car = $1
set mdf = $car:r.mdf
set mdfflag = ( -e $mdf )

# generate header
echo $car:r | awk '{printf("COMPND    %s\n",$1)}' >! tmp0_$$
echo "AUTHOR    GENERATED BY car2pdb.csh" >>! tmp0_$$
echo "REMARK   1 ATOM NAMES MAY BE CHANGED IF NOT IUPAC CONFORMANT" >>! tmp0_$$
echo "REMARK   2 OR IF FIRST TWO CHARACTERS DO NOT INDICATE ATOMIC SPECIES" >>! tmp0_$$
echo "REMARK   3 LIMITATIONS: ONLY H N C O S L ATOMIC SPECIES ARE RECOGNIZED" >>! tmp0_$$
echo "REMARK   4 ATOM NUMBERING IS RETAINED" >>! tmp0_$$
# generate atom records
car2pdbatom.awk $1 >! tmp1_$$
# number of ATOM records
set nratoms=`awk '/ATOM/' tmp1_$$ | wc -l`
# number of TER records
set nrters=`awk '/TER/' tmp1_$$ | wc -l`
# in case that mdf file is not present
set nrconects = 0
touch tmp2_$$ tmp3_$$ tmp4_$$

if ( $mdfflag ) then
	# generate conect records
	# connectivity by names
	mdf2connect.awk $mdf >! tmp2_$$
	# connectivity by indices origin 0
	name2number.awk $var c=$car tmp2_$$ >! tmp3_$$
	# output conect records using origin 1
	nawk '{printf("CONECT");for(i=1;i<=NF;++i)printf("%5i",$i+1);printf("\n")}' tmp3_$$ >! tmp4_$$
	# number of CONECT records
	set nrconects=`awk '/CONECT/' tmp4_$$ | wc -l`
endif

# MASTER and END records
echo $nratoms $nrters $nrconects | nawk '{printf("MASTER    %5i%5i%5i%5i%5i%5i%5i%5i%5i%5i%5i%5i\n",0,0,0,0,0,0,0,0,$1,$2,$3,0)}' >! tmp5_$$
echo END >>! tmp5_$$

# output
cat tmp0_$$ tmp1_$$ tmp4_$$ tmp5_$$

# delete temporary files
rm tmp0_$$ tmp1_$$ tmp2_$$ tmp3_$$ tmp4_$$ tmp5_$$
