# CPSC 1011 Lab 9 Grading Script
# Written by Lauren Dukes (lcairco@clemson.edu)

#set up the output csv file to hold the grades
rm -r -f gradelab9.csv
rm -r -f *.txt

echo "student_id, sort1, sort2, bounds, total, gradingcomment" >> gradelab9.csv

#find all student directories
for file in $(find . -type f -name "lab9.c" )
#for each of those files
do
	rm *.ppm -r -f
        #extract out the student's name from the path
        path=${file%/*}
        studentname=${path##*/}

	gcc $path/*.c
	return_value=$?

	if [ $return_value = 0 ]
	then
		#echo "About to run"$studentname
		timeout 1 ./a.out < lab9tests/tc1.txt > tc1out.txt
		timeout 1 ./a.out < lab9tests/tc2.txt > tc2out.txt

		cat tc1out.txt | sed 's/[^0-9]*//g' | sed '/^$/d' > tc1out.txt
		sort -h tc1out.txt  > tc1sorted.txt
		cat tc2out.txt | sed 's/[^0-9]*//g' | sed '/^$/d' > tc2out.txt
		sort -h tc2out.txt > tc2sorted.txt

		#echo "Diffing"
		diff tc1out.txt tc1sorted.txt > diff1.txt
		diff1=$?
		diff tc2out.txt tc2sorted.txt > diff2.txt
		diff2=$?

		if [ $diff1 -eq 0 ]
		then
			sort1=1
			bounds=1
		else
			cat tc1out.txt
			echo "Are the bounds ok? (right number of values, right values) "
			read bounds
			echo "Does this look sorted? 1 for yes, 0 for no "
			read sort1
		fi

		if [ $diff2 -eq 0 ]
		then
			sort2=1
		else
			cat tc2out.txt
			echo "Does this look sorted? 1 for yes, 0 for no "
			read sort2

		fi 
		note=""
	else
		sort1=0
		sort2=0
		note="did not compile"
	fi

        #write out the grading results for the file as a CSV

        #write out the student's name
        echo -n $studentname"," >> gradelab9.csv

        #write out the grading criteria and go to next line
        echo -n $(($sort1*38))"," >> gradelab9.csv
        echo -n $(($sort2*37))"," >> gradelab9.csv

        finalgrade=$(($sort1*20+$sort2*20+$bounds*35+25))

        echo -n $finalgrade",">> gradelab9.csv

	echo -n "Name: "$studentname >>${studentname}.txt
        echo -n  " sort 1: "$(($sort1*20))" " >> ${studentname}.txt
        echo -n  " sort 2: "$(($sort2*20))" " >> ${studentname}.txt
	echo -n  " bounds: "$(($bounds*35))" " >> ${studentname}.txt
        echo -n  " total: "$finalgrade" " >> ${studentname}.txt
	echo -n "note: "$note >> ${studentname}.txt

	cat ${studentname}.txt >> gradelab9.csv
	rm -rf ${studentname}.txt
	echo "" >> gradelab9.csv
     
        #let you know you're moving on to the next file
        echo "Done grading for "+$studentname+"."
done

