#!/bin/sh
#------------------------------------------------------------------------------
#
#  kpax_model_split: to split a multi-model PDB file into individual files.
#
#  examples: 
#
#  kpax_model_split multi.pdb          # -> multi_000001.pdb, multi_000002.pdb,..
#  kpax_model_split -o base <multi.pdb # -> base_000001.pdb, base_000002.pdb,..
#  cat multi.pdb | kpax_model_split    # -> kpax_model_split_000001.pdb,..
#
#  (also converts DOS line terminators to Unix "\r\f" -> "\n")
#
#  Dave Ritchie 07/12/06
#
#------------------------------------------------------------------------------
#

if [ -z "$1" ]; then
   base="kpax_model_split"
elif [ "$1" = "-o" ]; then
   shift
   base=$1
elif [ -f "$1" ]; then
   root=`basename $1`
   base=${root%.*}
   exec 0<$1
else
   echo "$0: file not found - $1"
   exit
fi

#------------------------------------------------------------------------------

awk 'BEGIN { new = 0; m = 0; RS = "[\n\f]"; ORS = "\n"; }
{
   gsub ("\r", "", $0);

   if (new == 1) {

      new = 0;

      m = m + 1;

      filename = sprintf("%s_%6.6d%s", base, m, ".pdb");

      print $0 > filename;                           # first line to current model file

   } else {

      if ($1 == "MODEL")       new = 1;

      else if ($1 == "ENDMDL") new = 0;

      else if (m > 0)          print $0 >> filename;  # next lines to model file
   }
}' base=$base

#------------------------------------------------------------------------------
