############################################################################
#
# This bash script calculates and returns the number of different 
# values in two files ($1 and $2). 
# It calculates the differences and returns the maximum difference found.
#
#############################################################################



######################
# check input files
######################
if [ -f $1 ]; then

numcol=`awk '{print NF}' $1 | sort -nu | tail -n 1`
numrow=`cat $1 | wc -l`

else
echo "ERROR: compare_numbertable can't find file $1"
exit 1
fi

if [ -f $2 ]; then

numcol2=`awk '{print NF}' $1 | sort -nu | tail -n 1`
numrow2=`cat $1 | wc -l`

else
echo "ERROR: compare_numbertable can't find file $2"
exit 1
fi


######################
# compare all numbers present in input files $1 and $2
######################
largestdiff="0.0"
countdiff=0
for y in `seq 1 $numrow`
do

line1=`cat $1 | head -$y | tail -1`
line2=`cat $2 | head -$y | tail -1`

  for x in `seq 1 $numcol`
  do
  number1=`echo "$line1" | awk '{printf $'$x'}'`
  number2=`echo "$line2" | awk '{printf $'$x'}'`

  is1number=`echo "$number1" | awk '$0 ~/[^-0-9.0-9]/ { print "ITSNOTANUMBER" }'`
  is2number=`echo "$number2" | awk '$0 ~/[^-0-9.0-9]/ { print "ITSNOTANUMBER" }'`
  if [[ $number1 == "" ]]; then
    is1number="ITSNOTANUMBER"
  fi
  if [[ $number2 == "" ]]; then
    is2number="ITSNOTANUMBER"
  fi



  # if only one of the entries contains a number, something has probably gone wrong so we set largestdiff:

  if [[ $is1number == *ITSNOTANUMBER* ]]; then
    if [[ $is2number != *ITSNOTANUMBER* ]]; then
      largestdiff=1000000000
    fi
  fi
  if [[ $is2number == *ITSNOTANUMBER* ]]; then
    if [[ $is1number != *ITSNOTANUMBER* ]]; then
      largestdiff=1000000000
    fi
  fi


  # if both entries are numbers we calculate their difference
  if [[ $is1number != *ITSNOTANUMBER* ]]; then
  if [[ $is2number != *ITSNOTANUMBER* ]]; then

  difference=`python -c "e=(($number1-$number2)**2)**0.5; print e" `
  difference=`python -c "e=(($number1-$number2)**2)**0.5; print e" `
    if [ $difference != "0.0" ]; then
      # if a tolerance value has been specified consider it here
      if [ "$#" -eq 3 ]; then
        tolbrake=`python -c "e=$difference > $3; print e" `
        if [[ "$tolbrake" == "True" ]]; then 
          countdiff=`python -c "e=$countdiff+1; print e" `
        fi
      else
        countdiff=`python -c "e=$countdiff+1; print e" `
      fi
    fi

    # if a tolerance value has been specified consider it here
    if [ "$#" -eq 3 ]; then
      if [[ "$tolbrake" == "True" ]]; then 
        largestdiff=`python -c "e=max($difference,$largestdiff); print e" `
      fi
    else
      largestdiff=`python -c "e=max($difference,$largestdiff); print e" `
    fi

  fi
  fi
   
  done

done

if [ $largestdiff != "0.0" ]; then
  echo "$countdiff numbers in file $1 and $2 differ."
  echo "The maximum difference between two numbers in files $1 and $2 is $largestdiff"
fi
