#!/bin/bash

#   __ _       ____                
#  / _(_) __ _|___ \ ___ _ __  ___ 
# | |_| |/ _` | __) / _ \ '_ \/ __|
# |  _| | (_| |/ __/  __/ |_) \__ \
# |_| |_|\__, |_____\___| .__/|___/
#        |___/          |_|
#
# usage: fig2eps FILENAME.fig
#        (convert FILENAME.fig to FILENAME.eps; with no line output)
#
#        fig2eps -v FILENAME.fig
#        (convert FILENAME.fig to FILENAME.eps; with line ouput)

echo "f i g 2 e p s (c) 2004-2026 Ventura (260216)"
echo "fig2eps: start"

# find 'fig2eps' path
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &> /dev/null && pwd)"

# load 'fig2eps.tex' into EPHEMERAL
IFS= read -r -d '' EPHEMERAL < "$SCRIPT_DIR/fig2eps.tex"

# set 'verbose' option
VERBOSE=false
while getopts "v" opt; do
  case $opt in
    v)
      VERBOSE=true           # set VERBOSE to 'true'
      shift $((OPTIND - 1))  # shift 'getopts' 
      FILE=$1                # set FILE to $1
      ;;
  esac
done

if [ -e $1 ] # if file exists
    then

    if [ ${1#*.} = "fig" ] # if file is FIG file
	then

	cd `dirname $1`
	FILE=`basename ${1%.*}`
	
	# building temporary PSTEX/PSTES_T files from FIG input file
	fig2dev -L pstex                  $FILE.fig $FILE.pstex
	fig2dev -L pstex_t -p $FILE.pstex $FILE.fig $FILE.pstex_t

	# building temporary LaTeX file
	echo $EPHEMERAL | sed -e s/PSTEXFILENAME/$FILE.pstex_t/ > tmp.tex

	# set 'vebose' options for latex and -q
	if [ "$VERBOSE" = false ]; then
	    QUIET_LATEX="> /dev/null"
	    QUIET_FLAGS="-q"
	else
	    QUIET_LATEX=""
	    QUIET_FLAGS=""
	fi

	# build EPS file
	eval "latex tmp.tex $QUIET_LATEX"
	dvips tmp.dvi -o $QUIET_FLAGS
	ps2eps $QUIET_FLAGS -f tmp.ps
	mv tmp.eps "$FILE.eps"
	
	# removing temporary files
	rm tmp.* $FILE.pstex $FILE.pstex_t

	# return to original folder
	cd - > /dev/null

	echo "fig2eps: file $1 processed"
	
    else
	echo "fig2eps: input file extesion is not .fig"

    fi

else
    echo "fig2eps: input file '$1' not found"
    
fi

echo "fig2eps: finished"
