#!/bin/bash
. /cluster/apps/courses/mmm/m_functions.bash

if [[ $# -ne 1 ]]
then
	echo "Error!!!
	Please specify one argument
Description:
	This program creates a series of z histograms (10 frames each) of a XYZ file
Usage:
	./doprof file.xyz" >&2 
	exit 1
fi

FILE=$1

NUM=`grep i $FILE | wc  | awk '{print $1}' `

echo $NUM frames in $FILE

DEL=10

i=1

j=$DEL

while (( j <= $NUM ))
do 
	./histo_z $FILE $i $j > $FILE.z.$i.$j
	if (( i == 1 ))
	then
		XMIN=`awk 'BEGIN {xmin=1000} (NR>2){if ($1 < xmin){xmin=$1}} END {print xmin}'  < $FILE.z.$i.$j ` 
		XMAX=`awk 'BEGIN {xmax=-1000}(NR>2) {if ($1 > xmax){xmax=$1}} END {print xmax}'  < $FILE.z.$i.$j ` 
		YMIN=`awk 'BEGIN {ymin=1000} (NR>2) {if ($2 < ymin){ymin=$2}} END {print ymin}'  < $FILE.z.$i.$j ` 
		YMAX=`awk 'BEGIN {ymax=-1000}(NR>2) {if ($2 > ymax){ymax=$2}} END {print ymax}'  < $FILE.z.$i.$j ` 
	fi
	
	sed "s/_NAME_/$FILE.z.$i.$j/g;s/_XMIN_/$XMIN/g;s/_YMIN_/$YMIN/g;s/_XMAX_/$XMAX/g;s/_YMAX_/$YMAX/g"< z.gnu > z.s.gnu
	gnuplot z.s.gnu 2> /dev/null
	mv a.gif $FILE.$i.$j.gif
	rm z.s.gnu
	rm $FILE.z.$i.$j 
	i=$[$i+$DEL]
	j=$[$i+$DEL-1]
done

convert -delay 100 $FILE.?.*gif $FILE.??.*gif $FILE.???.*gif  $FILE.????.*gif movie.$FILE.gif 2> /dev/null
rm  $FILE.?.*gif $FILE.??.*gif $FILE.???.*gif  $FILE.????.*gif 2> /dev/null
echo "Done."

echo "To animate the produced gif file run:
animate -loop 0 -delay 100 movie.half-pos-1.xyz.gif"

