#!/bin/sh

# Copyright  2019 by Global Phasing Limited
#
#           All rights reserved.
#
#           This software is proprietary to and embodies the confidential
#           technology of Global Phasing Limited (GPhL). Possession, use,
#           duplication or dissemination of the software is authorised
#           only pursuant to a valid written licence from GPhL.
#
# Contact   buster-develop@GlobalPhasing.com

[ ! -f BUSTER_model.cif ] && echo "ERROR: no BUSTER_model.cif file found" && exit 1
[ ! -f BUSTER_refln.cif ] && echo "ERROR: no BUSTER_refln.cif file found" && exit 1
[ -f BUSTER_model_new.cif ] && echo "ERROR: file BUSTER_model_new.cif exists already" && exit 1
[ -f BUSTER_refln_new.cif ] && echo "ERROR: file BUSTER_refln_new.cif exists already" && exit 1

# starting point for model:
model=BUSTER_model.cif

# the PDB doesn't like non-alphanumeric characters (although defined
# in dictionary, see
# e.g. http://mmcif.wwpdb.org/dictionaries/mmcif_pdbx_v50.dic/Items/_atom_site.label_asym_id.html)
for c in `awk '/^.:/{print $1}' $model`
do
  cc=`echo "$c" | sed "s/://g"`
  sed -e "s/^${c} /${cc} /g" -e "s/ ${c} / ${cc} /g" $model > __$$.cif && mv __$$.cif BUSTER_model_new.cif
  model=BUSTER_model_new.cif
done

# Although defined as non-mandatory
# (http://mmcif.wwpdb.org/dictionaries/mmcif_pdbx_v50.dic/Items/_entity_poly.pdbx_strand_id.html)
# the PDB wants _entity_poly.pdbx_strand_id to be present. Solution:
# remove the _entity_poly category.
grep -v "^_entity_poly\..* " BUSTER_model_new.cif > __$$.cif && mv __$$.cif BUSTER_model_new.cif
awk '{n++;l[n]=$0}
  /^_entity_poly\./{
    n=n-2
    while(NF>0) getline
  }END{for(i=1;i<=n;i++) print l[i]}' BUSTER_model_new.cif > __$$.cif && mv __$$.cif BUSTER_model_new.cif

# #-delimited comments produce warnings - better remove them:
sed "s/^_refln\(.*\)[ ]*#.*$/_refln\1/g" BUSTER_refln.cif > BUSTER_refln_new.cif

ls -l BUSTER_model_new.cif BUSTER_refln_new.cif
