# This is the script to connect ABCluster with CP2K.
#
# Usage: runCP2K.sh $inp$ $out$ $xxx$
#

cp2kcmd="mpirun cp2k.popt"

# Do NOT change lines below!
xyzfn=$1
outfn=$2
sysfn=$3

# Modify the coordinate file to meet the CP2K input grammar.
natoms=`head -n 1 ${xyzfn}`
natomsp2=`echo "${natoms}+2" | bc`
sed -i "1,2s/^/\!/" ${xyzfn}

# Create input file.
calctmpfn=CP2K.tmp
calcinpfn=${sysfn}.inp
calcoutfn=${sysfn}.out
cp ${calctmpfn} ${calcinpfn}
dsysfn=${sysfn##*/}
dxyzfn=${xyzfn##*/}
sed -i "s/sysname XXX/sysname ${dsysfn}/" ${calcinpfn}
sed -i "s/@INCLUDE XXX/@INCLUDE \"${dxyzfn}\"/" ${calcinpfn}

# Do the calculation.
${cp2kcmd} -i ${calcinpfn} -o ${calcoutfn}

# Collect results.
tac ${sysfn}-pos-1.xyz | head -n ${natomsp2} | tac > ${outfn}
energy=`grep "E =" ${outfn} | awk '{print $6}'`
sed -i "2c ${energy}" ${outfn}

# Decide if you want to delete any of them.
rm -rf ${sysfn}-pos-1.xyz ${sysfn}-1.restart* ${sysfn}-RESTART.wfn* ${sysfn}-BFGS.Hessian ${sysfn}.inp ${sysfn}.out
