#!/usr/bin/env bash

cat > energy.namd << EOF
outputname energy
outputEnergies 1
cellBasisVector1 30. 0. 0.
cellBasisVector2 0. 30. 0.
cellBasisVector3 0. 0. 30.

paratypeCharmm on
exclude scaled1-4
parameters toppar/par.prm
PME yes
PMEGridSizeX 36
PMEGridSizeY 36
PMEGridSizeZ 36 
PMETolerance   1.0e-6
PMEInterpOrder  4
switching      on
switchdist     10
cutoff         12
pairListDist   14

LJcorrection \$LJopt
temperature 0
run 0
EOF


for l in 0 1; do
    # single topology endpoints
    endpoint=lambda$l
    for LJopt in on off; do
 
        echo "#########################################"
        echo "The following systems should be identical"

        cat > $endpoint.namd << EOF
structure   toppar/$endpoint.psf
coordinates toppar/$endpoint.pdb
set LJopt $LJopt
source energy.namd
EOF
        namd2 $endpoint.namd | grep ETITLE: | tail -n 1

        echo "===="
        echo "$endpoint : LJcorr = $LJopt"
        echo "===="
        namd2 $endpoint.namd | grep ENERGY: | tail -n 1

        # dual topology endpoints
        cat > dualtopo.namd << EOF
structure   toppar/dualtopo.psf
coordinates toppar/dualtopo.pdb
set LJopt $LJopt
alch                on
alchDecouple        off
alchType            TI
alchOutFile         alchemy.out
alchOutFreq         0
alchVdwShiftCoeff   0.0
alchElecLambdaStart 0.0
alchVdwLambdaEnd    1.0
alchLambda          $l
alchLambda2         $l

reassignFreq 10
reassignTemp 0.

source energy.namd
EOF
        echo "===="
        echo "dualtopo (lambda=$l) : LJcorr = $LJopt"
        echo "===="
        namd2 dualtopo.namd | grep ENERGY: | tail -n 1

        echo "#########################################"
    done
done

rm -f *.namd *.out *.coor *.xsc *.vel *.BAK 2> /dev/null
