#!/bin/sh
#################################################################
##
##	@(#) pic2svg	(c) Sep 2015 H.Zuleger HZNET
##
##		Create a SVG file from a pic(1) graph
##
##	This command uses:
##
##		a) pic (of course) to generate the troff commands
##		   for the picture
##		b) soelim to allow the including of pic library files
##		c) groff to render the graphic and to "print" it on
##		   a postscript page
##		d) gostscript to convert the postscript page into SVG
##		e) sed to adjust the size of the SVG graphic to
##		   the size of the picture (This is necessary
##		   because groff prints out a whole page of paper
##		   (A4, letter, etc))
##
##	The whole conversion is done in one big pipe, so no temporary
##	files are needed.
##	However, the size of the bounding box must be known in advance,
##	so the pic(1) command (and soelim of course) is run twice:
##
##	- The first run is just to get the size of the picture (as
##	  arguments of the generated .PS macro). These values are
##	  evaluated as shell variables and later used in the last sed
##	  call to change the size of the SVG.
##
##	- The second run of pic is part of the groff command to
##	  produce the postscript output.
##
#################################################################
PATH=/bin:/usr/bin

debug=0

case "$1" in
*.pic)
	infile="$1"
	;;
*.*)
	echo "inputfile must have extension .pic" 1>&2
	exit 1
	;;
*)
	echo "$0 file.pic" 1>&2
	exit 1
	;;
esac

infile="$1"
outfile="`basename $infile .pic`"
outfile="${outfile}.svg"

test "$debug" -ge 1 && echo "Inputfile: $inputfile Outputfile: $outputfile"

#################################################################
#	first step:	get the size of the picture and store it in
#			two shell vars
#
#	pic replaces the original .PS macro with one with two
#	arguments (height and width)
#	sed is used to transform this into a shell variable definition 
#	
eval `soelim $infile | pic | sed -n '/^\.PS /s/\.PS \(.*\) \(.*\)/width=\2 height=\1/p'`

if test -z "$width" -o -z "$height"
then
	echo "unable to get bounding box from pic(ture) in file $infile" 1>&2
	exit 1
fi

# replace scale character 'i' (from pic) into 'in' (which is the right SVG syntax)
width="${width}n"
height="${height}n"

test "$debug" -ge 1 && echo "Width and Height of picture: $width x $height"

#################################################################
#	second step: generate SVG output
#
#	- groff create a postscript page
#	- gs "prints" it as a SVG graphic
#	- sed is used to correct the size of the SVG and to remove
#	  the HTML DOC Header
#
groff -s -p $infile |
gs -q -dNOPAUSE -dBATCH -sDEVICE=svg -sOutputFile=%stdout% - |
sed "
/<\?xml /d
/<!DOCTYPE svg /{
	N
	s/\\n//
	d
}
/<svg /{
	n
	s/width='[0-9][0-9]*pt'/width='$width'/
	s/height='[0-9][0-9]*pt'/height='$height'/
}" > $outfile

