#!/bin/bash					
rm a1a2ene							# rm the file a1a2ene
cp ini0.pdb ini.pdb						# cp file ini0.pdb to ini.pdb
for i in {0..4}							# external loop for i changes from 0 to 4
do
	a1=`echo -180 + 80 \* $i | bc -l `				# performs a1=-180+80*i. Where bc is a calculator
	for j in {0..4}							# internal loop for j changes from 0 to 4
	do
		a2=`echo -180 + 80 \* $j | bc -l `			# performs a2=-180+80*j. Where bc is a calculator
		echo $a1 $a2
		sed "s/_A1_/$a1/g;s/_A2_/$a2/g" < inp.templ > inp.$i.$j	# Reading file inp.templ and performing changes: _A1_ -> (value of) a1 and _A2_ -> (value of) a2. All changes will be saved in the file inp.1.1 (if i=1 and j=1)
		#    ^ s:substitute
		#	^ _A1_	will be substituted by (the value of) a1
		#	     ^  will substitute _A1_
		#		^ g: perform changes globally
		#		   ^s:substitute
		#		      ^ _A2_ will be substituted by (the value of) a2
		#			  ^ will substitute _A2_
		#			     ^g: perform changes globally
		#mpiexec -np ${NSLOTS} /home/apps/cp2k/bin/cp2k.popt -i inp.$i.$j > out.$i.$j
		cp2k.popt -i inp.$i.$j -o out.$i.$j			# running cp2k
		tail -25 ch-pos-1.pdb > opt.$i.$j.pdb			# saving the optimized geometry (last 25 lines of the optimization trajectory file) into opt.1.1.pdb (if i=1 and j=1)
		cp opt.$i.$j.pdb ini.pdb				# copying the optimized geometry into the file ini.pdb in order to use it as starting point for the next optimization
		af1=`grep -A 2 '&COLVAR_RESTART' ch-1.restart | head -2 | tail -1 `	# getting the value of the phi angle
		af2=`grep -A 2 '&COLVAR_RESTART' ch-1.restart | tail -1 ` 		# getting the value of the psi angle
		ef=`grep 'ENERGY|' out.$i.$j  | tail -1 | awk '{print $9}' `
		echo $af1 $af2 $ef >> a1a2ene				# adding the line "af1 af2 $ef" at the end of the file a1a2ene	
	done								
	echo " " >> a1a2ene						# adding a blanc line at the end of the file when internal loop finishes
done

