#! /bin/bash
#require a parameter input
if [ 1 -gt $# ]
then
	echo "please remember to indicate the layers to use."
	read -p "Is this your intention to use all layers ? y/n " answer
	if [[ $answer == "n" ]]
	then
		exit
	fi	
fi

#false positive or detection rate
read -p "negatives or positives ? p/n " pn
if [ $pn == "p" ]
then
	symbol="positives"
else
	symbol="negatives"
fi


#get all the positives I have
testExamples="test_$symbol.allIhave"
trainExamples="$symbol.allIhave"

#gather all the examples
rm allExamples
cat $testExamples >> allExamples
cat $trainExamples >> allExamples
size=$(cat allExamples | wc -l)
echo $size $symbol " to look at in all."
#maybe a sanity check here
cat allExamples | sort | uniq > allExamples_sorted
uniqueNames=$(cat allExamples_sorted | wc -l)
if [ "$uniqueNames" -ne "$size" ]
then
	echo -e "Duplicate examples appear!"
	exit
fi

#now run the detector on all the examples
rm logCache
for ((i = 1; i <= $size; i++))
do
	line=$(sed -n ${i}p allExamples)
	#which example now
	#echo $i ":" $line
	if [ $# -gt 0 ]
	then
		./detect $line $1 >> logCache
	else
		./detect $line >> logCache
	fi
done

if [ 1 -gt $# ]
then
	found="$symbol:allCouchesPositives"
	lost="$symbol:allCouchesNegatives"
else
	found="$symbol:$1CouchesPositives"
	lost="$symbol:$1CouchesNegatives"
fi


echo -e "\n\n#####################################################################################\n\n"
echo -e "RATE REPORT: \n"
if [ $# -gt 0 ]
then
	echo -e "Only the first $1 layers produced the following result:\n"
else
	echo -e "Full cascade produced the following result:\n"
fi

#which are the faces that are correctly classified
echo -e "\nsee how many are detected..."
rm $found
cat logCache | grep "I've found" | sed "s:^I've.*in ::g" > $found
echo -e "\n\tamong $size $symbol, detector has declared $(cat $found | wc -l)  entries positive\n"

#which are the faces that aren't identified
echo -e "\nsee how many are dismissed..."
rm $lost
cat logCache | grep "No f" | sed "s:^No f.*in ::g" > $lost
echo -e "\n\tamong $size $symbol, detector has declared $(cat $lost | wc -l) entries negative\n"


#sanity check, if there is a non-empty difference, that's a problem
rm foundLost
cat $found >> foundLost
cat $lost >> foundLost
cat foundLost  | sort > foundLost_sorted
diff foundLost_sorted allExamples_sorted --new-line-format="" --old-line-format="%L" --unchanged-line-format="" > difference
nInCons=$(cat difference | wc -l)
if [ $nInCons -gt 0 ] 
then
	echo -e "Note that there are $nInCons inconsistencies detected. Only 0 is expected! See difference"
else
	rm difference *_sorted
fi
