#!/bin/bash
#
#

export PATH="$PATH:/data/greenheron/apps/joy_related-1.06/hbond:/data/greenheron/apps/joy_related-1.06/sstruc:/data/greenheron/apps/joy-5.10:/data/greenheron/apps/muscle:/data/greenheron/apps/mp-t/bin:/data/greenheron/apps/ncbi-blast-2.2.27+/bin:/data/greenheron/apps/tmalign:/data/greenheron/apps/usearch"

ulimit -Ss `ulimit -Hs`

function abspath {
  if [[ -d "$1" ]]; then
    pushd "$1" >/dev/null
    pwd
    popd >/dev/null
  elif [[ -e "$1" ]]; then
    pushd $(dirname "$1") >/dev/null
    echo $(pwd)/$(basename "$1")
    popd >/dev/null
  else
    echo "$1" does not exist! >&2
    return 127
  fi
}

BINPATH=`abspath "$0"`
BINPATH=`dirname "$BINPATH"`
MAINPATH=`dirname "$BINPATH"`
LIBPATH="$MAINPATH/lib-python"


export PYTHONPATH="$LIBPATH:$PYTHONPATH"
export PATH="$BINPATH:$PATH"


getstruc() {
  code="$1"
  fname="$2"
  getpdbchain "$code"
  
  if ! [ -f "$code.pdb" ]; then
    echo -e "Unable to retrieve PDB structure: $code\nMessage:\n\n$log\n" 1>&2
    exit 7
  fi
  
  mv -f "$code.pdb" "$fname" || {
    echo -e "ERROR: Unable to rename PDB structure: $code to $fname" 1>&2
    exit 7
  }
}


if [[ "$1" == "-pdb" ]]; then
  shift
  pdbcode="$1"
  shift
  pdbfilename="$1"
  shift
  
  getstruc "$pdbcode" "$pdbfilename"
fi


alignment="$1"
structure="$2"
template="$3"
target="$4"
medeller_opts="$5"
imembrane_opts="$6"

if ! [ "$1" ]; then
  myname=`basename "$0"`
  echo "
  USAGE:
    $myname [-pdb <id> <filename>] <alignment_filename> <structure_filename> <structure_id> <target_id> [medeller_flags [imembrane_flags]]
    or
    $myname [-pdb <id> <filename>] <imembrane_options>
    " 1>&2
  exit 1
fi


if ! [ "$target" ]; then
  ## We're running just iMembrane
  #
  imembrane_opts="$1"
  mkdir -p imem
  echo
  echo "Runing command: imembrane --verbose --maxhits 10 --outdir imem $imembrane_opts"
  echo
  imembrane --verbose --maxhits 10 --outdir imem $imembrane_opts
  
  if ! [ -f "imem/hits.table" ]; then 
    echo "
    No iMembrane hits found for input protein.
    Cannot annotate membrane insertion." 1>&2
    exit 5
  fi
  
  exit 0
fi


if ! [ -s "$alignment" ]; then
  echo "alignment file empty or not found: $alignment" 1>&2
  exit 2
fi

if ! [ -s "$structure" ]; then
  echo "structure file empty or not found: $structure" 1>&2
  exit 3
fi

numseqs=`grep -c ">" "$alignment"`
if [ "$numseqs" != 2 ]; then
  echo "Error: Alignment file contains $numseqs sequences. Must contain 2 sequences: $targetfile" 1>&2
  exit 2
fi

specialcharacters=$(grep -v '>' "$alignment" | grep -Po '[^ACDEFGHIKLMNPQRSTVWY\s\-\*]' | xargs echo | tr -d ' ')
if [ "$specialcharacters" ]; then
  echo "Error: Alignment file contains ${#specialcharacters} non-standard amino acids: '$specialcharacters'. Please substitute them with standard amino acids or cut down your target sequence. Path to alignment file: $alignment" 1>&2
  exit 2
fi

chains=`splitchain --list "$structure"`
if [ ${#chains} != "1" ]; then
  echo "Error: Structure contains ${#chains} chains. Must contain 1 chain: $structure" 1>&2
  exit 2
fi


fasta2ali "$alignment" > input_alignment.ali
alignment=input_alignment.ali


strucname=`basename "$structure"`
strucname=${strucname%.*}


mkdir -p imem
echo
echo "Running command: imembrane --verbose --joy --transmembrane --maxhits 10 --inputid $template --struc $structure --outdir imem $imembrane_opts"
echo
imembrane --verbose --joy --transmembrane --maxhits 10 --inputid "$template" --struc "$structure" --outdir imem $imembrane_opts

success=$?
if (( $success != 0 )); then
  echo "
  iMembrane did not finish running. Cannot annotate membrane
  insertion, which is required for model building." 1>&2
  exit 5
fi

if ! [ -s "imem/hits.table" ]; then 
  echo "
  No iMembrane hits found for template structure. Cannot annotate membrane
  insertion, which is required for model building." 1>&2
  exit 6
fi

if ! [ -s "imem/tophit/query_annotation.tem" ]; then
  echo "
  No iMembrane hits found for template structure. Cannot annotate membrane
  insertion, which is required for model building." 1>&2
  exit 6
fi

echo
echo "Running command: temcat $alignment imem/tophit/query_annotation.tem > modelling.tem"
echo
temcat "$alignment" imem/tophit/query_annotation.tem > modelling.tem

success=$?
if (( $success != 0 )); then
  echo "
  Failed to merge template annotation with input alignment.
  This may be a bug. Please contact the sys-admin or the author." 1>&2
  exit 7
fi


mkdir -p medeller
cd medeller >/dev/null
echo
echo "Running command: medeller $medeller_opts --verbose --atm -a ../modelling.tem -i $target --pairs $template ../imem/tophit/layer.atm"
echo
medeller $medeller_opts --verbose --atm -a ../modelling.tem -i "$target" --pairs "$template" ../imem/tophit/layer.atm

success=$?

#a=(*.atm)
a=(*.{core,hiacc,hicov,complete}.atm)
for model in ${a[@]}; do
  if [ -f "$model" ]; then
    modeltype=`echo "$model" | cut -d. -f2`
    echo
    echo "Running command: imem_project --dbdir ../imem --insubdir tophit --dbid $template --inputid $target --struc $model --outsubdir $modeltype"
    echo
    imem_project --dbdir ../imem --insubdir tophit --dbid "$template" --inputid "$target" --struc "$model" --outsubdir "$modeltype"
  fi
done
cd .. >/dev/null

if (( $success != 0 )); then
  echo "
  MEDELLER did not finish running." 1>&2
  exit 8
fi
