#!/bin/sh

# Return just the root of the filename (equivalent to csh's ':r' function)
returnroot()
{
        expr $1 : '\(.*\)\.' \| $1
}

# Return just the extension of the filename (equivalent to csh's ':e' function)
returnext()
{
        expr $1 : '.*\.\(.*\)' \| ""
}

# Calculate the ratio between image and pattern
calc_ratio()
{
    ipixels="`../header_util < $1.raw | grep Pixels | sed -n 's/^.*= //p'`"
    iscans="`../header_util < $1.raw | grep Scanlines | sed -n 's/^.*= //p'`"
    ppixels="`../header_util < $1-pattern.raw | grep Pixels | sed -n 's/^.*= //p'`"
    pscans="`../header_util < $1-pattern.raw | grep Scanlines | sed -n 's/^.*= //p'`"
    num="`expr $ipixels \* $iscans`"
    den="`expr $ppixels \* $pscans`"

    nawk 'BEGIN { printf "%.2lf", '$num'/'$den'}'
}

cwd="`pwd`"
lps="509 557 237 380"
results="`basename $cwd`"

# Linear Pixel Shuffling values (manually given)
if [ "$1" = "-l" ]
then
  shift
  lps="$1"
  shift
fi

# Ratio (manually given)
if [ "$1" = "-r" ]
then
  shift
  ratio="$1"
  shift
else
  ratio=""
fi

if [ $# -eq 0 ]
then
  if [ -f $results.log ]
  then
    mv $results.log $results.log.old
  fi
  touch $results.log

  for pattern in *pattern*
  do
    name="`echo $pattern | sed -n 's/-pattern.*//p'`"
    if [ -z "$ratio" ]
    then
      ratio="`calc_ratio $name`"
    fi

    echo -n "Working on {$name} ... "

    ../sherlock -t $name -s "(ratio = $ratio:1)" -i $name.raw -p $pattern -b ../runbatch -l "$lps" -ip y -rc $name.corr.data -rd $name.dist.data >> $results.log

    gzip -f $name.corr.data $name.dist.data

    echo "done"
  done
else
  for name in $*
  do
    ext="`returnext $name`"
    root="`returnroot $name`"
    if [ -z "$ratio" ]
    then
      ratio="`calc_ratio $root`"
    fi

    if [ $ext = "0" ]
    then
      batchfile="../runbatch"
    else
      echo run $ext > /tmp/batchfile
      echo exit >> /tmp/batchfile
      batchfile="/tmp/batchfile"
    fi

    ../sherlock -t $root -s "(ratio = $ratio:1)" -i $root.raw -p $root-pattern.raw -b $batchfile -l "$lps" -ip y -rc $name.corr.data -rd $name.dist.data

    gzip -f $name.corr.data $name.dist.data
  done

  rm -f /tmp/batchfile
fi

