#!/bin/bash

nb_line=`cat input.cmd | grep "^: " | wc -l`
current_line=0
#echo ".0" > fraction_done

# Delete any previous output (important on any restarting)
rm -f input.ied


check_count=0
while read line;
do
    # lines starting with a single ":" are command-line, otherwise they are an input file "input.ied" for iedera (this input.ied file must be set before running iedera)
    if [[ $line = \:* ]];
    then
	# lines starting with a double "::" are comments
	if [[ $line = \:\:* ]];
	then
	    # lines starting with a "::CHECK:" are special comments (they must occur once only)
	    if [[ $line = \:\:CHECK\:* ]];
	    then
		if [[ $check_count > 0 ]];
		then
		    echo "::ERROR: input file with double ::CHECK: inside"
		    exit 1
		fi
		((check_count++))
	    fi
	    # lines starting with a "::ERROR:" are special comments (they must occur once only)
	    if [[ $line = \:\:ERROR\:* ]];
	    then
		echo "::ERROR: \"$line\" found"
		exit 2
            fi 
	    # copy comments to stdout if any
	    echo $line
	else 
	    #restart after last chechpoint
	   progress=`echo "${current_line}/${nb_line}" | bc -l`
	   checkpoint=`cat checkpoint.txt`
	  #echo "checkpoint $checkpoint progress:$progress current_line:$current_line nb_line:$nb_line"
		if (( $(echo "$checkpoint > $progress" |bc -l) )) 
		then
			#echo "skip line"
   			((current_line++))
			continue   #skip line
			
		fi
            # run iedera, then delete the input file
            ./iedera -e input.ied ${line:2}
            echo "${line}"
            # output multiple lines to "stdout something, but marker ":" help separating multiple output after a run ... so this echo "${line}" is important here!!"
            # note the full output file can be reused as input file !!! easy ;-)
	    # clean the input file (to avoid concatenation with other runs)
            rm -f input.ied
	    ((current_line++))
	    progress=`echo "${current_line}/${nb_line}" | bc -l`
            echo $progress > fraction_done
	    echo $progress > checkpoint.txt
	fi
    else
	# create the input file before running iedera
	echo $line >> input.ied
    fi
done < input.cmd
rm -f input.ied
