#!/bin/sh
#set -vx

# Create Amber input files for a combined receptor ligand complex
# from a receptor pdb file and a ligand mol2 file.

# The input is:
#    (1)  The receptor pdb filename prefix, ie, the filename without 
#         the .amber.pdb extension.
#    (2)  The ligand input filename prefix, ie, the filename without
#         the .gaff.mol2 extension.  

# The ligand name is assumed to match the regular expression
# [A-Z][A-Za-z0-9][A-Za-z0-9]

# The outputs are a pdb file, an Amber prmtop file, and an incidental
# Amber inpcrd file all for the combined receptor ligand complex.

# Scott Brozell and Dave Case , TSRI

if [ $# -eq 2 ]
then
    receptor_name=$1
	ligand_name=$2
else
    echo "usage:  $0  [receptor_name] [ligand_name]"
    exit
fi


leapin=`echo $0.leapin.$$ | sed 's@/@_@g'`  # convert pathname into filename
leapin=/tmp/$leapin

output_inpcrd=$receptor_name.$ligand_name.inpcrd
output_pdb=$receptor_name.$ligand_name.amber.pdb
output_prmtop=$receptor_name.$ligand_name.prmtop

# Extract unit name from the mol2 file:
##@<TRIPOS>ATOM
##      1 C1          3.4870   67.1120   65.0110 ca        1 EDR      -0.0219
##                                                           ^^^
unit=`
 cat $ligand_name.gaff.mol2 |
 sed '/^[       ]*$/d' |               # delete blank and whitespace-only lines
 sed -n '/@<TRIPOS>ATOM/{n;p;}' |  # print the line after @<TRIPOS>ATOM
 sed 's/        / /g' |                # convert a tab to a space
 sed 's/  */ /g' |                 # convert multiple spaces to a single space
 sed 's/^ //' |                    # delete a leading space
 cut -d' ' -f8                     # extract field 8 using space as a delimiter
`

# verbosity 2
# source ~/.leaprc
cat << EOF > $leapin
 source leaprc.ff94
 source leaprc.gaff
 frcmod=loadamberparams $ligand_name.frcmod
 $ligand_name=loadMol2 $ligand_name.gaff.mol2
 x=loadPdb $receptor_name.amber.pdb
 z=combine { x $ligand_name }
 savePdb z $output_pdb
 saveAmberParm z $output_prmtop $output_inpcrd
 quit
EOF

DOCKHOME/bin/tleap -s -f $leapin

rm $leapin
mv leap.log $receptor_name.$ligand_name.log
exit

