#!/bin/sh
version=2.3.1
#set -vx
################################################################################
#
# nplots - arranges automatically multiple PostScript graphs on a single A4-plot
#
# Copyright (C) 1996-2001, 2005, 2007, 2009, 2012-2013
#               Dimitar Ivanov <dimitar.ivanov@mirendom.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
################################################################################

progname=`basename $0`
ofile="$progname.$$"
OFile=
DVIPS_opts="-t a4 -D 600 -p 1 -l 1"
PDF_converter=ps2pdf

### LaTex environment variables
TEXINPUTS="$TEXINPUTS:/usr/share/texmf-texlive/tex/tex//:/usr/share/texmf-texlive/tex//:/usr/share/texmf-texlive/bibtex//:/etc/texmf//"
export TEXINPUTS

### Define default sizes, scale and rotation
un=cm
scale=1.0
hsize=8
rsize=8
hspace=postdef
vspace=postdef
ang=-90

### Find postscript viewer
gv=`which gv 2>&1 |grep "^/"` || gv=ghostview

### Remove tmp files when finished
Clean_up () { rm -f $ofile.tex $ofile.dvi $ofile.aux $ofile.log; }

### Help
if [ $# -eq 0 ]; then
     cat << HELP

--------------------------------------------------------------------------------
nplots ${version}: arranges automatically PostScript figures on a single A4-plot
--------------------------------------------------------------------------------

Usage:
------
$progname [OPTION...] <PSfile(s)>

Options:
--------
   -pdf
   -norotate
   -scale <float>
   -hspace <float>
   -vspace <float> 
   -ofile <name>

Maximum of 6 graphs can be put on a single A4-plot! The horizontal and vertical
spaces are measured in centimeters. This program requires 'latex' and 'epsfig'.
The 'epsfig' TeX-package should be included in the path defined by \$TEXINPUTS.
You can send the resulting PostScript to stdout by using "-" as otput file name.

HELP
exit
fi

### Check options
while [ $# -gt 0 ]
do
   case $1 in
        -norotate)
                   norotate=yes
                   ang=0
                   rsize=`echo "$hsize * 1.5" |bc -l`
                   ;;
          -hspace)
                   hspace=$2$un
                   shift
                   ;;
          -vspace)
                   vspace=$2$un
                   shift
                   ;;
          -scale)
                   scale=$2
                   shift
                   ;;
           -ofile)
                   OFile="-o $2"
                   shift
                   ;;
             -pdf)
                   PDF_form=yes
                   ;;
                *)
                   break
                   ;;
   esac
shift
done

### Check up number of figures to plot and whether the files exist
nr_graphs=$#
if [ $nr_graphs -eq 0 ]; then
     echo "No files to plot."
     exit 1
else
    for file in $*; do
       test ! -f "$file" && echo "No such file: $file" && exit 2
    done
fi

### Set up default vertical spaces btw. graphs if not specified
if [ "$vspace" = "postdef" ]; then
   if [ $nr_graphs -gt 3 ]; then
        vspace=0.8$un
   else
        vspace=1.0$un
   fi
fi
### Set up default horizontal spaces btw. graphs if not specified
if [ "$hspace" = "postdef" ]; then
   if [ $nr_graphs -gt 3 ]; then
        hspace=0.7$un
   else
        hspace=0.0$un
   fi
fi

### Define single figure's size
case $nr_graphs in
     1) 
        hsize=16
        ;;
     2)
        hsize=16
        ;;
     3)
        hsize=10
        ;;
     *) : # Default values (see at the beginning)
        ;;
esac

################################################################################
#
# Main 
#
Hsize=`printf "%.2f$un" $(echo "$hsize * $scale" |bc -l)`
Rsize=`printf "%.2f$un" $(echo "$rsize * $scale" |bc -l)`

trap 'eval rm -f $ofile.ps $OFile $OFile_pdf 2>/dev/null; Clean_up; exit' 1 2 3 6 15

#
# BEGIN document
#
cat << START_DOC >> $ofile.tex
\documentclass{article}
\usepackage{epsfig}
%\psdraft
\oddsidemargin=6mm
\voffset=-2.8cm
\textwidth=15.5cm
\textheight=24.6cm
\begin{document}
\thispagestyle{empty}
\begin{figure}
START_DOC

### Arrange figures
if [ $nr_graphs -eq 3 -o $nr_graphs -eq 2 ]; then
   cat << EOF1 >> $ofile.tex
   \centerline{\epsfig{file=$1,height=${Hsize},angle=$ang}}
   \vspace{$vspace}
   \centerline{\epsfig{file=$2,height=${Hsize},angle=$ang}}
EOF1
   if [ $nr_graphs -eq 3 ]; then
      cat << EOF2 >> $ofile.tex
      \vspace{$vspace}
      \oddsidemargin=1mm
      \centerline{\epsfig{file=$3,height=${Hsize},angle=$ang}}
EOF2
   fi
elif [ $nr_graphs -eq 1 ]; then
   cat << EOF3 >> $ofile.tex
   \centerline{\epsfig{file=$1,height=${Hsize},angle=$ang}}
EOF3
elif [ $nr_graphs -eq 4 ]; then
   cat << EOF4 >> $ofile.tex
   \centerline{\epsfig{file=$1,height=${Rsize},angle=$ang}\hspace*{$hspace}
   \epsfig{file=$2,height=${Rsize},angle=$ang}}
   \vspace{$vspace}
   \centerline{\epsfig{file=$3,height=${Rsize},angle=$ang}\hspace*{$hspace}
   \epsfig{file=$4,height=${Rsize},angle=$ang}}
EOF4
else 
   cat << EOF5 >> $ofile.tex
   \centerline{\epsfig{file=$1,height=${Hsize},angle=$ang}\hspace*{$hspace}
               \epsfig{file=$2,height=${Hsize},angle=$ang}}
   \vspace{$vspace}
   \centerline{\epsfig{file=$3,height=${Hsize},angle=$ang}\hspace*{$hspace}
               \epsfig{file=$4,height=${Hsize},angle=$ang}}
   \vspace{$vspace}
   \centerline{\epsfig{file=$5,height=${Hsize},angle=$ang}\hspace*{$hspace}
EOF5
   if [ $nr_graphs -eq 5 ]; then
      echo '}' >> $ofile.tex
   else
      cat << EOF6 >> $ofile.tex
      \epsfig{file=$6,height=${Hsize},angle=$ang}}
EOF6
   fi
fi

cat << END_DOC >> $ofile.tex
\end{figure}
\end{document}
END_DOC
#
# END document

>$ofile.aux

### In case output goes to stdout
if [ "$OFile" = "-o -" ]; then
     [ $PDF_form ] \
       && print_out="$PDF_converter - -" \
       || print_out=cat
     latex $ofile >/dev/null 2>&1
     dvips -q $DVIPS_opts $ofile $OFile 2>&1 \
           | $print_out
     Clean_up
     exit 0
fi

latex $ofile 2>/dev/null
dvips $DVIPS_opts $ofile $OFile

### Rename if necessary
if [ -z "$OFile" ]; then
     OFile=$ofile.ps
     OFile_pdf=$ofile.pdf
else
     OFile=`echo $OFile |cut -f2 -d " "`
     OFile_pdf=$OFile.pdf
fi

### Convert to PDF if requested
if [ $PDF_form ]; then
     $PDF_converter $OFile $OFile_pdf
     if [ "$OFile_pdf" != "$ofile.pdf" ]; then
          mv -f $OFile_pdf $OFile
     else
          rm $OFile
          OFile=$OFile_pdf
     fi
fi

echo 'Show graph [n/Y]?'
read answer
if [ "$answer" != n -a "$answer" != N ]; then
     $gv $OFile &
fi
echo ""
echo "Your plot file is $OFile"
echo ""

Clean_up

exit 0
