#!/bin/bash
PATH=~saied/bin:$PATH
while getopts  "o:f:" flag
do
	echo "[$flag]" $OPTIND $OPTARG
	case $flag in
		"o")
		case $OPTARG in
			"beamer")
			Beamer="true"
			;;
			"bib")
			BIB="true"
			;;
			"acroread")
			ACROREAD="true"
			;;
			"xpdf")
			XPDF="true"
			;;
			"gv")
			GV="true"
			;;
			"pdf")
			PDF="true"
			;;
			"pdfslides")
			PDF="true"
			PDFSlides="true"
			;;
		esac
		;;
		"f")
		File=`echo $OPTARG | sed 's/.tex$//'`
		;;
	esac
done
#echo B: $Beamer
#echo G: $GV
#echo X: $XPDF
#echo A: $ACROREAD
#echo P: $PDF
#echo F: $File
#exit
if( (test -z $1) || ! (test -f "$File.tex") ) then
	echo "$0 -o beamer -o bib -o gv -o pdf -o pdfslides -f <input tex file name>"
	echo "$0 -o beamer -o bib -o gv -o pdf -o pdfslides -f $1"
	exit
fi


latex $File.tex
if(! test "$?" = "0") then
	echo -e "\nAborted"
	exit
fi
if(test "$BIB" = "true") then
	echo -e "\nBib"
	bibtex $File
	echo -e "\nLaTeX again"
	latex $File.tex
fi

DVIPSOptions="-Ppdf -G0"  # Embed PS fonts, not bitmapped fonts, so that PDF looks good
#DVIPSOptions="$DVIPSOptions --bdpi 1200"
#    DVIPSOptions="$DVIPSOptions -t landscape"
    DVIPSOptions="$DVIPSOptions -t a4"  # A4
	DVIPSOptions=-Pcmz 

if(test "$Beamer" = "true") then
	echo -e "\nBeamer"
	dvips $DVIPSOptions $File.dvi -o $File.ps
else
	echo -e "\nNot Beamer"
	dvips $DVIPSOptions $File.dvi -o $File.tmp.ps
	PSMULTIOptions="-pages 1 -r0 -ibbox 0 0 595 842 -nodecor -maxx"
	psmulti $PSMULTIOptions $File.tmp.ps > $File.ps
fi
if(test "$PDF" = "true") then
	echo -e "\nPDF"
	ps2pdf14 -sPAPERSIZE=a4 $File.ps
fi
if(test "$PDFSlides" = "true") then
	echo -e "\nPDFSlides"
	pdfnup --nup "2x2" --offset "0cm 0cm" --delta ".25cm .25cm" --frame true --scale 0.9 $File.pdf

#	/bin/cp $File.pdf $File.tmp.pdf
#	echo -e "\nConverting PDF to PS"
#	pdftops.a $File.tmp.pdf
#
#	echo -e "\nPSmulti"
#	PSMULTIOptions="-pbbox a4 -pages 4 -ibbox 0 0 595 842 -btot -cmajor"
#	psmulti $PSMULTIOptions $File.tmp.ps \
#	| sed 's/^%%BoundingBox:.*/%%BoundingBox: 0 0 595 842/' \
#	> $File.4.ps
#
#	echo -e "\nConverting PS to PDF"
#	ps2pdf14 -sPAPERSIZE=a4 $File.4.ps
#	/bin/rm $File.tmp.pdf $File.tmp.ps # $File.tmp.ps.4.ps
fi
if(test "$GV" = "true") then
	echo -e "\nGV"
	/usr/bin/gv --scale=2 --center $File.ps
fi
if(test "$XPDF" = "true") then
	echo -e "\nXPDF"
	/usr/bin/xpdf -z page $File.pdf
fi
if(test "$ACROREAD" = "true") then
	echo -e "\nACROREAD"
	/home/saied/bin/acroread $File.pdf
fi
