#!/bin/bash
#
# This script is part of the OOoLatexMacro
# http://ooolatex.sourceforge.net
#
# Geoffroy Piroux (gpiroux@gmail.com)
#

## If the system cannot find an executable
## Update the environment variable PATH
PATH="${HOME}/bin:/bin:/usr/bin:/usr/X11R6/bin:/usr/local/bin:${PATH}"

# Create the emf file from ps or pdf.
# The rendering can be different.
emfopt=pdf
#emfopt=ps

# If "gs" doesn't support the pngalpha device or dEPSCrop option,
# use "convert" to create the png images (no transparancy). 
# note that "gs" is preferred...
pngprog=gs
#pngprog=convert


## End configuration #########################################################
## Do not edit below this line ###############################################

if [ "$1" = "" -o "$1" = "-h" -o "$1" = "-help" -o "$1" = "--help" ] 
then
cat << EOF

 Syntax: OOoLatex [options] latexfile.tex

  Options:
   -e png,eps,emf  sets the extension to png, eps or emf. (Default: png).   
   -p /Path/       defines the working directory where OOoLatex looks for the 
                   latex file and where it creates the image.
   -d dpi          sets the resolution of the png and eps image to 'dpi' (Default 600)
   -transp         make emf image transparant if there is a background color defined 
                   and try to remove white color for png image created with "convert"

 This script is part of the OOoLatexMacro package (test5)
 See http://ooolatex.sf.net
 Contact : gpiroux@gmail.com
 
EOF
exit 1
fi

### Some error function definitions ###########################################
errMsg(){
    echo "${1}"
    exit 1
}

error(){
    echo "Error during the process '${1}'" > error.log
    cat error.log
    exit 1
}

check(){
    ret=1
    for el in `echo $PATH | sed s/":"/" "/g`; do
        if [ -f "${el}/${1}" ] && [ -x "${el}/${1}" ];then ret=0; break; fi
    done
    ##
    if [ "${ret}" = "1" ];
    then
        echo "Cannot find the program '${1}', check the \$PATH in the script OOoLatex." > error.log
        echo "Current \$PATH :" >> error.log
        for el in `echo $PATH | sed s/":"/" "/g`; do
            echo "   ${el}" >> error.log
        done
        cat error.log
        exit 1
    fi
}


### Default configuration ####################################################
ext="png"
dpi="600"
bg=""


### Process the options...####################################################
while [ "$1" = "-p" -o "$1" = "-d" -o "$1" = "-transp" -o "$1" = "-e" ]
do
	case "$1" in
        -e)      ext="$2";shift;;
        -d)      dpi="$2";shift;;
        -p)      tmpPath="$2";shift;;
        -transp) bg="-transp";;
	esac
   shift
done


### go to the tmp directory ##################################################
if [ "${tmpPath}" != "" ] 
then
	[ ! -d $tmpPath ] && mkdir -p $tmpPath
	cd "${tmpPath}"
fi

### System check !  ##########################################################
## Exit if there is an error...

check gs
check latex 
if [ "${ext}" = "eps" ]; then check epstool; fi
if [ "${ext}" = "emf" ]; then check latex2emf; fi
if [ "${ext}" = "png" -a "${pngprog}" = "convert" ]; then check convert; fi


### Get the name of latex file... ###########################################
filename=`echo $1 | sed s/"\.tex"//`
[ -e ${filename}.tex ] || errMsg "latex file ${filename}.tex doesn't exist..."


### Remove old files... #####################################################
rm ${filename}.{ps,dvi,out,bbx,log,aux,eps,png,ascii,emf} &> /dev/null
rm error.log &> /dev/null


### Processing of the data... ##############################################
echo "latex"
latex -interaction=nonstopmode ${filename}.tex  &> \
      ${filename}.out || errMsg "Error with latex...";


echo "dvips"
#[ "${ext}" = "emf" ] && opts="-Ppdf -G1" || opts=""
[ "${ext}" = "emf" ] && opts="-G1" || opts=""
dvips ${opts} -E ${filename} -o &> /dev/null || error "dvips"


echo "get bbox"
gs -q -dNOPAUSE -dBATCH -sDEVICE=bbox ${filename}.ps  &> ${filename}.bbx
bbx=`grep "%%BoundingBox" ${filename}.ps |awk '{print $2,$3,$4,$5}'`
BBx=`grep "%%HiResBoundingBox" ${filename}.bbx |awk '{print $2,$3,$4,$5}'`
echo $bbx $BBx > ${filename}.bbx 

### Creation of the image ###################################################
##
if [ "${ext}" = "png" -a "$pngprog" = "gs" ]
then
	echo "convert to png (gs)"
	gs -dSAFTER -dBATCH -dNOPAUSE -sDEVICE=pngalpha -dEPSCrop -r${dpi} \
	   -sOutputFile=${filename}.png ${filename}.ps
##
elif [ "${ext}" = "png" -a "$pngprog" = "convert" ]
then
	echo "convert to png (convert)"
	[ "${bg}" != "" ] && coloropt="-matte -transparent \#FFFFFF" || coloropt=""
	convert ${coloropt} -type PaletteMatte -units PixelsPerInch -density $dpi \
		    ${filename}.ps ${filename}.png
##
elif [ "${ext}" = "eps" ]
then
	echo "convert to eps"
	epstool -w --dpi ${dpi} ${filename}.ps ${filename}.eps &> /dev/null
##
elif [ "${ext}" = "emf" ]
then
	echo "convert to ascii"
	[ "${emfopt}" = "pdf" ] && ps2pdf ${filename}.ps
	gs -q -dBATCH -dNODISPLAY -dSAFER -dDELAYBIND -dWRITESYSTEMDICT -dCOMPLEX \
	   ps2ascii.ps -f ${filename}.${emfopt} | \
	   sed 's/\(^F[^(]*\)(......+/\1(/' | \
	   sed 's/\(^F[^?]*\)?/\1/' > ${filename}.ascii
	latex2emf ${bg} -bb ${bbx} ${filename}.ascii ${filename}.emf
fi
