#!/bin/bash -

TEMP=`getopt -o ch -n 'pdb2svg' -- "$@"`

if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

eval set -- "$TEMP"
fill='colour[$12]'

while true ; do
	case "$1" in
		-c)
			fill='numcolour[chain[$5]]'
			shift
			;;
		-h)
			echo $0 '[-c] [file.pdb]'
			echo Converts a PDB file to SVG. File can come through stdin or on command line. Atoms will be coloured by element unless -c is given, in which case, they will be coloured by chain.
			exit 0
			;;
		--)
			shift
			break
			;;
		*) echo "Internal error!" 1>&2; exit 1 ;;
	esac
done

if [ $# -gt 1 ]
then
	echo Too many files. 1>&2
	exit 1
fi

( [ $# = 0 ] && cat || cat "$1" ) | egrep '^ATOM ' | sed -e 's/  */ /g' | sort -rnk 9 | awk 'BEGIN {colour["C"]="black";colour["H"]="grey";colour["O"]="red";colour["N"]="blue";colour["S"]="yellow";colour["P"]="violet"; radius["C"]=1.7; radius["H"]=1.2; radius["O"]=1.5; radius["N"]=1.4; radius["S"]=1.8; radius["P"]=1.8; numcolour[1]="blue"; numcolour[2]="green"; numcolour[3]="violet"; numcolour[4]="aqua"; numcolour[5]="darkorange"; numcolours[6]="darkred"; numcolours[7]="darkslateblue"; numcolours[8]="firebrick"; numcolours[9]="yellow"; numcolours[10]="teal"; numcolour[11]="darkmagenta"; chainidx=0; print "<?xml version=\"1.0\" standalone=\"no\"?><!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\"><svg width=\"100%\" height=\"100%\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">"} { if (chain[$5] == 0) chain[$5] = chainidx++; print "<circle cx=\""$7+10"\" cy=\""$8+10"\" r=\""radius[$12]"\" stroke=\"black\" stroke-width=\"0.1\" fill=\""'$fill'"\" style=\"fill-opacity:0.8;stroke-opacity:0.3;\"/>"} END {print "</svg>" }'

