#!/bin/sh

if test "$1" = ""
then
    echo "Usage: eps2svg <input.pdf> [ <output.svg> ]"
    exit 0
fi

if ! [ -r "$1" ]
then
    echo "$1" not found !
    exit 1
fi

# random name of intermediate PDF file
PDF=__eps2svg__$USER__$RANDOM__.pdf

while [ -r "$PDF" ]
do
    PDF=__eps2svg__$USER__$RANDOM__.pdf
done

ps2pdf -dEPSCrop "$1" "$PDF"

if ! [ -r "$PDF" ]
then
    echo Creation of "$PDF" has failed !
    exit 1
fi

if test "$2" != ""
then
    # SVG filename specified. Blindly overwrite any existing file
    SVG="$2"
else
    RADIX=`echo "$1" | rev | cut -d"." -f 2- | rev`
    SVG="$RADIX".svg
    i=0;
    # In this case (no SVG filename specified), check whether output exists
    # and change name if there is any risk of overwriting a file
    while [ -r "$SVG" ]
    do
	i=$(($i+1))
        SVG="$RADIX"_$i.svg
    done
fi

pdftocairo -svg "$PDF" "$SVG"
    
rm -f "$PDF"
exit 0

