#!/bin/bash

# Script which extract the REF geometries for file
# $1.cif and writes them to file $2


if [ "$#" -eq 0 ]
then
  echo "# Usage: grep_ref_boxes cell outfile" 1>&2
  echo "#" 1>&2
  echo "#   No file given. Please check." 1>&2
  exit 1
fi

if test -f $1.cif
then
  cell=$1
else
  echo "# Usage: grep_ref_boxes cell outfile" 1>&2
  echo "#" 1>&2
  echo "#   The cell name supplied "$1".cif does not exist. Please check." 1>&2
  exit 1
fi

if [ "$#" -eq 1 ]
then
  echo "# Usage: grep_ref_boxes cell outfile" 1>&2
  echo "#" 1>&2
  echo "#   The outfile for the REF information must be given. Please check." 1>&2
  exit 1
else
  outfile=$2
fi

ref_count=$(grep -c '^L  *REF;' $cell.cif)
if [ "$ref_count" -gt 0 ]
then
  sed -n '/^L  *REF;/,/^DF;/ p' $cell.cif | \
  grep -v '^L ' > $outfile
else
  echo "DF;" > $outfile
fi
