#!/bin/sh
#
# Recognize an image among the SR database (Shape Recognition Module)

usage() {
    echo "megawave_recognize <image>"
    echo "input:	the image to be identified"
    echo "output:	the recognized image"
}

if [ $# -ne 1 ]; then
    usage
    exit 1
fi

if [ "$1" = "-h" ]; then
    usage
    exit 1
fi

TMP=/tmp/megawave-$USERNAME
BASEDIR=$TMP/base

if [ ! -d $TMP ]; then
    echo "$TMP does not exist. Please call megawave_clear_base."
    exit 1
fi

if [ ! -d $BASEDIR ]; then
    echo "$BASEDIR is not a valid directory."
    exit 1
fi

IMAGE=$1
if [ ! -r $IMAGE ]; then
    echo "$IMAGE file not found or unreadable"
    exit 1
fi

# functions to access the reference array
name() {
    if [ $1 != 1 ]
    then
	AD1=`expr $1 - 1`
	AD2=`expr $1 + 1`
	sed -e '1,'$AD1'd' -e $AD2',$d' $BASEDIR/references | cut -f1 -d " "
    else 
	sed -e 2',$d' $BASEDIR/references | cut -f1 -d " "
    fi	
}

path() {
    if [ $1 != 1 ]
    then
	AD1=`expr $1 - 1`
	AD2=`expr $1 + 1`
	sed -e '1,'$AD1'd' -e $AD2',$d' $BASEDIR/references | cut -f2 -d " "
    else 
	sed -e 2',$d' $BASEDIR/references | cut -f2 -d " "
    fi
}

# produce the hypotheses list -> normalized shape
echo "Producing hypotheses"
CRVN=$TMP/foo.crv
LIST=`megawave sr_genhypo $BASEDIR/signature.fimg $IMAGE $CRVN`

# compute the distances (to get the best hypothesis)
echo "Computing distances"
RESULT=$TMP/result
rm -f $RESULT
touch $RESULT

for hypo in $LIST; do
    TRY=`name $hypo`
    VAL=`megawave sr_distance $CRVN $BASEDIR/$TRY.crv | cut -f2 -d "="`
    echo "Distance to" $TRY ":" $VAL
    echo $VAL $HYPO >> $RESULT
done

# sort hypotheses according to the distances and select the best one
BEST=`sort -n $RESULT`
I=`echo $BEST | cut -f2 -d " "`
P=`echo $BEST | cut -f1 -d " "`
Q=`echo $P | cut -f1 -d "."`
if [ $Q -lt 10 ]; then
    echo "Best hypothesis : "`name $i`" ("`path $i`"), error = "$P" %"
else
    echo "Shape non recognized ! (minimum error = "$P" %)"
fi
rm -f $CRVN $RESULT
	




