#! /bin/bash
# This script tests: pnmtops pstopnm
# Also requires: pamtopnm gs pbmmake pnmshear pnmpad pnmcat


# Failure message
## This test fails when ghostscript is not available.

tmpdir=${tmpdir:-/tmp}

# pstopnm does not use libnetpbm functions for output.
# Output is filtered through pamtopnm.

# Test 1.  Should print: 1926073387 101484 four times
test1_ps=${tmpdir}/testimg1.ps

for flag in "" "-ps" "-rle" "-ps -ascii"
  do
  pnmtops -nocenter -equalpixels -dpi 72 -noturn ${flag} testimg.ppm \
    > ${test1_ps} && \
  xysize1=`awk  '/BoundingBox/ {print "-xsize="$4,"-ysize="$5}' \
    ${test1_ps}` && \
  pstopnm -portrait -xborder=0 -yborder=0 $xysize1 -stdout -quiet \
    ${test1_ps} | pamtopnm | cksum
  done

rm ${test1_ps}
# Test 2.  Should print: 2918318199 62 seven times
# Test image designed to detect problems with run-length compression
#

g_pbm=${tmpdir}/g.pbm
t_pbm=${tmpdir}/t.pbm
grid_ps=${tmpdir}/testgrid.ps

pbmmake -g 2 2 > ${g_pbm}
pbmmake -g 8 4 | \
  pnmshear 45 -noantialias -background=black | \
  pnmpad -right 60 | \
  pnmcat -tb -jright - ${g_pbm} > ${t_pbm} &&
for flag in "" "-rle" "-ps -rle -ascii" \
            "-bitspersample=2 -rle" "-ps -bitspersample=4 -rle" \
            "-bitspersample=8 -rle" "-ps -bitspersample=12 -rle -dict"
  do
  pnmtops -nocenter -equalpixels -dpi 72 -noturn  ${flag} ${t_pbm} \
    > ${grid_ps} && \
  xysize2=`awk  '/BoundingBox/ {print "-xsize="$4,"-ysize="$5}' \
      ${grid_ps}` && \
  pstopnm -portrait -xborder=0 -yborder=0 $xysize2 -stdout \
    -quiet ${grid_ps} -pbm | pamtopnm | cksum
  done

rm ${grid_ps} ${g_pbm} ${t_pbm}

#Test 3. Should print: 1386192571 507420 three times
#
# Special care is needed when conducting round-trips with multiple-image
# files as input.
# (1) pnmtops: -setpage is mandatory
# (2) awk: xy values are taken from the first "BoundingBox" encountered.
#          Subsequent BoundingBox values are ignored.
# (3) pstopnm: input must be an ordinary file.  Input from stdin
#     (by pipe or input redirection: "< file" ) does not work.
#

test3_ps=${tmpdir}/testimg3.ps

for flag in "" "-ps" \
            "-ps -bitspersample=12 -rle -vmreclaim"
  do
cat testimg.ppm testimg.ppm testimg.ppm testgrid.pbm testgrid.pbm | \
pnmtops -nocenter -equalpixels -dpi 72 -noturn -setpage ${flag} \
  > ${test3_ps} &&
xysize3=`awk  '/BoundingBox/ {print "-xsize="$4,"-ysize="$5 ; exit}' \
  ${test3_ps}` &&
pstopnm -portrait -xborder=0 -yborder=0 $xysize3 -stdout  ${test3_ps} | \
  pamtopnm | cksum
  done

rm ${test3_ps}
