#!/bin/sh
#
# Put images in the SR database (Shape Recognition Module)

usage() {
    echo "megawave_put_to_base <image 1> [ <image 2> ... <image n> ]"
    echo "input:  images to put in the base"
    echo "effect: modifications in the base directory"
    echo "output: none"
}

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

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

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

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

while [ $# -ne 0 ]; do
    NAME=$1
    shift

    # Check the existence of the image file
    if [ ! -r $NAME ]; then
	echo "$NAME : file not found or unreadable"
	exit 1
    fi

    PREFIX=`basename $NAME | sed "s/.img//"`

    # Check that the image is not already in base
    if [ -r $BASEDIR/references ] 
    then 
	if ( grep "$PREFIX\," < $BASEDIR/references > /dev/null ); then
	    echo "$PREFIX already exists in the base"
	    break
	fi
    fi
    
    # Base completion
    FOO=$MY_MEGAWAVE2/tmp/foo.crv
    NORM=$BASEDIR/$PREFIX\.crv
    if extract_connex $NAME $FOO
    then
	megawave sr_normalize $FOO $NORM
	rm $FOO
	if [ -w $BASEDIR/signature.fimg ]
	then 
	    megawave sr_signature -a $BASEDIR/signature.fimg $NORM $BASEDIR/signature.fimg
	else 
	    echo "Creating parameter file"
	    megawave sr_signature $NORM $BASEDIR/signature.fimg
	    touch $BASEDIR/references
	fi
	echo "Putting in base *** "$nom" ***"
	echo $PREFIX $NAME >> $BASEDIR/references
    fi 
done
