#!/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`

COUNTER=0
UPPERCOUNTER=0
LOWERCOUNTER=0
INIUPPERCOUNTER=0
INILOWERCOUNTER=0

LOWERLIMIT=5.3
UPPERLIMIT=7.4
MIDDLELIMIT=6.3
FIRSTSTEP=0
LASTSTEP=5000

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

#read every line of each CHOL residue
while read -r -a line ; do
    VALUE=${line[1]}
#    echo "$VALUE"
    if [[ $LINE == $FIRSTSTEP ]]; then
     if [[ $UPPER == 0 ]] && [[ $LOWER == 0 ]]; then
         if [[ $VALUE < $MIDDLELIMIT ]]; then
          LOWER=1
          let INILOWERCOUNTER=INILOWERCOUNTER+1 
          else
          UPPER=1
          let INIUPPERCOUNTER=INIUPPERCOUNTER+1
          fi
       fi
     fi
    
    let LINE=LINE+1
    if [[ $VALUE > $UPPERLIMIT ]]; then
#	echo "upper"
	if [[ $LOWER == 1 ]]; then
	let COUNTER=COUNTER+1
        echo "$k flipping to upper at step $LINE"
	fi
	UPPER=1
	LOWER=0
    fi
    if [[ $VALUE < $LOWERLIMIT ]]; then
	if [[ $UPPER == 1 ]]; then
#	echo "lower"
        let COUNTER=COUNTER+1
        echo "$k flopping to lower at step $LINE"
	fi
	UPPER=0
	LOWER=1
    fi
#    echo $COUNTER
    if [[ $LINE == $LASTSTEP ]]; then
     if [[ $UPPER == 0 ]] && [[ $LOWER == 0 ]]; then
         if [[ $VALUE < $MIDDLELIMIT ]]; then
          LOWER=1
          else
          UPPER=1
          fi
       fi
#      echo "number of flipflops: $COUNTER"
       break
       fi
   
done < coord_CHOL${k}.xvg

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

done
echo "initial amount of molecules in upper at step $FIRSTSTEP: $INIUPPERCOUNTER"
echo "initial amount of molecules in lower at step $FIRSTSTEP: $INILOWERCOUNTER"
echo "number of flipflops: $COUNTER"
echo "final amount of molecules in upper at step $LASTSTEP: $UPPERCOUNTER"
echo "final amount of molecules in lower at step $LASTSTEP: $LOWERCOUNTER"

#rm \#*

