#!/bin/bash
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
#
#    convertit un fichier toto.ps en fichier toto.pdf
#
#                         Patrick ROBERT, 1996
#                   revision Nov 2011 pour compatibilite PostScript
#                   (image non compressees, et donc non deformees,
#                    requis pour les spectrogrammes)
#
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

appli=`basename $0`
appli36=`echo "$appli                                 " | cut -c1-36`

if( (test $# = 1 ) && (test $1 = -h ) ) ; then hh=1 ; else hh=0 ; fi

if (test $# != 1 && test $# != 2 ) || test $hh = 1
   then echo "$appli : produce .pdf file from .ps one"
        echo "$appli   require 1 or 2 arguments, ex :"
        echo "     ps_to_pdf.sh toto.ps"
        echo "     ps_to_pdf.sh toto.ps compress"
        echo "         (active image compression)"
        if test $hh = 1 ; then exit 0 ; fi
        echo "$appli36 : *** ERROR ! Command aborted." >&2
        exit 1
fi

# verification que le fichier .ps existe

if test ! -f $1
   then echo "no-existing ps file $1"
        echo "$appli36 : *** ERROR ! Command aborted." >&2
        exit 2
fi

# fabrication du pdf
# si il existe un deuxielme argument, de type "compress",
# on compresse les images.

nompdf=`basename $1 .ps`.pdf
if test -f $nompdf ; then \rm $nompdf ; fi

Syst=`uname -s | cut -c1-5`
if (test $Syst = 'MINGW') 
    then lgs=gswin32c.exe
    else lgs=gs
fi

which $lgs > /dev/null
if test $? != 0
   then echo "gs is not installed on your $Syst system"
        echo "$appli36 : *** ERROR ! Command aborted." >&2
        exit 3
fi


if (test $# -eq 2) && (test $2 = compress)
   then 
#       echo "conversion of $1 in $nompdf WITH image compression"
        $lgs  -dBATCH -dNOPAUSE -dSAFER -dQUIET -sPAPERSIZE=a4 \
              -sDEVICE=pdfwrite -sOutputFile=$nompdf $1  
   else 
#       echo "conversion of $1 in $nompdf WITHOUT image compression, res=300 dpi"
        $lgs  -dBATCH -dNOPAUSE -dSAFER -dQUIET -sPAPERSIZE=a4 \
              -sDEVICE=pdfwrite -r300 -sOutputFile=$nompdf $1  

# old version non portable sur gs de lx-robert
#       $lgs -dBATCH -dNOPAUSE -dSAFER -dQUIET -sDEVICE=pdfwrite -sOUTPUTFILE=$nompdf \
#           -sPAPERSIZE=a4  -dCompatibilityLevel=1.3  \
#           -dEmbedAllFonts=true          -dSubsetFonts=true  -dMaxSubsetPct=100  \
#           -dAutoFilterColorImages=false -dColorImageFilter=false  \
#           -dAutoFilterGrayImages=false  -dGrayImageFilter=false  \
#           -dAutoFilterMonoImages=false  -dMonoImageFilter=false  $1
fi

echo " $nompdf    created !"
