#!/bin/bash
#
# Code by  venkentom@gmail.com
#
# Licenced by the GPL General Public License
# Have a look at:
# http://www.gnu.org/copyleft/gpl.html
# For more information about the GPL License
#
# I am not responsible for what this code does to your hw/sw/mind
# Use at your own risk
# 

#Put gromacs commands after this line

DIR=`pwd`

make_ndx -f dynamic.gro -o index_chol.ndx <<EOL
splitres 14
q 
EOL

for i in {16..61}
do
j=$(($i + 57))
echo $j

#write out z-coordinates of each cholesterol molecule based on the center of mass
g_traj -s dynamic.tpr -f dynamic_pbc.xtc -ox coord_CHOL${j}.xvg -nox -noy -com -n index_chol.ndx -xvg none -tu us <<EOL
$i
EOL

done

rm out.txt

COUNTER=0

UPPERCOUNTER=0
LOWERCOUNTER=0

#loop over all CHOL residues
for k in {73..118} #118
do
VALUE=0
UPPER=0
LOWER=0

#read every line of each CHOL residue
while read -r -a line ; do
    VALUE=${line[1]}
#    echo "$VALUE"
    if [[ $VALUE > 7 ]]; then 
#	echo "upper"
	if [[ $LOWER == 1 ]]; then
	let COUNTER=COUNTER+1
	fi
	UPPER=1
	LOWER=0
    fi
    if [[ $VALUE < 5 ]]; then 
	if [[ $UPPER == 1 ]]; then
#	echo "lower"
        let COUNTER=COUNTER+1
	fi
	UPPER=0
	LOWER=1
    fi
    echo "$COUNTER"
done < coord_CHOL${k}.xvg

if [[ $UPPER == 1 ]]; then
   let UPPERCOUNTER=UPPERCOUNTER+1
fi
if [[ $LOWER == 1 ]]; then
   let LOWERCOUNTER=LOWERCOUNTER+1
fi

done

echo "final amount of molecules in upper: $UPPERCOUNTER"
echo "final amount of molecules in lower: $LOWERCOUNTER"

rm \#*

