#!/bin/bash

DATA_STORAGE="/mnt/raid/storage/lsbb/elm"

ELM_SPECTRUM="/home/prokop/idl_temp/elmavan_spectrogram.idl"

ELM_PRO_TMP="/tmp/runelm.pro"

ELM_DIR="/mnt/raid/delos/delo4/elm/"

ELM_TMP_DIR="/tmp/delo4/elmavan"

HTML_PICS="/var/www/html/lsbb/pics_d"
HTML_LOG="/var/www/html/lsbb/elm.txt"
HTML_LOG_MAX="/var/www/html/lsbb/elm_max.txt"

create_elm_config() {
	echo -n "" > $ELM_PRO_TMP
	echo ".run /home/prokop/scripts/elm.pro" >> $ELM_PRO_TMP
	echo ".run /home/prokop/scripts/elm.pro" >> $ELM_PRO_TMP
	echo ".run /home/prokop/scripts/elm.pro" >> $ELM_PRO_TMP
	echo "process,'$1',/ground" >> $ELM_PRO_TMP
	echo "exit" >> $ELM_PRO_TMP
}

process_data() {
        #elmavan data parsing
        cd $ELM_TMP_DIR
        cp $ELM_SPECTRUM elmavan_spectrogram.idl
        create_elm_config $(ls *.bin)
        idl $ELM_PRO_TMP 2>/dev/null
        #convert -density 200 -flatten -rotate 270 -crop 1967x650+0+0 +repage *.ps[0] $HTML_PICS/el.png &

	ps2pdf -dOptimize=true -dDownsampleColorImages=true -dColorImageResolution=150 001__*dat00.ps data.pdf &	

        convert -density 150 -flatten -rotate 270 el.ps $HTML_PICS/el.png &
        convert -density 150 -flatten -rotate 270 -resize 380x272 el.ps $HTML_PICS/el380.png &
        convert -density 150 -flatten -rotate 270 *_elspg.ps $HTML_PICS/elspg.png &
        convert -density 150 -flatten -rotate 270 -resize 600x391 *_elspg.ps $HTML_PICS/elspg600.png &

        convert -density 150 -flatten -rotate 270 el1.ps $HTML_PICS/el1.png &
        convert -density 150 -flatten -rotate 270 el10.ps $HTML_PICS/el10.png &

        mv -f elmavan_spectrogram.idl $ELM_SPECTRUM
	cat $ELM_TMP_DIR/elm.txt >> $HTML_LOG && rm $ELM_TMP_DIR/elm.txt
	echo -n "$1" >> $HTML_LOG_MAX
	# extract maximum waveform data from txt file
	sed -n '20{p;q}' 001__*.txt >> $HTML_LOG_MAX
        wait
	rm -rf crcfile.txt *.bin elm*.txt *.log *.ps

	cp $HTML_PICS/el.png $HTML_PICS/el1.png $HTML_PICS/el10.png $HTML_PICS/elspg.png .

	nice -n 19 zip -r $DATA_STORAGE/elm_${1}_pics.zip * && rm -rf $ELM_TMP_DIR/* && mv $ELM_DIR/elm_${1}.7z $DATA_STORAGE/
}

if [ -d "$ELM_TMP_DIR" ]
then
	rm -rf $ELM_TMP_DIR/*
else
	mkdir -p $ELM_TMP_DIR
fi


INPUT=""

while [ "$INPUT" != "q" ]
do
        #FNAME=$(ls -tr1 $ELM_DIR | head -1)
        FNAME=$(ls -1 $ELM_DIR | head -1)

        if [ -z $FNAME ]
        then
                sleep 5
                echo -n "."
                continue
        fi

        if [ -e $ELM_DIR/$FNAME ]
        then
		echo "Unpacking $FNAME"
		cd $ELM_TMP_DIR
		#tar xjf $ELM_DIR/$FNAME
		7za e $ELM_DIR/$FNAME
		echo "Processing ${FNAME:4:15}"
		process_data ${FNAME:4:15}
                #rm $LOG_DIR/$FNAME
        fi
	read -t 0.1 INPUT
done
