#!/bin/bash
resolution=72
pixwidth=$((resolution*50/10))
linerwidth=$((resolution*4))
liner=0
rm -f /tmp/$1.ps
if [ -e $1-card.txt ]; then
    title=$(head -1 $1-card.txt)
else
    title=$2
fi
if [ "$title" = "" ] ; then
   echo "No CD title given on command line or in $1-card.txt file" >&2
   exit 1
fi

cat << STOP > /tmp/$1.ps
%!
gsave
130 400 translate
0 0 moveto
gsave
STOP
tifftopnm $1-a-autojoin.tif | ppmtopgm | \
  pnmscale -xysize $pixwidth  $pixwidth | \
  pnmtops -width 5 -height 5 -dpi 300 -noturn | \
  fgrep -v showpage >> /tmp/$1.ps
cat << STOP >> /tmp/$1.ps
grestore

/left 10 def
/bottom 5 def
/right 350 def
/top 345 def

/margin 10 def

[1 4] 0 setdash
0 setlinewidth

left  margin sub bottom moveto
right margin add bottom lineto
stroke

left  margin sub top moveto
right margin add top lineto
stroke

left  bottom margin sub  moveto
left  top    margin add  lineto
stroke

right  bottom margin sub  moveto
right  top    margin add  lineto
stroke

[] 0 setdash
grestore

gsave

%
% Now do the J-card
%

130 34 translate
0 0 moveto
gsave
STOP
if [ -e $1-card.txt ]; then
    texttocard < $1-card.txt >>  /tmp/$1.ps
else
cardfile=$1-b-autojoin.tif
if [ -e $1-card.tif ] ; then
  cardfile=$1-card.tif
fi
tifftopnm $cardfile | ppmtopgm | \
  pnmscale -xysize $pixwidth  $pixwidth | \
  pnmtops -width 5 -height 5 -dpi 300 -noturn | \
  fgrep -v showpage >> /tmp/$1.ps
fi
cat << STOP >> /tmp/$1.ps
grestore

/Palatino-Bold findfont
10 scalefont
setfont

[1 4] 0 setdash
0 setlinewidth

/left -17 def
/bottom 10 def
/right 375 def
/top 345 def

/margin 10 def

/edge 17 def

[1 4] 0 setdash
0 setlinewidth

left  margin sub bottom moveto
right margin add bottom lineto
stroke

left  margin sub top moveto
right margin add top lineto
stroke

left  bottom margin sub  moveto
left  top    margin add  lineto
stroke

right  bottom margin sub  moveto
right  top    margin add  lineto
stroke

left  edge sub bottom margin sub  moveto
left  edge  sub top    margin add  lineto
stroke

right edge add bottom margin sub  moveto
right edge add top    margin add  lineto
stroke

[] 0 setdash

%
% Now label the outer edge of the jewel card
%

/stringheight 10 def
/stringdescend 2 def

/Palatino-Bold findfont
stringheight scalefont
setfont
($title) stringwidth /stringy exch def /stringx exch def

gsave

edge stringheight sub 2 div right add stringdescend add

top bottom add stringx add 2 div

translate

0 0 moveto

-90 rotate

($title) show

grestore

gsave

edge stringheight sub 2 div left edge sub add stringdescend add

top bottom add stringx add 2 div

translate

0 0 moveto

-90 rotate

($title) show

grestore

statusdict begin
% /manualfeed true def
% /manualfeedtimeout 20 def
showpage
STOP
cat /tmp/$1.ps
rm -f /tmp/$1.ps
