#!/bin/sh

PDB=$1
PG=$2
WAVEL=$3
RESOLUTION=$4

function show_help()
{
	echo -n "Syntax: $0 <PDB file> <point group> <wavelength in Angstroms> [<resolution>]"
	echo
	echo "The space group and point group must be consistent, it's just"
	echo "that I don't know how to convert the space group to a point"
	echo "group."
}

if [ "x$PDB" = "x" ]; then
	show_help
	exit
fi

if [ "x$RESOLUTION" = "x" ]; then
	echo "Resolution not given.  Using 3 Angstroms."
	RESOLUTION=3
fi

echo "Running ano_sfall.com to calculate structure factors..."
./ano_sfall.com ${PDB} ${RESOLUTION}A wave=${WAVEL}
if [ $? -ne 0 ]; then exit 1; fi

echo "Converting structure factors to text..."
mtz2various hklin ideal_ano.mtz hklout ${PDB}-temp1.hkl >> gen-sfs.html <<EOF
LABIN H=H K=K L=L DUM1=Fplus DUM2=Fminus
OUTPUT USER '(3I4,2F9.1)'
EOF
if [ $? -ne 0 ]; then exit 1; fi
rm -f ${PDB}.mtz
perl > ${PDB}-temp2.hkl << WIBBLE
use strict;

my \$line;
open(FILE, "${PDB}-temp1.hkl");

printf("CrystFEL reflection list version 2.0\n");
printf("Symmetry: %s\n", "${PG}");

printf("   h    k    l          I    phase   sigma(I)   nmeas\n");

while ( \$line = <FILE> ) {

        if ( \$line =~ /^\s*([\d\-]+)\s+([\d\-]+)\s+([\d\-]+)\s+([\d\-\.]+)\s+([\d\-\.]+)/ ) {

                my \$h = \$1;
                my \$k = \$2;
                my \$l = \$3;
                my \$iplus = \$4*\$4;  # Square to convert F->I
                my \$iminus = \$5*\$5;
                my \$sigi = 0.0;

                printf("%4i %4i %4i %10.2f %s %10.2f %7i\n",
                       \$h, \$k, \$l, \$iplus, "       -", \$sigi, 1);

                printf("%4i %4i %4i %10.2f %s %10.2f %7i\n",
                       -\$h, -\$k, -\$l, \$iminus, "       -", \$sigi, 1);

        } else {
        	printf(STDERR "Couldn't understand line '%s'\n", \$line);
        }

}
close(FILE);
printf("End of reflections\n");
WIBBLE

get_hkl -i ${PDB}-temp2.hkl -o ${PDB}.hkl -y ${PG} --trim-centrics
if [ $? -ne 0 ]; then exit 1; fi

rm -f ${PDB}-temp1.hkl
rm -f ${PDB}-temp2.hkl
