#!/bin/sh
#Usage: sort_results.sh <key file> <results file>
#Reads the key file generated by make_testcase.sh and a results file, which
# consists of one line per image, each line containing the (0-based) index of
# the image followed by the ranking (0 = best to nconditions-1 = worst) of each
# condition in the index.html created by make_testcase.sh, all simple integers
# separated by whitespace.
set -e
key="$1"
ranks="$2"

declare -a key_line
exec {key_fd}<"${key}"
read -a key_line -u "${key_fd}"
nkey_line="${#key_line[@]}"
nconditions=$((nkey_line-2))
if [[ "${nconditions}" -lt 1 ]] ; then
  echo "Error in key file (no conditions found)" | /dev/stderr
  exit 1
fi
declare -a conditions
declare -a rank_counts
for ((i=0;i<nconditions;i++)) ; do
  conditions[i]="${key_line[i+1]}"
  for ((j=0;j<nconditions;j++)) ; do
    rank_counts[i*nconditions+j]="0"
  done
done
declare -a ranks_line
declare -a cond_map
nrefs=0
exec {ranks_fd}<"${ranks}"
while read -a ranks_line -u "${ranks_fd}" ; do
  nranks_line="${#ranks_line[@]}"
  if [[ "${nranks_line}" != "$((nconditions+1))" ]] ; then
    echo "Expecting $((nconditions+1)) ranks on line $((nrefs+1)) of rank file, but found ${nranks_line}." > /dev/stderr
    exit 1
  fi
  for ((i=0;i<nconditions;i++)) ; do
    for ((j=0;j<nconditions;j++)) ; do
      [[ "${key_line[i+1]}" = "${conditions[j]}" ]] && break
    done
    if [[ "${j}" -ge "${nconditions}" ]] ; then
      echo "Condition ${key_line[j+1]} not found in condition" \
       "list at line $((nrefs+1)) in key file." > /dev/stderr
      exit 1
    fi
    cond_map[i]="${j}"
  done
  for ((i=0;i<nconditions;i++)) ; do
    cond="${ranks_line[i+1]}"
    if [[ "${cond}" -ge "0" && "${cond}" -lt "${nconditions}" ]] ; then
      rank_counts[cond_map[cond]*nconditions+i]="$((rank_counts[cond_map[cond]*nconditions+i]+1))"
      echo -n "${key_line[cond+1]} "
    else
      echo "Condition ${cond} not found at line $((nrefs+1)) in rank file." \
       > /dev/stderr
      exit 1
    fi
  done
  echo "${key_line[nconditions+1]}"
  nrefs="$((nrefs+1))"
  read -a key_line -u "${key_fd}" || break
done
for ((i=0;i<nconditions;i++)) ; do
  echo -n "${conditions[i]}"
  for ((j=0;j<nconditions;j++)) ; do
    echo -n "	${rank_counts[i*nconditions+j]}"
  done
  echo
done
