#!/bin/sh

# Usage:
# gensubfig [-p figdepthname] [-v VARNAME] [fig_in [prefix_out [suffix_out]]]

# Format d'entre du fichier d'entre:

# [DESC: fig_in [prefix_out [suffix_out]]]
# [NOAUTONUM]
# [midfix_out] depth [depth ...]
# ...

# midfix_out autogenerates to 1 2 3 ... if NOAUTONUM not supplied
# lines beging with # are ignored

warning() {
    echo "*******************************" 1>&2
    echo "********   WARNING   **********" 1>&2
    echo "*******************************" 1>&2
    for l ; do
    	echo "* $l" 1>&2
    done
    echo "*******************************" 1>&2
    echo "Waiting 2s before continuing" 1>&2
    sleep 2
}

read_ligne() {
    line=""
    until [ "$line" ]; do
	read line || return $?
	line=`echo "$line" | sed -e 's/^[[:space:]]*//g' -e 's/#.*$//'`
    done
    eval "$1="'"$line"'
}

FIG_IN=figure.fig
FIG_IN_SET=no
PREFIX_OUT=figure_
PREFIX_OUT_SET=no
SUFFIX_OUT=.fig
SUFFIX_OUT_SET=no
PROG='./figdepth < $< > $@'
VARNAME=FIGURE_FIGS
VARNAME_SET=no

set_var() {
    if [ "$1" ]; then
	FIG_IN="$1"
	FIG_IN_SET=yes
	if [ "$VARNAME_SET" = no ]; then
	    VARNAME=`basename "$FIG_IN" .fig | tr [a-z] [A-Z]`_FIGS
	fi
	if [ "$2" ]; then
	    PREFIX_OUT="$2"
	    PREFIX_OUT_SET=yes
	    if [ "$3" ]; then
		SUFFIX_OUT="$3"
		SUFFIX_OUT_SET=yes
	    fi
	elif [ "$PREFIX_OUT_SET" = no ]; then
	    PREFIX_OUT=`echo "$FIG_IN" | sed -e 's/.fig$//'`_
	fi
    fi
}

LIST_MID=""

genfig() {
    local mid
    mid="$1";
    LIST_MID="$LIST_MID $mid"
    shift

    echo "$PREFIX_OUT$mid$SUFFIX_OUT: $FIG_IN"
    printf "\t%s %s\n" "$PROG" "$*"
    test "$SUBFIG" && echo "$PREFIX_OUT$mid$SUFFIX_OUT: $SUBFIG"
    echo
}

while [ $# != 0 ]; do
    case "$1" in
	-p)
	    PROG="$2"
	    shift
	    shift;;
	-s)
	    SUBFIG="$2"
	    shift
	    shift;;
	--)
	    shift
	    set_var "$@"
	    set -- ;;
	-*)
	    echo "Unknown option $1"
	    exit 1;;
	*)
	    set_var "$@"
	    set -- ;;
    esac
done

AUTONUM=true
LAST_AUTO_MID=0

while read_ligne line; do
    set -- $line
    case "$1" in
	DESC:*)
	    shift;
	    set_var "$@";;
	FIGSRC:*)
	    #test "$2" && FIG_IN="$2";;
	    warning "FIGSRC is no more supported in file '$FIG_IN'" \
	    	"Ignoring the value '$2' and using default '$FIG_IN'"
	    ;;
	NOAUTONUM)
	    AUTONUM=false;;
	*)
	    if [ "$AUTONUM" = true ]; then
		LAST_AUTO_MID=`expr $LAST_AUTO_MID + 1`
		set -- "$LAST_AUTO_MID" "$@"
	    fi
	    genfig "$@";;
    esac
done

echo "$VARNAME := \$(foreach n,$LIST_MID,$PREFIX_OUT\$(n)$SUFFIX_OUT)"
echo
printf 'FILES_TO_DISTCLEAN += $(%s)\n' "$VARNAME"
printf 'FIGS2CREATE_LIST += $(%s) \n' "$VARNAME"
printf '$(TEMPORAIRE): $(%s)\n' "$VARNAME" "$VARNAME"
echo
