#!/bin/bash
#
# cct
#
# Script to get a proper vector eps file as well as a bitmap png file at
# fairly low resolution from a Circuit Macros (or any gpic) file, suitable
# for the Web. (Google burnallgifs :-)
#
# Alan Robert Clark a.clark@ee.wits.ac.za
#
# Created: 10 September 2003.
# Modified for version 5.82 7 December 2005
#
# Usage: cct fn OR cct fn.m4 OR cct *.m4 OR cct * :-)
#        Output is both a vector graphic .eps file 
#                   and a bitmap graphic .png file.
#        See cctcct for the olde style .cct output.

# If you **REALLY** have this filename, I guess you can change it :-)
TMPNAME=tempA1R2C3W4i5e6r6d7
CIRCUIT_MACROS_PATH=/home/agostine/.kde/share/apps/cirkuit/circuit_macros/

function mkltx()
{
cat > $TMPNAME.tex << EOF
\documentclass[a4paper]{article}
% Get max paper size (empty except for one figure!)
% Clear all textual allowances other than the main canvas
\setlength{\oddsidemargin}{0pt}
\setlength{\topmargin}{0pt}
\setlength{\headheight}{0pt}
\setlength{\headsep}{0pt}
\setlength{\marginparsep}{0pt}
\setlength{\marginparwidth}{0pt}
\setlength{\footskip}{0pt}
% Top Left is 5mm,5mm Not 1inch,1inch
\addtolength{\oddsidemargin}{-20mm}
\addtolength{\topmargin}{-20mm}
% A4 is 210 x 297 mm. Make bottom right 5,5 remaining!
\setlength{\textwidth}{205mm}
\setlength{\textheight}{292mm}

\usepackage{rotating} % For rotated text in figs.
\usepackage{amsmath}
\usepackage{pstricks}
\usepackage{boxdims}
\newbox\graph
\thispagestyle{empty}
\begin{document}
  {\vspace{2ex}\input{$TMPNAME.cct}
  \box\graph
  }
\end{document}
EOF
return
}

  filpath=`dirname $1`
  fn=$filpath/`basename $1 .m4`
  if [ -e $fn.m4 ]
    then
      echo -e "\n\n\nProcessing $fn.m4\n"
      m4 $CIRCUIT_MACROS_PATH/pstricks.m4 $CIRCUIT_MACROS_PATH/libcct.m4 $fn.m4 | dpic -p > $TMPNAME.cct
      if [ ! -e $TMPNAME.tex ]
        then mkltx
      fi
      cp $TMPNAME.cct $fn.pst
      latex $TMPNAME.tex -output-format=dvi
      dvips -O 1in,1in -Pcmz -Pamz -o $TMPNAME.ps $TMPNAME
      cp $TMPNAME.ps $fn.ps
      gs -sDEVICE=ppmraw -r200 -sOutputFile=- -sNOPAUSE -q $TMPNAME.ps \
         -c showpage -c quit | pnmcrop| pnmmargin -white 10 | pnmalias \
         | pnmtopng >$fn.png

      # Fix bounding box
      ps2eps -f $fn.ps
      epstopdf $fn.eps

      rm -f $TMPNAME.*
    else 
      echo "$fn.m4 does not exist!"
  fi     
