about summary refs log tree commit diff
path: root/converter
diff options
context:
space:
mode:
Diffstat (limited to 'converter')
-rw-r--r--converter/other/Makefile34
-rw-r--r--converter/other/cameratopam/Makefile2
-rw-r--r--converter/other/cameratopam/camera.c245
-rw-r--r--converter/other/cameratopam/cameratopam.c2
-rw-r--r--converter/other/cameratopam/canon.c24
-rw-r--r--converter/other/cameratopam/foveon.c102
-rw-r--r--converter/other/cameratopam/identify.c49
-rw-r--r--converter/other/cameratopam/ljpeg.c16
-rw-r--r--converter/other/cameratopam/stdio_nofail.c120
-rw-r--r--converter/other/cameratopam/stdio_nofail.h29
-rw-r--r--converter/other/cameratopam/util.c34
-rw-r--r--converter/other/fiasco/codec/coder.c142
-rw-r--r--converter/other/fiasco/codec/cwfa.h2
-rw-r--r--converter/other/fiasco/codec/dfiasco.c40
-rw-r--r--converter/other/fiasco/codec/ip.c76
-rw-r--r--converter/other/fiasco/codec/prediction.c114
-rw-r--r--converter/other/fiasco/codec/subdivide.c124
-rw-r--r--converter/other/fiasco/codec/wfa.h8
-rw-r--r--converter/other/fiasco/doc/fiasco_c_options_new.35
-rw-r--r--converter/other/fiasco/doc/fiasco_coder.32
-rw-r--r--converter/other/fiasco/doc/fiasco_d_options_new.34
-rw-r--r--converter/other/fiasco/doc/fiasco_decoder_new.316
-rw-r--r--converter/other/fiasco/doc/fiasco_get_error_message.36
-rw-r--r--converter/other/fiasco/doc/fiasco_image_new.36
-rw-r--r--converter/other/fiasco/doc/fiasco_options_new.34
-rw-r--r--converter/other/fiasco/doc/fiasco_renderer_new.32
-rw-r--r--converter/other/fiasco/input/basis.c33
-rw-r--r--converter/other/fiasco/input/matrices.c80
-rw-r--r--converter/other/fiasco/input/mc.c61
-rw-r--r--converter/other/fiasco/input/nd.c31
-rw-r--r--converter/other/fiasco/input/read.c91
-rw-r--r--converter/other/fiasco/input/tree.c46
-rw-r--r--converter/other/fiasco/lib/arith.c130
-rw-r--r--converter/other/fiasco/lib/bit-io.c56
-rw-r--r--converter/other/fiasco/lib/image.c58
-rw-r--r--converter/other/fiasco/lib/image.h2
-rw-r--r--converter/other/fiasco/lib/macros.h2
-rw-r--r--converter/other/fiasco/output/mc.c40
-rw-r--r--converter/other/fiasco/output/nd.c38
-rw-r--r--converter/other/fiasco/output/tree.c18
-rw-r--r--converter/other/fiasco/params.c94
-rw-r--r--converter/other/fiasco/pnmtofiasco.c77
-rw-r--r--converter/other/fitstopnm.c210
-rw-r--r--converter/other/gemtopnm.c2
-rw-r--r--converter/other/giftopnm.c4
-rw-r--r--converter/other/infotopam.c33
-rw-r--r--converter/other/ipdb.c222
-rw-r--r--converter/other/ipdb.h23
-rw-r--r--converter/other/jbig/libjbig/include/jbig_ar.h4
-rw-r--r--converter/other/jbig/libjbig/jbig.c10
-rw-r--r--converter/other/jpeg2000/Makefile6
-rw-r--r--converter/other/jpeg2000/jpeg2ktopam.c34
-rw-r--r--converter/other/jpeg2000/libjasper/base/jas_image.c74
-rw-r--r--converter/other/jpeg2000/libjasper/base/jas_stream.c31
-rw-r--r--converter/other/jpeg2000/libjasper/include/jasper/jas_image.h27
-rw-r--r--converter/other/jpeg2000/libjasper/jp2/jp2_dec.c93
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_dec.c1085
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_dec.h2
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_enc.c1377
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_enc.h2
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_math.c2
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_mqenc.c31
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_t1dec.c1566
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_t1dec.h14
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_t1enc.c163
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_util.c71
-rw-r--r--converter/other/jpeg2000/libjasper_compat.c26
-rw-r--r--converter/other/jpeg2000/libjasper_compat.h35
-rw-r--r--converter/other/jpeg2000/pamtojpeg2k.c29
-rw-r--r--converter/other/jpegtopnm.c604
-rw-r--r--converter/other/pamtofits.c19
-rw-r--r--converter/other/pamtogif.c55
-rw-r--r--converter/other/pamtopdbimg.c93
-rw-r--r--converter/other/pamtopng.c8
-rw-r--r--converter/other/pamtoqoi.c439
-rw-r--r--converter/other/pamtosvg/fit.c148
-rw-r--r--converter/other/pamtotiff.c2
-rw-r--r--converter/other/pamtowinicon.c50
-rw-r--r--converter/other/pamtoxvmini.c77
-rw-r--r--converter/other/pbmtopgm.c37
-rw-r--r--converter/other/pdbimgtopam.c127
-rw-r--r--converter/other/pgmtopbm.c122
-rw-r--r--converter/other/pgmtoppm.c156
-rw-r--r--converter/other/pngtopam.c26
-rw-r--r--converter/other/pngx.c22
-rw-r--r--converter/other/pnmtoddif.c4
-rw-r--r--converter/other/pnmtojpeg.c163
-rw-r--r--converter/other/pnmtopalm/README2
-rw-r--r--converter/other/pnmtopalm/palmtopnm.c28
-rw-r--r--converter/other/pnmtopalm/pnmtopalm.c281
-rw-r--r--converter/other/pnmtopng.c94
-rw-r--r--converter/other/pnmtops.c198
-rw-r--r--converter/other/pnmtorle.c290
-rw-r--r--converter/other/pnmtosir.c35
-rw-r--r--converter/other/pstopnm.c55
-rwxr-xr-xconverter/other/pstopnm.csh2
-rw-r--r--converter/other/qoi.h101
-rw-r--r--converter/other/qoitopam.c323
-rw-r--r--converter/other/rlatopam.c23
-rw-r--r--converter/other/rletopnm.c78
-rw-r--r--converter/other/sunicontopnm.c12
-rw-r--r--converter/other/tifftopnm.c235
-rw-r--r--converter/other/winicon.h3
-rw-r--r--converter/other/winicontopam.c149
-rw-r--r--converter/other/xwdtopnm.c217
-rw-r--r--converter/other/yuy2topam.c8
-rw-r--r--converter/pbm/atktopbm.c34
-rw-r--r--converter/pbm/escp2topbm.c18
-rw-r--r--converter/pbm/g3topbm.c11
-rw-r--r--converter/pbm/mdatopbm.c2
-rw-r--r--converter/pbm/mgrtopbm.c30
-rw-r--r--converter/pbm/pbmtoatk.c31
-rw-r--r--converter/pbm/pbmtoescp2.c23
-rw-r--r--converter/pbm/pbmtogem.c2
-rw-r--r--converter/pbm/pbmtogo.c72
-rw-r--r--converter/pbm/pbmtoibm23xx.c6
-rw-r--r--converter/pbm/pbmtolps.c378
-rw-r--r--converter/pbm/pbmtomacp.c2
-rw-r--r--converter/pbm/pbmtomgr.c14
-rw-r--r--converter/pbm/pbmtonokia.c87
-rw-r--r--converter/pbm/pbmtopk.c120
-rw-r--r--converter/pbm/pbmtoppa/README.REDHAT2
-rw-r--r--converter/pbm/pbmtoppa/ppa.c10
-rw-r--r--converter/pbm/pbmtoptx.c11
-rw-r--r--converter/pbm/pbmtox10bm15
-rw-r--r--converter/pbm/xbmtopbm.c36
-rw-r--r--converter/pbm/ybmtopbm.c6
-rw-r--r--converter/pgm/rawtopgm.c174
-rw-r--r--converter/pgm/st4topgm.c8
-rw-r--r--converter/ppm/hpcdtoppm/Makefile22
-rw-r--r--converter/ppm/hpcdtoppm/README37
-rwxr-xr-xconverter/ppm/hpcdtoppm/hpcdtoppm18
-rwxr-xr-xconverter/ppm/hpcdtoppm/pcdovtoppm172
-rw-r--r--converter/ppm/ilbm.h92
-rw-r--r--converter/ppm/ilbmtoppm.c4
-rw-r--r--converter/ppm/picttoppm.c2265
-rw-r--r--converter/ppm/pjtoppm.c2
-rw-r--r--converter/ppm/ppmtoapplevol.c2
-rw-r--r--converter/ppm/ppmtoarbtxt.c2
-rw-r--r--converter/ppm/ppmtobmp.c2
-rw-r--r--converter/ppm/ppmtoilbm.c210
-rw-r--r--converter/ppm/ppmtomitsu.c2
-rw-r--r--converter/ppm/ppmtompeg/LOGIC2
-rw-r--r--converter/ppm/ppmtompeg/Makefile2
-rw-r--r--converter/ppm/ppmtompeg/bsearch.c58
-rw-r--r--converter/ppm/ppmtompeg/docs/template.param2
-rw-r--r--converter/ppm/ppmtompeg/examples/payam.param2
-rw-r--r--converter/ppm/ppmtompeg/examples/payam18.param2
-rw-r--r--converter/ppm/ppmtompeg/examples/template.param2
-rw-r--r--converter/ppm/ppmtompeg/frame.c68
-rw-r--r--converter/ppm/ppmtompeg/frametype.c39
-rw-r--r--converter/ppm/ppmtompeg/jpeg.c230
-rw-r--r--converter/ppm/ppmtompeg/mheaders.c4
-rw-r--r--converter/ppm/ppmtompeg/mpeg.c241
-rw-r--r--converter/ppm/ppmtompeg/opts.c110
-rw-r--r--converter/ppm/ppmtompeg/parallel.c379
-rw-r--r--converter/ppm/ppmtompeg/param.c83
-rw-r--r--converter/ppm/ppmtompeg/parse_huff.pl2
-rw-r--r--converter/ppm/ppmtompeg/psearch.c2
-rw-r--r--converter/ppm/ppmtompeg/psocket.c63
-rw-r--r--converter/ppm/ppmtompeg/rate.c192
-rw-r--r--converter/ppm/ppmtompeg/readframe.c103
-rw-r--r--converter/ppm/ppmtompeg/specifics.c74
-rw-r--r--converter/ppm/ppmtopcx.c584
-rw-r--r--converter/ppm/ppmtospu.c2
-rw-r--r--converter/ppm/sldtoppm.c2
-rw-r--r--converter/ppm/xim.h14
-rw-r--r--converter/ppm/ximtoppm.c93
-rw-r--r--converter/ppm/xpmtoppm.README2
-rw-r--r--converter/ppm/xpmtoppm.c8
170 files changed, 10118 insertions, 7696 deletions
diff --git a/converter/other/Makefile b/converter/other/Makefile
index 2be88781..3b3b6aa0 100644
--- a/converter/other/Makefile
+++ b/converter/other/Makefile
@@ -7,10 +7,26 @@ VPATH=.:$(SRCDIR)/$(SUBDIR)
 
 include $(BUILDDIR)/config.mk
 
-TEST_PKGCONFIG_LIBXML2 = if $(PKG_CONFIG) libxml-2.0; then echo exists; fi
+# The pkg-config test used to be just 'pkg-config libxml-2.0', without the
+# --exists, and on at least one system, it does the same thing as --exists:
+# exit code 0 if the package exists; 1 if it does not, with no Standard
+# Output.  But we have evidence that on one system, it issues the whole
+# package not found try a different path, blah, blah, blah message that
+# looks like a failure in the build.  We're hoping --exists does not do that.
+# But maybe we didn't do --exists in the first place because it doesn't exist
+# on older pkg-config.  19.09.20.
+#
+# Note that --exists is better for another reason - it fails when the named
+# package exists, but it is unusable because its prerequisite packages don't.
+#
+# Also note that in both cases, the shell command fails if pkg-config
+# doesn't even exist.
+
+TEST_PKGCONFIG_LIBXML2 := \
+  if $(PKG_CONFIG) libxml-2.0 --exists; then echo exists; fi
 
 ifneq ($(shell $(TEST_PKGCONFIG_LIBXML2)),)
-  # pkg-config libxml2 works on this system
+  # pkg-config works and says libxml2 exists on this system
   XML2_LIBS = $(shell $(PKG_CONFIG) libxml-2.0 --libs)
   XML2_CFLAGS = $(shell $(PKG_CONFIG) libxml-2.0 --cflags)
 else
@@ -34,10 +50,11 @@ ifneq ($(TIFFLIB),NONE)
   endif
 endif
 
-TEST_PKGCONFIG_LIBPNG = if $(PKG_CONFIG) libpng$(PNGVER); then echo exists; fi
+TEST_PKGCONFIG_LIBPNG := \
+  if $(PKG_CONFIG) libpng$(PNGVER) --exists; then echo exists; fi
 
 ifneq ($(shell $(TEST_PKGCONFIG_LIBPNG)),)
-  # pkg-config libpng works on this system
+  # pkg-config works and says libpng exists on this system
   HAVE_PNGLIB = Y
   EXTERN_INCLUDES += $(shell $(PKG_CONFIG) libpng$(PNGVER) --cflags)
 else
@@ -117,14 +134,15 @@ PORTBINARIES =  avstopam bmptopnm fitstopnm \
 		gemtopnm giftopnm hdifftopam infotopam \
 		pamtoavs pamtodjvurle pamtofits pamtogif \
 		pamtohdiff pamtohtmltbl pamtompfont pamtooctaveimg \
-		pamtopam pamtopdbimg pamtopfm pamtopnm pamtosrf pamtouil \
+		pamtopam pamtopdbimg pamtopfm pamtopnm \
+                pamtoqoi pamtosrf pamtouil \
 		pamtowinicon pamtoxvmini \
 		pbmtopgm pdbimgtopam pfmtopam \
 	        pgmtopbm pgmtoppm ppmtopgm pnmtoddif \
 		pnmtopclxl pnmtorast \
-		pnmtosgi pnmtosir pamtotga pnmtoxwd \
+		pnmtosgi pnmtosir pamtotga pnmtoxwd qoitopam \
 		rasttopnm rlatopam sgitopnm sirtopnm srftopam sunicontopnm \
-		winicontopam xwdtopnm yuy2topam zeisstopnm
+		winicontopam xwdtopnm yuy2topam zeisstopnm \
 
 ifneq ($(DONT_HAVE_PROCESS_MGMT),Y)
   PORTBINARIES += pstopnm pnmtops
@@ -193,7 +211,7 @@ tifftopnm pamtotiff pnmtotiffcmyk: \
  $(shell $(LIBOPT)  $(LIBOPTR) $(TIFFLIB) $(TIFFLIB_EXTRALIBS))
 
 ifneq ($(shell $(TEST_PKGCONFIG_LIBPNG)),)
-  # pkg-config libpng works on this system
+  # pkg-config works and says libpng exists on this system
   PNGLIB_LIBOPTS = $(shell $(PKG_CONFIG) libpng$(PNGVER) --libs)
 else
   ifneq ($(shell libpng$(PNGVER)-config --version),)
diff --git a/converter/other/cameratopam/Makefile b/converter/other/cameratopam/Makefile
index d6207aea..bb4c4cde 100644
--- a/converter/other/cameratopam/Makefile
+++ b/converter/other/cameratopam/Makefile
@@ -20,7 +20,7 @@ include $(BUILDDIR)/config.mk
 all: cameratopam
 
 ADDL_OBJECTS = util.o identify.o camera.o foveon.o decode.o \
-	canon.o ljpeg.o dng.o
+	canon.o ljpeg.o dng.o stdio_nofail.o
 
 OBJECTS = cameratopam.o $(ADDL_OBJECTS)
 
diff --git a/converter/other/cameratopam/camera.c b/converter/other/cameratopam/camera.c
index 439c9413..4610462c 100644
--- a/converter/other/cameratopam/camera.c
+++ b/converter/other/cameratopam/camera.c
@@ -24,6 +24,7 @@
 #include "bayer.h"
 #include "ljpeg.h"
 #include "dng.h"
+#include "stdio_nofail.h"
 
 #include "camera.h"
 
@@ -94,8 +95,8 @@ adobe_dng_load_raw_lj(Image const image) {
     unsigned short *rp;
 
     while (1) {
-        save = ftell(ifp);
-        fseek (ifp, get4(ifp), SEEK_SET);
+        save = ftell_nofail(ifp);
+        fseek_nofail (ifp, get4(ifp), SEEK_SET);
         if (!ljpeg_start (ifp, &jh)) break;
         if (trow >= raw_height) break;
         if (jh.high > raw_height-trow)
@@ -113,7 +114,7 @@ adobe_dng_load_raw_lj(Image const image) {
                 adobeCopyPixel(image,
                                trow+jrow, tcol+jcol, &rp, use_secondary);
         }
-        fseek (ifp, save+4, SEEK_SET);
+        fseek_nofail (ifp, save+4, SEEK_SET);
         if ((tcol += twide) >= raw_width) {
             tcol = 0;
             trow += jh.high;
@@ -157,14 +158,14 @@ nikon_compressed_load_raw(Image const image) {
     init_decoder();
     make_decoder (nikon_tree, 0);
 
-    fseek (ifp, nikon_curve_offset, SEEK_SET);
+    fseek_nofail (ifp, nikon_curve_offset, SEEK_SET);
     read_shorts (ifp, vpred, 4);
     csize = get2(ifp);
     curve = calloc (csize, sizeof *curve);
     merror (curve, "nikon_compressed_load_raw()");
     read_shorts (ifp, curve, csize);
 
-    fseek (ifp, data_offset, SEEK_SET);
+    fseek_nofail (ifp, data_offset, SEEK_SET);
     getbits(ifp, -1);
 
     for (row=0; row < height; row++)
@@ -197,8 +198,8 @@ nikon_load_raw(Image const image) {
     if (model[0] == 'E') {
       row = irow * 2 % height + irow / (height/2);
       if (row == 1 && atoi(model+1) < 5000) {
-    fseek (ifp, 0, SEEK_END);
-    fseek (ifp, ftell(ifp)/2, SEEK_SET);
+    fseek_nofail (ifp, 0, SEEK_END);
+    fseek_nofail (ifp, ftell_nofail(ifp)/2, SEEK_SET);
     getbits(ifp, -1);
       }
     }
@@ -227,8 +228,8 @@ nikon_is_compressed()
     return 0;
   if (strcmp(model,"D100"))
     return 1;
-  fseek (ifp, data_offset, SEEK_SET);
-  fread (test, 1, 256, ifp);
+  fseek_nofail (ifp, data_offset, SEEK_SET);
+  fread_nofail (test, 1, 256, ifp);
   for (i=15; i < 256; i+=16)
     if (test[i]) return 1;
   return 0;
@@ -244,9 +245,9 @@ nikon_e990()
   const unsigned char often[] = { 0x00, 0x55, 0xaa, 0xff };
 
   memset (histo, 0, sizeof histo);
-  fseek (ifp, 2064*1540*3/4, SEEK_SET);
+  fseek_nofail (ifp, 2064*1540*3/4, SEEK_SET);
   for (i=0; i < 2000; i++)
-    histo[fgetc(ifp)]++;
+    histo[fgetc_nofail(ifp)]++;
   for (i=0; i < 4; i++)
     if (histo[often[i]] > 400)
       return 1;
@@ -262,9 +263,9 @@ nikon_e2100()
   unsigned char t[12];
   int i;
 
-  fseek (ifp, 0, SEEK_SET);
+  fseek_nofail (ifp, 0, SEEK_SET);
   for (i=0; i < 1024; i++) {
-    fread (t, 1, 12, ifp);
+    fread_nofail (t, 1, 12, ifp);
     if (((t[2] & t[4] & t[7] & t[9]) >> 4
     & t[1] & t[6] & t[8] & t[11] & 3) != 3)
       return 0;
@@ -281,8 +282,8 @@ pentax_optio33()
   int i, sum[] = { 0, 0 };
   unsigned char tail[952];
 
-  fseek (ifp, -sizeof tail, SEEK_END);
-  fread (tail, 1, sizeof tail, ifp);
+  fseek_nofail (ifp, -sizeof tail, SEEK_END);
+  fread_nofail (tail, 1, sizeof tail, ifp);
   for (i=0; i < sizeof tail; i++)
     sum[(i>>2) & 1] += tail[i];
   return sum[0] < sum[1]*4;
@@ -297,8 +298,8 @@ minolta_z2()
   int i;
   char tail[424];
 
-  fseek (ifp, -sizeof tail, SEEK_END);
-  fread (tail, 1, sizeof tail, ifp);
+  fseek_nofail (ifp, -sizeof tail, SEEK_END);
+  fread_nofail (tail, 1, sizeof tail, ifp);
   for (i=0; i < sizeof tail; i++)
     if (tail[i]) return 1;
   return 0;
@@ -313,10 +314,10 @@ nikon_e2100_load_raw(Image const image) {
 
   for (row=0; row <= height; row+=2) {
     if (row == height) {
-      fseek (ifp, ((width==1616) << 13) - (-ftell(ifp) & -2048), SEEK_SET);
+      fseek_nofail (ifp, ((width==1616) << 13) - (-ftell_nofail(ifp) & -2048), SEEK_SET);
       row = 1;
     }
-    fread (data, 1, width*3/2, ifp);
+    fread_nofail (data, 1, width*3/2, ifp);
     for (dp=data, pix=pixel; pix < pixel+width; dp+=12, pix+=8) {
       pix[0] = (dp[2] >> 4) + (dp[ 3] << 4);
       pix[1] = (dp[2] << 8) +  dp[ 1];
@@ -356,7 +357,7 @@ fuji_s2_load_raw(Image const image) {
   unsigned short pixel[2944];
   int row, col, r, c;
 
-  fseek (ifp, (2944*24+32)*2, SEEK_CUR);
+  fseek_nofail (ifp, (2944*24+32)*2, SEEK_CUR);
   for (row=0; row < 2144; row++) {
     read_shorts(ifp, pixel, 2944);
     for (col=0; col < 2880; col++) {
@@ -372,7 +373,7 @@ fuji_s3_load_raw(Image const image) {
   unsigned short pixel[4352];
   int row, col, r, c;
 
-  fseek (ifp, (4352*2+32)*2, SEEK_CUR);
+  fseek_nofail (ifp, (4352*2+32)*2, SEEK_CUR);
   for (row=0; row < 1440; row++) {
     read_shorts(ifp, pixel, 4352);
     for (col=0; col < 4288; col++) {
@@ -408,7 +409,7 @@ fuji_common_load_raw(Image        const image,
 void
 fuji_s5000_load_raw(Image const image) {
 
-  fseek (ifp, (1472*4+24)*2, SEEK_CUR);
+  fseek_nofail (ifp, (1472*4+24)*2, SEEK_CUR);
   fuji_common_load_raw(image, 1472, 1423, 2152);
 }
 
@@ -449,7 +450,7 @@ rollei_load_raw(Image const image) {
   unsigned iten=0, isix, i, buffer=0, row, col, todo[16];
 
   isix = raw_width * raw_height * 5 / 8;
-  while (fread (pixel, 1, 10, ifp) == 10) {
+  while (fread_or_eof_nofail (pixel, 1, 10, ifp) == 10) {
     for (i=0; i < 10; i+=2) {
       todo[i]   = iten++;
       todo[i+1] = pixel[i] << 8 | pixel[i+1];
@@ -474,11 +475,11 @@ phase_one_load_raw(Image const image) {
   int row, col, a, b;
   unsigned short *pixel, akey, bkey;
 
-  fseek (ifp, 8, SEEK_CUR);
-  fseek (ifp, get4(ifp) + 296, SEEK_CUR);
+  fseek_nofail (ifp, 8, SEEK_CUR);
+  fseek_nofail (ifp, get4(ifp) + 296, SEEK_CUR);
   akey = get2(ifp);
   bkey = get2(ifp);
-  fseek (ifp, data_offset + 12 + top_margin*raw_width*2, SEEK_SET);
+  fseek_nofail (ifp, data_offset + 12 + top_margin*raw_width*2, SEEK_SET);
   pixel = calloc (raw_width, sizeof *pixel);
   merror (pixel, "phase_one_load_raw()");
   for (row=0; row < height; row++) {
@@ -501,7 +502,7 @@ ixpress_load_raw(Image const image) {
   int row, col;
 
   order = 0x4949;
-  fseek (ifp, 304 + 6*2*4090, SEEK_SET);
+  fseek_nofail (ifp, 304 + 6*2*4090, SEEK_SET);
   for (row=height; --row >= 0; ) {
     read_shorts(ifp, pixel, 4090);
     for (col=0; col < width; col++)
@@ -567,7 +568,7 @@ olympus_e300_load_raw(Image const image) {
   merror (data, "olympus_e300_load_raw()");
   pixel = (unsigned short *) (data + dwide);
   for (row=0; row < height; row++) {
-    fread (data, 1, dwide, ifp);
+    fread_nofail (data, 1, dwide, ifp);
     for (dp=data, pix=pixel; pix < pixel+raw_width; dp+=3, pix+=2) {
       if (((dp-data) & 15) == 15) dp++;
       pix[0] = dp[1] << 8 | dp[0];
@@ -586,7 +587,7 @@ olympus_cseries_load_raw(Image const image) {
   for (irow=0; irow < height; irow++) {
     row = irow * 2 % height + irow / (height/2);
     if (row < 2) {
-      fseek (ifp, data_offset - row*(-width*height*3/4 & -2048), SEEK_SET);
+      fseek_nofail (ifp, data_offset - row*(-width*height*3/4 & -2048), SEEK_SET);
       getbits(ifp, -1);
     }
     for (col=0; col < width; col++)
@@ -602,7 +603,7 @@ eight_bit_load_raw(Image const image) {
   pixel = calloc (raw_width, sizeof *pixel);
   merror (pixel, "eight_bit_load_raw()");
   for (row=0; row < height; row++) {
-    fread (pixel, 1, raw_width, ifp);
+    fread_nofail (pixel, 1, raw_width, ifp);
     for (col=0; col < width; col++)
       BAYER(row,col) = pixel[col];
   }
@@ -617,7 +618,7 @@ casio_qv5700_load_raw(Image const image) {
   int row, col;
 
   for (row=0; row < height; row++) {
-    fread (data, 1, 3232, ifp);
+    fread_nofail (data, 1, 3232, ifp);
     for (dp=data, pix=pixel; dp < data+3220; dp+=5, pix+=4) {
       pix[0] = (dp[0] << 2) + (dp[1] >> 6);
       pix[1] = (dp[1] << 4) + (dp[2] >> 4);
@@ -783,7 +784,7 @@ fill_input_buffer (j_decompress_ptr cinfo)
   static char jpeg_buffer[4096];
   size_t nbytes;
 
-  nbytes = fread (jpeg_buffer, 1, 4096, ifp);
+  nbytes = fread_or_eof_nofail (jpeg_buffer, 1, 4096, ifp);
   swab (jpeg_buffer, jpeg_buffer, nbytes);
   cinfo->src->next_input_byte = jpeg_buffer;
   cinfo->src->bytes_in_buffer = nbytes;
@@ -840,7 +841,7 @@ kodak_dc120_load_raw(Image const image)
   int row, shift, col;
 
   for (row=0; row < height; row++) {
-    fread (pixel, 848, 1, ifp);
+    fread_nofail (pixel, 848, 1, ifp);
     shift = row * mul[row & 3] + add[row & 3];
     for (col=0; col < width; col++)
       BAYER(row,col) = (unsigned short) pixel[(col + shift) % 848];
@@ -878,7 +879,7 @@ kodak_easy_load_raw(Image const image)
   pixel = calloc (raw_width, sizeof *pixel);
   merror (pixel, "kodak_easy_load_raw()");
   for (row=0; row < height; row++) {
-    fread (pixel, 1, raw_width, ifp);
+    fread_nofail (pixel, 1, raw_width, ifp);
     for (col=0; col < raw_width; col++) {
       icol = col - left_margin;
       if (icol < width)
@@ -912,21 +913,21 @@ kodak_compressed_load_raw(Image const image)
       if ((col & 255) == 0) {       /* Get the bit-lengths of the */
     len = width - col;      /* next 256 pixel values      */
     if (len > 256) len = 256;
-    save = ftell(ifp);
+    save = ftell_nofail(ifp);
     for (israw=i=0; i < len; i+=2) {
-      c = fgetc(ifp);
+      c = fgetc_nofail(ifp);
       if ((blen[i+0] = c & 15) > 12 ||
           (blen[i+1] = c >> 4) > 12 )
         israw = 1;
     }
     bitbuf = bits = pred[0] = pred[1] = 0;
     if (len % 8 == 4) {
-      bitbuf  = fgetc(ifp) << 8;
-      bitbuf += fgetc(ifp);
+      bitbuf  = fgetc_nofail(ifp) << 8;
+      bitbuf += fgetc_nofail(ifp);
       bits = 16;
     }
     if (israw)
-      fseek (ifp, save, SEEK_SET);
+      fseek_nofail (ifp, save, SEEK_SET);
       }
       if (israw) {          /* If the data is not compressed */
     switch (col & 7) {
@@ -944,7 +945,7 @@ kodak_compressed_load_raw(Image const image)
     len = blen[col & 255];      /* Number of bits for this pixel */
     if (bits < len) {       /* Got enough bits in the buffer? */
       for (i=0; i < 32; i+=8)
-        bitbuf += (INT64) fgetc(ifp) << (bits+(i^8));
+        bitbuf += (INT64) fgetc_nofail(ifp) << (bits+(i^8));
       bits += 32;
     }
     diff = bitbuf & (0xffff >> (16-len));  /* Pull bits from buffer */
@@ -976,14 +977,14 @@ kodak_yuv_load_raw(Image const image)
     len = (width - col + 1) * 3 & -4;
     if (len > 384) len = 384;
     for (i=0; i < len; ) {
-      c = fgetc(ifp);
+      c = fgetc_nofail(ifp);
       blen[i++] = c & 15;
       blen[i++] = c >> 4;
     }
     li = bitbuf = bits = y[1] = y[3] = cb = cr = 0;
     if (len % 8 == 4) {
-      bitbuf  = fgetc(ifp) << 8;
-      bitbuf += fgetc(ifp);
+      bitbuf  = fgetc_nofail(ifp) << 8;
+      bitbuf += fgetc_nofail(ifp);
       bits = 16;
     }
       }
@@ -991,7 +992,7 @@ kodak_yuv_load_raw(Image const image)
     len = blen[li++];
     if (bits < len) {
       for (i=0; i < 32; i+=8)
-        bitbuf += (INT64) fgetc(ifp) << (bits+(i^8));
+        bitbuf += (INT64) fgetc_nofail(ifp) << (bits+(i^8));
       bits += 32;
     }
     diff = bitbuf & (0xffff >> (16-len));
@@ -1062,20 +1063,20 @@ sony_load_raw(Image const image)
   struct pixel * pixelrow;
   unsigned i, key, row, col;
 
-  fseek (ifp, 200896, SEEK_SET);
-  fseek (ifp, (unsigned) fgetc(ifp)*4 - 1, SEEK_CUR);
+  fseek_nofail (ifp, 200896, SEEK_SET);
+  fseek_nofail (ifp, (unsigned) fgetc_nofail(ifp)*4 - 1, SEEK_CUR);
   order = 0x4d4d;
   key = get4(ifp);
-  fseek (ifp, 164600, SEEK_SET);
-  fread (head, 1, 40, ifp);
+  fseek_nofail (ifp, 164600, SEEK_SET);
+  fread_nofail (head, 1, 40, ifp);
   sony_decrypt ((void *) head, 10, 1, key);
   for (i=26; i-- > 22; )
     key = key << 8 | head[i];
-  fseek (ifp, data_offset, SEEK_SET);
+  fseek_nofail (ifp, data_offset, SEEK_SET);
   MALLOCARRAY(pixelrow, raw_width);
   merror (pixelrow, "sony_load_raw()");
   for (row=0; row < height; row++) {
-    fread (pixelrow, 2, raw_width, ifp);
+    fread_nofail (pixelrow, 2, raw_width, ifp);
     sony_decrypt ((void *) pixelrow, raw_width/2, !row, key);
     for (col=9; col < left_margin; col++)
       black += pixelrow[col].bytes[0] * 256 + pixelrow[col].bytes[1];
@@ -1095,14 +1096,14 @@ parse_minolta(FILE * const ifp)
 {
   int save, tag, len, offset, high=0, wide=0;
 
-  fseek (ifp, 4, SEEK_SET);
+  fseek_nofail (ifp, 4, SEEK_SET);
   offset = get4(ifp) + 8;
-  while ((save=ftell(ifp)) < offset) {
+  while ((save=ftell_nofail(ifp)) < offset) {
     tag = get4(ifp);
     len = get4(ifp);
     switch (tag) {
       case 0x505244:                /* PRD */
-    fseek (ifp, 8, SEEK_CUR);
+    fseek_nofail (ifp, 8, SEEK_CUR);
     high = get2(ifp);
     wide = get2(ifp);
     break;
@@ -1114,9 +1115,9 @@ parse_minolta(FILE * const ifp)
     camera_blue = get2(ifp) / camera_blue;
     break;
       case 0x545457:                /* TTW */
-    parse_tiff(ifp, ftell(ifp));
+    parse_tiff(ifp, ftell_nofail(ifp));
     }
-    fseek (ifp, save+len+8, SEEK_SET);
+    fseek_nofail (ifp, save+len+8, SEEK_SET);
   }
   raw_height = high;
   raw_width  = wide;
@@ -1168,24 +1169,24 @@ parse_ciff(FILE * const ifp,
       strcmp(model,"Canon PowerShot S70") &&
       strcmp(model,"Canon PowerShot Pro1"))
     key[0] = key[1] = 0;
-  fseek (ifp, offset+length-4, SEEK_SET);
+  fseek_nofail (ifp, offset+length-4, SEEK_SET);
   tboff = get4(ifp) + offset;
-  fseek (ifp, tboff, SEEK_SET);
+  fseek_nofail (ifp, tboff, SEEK_SET);
   nrecs = get2(ifp);
   for (i = 0; i < nrecs; i++) {
     type = get2(ifp);
     len  = get4(ifp);
     roff = get4(ifp);
     aoff = offset + roff;
-    save = ftell(ifp);
+    save = ftell_nofail(ifp);
     if (type == 0x080a) {       /* Get the camera make and model */
-      fseek (ifp, aoff, SEEK_SET);
-      fread (make, 64, 1, ifp);
-      fseek (ifp, aoff+strlen(make)+1, SEEK_SET);
-      fread (model, 64, 1, ifp);
+      fseek_nofail (ifp, aoff, SEEK_SET);
+      fread_nofail (make, 64, 1, ifp);
+      fseek_nofail (ifp, aoff+strlen(make)+1, SEEK_SET);
+      fread_nofail (model, 64, 1, ifp);
     }
     if (type == 0x102a) {       /* Find the White Balance index */
-      fseek (ifp, aoff+14, SEEK_SET);   /* 0=auto, 1=daylight, 2=cloudy ... */
+      fseek_nofail (ifp, aoff+14, SEEK_SET);   /* 0=auto, 1=daylight, 2=cloudy ... */
       wbi = get2(ifp);
       if (((!strcmp(model,"Canon EOS DIGITAL REBEL") ||
         !strcmp(model,"Canon EOS 300D DIGITAL"))) && wbi == 6)
@@ -1194,19 +1195,19 @@ parse_ciff(FILE * const ifp,
     if (type == 0x102c) {       /* Get white balance (G2) */
       if (!strcmp(model,"Canon PowerShot G1") ||
       !strcmp(model,"Canon PowerShot Pro90 IS")) {
-    fseek (ifp, aoff+120, SEEK_SET);
+    fseek_nofail (ifp, aoff+120, SEEK_SET);
     white[0][1] = get2(ifp);
     white[0][0] = get2(ifp);
     white[1][0] = get2(ifp);
     white[1][1] = get2(ifp);
       } else {
-    fseek (ifp, aoff+100, SEEK_SET);
+    fseek_nofail (ifp, aoff+100, SEEK_SET);
     goto common;
       }
     }
     if (type == 0x0032) {       /* Get white balance (D30 & G3) */
       if (!strcmp(model,"Canon EOS D30")) {
-    fseek (ifp, aoff+72, SEEK_SET);
+    fseek_nofail (ifp, aoff+72, SEEK_SET);
 common:
     camera_red   = get2(ifp) ^ key[0];
     camera_red   =(get2(ifp) ^ key[1]) / camera_red;
@@ -1214,13 +1215,13 @@ common:
     camera_blue /= get2(ifp) ^ key[1];
       } else if (!strcmp(model,"Canon PowerShot G6") ||
          !strcmp(model,"Canon PowerShot S70")) {
-    fseek (ifp, aoff+96 + remap_s70[wbi]*8, SEEK_SET);
+    fseek_nofail (ifp, aoff+96 + remap_s70[wbi]*8, SEEK_SET);
     goto common;
       } else if (!strcmp(model,"Canon PowerShot Pro1")) {
-    fseek (ifp, aoff+96 + wbi*8, SEEK_SET);
+    fseek_nofail (ifp, aoff+96 + wbi*8, SEEK_SET);
     goto common;
       } else {
-    fseek (ifp, aoff+80 + (wbi < 6 ? remap[wbi]*8 : 0), SEEK_SET);
+    fseek_nofail (ifp, aoff+80 + (wbi < 6 ? remap[wbi]*8 : 0), SEEK_SET);
     if (!camera_red)
       goto common;
       }
@@ -1228,38 +1229,38 @@ common:
     if (type == 0x10a9) {       /* Get white balance (D60) */
       if (!strcmp(model,"Canon EOS 10D"))
     wbi = remap_10d[wbi];
-      fseek (ifp, aoff+2 + wbi*8, SEEK_SET);
+      fseek_nofail (ifp, aoff+2 + wbi*8, SEEK_SET);
       camera_red  = get2(ifp);
       camera_red /= get2(ifp);
       camera_blue = get2(ifp);
       camera_blue = get2(ifp) / camera_blue;
     }
     if (type == 0x1030 && (wbi == 6 || wbi == 15)) {
-      fseek (ifp, aoff, SEEK_SET);  /* Get white sample */
+      fseek_nofail (ifp, aoff, SEEK_SET);  /* Get white sample */
       ciff_block_1030();
     }
     if (type == 0x1031) {       /* Get the raw width and height */
-      fseek (ifp, aoff+2, SEEK_SET);
+      fseek_nofail (ifp, aoff+2, SEEK_SET);
       raw_width  = get2(ifp);
       raw_height = get2(ifp);
     }
     if (type == 0x180e) {       /* Get the timestamp */
-      fseek (ifp, aoff, SEEK_SET);
+      fseek_nofail (ifp, aoff, SEEK_SET);
       timestamp = get4(ifp);
     }
     if (type == 0x580e)
       timestamp = len;
     if (type == 0x1810) {       /* Get the rotation */
-      fseek (ifp, aoff+12, SEEK_SET);
+      fseek_nofail (ifp, aoff+12, SEEK_SET);
       flip = get4(ifp);
     }
     if (type == 0x1835) {       /* Get the decoder table */
-      fseek (ifp, aoff, SEEK_SET);
+      fseek_nofail (ifp, aoff, SEEK_SET);
       crw_init_tables (get4(ifp));
     }
     if (type >> 8 == 0x28 || type >> 8 == 0x30) /* Get sub-tables */
       parse_ciff(ifp, aoff, len);
-    fseek (ifp, save, SEEK_SET);
+    fseek_nofail (ifp, save, SEEK_SET);
   }
   if (wbi == 0 && !strcmp(model,"Canon EOS D30"))
     camera_red = -1;            /* Use my auto WB for this photo */
@@ -1273,9 +1274,9 @@ parse_rollei(FILE * const ifp)
   struct tm t;
   time_t ts;
 
-  fseek (ifp, 0, SEEK_SET);
+  fseek_nofail (ifp, 0, SEEK_SET);
   do {
-    fgets (line, 128, ifp);
+    fgets_nofail (line, 128, ifp);
     if ((val = strchr(line,'=')))
       *val++ = 0;
     else
@@ -1314,13 +1315,13 @@ parse_mos(FILE * const ifp,
     char data[40];
     int skip, from, i, neut[4];
 
-    fseek (ifp, offset, SEEK_SET);
+    fseek_nofail (ifp, offset, SEEK_SET);
     while (1) {
-        fread (data, 1, 8, ifp);
+        fread_nofail (data, 1, 8, ifp);
         if (strcmp(data,"PKTS")) break;
-        fread (data, 1, 40, ifp);
+        fread_nofail (data, 1, 40, ifp);
         skip = get4(ifp);
-        from = ftell(ifp);
+        from = ftell_nofail(ifp);
         if (!strcmp(data,"NeutObj_neutrals")) {
             for (i=0; i < 4; i++)
                 fscanf (ifp, "%d", neut+i);
@@ -1328,7 +1329,7 @@ parse_mos(FILE * const ifp,
             camera_blue = (float) neut[2] / neut[3];
         }
         parse_mos(ifp, from);
-        fseek (ifp, skip+from, SEEK_SET);
+        fseek_nofail (ifp, skip+from, SEEK_SET);
     }
 }
 
@@ -1369,43 +1370,43 @@ parse_makernote(FILE * const ifp)
    its own byte-order!), or it might just be a table.
  */
   sorder = order;
-  fread (buf, 1, 10, ifp);
+  fread_nofail (buf, 1, 10, ifp);
   if (!strncmp (buf,"KC" ,2) ||     /* these aren't TIFF format */
       !strncmp (buf,"MLY",3)) return;
   if (!strcmp (buf,"Nikon")) {
-    base = ftell(ifp);
+    base = ftell_nofail(ifp);
     order = get2(ifp);
     if (get2(ifp) != 42) goto quit;
     offset = get4(ifp);
-    fseek (ifp, offset-8, SEEK_CUR);
+    fseek_nofail (ifp, offset-8, SEEK_CUR);
   } else if (!strncmp (buf,"FUJIFILM",8) ||
          !strcmp  (buf,"Panasonic")) {
     order = 0x4949;
-    fseek (ifp,  2, SEEK_CUR);
+    fseek_nofail (ifp,  2, SEEK_CUR);
   } else if (!strcmp (buf,"OLYMP") ||
          !strcmp (buf,"LEICA") ||
          !strcmp (buf,"EPSON"))
-    fseek (ifp, -2, SEEK_CUR);
+    fseek_nofail (ifp, -2, SEEK_CUR);
   else if (!strcmp (buf,"AOC") ||
        !strcmp (buf,"QVC"))
-    fseek (ifp, -4, SEEK_CUR);
-  else fseek (ifp, -10, SEEK_CUR);
+    fseek_nofail (ifp, -4, SEEK_CUR);
+  else fseek_nofail (ifp, -10, SEEK_CUR);
 
   entries = get2(ifp);
   while (entries--) {
     tag  = get2(ifp);
     type = get2(ifp);
     len  = get4(ifp);
-    save = ftell(ifp);
+    save = ftell_nofail(ifp);
     if (len * size[type < 13 ? type:0] > 4)
-      fseek (ifp, get4(ifp)+base, SEEK_SET);
+      fseek_nofail (ifp, get4(ifp)+base, SEEK_SET);
 
     if (tag == 0xc && len == 4) {
       camera_red  = getrat();
       camera_blue = getrat();
     }
     if (tag == 0x14 && len == 2560 && type == 7) {
-      fseek (ifp, 1248, SEEK_CUR);
+      fseek_nofail (ifp, 1248, SEEK_CUR);
       goto get2_256;
     }
     if (strstr(make,"PENTAX")) {
@@ -1413,19 +1414,19 @@ parse_makernote(FILE * const ifp)
       if (tag == 0x1c) tag = 0x1017;
     }
     if (tag == 0x8c)
-      nikon_curve_offset = ftell(ifp) + 2112;
+      nikon_curve_offset = ftell_nofail(ifp) + 2112;
     if (tag == 0x96)
-      nikon_curve_offset = ftell(ifp) + 2;
+      nikon_curve_offset = ftell_nofail(ifp) + 2;
     if (tag == 0x97) {
       if (!strcmp(model,"NIKON D100 ")) {
-    fseek (ifp, 72, SEEK_CUR);
+    fseek_nofail (ifp, 72, SEEK_CUR);
     camera_red  = get2(ifp) / 256.0;
     camera_blue = get2(ifp) / 256.0;
       } else if (!strcmp(model,"NIKON D2H")) {
-    fseek (ifp, 10, SEEK_CUR);
+    fseek_nofail (ifp, 10, SEEK_CUR);
     goto get2_rggb;
       } else if (!strcmp(model,"NIKON D70")) {
-    fseek (ifp, 20, SEEK_CUR);
+    fseek_nofail (ifp, 20, SEEK_CUR);
     camera_red  = get2(ifp);
     camera_red /= get2(ifp);
     camera_blue = get2(ifp);
@@ -1449,12 +1450,12 @@ parse_makernote(FILE * const ifp)
       black = (get4(ifp)+get4(ifp)+get4(ifp)+get4(ifp))/4;
     }
     if (tag == 0xe80 && len == 256 && type == 7) {
-      fseek (ifp, 48, SEEK_CUR);
+      fseek_nofail (ifp, 48, SEEK_CUR);
       camera_red  = get2(ifp) * 508 * 1.078 / 0x10000;
       camera_blue = get2(ifp) * 382 * 1.173 / 0x10000;
     }
     if (tag == 0xf00 && len == 614 && type == 7) {
-      fseek (ifp, 188, SEEK_CUR);
+      fseek_nofail (ifp, 188, SEEK_CUR);
       goto get2_256;
     }
     if (tag == 0x1017)
@@ -1468,14 +1469,14 @@ get2_256:
       camera_blue = get2(ifp) / 256.0;
     }
     if (tag == 0x4001) {
-      fseek (ifp, strstr(model,"EOS-1D") ? 68:50, SEEK_CUR);
+      fseek_nofail (ifp, strstr(model,"EOS-1D") ? 68:50, SEEK_CUR);
 get2_rggb:
       camera_red  = get2(ifp);
       camera_red /= get2(ifp);
       camera_blue = get2(ifp);
       camera_blue = get2(ifp) / camera_blue;
     }
-    fseek (ifp, save+4, SEEK_SET);
+    fseek_nofail (ifp, save+4, SEEK_SET);
   }
 quit:
   order = sorder;
@@ -1514,8 +1515,8 @@ parse_exif(FILE * const ifp, int base)
     /* type = */ get2(ifp);
     len  = get4(ifp);
     val  = get4(ifp);
-    save = ftell(ifp);
-    fseek (ifp, base+val, SEEK_SET);
+    save = ftell_nofail(ifp);
+    fseek_nofail (ifp, base+val, SEEK_SET);
     if (tag == 0x9003 || tag == 0x9004)
       get_timestamp(ifp);
     if (tag == 0x927c) {
@@ -1524,7 +1525,7 @@ parse_exif(FILE * const ifp, int base)
       else
     parse_makernote(ifp);
     }
-    fseek (ifp, save, SEEK_SET);
+    fseek_nofail (ifp, save, SEEK_SET);
   }
 }
 
@@ -1550,10 +1551,10 @@ parse_tiff_ifd(FILE * const ifp, int base, int level)
     tag  = get2(ifp);
     type = get2(ifp);
     len  = get4(ifp);
-    save = ftell(ifp);
+    save = ftell_nofail(ifp);
     if (tag > 50700 && tag < 50800) done = 1;
     if (len * size[type < 13 ? type:0] > 4)
-      fseek (ifp, get4(ifp)+base, SEEK_SET);
+      fseek_nofail (ifp, get4(ifp)+base, SEEK_SET);
     switch (tag) {
       case 0x11:
     camera_red  = get4(ifp) / 256.0;
@@ -1580,10 +1581,10 @@ parse_tiff_ifd(FILE * const ifp, int base, int level)
     kodak_data_compression = get2(ifp);
     break;
       case 0x10f:           /* Make */
-    fgets (make, 64, ifp);
+    fgets_nofail (make, 64, ifp);
     break;
       case 0x110:           /* Model */
-    fgets (model, 64, ifp);
+    fgets_nofail (model, 64, ifp);
     break;
       case 0x111:           /* StripOffset */
     data_offset = get4(ifp);
@@ -1595,7 +1596,7 @@ parse_tiff_ifd(FILE * const ifp, int base, int level)
     tiff_samples = get2(ifp);
     break;
       case 0x131:           /* Software tag */
-    fgets (software, 64, ifp);
+    fgets_nofail (software, 64, ifp);
     if (!strncmp(software,"Adobe",5))
       make[0] = 0;
     break;
@@ -1604,7 +1605,7 @@ parse_tiff_ifd(FILE * const ifp, int base, int level)
     break;
       case 0x144:           /* TileOffsets */
     if (level) {
-      data_offset = ftell(ifp);
+      data_offset = ftell_nofail(ifp);
     } else {
       strcpy (make, "Leaf");
       data_offset = get4(ifp);
@@ -1614,18 +1615,18 @@ parse_tiff_ifd(FILE * const ifp, int base, int level)
     if (len > 2 && !is_dng && !strcmp(make,"Kodak"))
         len = 2;
     while (len--) {
-      i = ftell(ifp);
-      fseek (ifp, get4(ifp)+base, SEEK_SET);
+      i = ftell_nofail(ifp);
+      fseek_nofail (ifp, get4(ifp)+base, SEEK_SET);
       if (parse_tiff_ifd(ifp, base, level+1)) break;
-      fseek (ifp, i+4, SEEK_SET);
+      fseek_nofail (ifp, i+4, SEEK_SET);
     }
     break;
       case 33405:           /* Model2 */
-    fgets (model2, 64, ifp);
+    fgets_nofail (model2, 64, ifp);
     break;
       case 33422:           /* CFAPattern */
     if ((plen=len) > 16) plen = 16;
-    fread (cfa_pat, 1, plen, ifp);
+    fread_nofail (cfa_pat, 1, plen, ifp);
     for (colors=cfa=i=0; i < plen; i++) {
       colors += !(cfa & (1 << cfa_pat[i]));
       cfa |= 1 << cfa_pat[i];
@@ -1634,7 +1635,7 @@ parse_tiff_ifd(FILE * const ifp, int base, int level)
     if (cfa == 072) memcpy (cfa_pc,"\005\003\004\001",4);   /* GMCY */
     goto guess_cfa_pc;
       case 34665:           /* EXIF tag */
-    fseek (ifp, get4(ifp)+base, SEEK_SET);
+    fseek_nofail (ifp, get4(ifp)+base, SEEK_SET);
     parse_exif(ifp, base);
     break;
       case 50706:           /* DNGVersion */
@@ -1644,7 +1645,7 @@ parse_tiff_ifd(FILE * const ifp, int base, int level)
       case 50710:           /* CFAPlaneColor */
     if (len > 4) len = 4;
     colors = len;
-    fread (cfa_pc, 1, colors, ifp);
+    fread_nofail (cfa_pc, 1, colors, ifp);
 guess_cfa_pc:
     FORC4 tab[cfa_pc[c]] = c;
     for (i=16; i--; )
@@ -1701,7 +1702,7 @@ guess_cfa_pc:
     xyz[1] = getrat();
     xyz[2] = 1 - xyz[0] - xyz[1];
     }
-    fseek (ifp, save+4, SEEK_SET);
+    fseek_nofail (ifp, save+4, SEEK_SET);
   }
   for (i=0; i < colors; i++)
     FORC4 cc[i][c] *= ab[i];
@@ -1729,16 +1730,16 @@ parse_tiff(FILE * const ifp, int base)
 {
   int doff;
 
-  fseek (ifp, base, SEEK_SET);
+  fseek_nofail (ifp, base, SEEK_SET);
   order = get2(ifp);
   if (order != 0x4949 && order != 0x4d4d) return;
   get2(ifp);
   while ((doff = get4(ifp))) {
-    fseek (ifp, doff+base, SEEK_SET);
+    fseek_nofail (ifp, doff+base, SEEK_SET);
     if (parse_tiff_ifd(ifp, base, 0)) break;
   }
   if (!is_dng && !strncmp(make,"Kodak",5)) {
-    fseek (ifp, 12+base, SEEK_SET);
+    fseek_nofail (ifp, 12+base, SEEK_SET);
     parse_tiff_ifd(ifp, base, 2);
   }
 }
diff --git a/converter/other/cameratopam/cameratopam.c b/converter/other/cameratopam/cameratopam.c
index 2c832714..78eb6854 100644
--- a/converter/other/cameratopam/cameratopam.c
+++ b/converter/other/cameratopam/cameratopam.c
@@ -10,7 +10,7 @@
 #define _DEFAULT_SOURCE 1 /* New name for SVID & BSD source defines */
 #define _BSD_SOURCE 1   /* Make sure string.h contains strdup() */
 #define _XOPEN_SOURCE 500
-   /* Make sure unistd.h contains swab(), string.h constains strdup() */
+   /* Make sure unistd.h contains swab(), string.h contains strdup() */
 
 #include "pm_config.h"
 
diff --git a/converter/other/cameratopam/canon.c b/converter/other/cameratopam/canon.c
index 96a6210b..cbf5ece0 100644
--- a/converter/other/cameratopam/canon.c
+++ b/converter/other/cameratopam/canon.c
@@ -6,9 +6,10 @@
 #include "decode.h"
 #include "bayer.h"
 #include "canon.h"
+#include "stdio_nofail.h"
 
 
-void 
+void
 canon_600_load_raw(Image const image) {
     unsigned char  data[1120], *dp;
     unsigned short pixel[896], *pix;
@@ -16,7 +17,7 @@ canon_600_load_raw(Image const image) {
 
     for (irow=orow=0; irow < height; irow++)
     {
-        fread (data, 1120, 1, ifp);
+        fread_nofail (data, 1120, 1, ifp);
         for (dp=data, pix=pixel; dp < data+1120; dp+=10, pix+=8)
         {
             pix[0] = (dp[0] << 2) + (dp[1] >> 6    );
@@ -48,7 +49,7 @@ canon_a5_load_raw(Image const image) {
     int row, col;
 
     for (row=0; row < height; row++) {
-        fread (data, raw_width * 10 / 8, 1, ifp);
+        fread_nofail (data, raw_width * 10 / 8, 1, ifp);
         for (dp=data, pix=pixel; pix < pixel+raw_width; dp+=10, pix+=8)
         {
             pix[0] = (dp[1] << 2) + (dp[0] >> 6);
@@ -84,8 +85,8 @@ canon_has_lowbits()
     unsigned char test[0x4000];
     int ret=1, i;
 
-    fseek (ifp, 0, SEEK_SET);
-    fread (test, 1, sizeof test, ifp);
+    fseek_nofail (ifp, 0, SEEK_SET);
+    fread_nofail (test, 1, sizeof test, ifp);
     for (i=540; i < sizeof test - 1; i++)
         if (test[i] == 0xff) {
             if (test[i+1]) return 1;
@@ -96,7 +97,7 @@ canon_has_lowbits()
 
 
 
-void 
+void
 canon_compressed_load_raw(Image const image) {
     unsigned short *pixel, *prow;
     int lowbits, i, row, r, col, save, val;
@@ -110,7 +111,7 @@ canon_compressed_load_raw(Image const image) {
         pm_error("Unable to allocate space for %u pixels", raw_width*8);
     lowbits = canon_has_lowbits();
     if (!lowbits) maximum = 0x3ff;
-    fseek (ifp, 540 + lowbits*raw_height*raw_width/4, SEEK_SET);
+    fseek_nofail (ifp, 540 + lowbits*raw_height*raw_width/4, SEEK_SET);
     zero_after_ff = 1;
     getbits(ifp, -1);
     for (row = 0; row < raw_height; row += 8) {
@@ -141,17 +142,17 @@ canon_compressed_load_raw(Image const image) {
             }
         }
         if (lowbits) {
-            save = ftell(ifp);
-            fseek (ifp, 26 + row*raw_width/4, SEEK_SET);
+            save = ftell_nofail(ifp);
+            fseek_nofail (ifp, 26 + row*raw_width/4, SEEK_SET);
             for (prow=pixel, i=0; i < raw_width*2; i++) {
-                c = fgetc(ifp);
+                c = fgetc_nofail(ifp);
                 for (r=0; r < 8; r+=2, prow++) {
                     val = (*prow << 2) + ((c >> r) & 3);
                     if (raw_width == 2672 && val < 512) val += 2;
                     *prow = val;
                 }
             }
-            fseek (ifp, save, SEEK_SET);
+            fseek_nofail (ifp, save, SEEK_SET);
         }
         for (r=0; r < 8; r++) {
             irow = row - top_margin + r;
@@ -169,4 +170,3 @@ canon_compressed_load_raw(Image const image) {
     if (raw_width > width)
         black /= (raw_width - width) * height;
 }
-
diff --git a/converter/other/cameratopam/foveon.c b/converter/other/cameratopam/foveon.c
index 992f3883..5a26777b 100644
--- a/converter/other/cameratopam/foveon.c
+++ b/converter/other/cameratopam/foveon.c
@@ -2,7 +2,6 @@
 
 #define _XOPEN_SOURCE 500  /* get M_PI in math.h */
 
-#include <stdio.h>
 #include <assert.h>
 #include <string.h>
 #include <float.h>
@@ -13,6 +12,7 @@
 #include "global_variables.h"
 #include "decode.h"
 #include "foveon.h"
+#include "stdio_nofail.h"
 
 #if HAVE_INT64
    typedef int64_t INT64;
@@ -32,13 +32,13 @@
 
 
 
-static char *  
-foveon_gets(int    const offset, 
-            char * const str, 
+static char *
+foveon_gets(int    const offset,
+            char * const str,
             int    const len) {
 
     unsigned int i;
-    fseek (ifp, offset, SEEK_SET);
+    fseek_nofail (ifp, offset, SEEK_SET);
     for (i=0; i < len-1; ++i) {
         /* It certains seems wrong that we're reading a 16 bit integer
            and assigning it to char, but that's what Dcraw does.
@@ -55,7 +55,7 @@ foveon_gets(int    const offset,
 
 
 
-void 
+void
 parse_foveon(FILE * const ifp) {
     long fliplong;
     long pos;
@@ -63,14 +63,14 @@ parse_foveon(FILE * const ifp) {
     long junk;
     long entries;
 
-    fseek (ifp, 36, SEEK_SET);
+    fseek_nofail (ifp, 36, SEEK_SET);
     pm_readlittlelong(ifp, &fliplong);
     flip = fliplong;
-    fseek (ifp, -4, SEEK_END);
+    fseek_nofail (ifp, -4, SEEK_END);
     pm_readlittlelong(ifp, &pos);
-    fseek (ifp, pos, SEEK_SET);
+    fseek_nofail (ifp, pos, SEEK_SET);
     pm_readlittlelong(ifp, &magic);
-    if (magic != 0x64434553) 
+    if (magic != 0x64434553)
         return; /* SECd */
     pm_readlittlelong(ifp, &junk);
     pm_readlittlelong(ifp, &entries);
@@ -85,17 +85,17 @@ parse_foveon(FILE * const ifp) {
         pm_readlittlelong(ifp, &off);
         pm_readlittlelong(ifp, &len);
         pm_readlittlelong(ifp, &tag);
-            
-        save = ftell(ifp);
-        fseek (ifp, off, SEEK_SET);
+
+        save = ftell_nofail(ifp);
+        fseek_nofail (ifp, off, SEEK_SET);
         pm_readlittlelong(ifp, &sec_);
         if (sec_ != (0x20434553 | (tag << 24))) return;
         switch (tag) {
         case 0x47414d49:          /* IMAG */
-            if (data_offset) 
+            if (data_offset)
                 break;
             data_offset = off + 28;
-            fseek (ifp, 12, SEEK_CUR);
+            fseek_nofail (ifp, 12, SEEK_CUR);
             {
                 long wlong, hlong;
                 pm_readlittlelong(ifp, &wlong);
@@ -113,7 +113,7 @@ parse_foveon(FILE * const ifp) {
         case 0x504f5250:          /* PROP */
             pm_readlittlelong(ifp, &junk);
             pm_readlittlelong(ifp, &pent);
-            fseek (ifp, 12, SEEK_CUR);
+            fseek_nofail (ifp, 12, SEEK_CUR);
             off += pent*8 + 24;
             if (pent > 256) pent=256;
             for (i=0; i < pent*2; i++) {
@@ -133,14 +133,14 @@ parse_foveon(FILE * const ifp) {
                     timestamp = atoi (foveon_gets (poff[i][1], name, 64));
             }
         }
-        fseek (ifp, save, SEEK_SET);
+        fseek_nofail (ifp, save, SEEK_SET);
     }
     is_foveon = 1;
 }
 
 
 
-void  
+void
 foveon_coeff(int * const useCoeffP,
              float       coeff[3][4]) {
 
@@ -159,8 +159,8 @@ foveon_coeff(int * const useCoeffP,
 
 
 
-static void  
-foveon_decoder (unsigned int const huff[1024], 
+static void
+foveon_decoder (unsigned int const huff[1024],
                 unsigned int const code) {
 
     struct decode *cur;
@@ -180,7 +180,7 @@ foveon_decoder (unsigned int const huff[1024],
             }
         }
     }
-    if ((len = code >> 27) > 26) 
+    if ((len = code >> 27) > 26)
         return;
     code2 = (len+1) << 27 | (code & 0x3ffffff) << 1;
 
@@ -192,14 +192,14 @@ foveon_decoder (unsigned int const huff[1024],
 
 
 
-static void  
+static void
 foveon_load_camf() {
     unsigned int i, val;
     long key;
 
-    fseek (ifp, meta_offset, SEEK_SET);
+    fseek_nofail (ifp, meta_offset, SEEK_SET);
     pm_readlittlelong(ifp, &key);
-    fread (meta_data, 1, meta_length, ifp);
+    fread_nofail (meta_data, 1, meta_length, ifp);
     for (i=0; i < meta_length; i++) {
         key = (key * 1597 + 51749) % 244944;
         assert(have64BitArithmetic);
@@ -210,7 +210,7 @@ foveon_load_camf() {
 
 
 
-void  
+void
 foveon_load_raw(Image const image) {
 
     struct decode *dindex;
@@ -234,14 +234,14 @@ foveon_load_raw(Image const image) {
     for (row=0; row < height; row++) {
         long junk;
         memset (pred, 0, sizeof pred);
-        if (!bit) 
+        if (!bit)
             pm_readlittlelong(ifp, &junk);
         for (col=bit=0; col < width; col++) {
             FORC3 {
                 for (dindex=first_decode; dindex->branch[0]; ) {
                     if ((bit = (bit-1) & 31) == 31)
                         for (i=0; i < 4; i++)
-                            bitbuf = (bitbuf << 8) + fgetc(ifp);
+                            bitbuf = (bitbuf << 8) + fgetc_nofail(ifp);
                     dindex = dindex->branch[bitbuf >> bit & 1];
                 }
                 pred[c] += diff[dindex->leaf];
@@ -262,8 +262,8 @@ sget4(char const s[]) {
 
 
 
-static char *  
-foveon_camf_param (const char * const block, 
+static char *
+foveon_camf_param (const char * const block,
                    const char * const param) {
     unsigned idx, num;
     char *pos, *cp, *dp;
@@ -287,8 +287,8 @@ foveon_camf_param (const char * const block,
 
 
 
-static void *  
-foveon_camf_matrix (int                dim[3], 
+static void *
+foveon_camf_matrix (int                dim[3],
                     const char * const name) {
 
     unsigned i, idx, type, ndim, size, *mat;
@@ -325,9 +325,9 @@ foveon_camf_matrix (int                dim[3],
 
 
 
-static int  
-foveon_fixed (void *       const ptr, 
-              int          const size, 
+static int
+foveon_fixed (void *       const ptr,
+              int          const size,
               const char * const name) {
     void *dp;
     int dim[3];
@@ -345,7 +345,7 @@ static float  foveon_avg (unsigned short *pix, int range[2], float cfilt)
     float val, min=FLT_MAX, max=-FLT_MAX, sum=0;
 
     for (i=range[0]; i <= range[1]; i++) {
-        sum += val = 
+        sum += val =
             (short)pix[i*4] + ((short)pix[i*4]-(short)pix[(i-1)*4]) * cfilt;
         if (min > val) min = val;
         if (max < val) max = val;
@@ -390,11 +390,11 @@ static int  foveon_apply_curve (short *curve, int i)
     return i < 0 ? -(unsigned short)curve[1-i] : (unsigned short)curve[1+i];
 }
 
-void  
+void
 foveon_interpolate(Image const image,
                    float coeff[3][4]) {
 
-    static const short hood[] = { 
+    static const short hood[] = {
         -1,-1, -1,0, -1,1, 0,-1, 0,1, 1,-1, 1,0, 1,1 };
     short *pix, prev[3], *curve[8], (*shrink)[3];
     float cfilt=0.8, ddft[3][3][2], ppm[3][3][3];
@@ -441,7 +441,7 @@ foveon_interpolate(Image const image,
         for (i=0; i < 3; i++)
             FORC3 diag[c][i] = LAST(1,1)*LAST(2,2) - LAST(1,2)*LAST(2,1);
 #undef LAST
-        FORC3 div[c] = 
+        FORC3 div[c] =
             diag[c][0]*0.3127 + diag[c][1]*0.329 + diag[c][2]*0.3583;
     }
     num = 0;
@@ -494,11 +494,11 @@ foveon_interpolate(Image const image,
     for (row=1; row < height-1; row++) {
         FORC3 if (last[1][c] > last[0][c]) {
             if (last[1][c] > last[2][c])
-                black[row][c] = 
+                black[row][c] =
                     (last[0][c] > last[2][c]) ? last[0][c]:last[2][c];
         } else
             if (last[1][c] < last[2][c])
-                black[row][c] = 
+                black[row][c] =
                     (last[0][c] < last[2][c]) ? last[0][c]:last[2][c];
         memmove (last, last+1, 2*sizeof last[0]);
         memcpy (last[2], black[row+1], sizeof last[2]);
@@ -547,8 +547,8 @@ foveon_interpolate(Image const image,
                 diff = pix[c] - prev[c];
                 prev[c] = pix[c];
                 ipix[c] = pix[c] + floor ((diff + (diff*diff >> 14)) * cfilt
-                                          - ddft[0][c][1] 
-                                          - ddft[0][c][0] 
+                                          - ddft[0][c][1]
+                                          - ddft[0][c][0]
                                             * ((float) col/width - 0.5)
                                           - black[row][c] );
             }
@@ -563,7 +563,7 @@ foveon_interpolate(Image const image,
                         val += ppm[c][i][j] * work[i][j];
                 ipix[c] = floor ((ipix[c] + floor(val)) *
                                  ( sgrow[col/sgx  ][c] * (sgx - col%sgx) +
-                                   sgrow[col/sgx+1][c] * (col%sgx) ) / sgx / 
+                                   sgrow[col/sgx+1][c] * (col%sgx) ) / sgx /
                                  div[c]);
                 if (ipix[c] > 32000) ipix[c] = 32000;
                 pix[c] = ipix[c];
@@ -584,7 +584,7 @@ foveon_interpolate(Image const image,
             memset (fsum, 0, sizeof fsum);
             for (sum=j=0; j < 8; j++)
                 if (badpix[i] & (1 << j)) {
-                    FORC3 fsum[c] += 
+                    FORC3 fsum[c] +=
                         image[(row+hood[j*2])*width+col+hood[j*2+1]][c];
                     sum++;
                 }
@@ -665,8 +665,8 @@ foveon_interpolate(Image const image,
         pix = (short*)image[row*width+2];
         for (col=2; col < width-2; col++) {
             FORC3 dev[c] = -foveon_apply_curve (curve[7], pix[c] -
-                                                ((smrow[1][col][c] + 
-                                                  2*smrow[2][col][c] + 
+                                                ((smrow[1][col][c] +
+                                                  2*smrow[2][col][c] +
                                                   smrow[3][col][c]) >> 2));
             sum = (dev[0] + dev[1] + dev[2]) >> 3;
             FORC3 pix[c] += dev[c] - sum;
@@ -695,7 +695,7 @@ foveon_interpolate(Image const image,
             if (sum < 0) sum = 0;
             j = total[3] > 375 ? (sum << 16) / total[3] : sum * 174;
             FORC3 pix[c] += foveon_apply_curve (curve[6],
-                                                ((j*total[c] + 0x8000) >> 16) 
+                                                ((j*total[c] + 0x8000) >> 16)
                                                 - pix[c]);
             pix += 4;
         }
@@ -732,7 +732,7 @@ foveon_interpolate(Image const image,
                     shrink[row*(width/4)+col][c] = ipix[c] >> 4;
                 else
                     shrink[row*(width/4)+col][c] =
-                        (shrink[(row+1)*(width/4)+col][c]*1840 + 
+                        (shrink[(row+1)*(width/4)+col][c]*1840 +
                          ipix[c]*141 + 2048) >> 12;
         }
     }
@@ -742,7 +742,7 @@ foveon_interpolate(Image const image,
         if ((row & 3) == 0)
             for (col = width & ~3 ; col--; )
                 FORC3 smrow[0][col][c] = ipix[c] =
-                    (shrink[(row/4)*(width/4)+col/4][c]*1485 + 
+                    (shrink[(row/4)*(width/4)+col/4][c]*1485 +
                      ipix[c]*6707 + 4096) >> 13;
 
         /* Then smooth left-to-right */
@@ -757,7 +757,7 @@ foveon_interpolate(Image const image,
         else
             for (col=0; col < (width & ~3); col++)
                 FORC3 smrow[2][col][c] =
-                    (smrow[2][col][c]*6707 + smrow[1][col][c]*1485 + 4096) 
+                    (smrow[2][col][c]*6707 + smrow[1][col][c]*1485 + 4096)
                         >> 13;
 
         /* Adjust the chroma toward the smooth values */
@@ -770,7 +770,7 @@ foveon_interpolate(Image const image,
             for (sum=c=0; c < 3; c++) {
                 ipix[c] = foveon_apply_curve(
                     curve[c+3],
-                    ((smrow[2][col][c] * j + 0x8000) >> 16) - 
+                    ((smrow[2][col][c] * j + 0x8000) >> 16) -
                     image[row*width+col][c]);
                 sum += ipix[c];
             }
diff --git a/converter/other/cameratopam/identify.c b/converter/other/cameratopam/identify.c
index 26fa329e..e5df6b22 100644
--- a/converter/other/cameratopam/identify.c
+++ b/converter/other/cameratopam/identify.c
@@ -13,6 +13,7 @@
 #include "dng.h"
 #include "ljpeg.h"
 #include "camera.h"
+#include "stdio_nofail.h"
 
 #include "identify.h"
 
@@ -38,7 +39,7 @@ static const char *memmem_internal (const char *haystack, size_t haystacklen,
 
 
 
-static void 
+static void
 adobeCoeff(const char * const make,
            const char * const model) {
     /*
@@ -47,7 +48,7 @@ adobeCoeff(const char * const make,
     struct CoeffTableEntry {
         const char * prefix;
         short trans[12];
-    }; 
+    };
 
     static struct CoeffTableEntry const table[] = {
         { "Canon EOS D2000C",
@@ -331,17 +332,17 @@ identify(FILE *       const ifp,
 
     order = get2(ifp);
     hlen = get4(ifp);
-    fseek (ifp, 0, SEEK_SET);
-    fread (head, 1, 32, ifp);
-    fseek (ifp, 0, SEEK_END);
-    fsize = ftell(ifp);
+    fseek_nofail (ifp, 0, SEEK_SET);
+    fread_nofail (head, 1, 32, ifp);
+    fseek_nofail (ifp, 0, SEEK_END);
+    fsize = ftell_nofail(ifp);
     if ((c = (char*)memmem_internal(head, 32, "MMMMRawT", 8))) {
         strcpy (make, "Phase One");
         data_offset = c - head;
-        fseek (ifp, data_offset + 8, SEEK_SET);
-        fseek (ifp, get4(ifp) + 136, SEEK_CUR);
+        fseek_nofail (ifp, data_offset + 8, SEEK_SET);
+        fseek_nofail (ifp, get4(ifp) + 136, SEEK_CUR);
         raw_width = get4(ifp);
-        fseek (ifp, 12, SEEK_CUR);
+        fseek_nofail (ifp, 12, SEEK_CUR);
         raw_height = get4(ifp);
     } else if (order == 0x4949 || order == 0x4d4d) {
         if (!memcmp (head+6, "HEAPCCDR", 8)) {
@@ -356,14 +357,14 @@ identify(FILE *       const ifp,
         parse_minolta(ifp);
     else if (!memcmp (head, "\xff\xd8\xff\xe1", 4) &&
              !memcmp (head+6, "Exif", 4)) {
-        fseek (ifp, 4, SEEK_SET);
-        fseek (ifp, 4 + get2(ifp), SEEK_SET);
-        if (fgetc(ifp) != 0xff)
+        fseek_nofail (ifp, 4, SEEK_SET);
+        fseek_nofail (ifp, 4 + get2(ifp), SEEK_SET);
+        if (fgetc_nofail(ifp) != 0xff)
             parse_tiff(ifp, 12);
     } else if (!memcmp (head, "BM", 2)) {
         data_offset = 0x1000;
         order = 0x4949;
-        fseek (ifp, 38, SEEK_SET);
+        fseek_nofail (ifp, 38, SEEK_SET);
         if (get4(ifp) == 2834 && get4(ifp) == 2834) {
             strcpy (model, "BMQ");
             flip = 3;
@@ -374,7 +375,7 @@ identify(FILE *       const ifp,
     nucore:
         strcpy (make, "Nucore");
         order = 0x4949;
-        fseek (ifp, 10, SEEK_SET);
+        fseek_nofail (ifp, 10, SEEK_SET);
         data_offset += get4(ifp);
         get4(ifp);
         raw_width  = get4(ifp);
@@ -386,16 +387,16 @@ identify(FILE *       const ifp,
     } else if (!memcmp (head+25, "ARECOYK", 7)) {
         strcpy (make, "Contax");
         strcpy (model,"N Digital");
-        fseek (ifp, 60, SEEK_SET);
+        fseek_nofail (ifp, 60, SEEK_SET);
         camera_red  = get4(ifp);
         camera_red /= get4(ifp);
         camera_blue = get4(ifp);
         camera_blue = get4(ifp) / camera_blue;
     } else if (!memcmp (head, "FUJIFILM", 8)) {
         long data_offset_long;
-        fseek (ifp, 84, SEEK_SET);
+        fseek_nofail (ifp, 84, SEEK_SET);
         parse_tiff(ifp, get4(ifp)+12);
-        fseek (ifp, 100, SEEK_SET);
+        fseek_nofail (ifp, 100, SEEK_SET);
         pm_readbiglong(ifp, &data_offset_long);
         data_offset = data_offset_long;
     } else if (!memcmp (head, "DSC-Image", 9))
@@ -737,13 +738,13 @@ identify(FILE *       const ifp,
         width  = 2312;
         raw_width = 2336;
         data_offset = 4034;
-        fseek (ifp, 2032, SEEK_SET);
+        fseek_nofail (ifp, 2032, SEEK_SET);
         goto konica_400z;
     } else if (!strcmp(model,"Digital Camera KD-510Z")) {
         data_offset = 4032;
         pre_mul[0] = 1.297;
         pre_mul[2] = 1.438;
-        fseek (ifp, 2032, SEEK_SET);
+        fseek_nofail (ifp, 2032, SEEK_SET);
         goto konica_510z;
     } else if (!strcasecmp(make,"MINOLTA")) {
         load_raw = unpacked_load_raw;
@@ -767,19 +768,19 @@ identify(FILE *       const ifp,
                 data_offset = 5056;
                 pre_mul[0] = 1.602;
                 pre_mul[2] = 1.441;
-                fseek (ifp, 2078, SEEK_SET);
+                fseek_nofail (ifp, 2078, SEEK_SET);
                 height = 1716;
                 width  = 2304;
             } else if (model[8] == '5') {
                 data_offset = 4016;
-                fseek (ifp, 1936, SEEK_SET);
+                fseek_nofail (ifp, 1936, SEEK_SET);
             konica_510z:
                 height = 1956;
                 width  = 2607;
                 raw_width = 2624;
             } else if (model[8] == '6') {
                 data_offset = 4032;
-                fseek (ifp, 2030, SEEK_SET);
+                fseek_nofail (ifp, 2030, SEEK_SET);
                 height = 2136;
                 width  = 2848;
             }
@@ -885,7 +886,7 @@ identify(FILE *       const ifp,
         pre_mul[0] = 1.963;
         pre_mul[2] = 1.430;
     } else if (!strcmp(make,"Sinar") && !memcmp(head,"8BPS",4)) {
-        fseek (ifp, 14, SEEK_SET);
+        fseek_nofail (ifp, 14, SEEK_SET);
         height = get4(ifp);
         width  = get4(ifp);
         filters = 0x61616161;
@@ -1199,7 +1200,7 @@ dng_skip:
             for (i=0; i < 3; i++)
                 coeff[i][3] = coeff[i][1] /= 2;
     }
-    fseek (ifp, data_offset, SEEK_SET);
+    fseek_nofail (ifp, data_offset, SEEK_SET);
 
     *loadRawFnP = load_raw;
 
diff --git a/converter/other/cameratopam/ljpeg.c b/converter/other/cameratopam/ljpeg.c
index 331d258c..35f50f4b 100644
--- a/converter/other/cameratopam/ljpeg.c
+++ b/converter/other/cameratopam/ljpeg.c
@@ -2,7 +2,6 @@
 #define _BSD_SOURCE    /* Make sure string.h containst strcasecmp() */
 #include <stdlib.h>
 #include <string.h>
-#include <stdio.h>
 #include <limits.h>
 
 #include "pm.h"
@@ -11,6 +10,7 @@
 #include "util.h"
 #include "decode.h"
 #include "bayer.h"
+#include "stdio_nofail.h"
 
 #include "ljpeg.h"
 
@@ -20,7 +20,7 @@
    enough to decode Canon, Kodak and Adobe DNG images.
  */
 
-int  
+int
 ljpeg_start(FILE *         const ifP,
             struct jhead * const jhP) {
 
@@ -30,12 +30,12 @@ ljpeg_start(FILE *         const ifP,
     init_decoder();
     for (i=0; i < 4; i++)
         jhP->huff[i] = free_decode;
-    fread (data, 2, 1, ifP);
+    fread_nofail (data, 2, 1, ifP);
     if (data[0] != 0xff || data[1] != 0xd8) return 0;
     do {
         unsigned int len;
 
-        fread (data, 2, 2, ifP);
+        fread_nofail (data, 2, 2, ifP);
         tag =  data[0] << 8 | data[1];
         len = data[2] << 8 | data[3];
 
@@ -45,7 +45,7 @@ ljpeg_start(FILE *         const ifP,
             unsigned int const dataLen = len - 2;
 
             if (tag <= 0xff00 || dataLen > 255) return 0;
-            fread (data, 1, dataLen, ifP);
+            fread_nofail (data, 1, dataLen, ifP);
             switch (tag) {
             case 0xffc3:
                 jhP->bits = data[0];
@@ -73,7 +73,7 @@ ljpeg_start(FILE *         const ifP,
 
 
 
-int 
+int
 ljpeg_diff(FILE *          const ifP,
            struct decode * const dindexHeadP) {
 
@@ -111,7 +111,7 @@ ljpeg_row(FILE *         const ifP,
 
 
 
-void  
+void
 lossless_jpeg_load_raw(Image  const image) {
 
     int jwide, jrow, jcol, val, jidx, i, row, col;
@@ -161,5 +161,3 @@ lossless_jpeg_load_raw(Image  const image) {
     if (!strcasecmp(make,"KODAK"))
         black = min;
 }
-
-
diff --git a/converter/other/cameratopam/stdio_nofail.c b/converter/other/cameratopam/stdio_nofail.c
new file mode 100644
index 00000000..97a8796d
--- /dev/null
+++ b/converter/other/cameratopam/stdio_nofail.c
@@ -0,0 +1,120 @@
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include <netpbm/pm.h>
+
+#include "stdio_nofail.h"
+
+
+
+size_t
+fread_or_eof_nofail(void * const ptr,
+                    size_t const size,
+                    size_t const nmemb,
+                    FILE * const streamP) {
+
+    size_t rc;
+
+    rc = fread(ptr, size, nmemb, streamP);
+
+    if (rc < nmemb) {
+        if (!feof(streamP))
+            pm_error("File read failed.  Errno=%d (%s)",
+                     errno, strerror(errno));
+    }
+    return rc;
+}
+
+
+
+void
+fread_nofail(void * const ptr,
+             size_t const size,
+             size_t const nmemb,
+             FILE * const streamP) {
+
+    size_t rc;
+
+    rc = fread(ptr, size, nmemb, streamP);
+
+    if (rc < nmemb) {
+        if (feof(streamP))
+            pm_error("File read failed.  Premature end of file");
+        else
+            pm_error("File read failed.  Errno=%d (%s)",
+                     errno, strerror(errno));
+    }
+}
+
+
+
+int
+fgetc_nofail(FILE * streamP) {
+
+    int rc;
+
+    rc = fgetc(streamP);
+
+    if (rc == EOF) {
+        if (feof(streamP))
+            pm_error("File read failed.  Premature end of file");
+        else
+            pm_error("File read failed.  Errno=%d (%s)",
+                     errno, strerror(errno));
+    }
+    return rc;
+}
+
+
+
+int
+fseek_nofail(FILE * const streamP,
+             long   const offset,
+             int    const whence) {
+
+    int rc;
+
+    rc = fseek(streamP, offset, whence);
+
+    if (rc < 0)
+        pm_error("File seek failed.  Errno=%d (%s)", errno, strerror(errno));
+
+    return rc;
+}
+
+
+
+long
+ftell_nofail(FILE * const streamP) {
+
+    long rc;
+
+    rc = ftell(streamP);
+
+    if (rc < 0)
+        pm_error("File position query failed.  Errno=%d (%s)",
+                 errno, strerror(errno));
+
+    return rc;
+}
+
+
+
+char *
+fgets_nofail(char * const s,
+             int    const size,
+             FILE * const streamP) {
+
+    char * rc;
+
+    rc = fgets(s, size, streamP);
+
+    if (ferror(streamP))
+        pm_error("File read failed.  Errno=%d (%s)", errno, strerror(errno));
+
+    return rc;
+}
+
+
+
diff --git a/converter/other/cameratopam/stdio_nofail.h b/converter/other/cameratopam/stdio_nofail.h
new file mode 100644
index 00000000..8f45b537
--- /dev/null
+++ b/converter/other/cameratopam/stdio_nofail.h
@@ -0,0 +1,29 @@
+#include <stdio.h>
+
+size_t
+fread_or_eof_nofail(void * const ptr,
+                    size_t const size,
+                    size_t const nmemb,
+                    FILE * const streamP);
+
+void
+fread_nofail(void * const ptr,
+             size_t const size,
+             size_t const nmemb,
+             FILE * const streamP);
+
+int
+fgetc_nofail(FILE * const streamP);
+
+int
+fseek_nofail(FILE * const streamP,
+             long   const offset,
+             int    const whence);
+
+long
+ftell_nofail(FILE * const streamP);
+
+char *
+fgets_nofail(char * const s,
+             int    const size,
+             FILE * const streamP);
diff --git a/converter/other/cameratopam/util.c b/converter/other/cameratopam/util.c
index b3ccf7e9..ede5ef69 100644
--- a/converter/other/cameratopam/util.c
+++ b/converter/other/cameratopam/util.c
@@ -1,10 +1,12 @@
 #define _XOPEN_SOURCE   /* Make sure unistd.h contains swab() */
 #include <unistd.h>
-#include <stdio.h>
 
-#include "pm.h"
+#include "netpbm/pm.h"
+#include "netpbm/mallocvar.h"
+
 #include "global_variables.h"
 #include "util.h"
+#include "stdio_nofail.h"
 
 #ifndef LONG_BITS
 #define LONG_BITS (8 * sizeof(long))
@@ -18,7 +20,7 @@ get2(FILE * const ifp)
 {
     unsigned char a, b;
 
-    a = fgetc(ifp);  b = fgetc(ifp);
+    a = fgetc_nofail(ifp);  b = fgetc_nofail(ifp);
 
     if (order == 0x4949)      /* "II" means little-endian */
         return a | b << 8;
@@ -34,8 +36,8 @@ get4(FILE * const ifp)
 {
     unsigned char a, b, c, d;
 
-    a = fgetc(ifp);  b = fgetc(ifp);
-    c = fgetc(ifp);  d = fgetc(ifp);
+    a = fgetc_nofail(ifp);  b = fgetc_nofail(ifp);
+    c = fgetc_nofail(ifp);  d = fgetc_nofail(ifp);
 
     if (order == 0x4949)
         return a | b << 8 | c << 16 | d << 24;
@@ -49,9 +51,21 @@ get4(FILE * const ifp)
 void
 read_shorts (FILE * const ifp, unsigned short *pixel, int count)
 {
-    fread (pixel, 2, count, ifp);
-    if ((order == 0x4949) == (BYTE_ORDER == BIG_ENDIAN))
-        swab (pixel, pixel, count*2);
+    unsigned short * buffer;
+
+    MALLOCARRAY(buffer, count);
+
+    if (!buffer)
+        pm_error("Failed to allocate a buffer for reading %u short "
+                 "integers from file", count);
+    else {
+        fread_nofail(buffer, 2, count, ifp);
+
+        if ((order == 0x4949) == (BYTE_ORDER == BIG_ENDIAN))
+            swab(buffer, pixel, count*2);
+
+        free(buffer);
+    }
 }
 
 /*
@@ -73,10 +87,10 @@ getbits (FILE * const ifp, int nbits)
         vbits -= nbits;
     }
     while (vbits < LONG_BITS - 7) {
-        c = fgetc(ifp);
+        c = fgetc_nofail(ifp);
         bitbuf = (bitbuf << 8) + c;
         if (c == 0xff && zero_after_ff)
-            fgetc(ifp);
+            fgetc_nofail(ifp);
         vbits += 8;
     }
     return ret;
diff --git a/converter/other/fiasco/codec/coder.c b/converter/other/fiasco/codec/coder.c
index 1e21994d..dc774a19 100644
--- a/converter/other/fiasco/codec/coder.c
+++ b/converter/other/fiasco/codec/coder.c
@@ -2,7 +2,7 @@
  *  coder.c:        WFA coder toplevel functions
  *
  *  Written by:     Ullrich Hafner
- *      
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -56,7 +56,7 @@
 /*****************************************************************************
 
                 global variables
-  
+
 *****************************************************************************/
 
 const real_t MAXCOSTS = 1e20;
@@ -64,7 +64,7 @@ const real_t MAXCOSTS = 1e20;
 /*****************************************************************************
 
                 private code
-  
+
 *****************************************************************************/
 
 static char *
@@ -109,44 +109,44 @@ get_input_image_name (char const * const *templptr, unsigned ith_image)
 
             strcpy (prefix, template);
             prefix [s - template] = '\0';
-   
+
             for (s2 = ++s, n_digits = 0; ISDIGIT (*s2); s2++, n_digits++)
                 ;
             if (sscanf (s, "%d", &dummy) == 0 || dummy < 0)
                 error ("Input name template conversion failure.\n"
                        "Check spelling of template.");
             first = (unsigned) dummy;
-     
+
             if (*s2++ != '-')
                 error ("Input name template conversion failure.\n"
                        "Check spelling of template.");
-   
+
             for (s = s2; ISDIGIT (*s2); s2++)
                 ;
             if (sscanf (s, "%d", &dummy) == 0 || dummy < 0)
                 error ("Input name template conversion failure.\n"
                        "Check spelling of template.");
             last = (unsigned) dummy;
-     
-            if (*s2 == '+' || *s2 == '-') 
+
+            if (*s2 == '+' || *s2 == '-')
             {
                 for (s = s2++; ISDIGIT (*s2); s2++)
                     ;
                 if (sscanf (s, "%d", &increment) == 0)
                     error ("Input name template conversion failure.\n"
                            "Check spelling of template.");
-            }   
+            }
             if (*s2 != ']')
                 error ("Input name template conversion failure.\n"
                        "Check spelling of template.");
             suffix = s2 + 1;
-   
+
             image_num = first + increment * ith_image;
             if (image_num < 0)
                 error ("Input name template conversion failure.\n"
                        "Check spelling of template.");
-     
-            if ((increment >  0 && (unsigned) image_num > last) || 
+
+            if ((increment >  0 && (unsigned) image_num > last) ||
                 (increment <= 0 && (unsigned) image_num < last))
             {
                 /* TODO: check this */
@@ -158,7 +158,7 @@ get_input_image_name (char const * const *templptr, unsigned ith_image)
                     /* format string for image filename */
                 char image_name [MAXSTRLEN];
                     /* image file name to be composed */
-        
+
                 strcpy (formatstr, "%s%0?d%s");
                 formatstr [4] = '0' + (char) n_digits;
                 sprintf (image_name, formatstr, prefix, image_num, suffix);
@@ -167,7 +167,7 @@ get_input_image_name (char const * const *templptr, unsigned ith_image)
         }
     }
     return NULL;
-}   
+}
 
 
 
@@ -191,7 +191,7 @@ alloc_coder (char const * const * const inputname,
     coding_t * c;
 
     c = NULL;  /* initial value */
-   
+
    /*
     *  Check whether all specified image frames are readable and of same type
     */
@@ -200,7 +200,7 @@ alloc_coder (char const * const * const inputname,
         int     width, w = 0, height, h = 0;
         bool_t  color, c = NO;
         unsigned    n;
-      
+
         for (n = 0; (filename = get_input_image_name (inputname, n)); n++)
         {
             xelval maxval;
@@ -220,7 +220,7 @@ alloc_coder (char const * const * const inputname,
                 pm_close(file);
             }
             color = (PNM_FORMAT_TYPE(format) == PPM_FORMAT) ? TRUE: FALSE;
-                
+
             if (n > 0)
             {
                 if (w != width || h != height || c != color)
@@ -249,13 +249,13 @@ alloc_coder (char const * const * const inputname,
     */
     {
         unsigned lx, ly;
-      
+
         lx = (unsigned) (log2 (wi->width - 1) + 1);
         ly = (unsigned) (log2 (wi->height - 1) + 1);
-      
+
         wi->level = MAX(lx, ly) * 2 - ((ly == lx + 1) ? 1 : 0);
     }
-   
+
     c = Calloc (1, sizeof (coding_t));
 
     c->options             = *options;
@@ -278,10 +278,10 @@ alloc_coder (char const * const * const inputname,
                  c->options.lc_max_level, wi->level - c->tiling->exponent - 1);
         c->options.lc_max_level = wi->level - c->tiling->exponent - 1;
     }
-   
+
     if (c->options.lc_min_level > c->options.lc_max_level)
         c->options.lc_min_level = c->options.lc_max_level;
-   
+
     /*
      *  p_min_level, p_max_level min and max level for ND/MC prediction
      *  [p_min_level, p_max_level] must be a subset of [min_level, max_level] !
@@ -293,7 +293,7 @@ alloc_coder (char const * const * const inputname,
 
     c->options.images_level = MIN(c->options.images_level,
                                   c->options.lc_max_level - 1);
-   
+
     c->products_level  = MAX(0, ((signed int) c->options.lc_max_level
                                  - (signed int) c->options.images_level - 1));
     c->pixels         = Calloc (size_of_level (c->options.lc_max_level),
@@ -301,7 +301,7 @@ alloc_coder (char const * const * const inputname,
     c->images_of_state = Calloc (MAXSTATES, sizeof (real_t *));
     c->ip_images_state = Calloc (MAXSTATES, sizeof (real_t *));
     c->ip_states_state = Calloc (MAXSTATES * MAXLEVEL, sizeof (real_t *));
-   
+
     debug_message ("Imageslevel :%d, Productslevel :%d",
                    c->options.images_level, c->products_level);
     debug_message ("Memory : (%d + %d + %d * 'states') * 'states' + %d",
@@ -309,7 +309,7 @@ alloc_coder (char const * const * const inputname,
                    size_of_tree (c->products_level) * 4,
                    (c->options.lc_max_level - c->options.images_level),
                    size_of_level (c->options.lc_max_level));
-   
+
     /*
     *  Domain pools ...
     */
@@ -333,7 +333,7 @@ alloc_coder (char const * const * const inputname,
      */
     wi->title   = strdup (options->title);
     wi->comment = strdup (options->comment);
-   
+
     /*
      *  Reduced precision format
      */
@@ -345,7 +345,7 @@ alloc_coder (char const * const * const inputname,
         = alloc_rpf (options->d_rpf_mantissa, options->d_rpf_range);
     wi->d_dc_rpf
         = alloc_rpf (options->d_dc_rpf_mantissa, options->d_dc_rpf_range);
-   
+
     /*
      *  Color image options ...
      */
@@ -361,7 +361,7 @@ alloc_coder (char const * const * const inputname,
     wi->cross_B_search = options->half_pixel_prediction;
     wi->B_as_past_ref  = options->B_as_past_ref;
     wi->smoothing      = options->smoothing;
-   
+
     c->mt = alloc_motion (wi);
 
     return c;
@@ -383,7 +383,7 @@ free_coder (coding_t *c)
 {
    free_tiling (c->tiling);
    free_motion (c->mt);
-   
+
    Free (c->pixels);
    Free (c->images_of_state);
    Free (c->ip_images_state);
@@ -424,13 +424,13 @@ print_statistics (char c, real_t costs, const wfa_t *wfa, const image_t *image,
           const range_t *range)
 {
    unsigned max_level, min_level, state, label, lincomb;
-   
+
    for (max_level = 0, min_level = MAXLEVEL, state = wfa->basis_states;
     state < wfa->states; state++)
    {
       for (lincomb = 0, label = 0; label < MAXLABELS; label++)
      lincomb += isrange(wfa->tree[state][label]) ? 1 : 0;
-     
+
       if (lincomb)
       {
      max_level = MAX(max_level,
@@ -483,10 +483,10 @@ print_statistics (char c, real_t costs, const wfa_t *wfa, const image_t *image,
 
 
 
-static void 
+static void
 frame_coder (wfa_t *wfa, coding_t *c, bitfile_t *output)
 /*
- * 
+ *
  *  WFA Coding of next frame.  All important coding parameters are
  *  stored in 'c'.  The generated 'wfa' is written to stream 'output'
  *  immediately after coding.
@@ -499,11 +499,11 @@ frame_coder (wfa_t *wfa, coding_t *c, bitfile_t *output)
    real_t   costs;          /* total costs (minimized quantity) */
    unsigned bits;           /* number of bits written on disk */
    clock_t  ptimer;
-   
+
    prg_timer (&ptimer, START);
 
    bits = bits_processed (output);
-   
+
    init_tree_model (&c->tree);
    init_tree_model (&c->p_tree);
 
@@ -552,9 +552,9 @@ frame_coder (wfa_t *wfa, coding_t *c, bitfile_t *output)
        int     YCb_node = -1;
        int     tree [3];         /* 3 root states of each color comp. */
        color_e band;
-      
+
        /*
-        *  When compressing color images, the three color components (YCbCr) 
+        *  When compressing color images, the three color components (YCbCr)
         *  are copied into a large image:
         *  [  Y  Cr ]
         *  [  Cb 0  ]
@@ -573,14 +573,14 @@ frame_coder (wfa_t *wfa, coding_t *c, bitfile_t *output)
                c->domain_pool->chroma (wfa->wfainfo->chroma_max_states, wfa,
                                        c->domain_pool->model);
                /*
-                *  Don't use a finer partioning for the chrominancy bands than
-                *  for the luminancy band.
+                *  Don't use a finer partitioning for the chrominancy bands
+                *  than for the luminancy band.
                 */
                for (min_level = MAXLEVEL, state = wfa->basis_states;
                     state < wfa->states; state++)
                {
                    unsigned lincomb, label;
-           
+
                    for (lincomb = 0, label = 0; label < MAXLABELS; label++)
                        lincomb += isrange (wfa->tree [state][label]) ? 1 : 0;
                    if (lincomb)
@@ -596,23 +596,23 @@ frame_coder (wfa_t *wfa, coding_t *c, bitfile_t *output)
 
            memset (&range, 0, sizeof (range_t));
            range.level = wfa->wfainfo->level;
-     
+
            costs = subdivide (MAXCOSTS, band, tree [Y], &range, wfa, c,
                               c->mt->frame_type != I_FRAME && band == Y, NO);
            if (c->options.progress_meter != FIASCO_PROGRESS_NONE)
                message ("");
            {
                char colors [] = {'Y', 'B', 'R'};
-        
+
                print_statistics (colors [band], costs, wfa,
                                  c->mt->original, &range);
            }
-     
+
            if (isrange (range.tree))  /* whole image is approx. by a l.c. */
                error ("No root state generated for color component %d!", band);
            else
                tree[band] = range.tree;
-     
+
            if (band == Cb)
            {
                wfa->tree [wfa->states][0] = tree[Y];
@@ -623,13 +623,13 @@ frame_coder (wfa_t *wfa, coding_t *c, bitfile_t *output)
            }
       }
       /*
-       *  generate two virtual states (*) 
+       *  generate two virtual states (*)
        *
        *              *
        *            /   \
        *           +     *
-       *          / \   /  
-       *         Y   CbCr 
+       *          / \   /
+       *         Y   CbCr
        */
       wfa->tree [wfa->states][0] = tree[Cr];
       wfa->tree [wfa->states][1] = RANGE;
@@ -646,7 +646,7 @@ frame_coder (wfa_t *wfa, coding_t *c, bitfile_t *output)
    for (state = wfa->basis_states; state < MAXSTATES; state++)
    {
       unsigned level;
-      
+
       if (c->images_of_state [state])
       {
      Free (c->images_of_state [state]);
@@ -665,12 +665,12 @@ frame_coder (wfa_t *wfa, coding_t *c, bitfile_t *output)
         Free (c->ip_states_state [state][level]);
         c->ip_states_state [state][level] = NULL;
      }
-      
+
    }
-   
+
    locate_delta_images (wfa);
    write_next_wfa (wfa, c, output);
-   
+
    bits = bits_processed (output) - bits;
    debug_message ("Total number of bits written: %d (%d bytes, %5.3f bpp)",
           bits, bits >> 3,
@@ -712,7 +712,7 @@ video_coder(char const * const * const image_template,
         /* image name of current frame.  File name or "-" for Standard Input */
     image_t  *reconst      = NULL;   /* decoded reference image */
     bool_t    future_frame = NO;     /* YES if last frame was in future */
-   
+
     debug_message ("Generating %d WFA's ...", wfa->wfainfo->frames);
 
     future_display = -1;
@@ -722,7 +722,7 @@ video_coder(char const * const * const image_template,
     while ((image_name = get_input_image_name (image_template, display)))
     {
         frame_type_e type;        /* current frame type: I, B, P */
-      
+
         /*
          *  Determine type of next frame.
          *  Skip already coded frames (future reference!)
@@ -731,7 +731,7 @@ video_coder(char const * const * const image_template,
             type = I_FRAME;        /* Force first frame to be intra */
         else
             type = pattern2type (display, c->options.pattern);
-      
+
         if (type != I_FRAME && c->options.reference_filename)
             /* Load reference from disk */
         {
@@ -741,12 +741,12 @@ video_coder(char const * const * const image_template,
             c->options.reference_filename = NULL;
         }
         if ((int) display == future_display)
-        {             
+        {
             /* Skip already coded future ref */
             display++;
             continue;
-        }   
-        else if (type == B_FRAME && (int) display > future_display) 
+        }
+        else if (type == B_FRAME && (int) display > future_display)
         {
             unsigned i = display;
             /*
@@ -758,7 +758,7 @@ video_coder(char const * const * const image_template,
 
                 i++;
                 name = get_input_image_name (image_template, i);
-        
+
                 if (!name)          /* Force last valid frame to be 'P' */
                 {
                     future_display = i - 1;
@@ -766,7 +766,7 @@ video_coder(char const * const * const image_template,
                 }
                 else
                 {
-                    future_display = i;    
+                    future_display = i;
                     image_name     = name;
                     type           = pattern2type (i, c->options.pattern);
                 }
@@ -781,7 +781,7 @@ video_coder(char const * const * const image_template,
 
         debug_message ("Coding \'%s\' [%c-frame].", image_name,
                        type == I_FRAME ? 'I' : (type == P_FRAME ? 'P' : 'B'));
-       
+
         /*
          *  Depending on current frame type update past and future frames
          *  which are needed as reference frames.
@@ -846,10 +846,10 @@ video_coder(char const * const * const image_template,
             c->mt->original = read_image_stream(stdin,
                                                 stdinwidth, stdinheight,
                                                 stdinmaxval, stdinformat);
-        else 
+        else
             c->mt->original = read_image_file(image_name);
 
-        if (c->tiling->exponent && type == I_FRAME) 
+        if (c->tiling->exponent && type == I_FRAME)
             perform_tiling (c->mt->original, c->tiling);
 
         frame_coder (wfa, c, output);
@@ -869,7 +869,7 @@ video_coder(char const * const * const image_template,
         if (c->mt->original)
             free_image (c->mt->original);
         c->mt->original = NULL;
-      
+
         remove_states (wfa->basis_states, wfa); /* Clear WFA structure */
     }
 
@@ -927,7 +927,7 @@ read_stdin_header(const char * const * const template,
 /*****************************************************************************
 
                 public code
-  
+
 *****************************************************************************/
 
 int
@@ -957,7 +957,7 @@ fiasco_coder (char const * const *inputname, const char *outputname,
             unsigned int stdinheight, stdinwidth;
             xelval stdinmaxval;
             int stdinformat;
-      
+
             /*
              *  Check parameters
              */
@@ -965,7 +965,7 @@ fiasco_coder (char const * const *inputname, const char *outputname,
                 template = default_input;
             else
                 template = inputname;
-      
+
             if (quality <= 0)
             {
                 set_error (_("Compression quality has to be positive."));
@@ -1013,20 +1013,20 @@ fiasco_coder (char const * const *inputname, const char *outputname,
                     coding_t *c   = alloc_coder(template, cop, wfa->wfainfo,
                                                 stdinwidth, stdinheight,
                                                 stdinmaxval, stdinformat);
-     
+
                     read_basis (cop->basis_name, wfa);
                     append_basis_states (wfa->basis_states, wfa, c);
-     
+
                     c->price = 128 * 64 / quality;
-     
+
                     video_coder (template, output, wfa, c,
                                  stdinwidth, stdinheight, stdinmaxval,
                                  stdinformat);
-     
+
                     close_bitfile (output);
                     free_wfa (wfa);
                     free_coder (c);
-     
+
                     if (default_options)
                         fiasco_c_options_delete (default_options);
                 }
diff --git a/converter/other/fiasco/codec/cwfa.h b/converter/other/fiasco/codec/cwfa.h
index dd86fbfc..e8e2d474 100644
--- a/converter/other/fiasco/codec/cwfa.h
+++ b/converter/other/fiasco/codec/cwfa.h
@@ -33,7 +33,7 @@ extern const real_t MAXCOSTS;
 typedef struct motion
 {
    image_t	 *original;		/* Current image */
-   image_t	 *past;			/* Preceeding image */
+   image_t	 *past;			/* Preceding image */
    image_t	 *future;		/* Succeeding image */
    frame_type_e	  frame_type;		/* frame type: B_, P_ I_FRAME */
    unsigned	  number;		/* display number of frame */
diff --git a/converter/other/fiasco/codec/dfiasco.c b/converter/other/fiasco/codec/dfiasco.c
index d45c9e39..ce25654a 100644
--- a/converter/other/fiasco/codec/dfiasco.c
+++ b/converter/other/fiasco/codec/dfiasco.c
@@ -2,11 +2,11 @@
  *  dfiasco.c:		Decoder public interface
  *
  *  Written by:		Ullrich Hafner
- *		
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
- 
+
 /*
  *  $Date: 2000/10/28 17:39:30 $
  *  $Author: hafner $
@@ -38,7 +38,7 @@
 /*****************************************************************************
 
 				prototypes
-  
+
 *****************************************************************************/
 
 static dfiasco_t *
@@ -52,7 +52,7 @@ alloc_dfiasco (wfa_t *wfa, video_t *video, bitfile_t *input,
 /*****************************************************************************
 
 				public code
-  
+
 *****************************************************************************/
 
 fiasco_decoder_t *
@@ -79,7 +79,7 @@ fiasco_decoder_new (const char *filename, const fiasco_d_options_t *options)
 	 default_options = fiasco_d_options_new ();
 	 dop 		 = cast_d_options (default_options);
       }
-      
+
       wfa   = alloc_wfa (NO);
       video = alloc_video (NO);
       input = open_wfa (filename, wfa->wfainfo);
@@ -102,7 +102,7 @@ fiasco_decoder_new (const char *filename, const fiasco_d_options_t *options)
 					dop->magnification,
 					dop->smoothing,
 					dop->image_format);
-   
+
       if (default_options)
 	 fiasco_d_options_delete (default_options);
       if (dfiasco->enlarge_factor >= 0)
@@ -115,7 +115,7 @@ fiasco_decoder_new (const char *filename, const fiasco_d_options_t *options)
 	    if (pixels << (n << 1) > 2048 * 2048)
 	    {
 	       set_error (_("Magnifaction factor `%d' is too large. "
-			    "Maximium value is %d."),
+			    "Maximum value is %d."),
 			  dfiasco->enlarge_factor, MAX(0, n - 1));
 	       fiasco_decoder_delete (decoder);
 	       return NULL;
@@ -152,7 +152,7 @@ fiasco_decoder_write_frame (fiasco_decoder_t *decoder,
 			    const char *filename)
 {
    dfiasco_t *dfiasco = cast_dfiasco (decoder);
-   
+
    if (!dfiasco)
       return 0;
    else
@@ -177,7 +177,7 @@ fiasco_image_t *
 fiasco_decoder_get_frame (fiasco_decoder_t *decoder)
 {
    dfiasco_t *dfiasco = cast_dfiasco (decoder);
-   
+
    if (!dfiasco)
       return NULL;
    else
@@ -197,7 +197,7 @@ fiasco_decoder_get_frame (fiasco_decoder_t *decoder)
 	 image->get_width  = fiasco_image_get_width;
 	 image->get_height = fiasco_image_get_height;
 	 image->is_color   = fiasco_image_is_color;
-	 
+
 	 return image;
       }
       catch
@@ -211,7 +211,7 @@ unsigned
 fiasco_decoder_get_length (fiasco_decoder_t *decoder)
 {
    dfiasco_t *dfiasco = cast_dfiasco (decoder);
-   
+
    if (!dfiasco)
       return 0;
    else
@@ -222,7 +222,7 @@ unsigned
 fiasco_decoder_get_rate (fiasco_decoder_t *decoder)
 {
    dfiasco_t *dfiasco = cast_dfiasco (decoder);
-   
+
    if (!dfiasco)
       return 0;
    else
@@ -239,12 +239,12 @@ fiasco_decoder_get_width (fiasco_decoder_t *decoder)
    else
    {
       unsigned width;
-      
+
       if (dfiasco->enlarge_factor >= 0)
 	 width = dfiasco->wfa->wfainfo->width << dfiasco->enlarge_factor;
       else
 	 width = dfiasco->wfa->wfainfo->width >> - dfiasco->enlarge_factor;
-      
+
       return width & 1 ? width + 1 : width;
    }
 }
@@ -259,7 +259,7 @@ fiasco_decoder_get_height (fiasco_decoder_t *decoder)
    else
    {
       unsigned height;
-      
+
       if (dfiasco->enlarge_factor >= 0)
 	 height = dfiasco->wfa->wfainfo->height << dfiasco->enlarge_factor;
       else
@@ -306,10 +306,10 @@ int
 fiasco_decoder_delete (fiasco_decoder_t *decoder)
 {
    dfiasco_t *dfiasco = cast_dfiasco (decoder);
-   
+
    if (!dfiasco)
       return 1;
-   
+
    try
    {
       free_wfa (dfiasco->wfa);
@@ -330,7 +330,7 @@ fiasco_decoder_delete (fiasco_decoder_t *decoder)
 /*****************************************************************************
 
 				private code
-  
+
 *****************************************************************************/
 
 static dfiasco_t *
@@ -347,14 +347,14 @@ alloc_dfiasco (wfa_t *wfa, video_t *video, bitfile_t *input,
    dfiasco_t *dfiasco = Calloc (1, sizeof (dfiasco_t));
 
    strcpy (dfiasco->id, "DFIASCO");
-   
+
    dfiasco->wfa 	   = wfa;
    dfiasco->video 	   = video;
    dfiasco->input 	   = input;
    dfiasco->enlarge_factor = enlarge_factor;
    dfiasco->smoothing  	   = smoothing;
    dfiasco->image_format   = image_format;
-   
+
    return dfiasco;
 }
 
diff --git a/converter/other/fiasco/codec/ip.c b/converter/other/fiasco/codec/ip.c
index 56b0ae9a..18257a06 100644
--- a/converter/other/fiasco/codec/ip.c
+++ b/converter/other/fiasco/codec/ip.c
@@ -2,7 +2,7 @@
  *  ip.c:		Computation of inner products
  *
  *  Written by:		Ullrich Hafner
- *		
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -27,40 +27,40 @@
 /*****************************************************************************
 
 				prototypes
-  
+
 *****************************************************************************/
 
-static real_t 
+static real_t
 standard_ip_image_state (unsigned address, unsigned level, unsigned domain,
 			 const coding_t *c);
-static real_t 
+static real_t
 standard_ip_state_state (unsigned domain1, unsigned domain2, unsigned level,
 			 const coding_t *c);
 
 /*****************************************************************************
 
 				public code
-  
+
 *****************************************************************************/
 
-real_t 
+real_t
 get_ip_image_state (unsigned image, unsigned address, unsigned level,
 		    unsigned domain, const coding_t *c)
 /*
  *  Return value:
  *	Inner product between 'image' ('address') and
- *      'domain' at given 'level' 
+ *      'domain' at given 'level'
  */
 {
    if (level <= c->options.images_level)
    {
       /*
-       *  Compute the inner product in the standard way by multiplying 
+       *  Compute the inner product in the standard way by multiplying
        *  the pixel-values of the given domain and range image.
-       */ 
+       */
       return standard_ip_image_state (address, level, domain, c);
    }
-   else 
+   else
    {
       /*
        *  Use the already computed inner products stored in 'ip_images_states'
@@ -69,29 +69,29 @@ get_ip_image_state (unsigned image, unsigned address, unsigned level,
    }
 }
 
-void 
+void
 compute_ip_images_state (unsigned image, unsigned address, unsigned level,
 			 unsigned n, unsigned from,
 			 const wfa_t *wfa, coding_t *c)
 /*
  *  Compute the inner products between all states
  *  'from', ... , 'wfa->max_states' and the range images 'image'
- *  (and childs) up to given level.
+ *  (and children) up to given level.
  *
  *  No return value.
  *
  *  Side effects:
  *	inner product tables 'c->ip_images_states' are updated
- */ 
+ */
 {
-   if (level > c->options.images_level) 
+   if (level > c->options.images_level)
    {
       unsigned state, label;
 
       if (level > c->options.images_level + 1)	/* recursive computation */
 	 compute_ip_images_state (MAXLABELS * image + 1, address * MAXLABELS,
 				  level - 1, MAXLABELS * n, from, wfa, c);
-      
+
       /*
        *  Compute inner product <f, Phi_i>
        */
@@ -102,7 +102,7 @@ compute_ip_images_state (unsigned image, unsigned address, unsigned level,
 	       unsigned  edge, count;
 	       int     	 domain;
 	       real_t 	*dst, *src;
-	       
+
 	       if (ischild (domain = wfa->tree [state][label]))
 	       {
 		  if (level > c->options.images_level + 1)
@@ -116,9 +116,9 @@ compute_ip_images_state (unsigned image, unsigned address, unsigned level,
 		  else
 		  {
 		     unsigned newadr = address * MAXLABELS + label;
-		     
+
 		     dst = c->ip_images_state [state] + image;
-		     
+
 		     for (count = n; count; count--, newadr += MAXLABELS)
 			*dst++ += standard_ip_image_state (newadr, level - 1,
 							   domain, c);
@@ -128,7 +128,7 @@ compute_ip_images_state (unsigned image, unsigned address, unsigned level,
 		    edge++)
 	       {
 		  real_t weight = wfa->weight [state][label][edge];
-		  
+
 		  if (level > c->options.images_level + 1)
 		  {
 		     dst = c->ip_images_state [state] + image;
@@ -142,7 +142,7 @@ compute_ip_images_state (unsigned image, unsigned address, unsigned level,
 		     unsigned newadr = address * MAXLABELS + label;
 
 		     dst = c->ip_images_state [state] + image;
-		     
+
 		     for (count = n; count; count--, newadr += MAXLABELS)
 			*dst++ += weight *
 				  standard_ip_image_state (newadr, level - 1,
@@ -153,7 +153,7 @@ compute_ip_images_state (unsigned image, unsigned address, unsigned level,
    }
 }
 
-real_t 
+real_t
 get_ip_state_state (unsigned domain1, unsigned domain2, unsigned level,
 		    const coding_t *c)
 /*
@@ -164,12 +164,12 @@ get_ip_state_state (unsigned domain1, unsigned domain2, unsigned level,
    if (level <= c->options.images_level)
    {
       /*
-       *  Compute the inner product in the standard way by multiplying 
+       *  Compute the inner product in the standard way by multiplying
        *  the pixel-values of both state-images
-       */ 
+       */
       return standard_ip_state_state (domain1, domain2, level, c);
    }
-   else 
+   else
    {
       /*
        *  Use already computed inner products stored in 'ip_images_states'
@@ -181,7 +181,7 @@ get_ip_state_state (unsigned domain1, unsigned domain2, unsigned level,
    }
 }
 
-void 
+void
 compute_ip_states_state (unsigned from, unsigned to,
 			 const wfa_t *wfa, coding_t *c)
 /*
@@ -192,7 +192,7 @@ compute_ip_states_state (unsigned from, unsigned to,
  *
  *  Side effects:
  *	inner product tables 'c->ip_states_state' are computed.
- */ 
+ */
 {
    unsigned level;
    unsigned state1, state2;
@@ -204,25 +204,25 @@ compute_ip_states_state (unsigned from, unsigned to,
    for (level = c->options.images_level + 1;
 	level <= c->options.lc_max_level; level++)
       for (state1 = from; state1 <= to; state1++)
-	 for (state2 = 0; state2 <= state1; state2++) 
+	 for (state2 = 0; state2 <= state1; state2++)
 	    if (need_image (state2, wfa))
 	    {
 	       unsigned	label;
 	       real_t	ip = 0;
-	       
+
 	       for (label = 0; label < MAXLABELS; label++)
 	       {
 		  int	   domain1, domain2;
 		  unsigned edge1, edge2;
 		  real_t   sum, weight2;
-		  
+
 		  if (ischild (domain1 = wfa->tree [state1][label]))
 		  {
 		     sum = 0;
 		     if (ischild (domain2 = wfa->tree [state2][label]))
 			sum = get_ip_state_state (domain1, domain2,
 						  level - 1, c);
-		     
+
 		     for (edge2 = 0;
 			  isedge (domain2 = wfa->into [state2][label][edge2]);
 			  edge2++)
@@ -238,12 +238,12 @@ compute_ip_states_state (unsigned from, unsigned to,
 		       edge1++)
 		  {
 		     real_t weight1 = wfa->weight [state1][label][edge1];
-		     
+
 		     sum = 0;
 		     if (ischild (domain2 = wfa->tree [state2][label]))
 			sum = get_ip_state_state (domain1, domain2,
 						  level - 1, c);
-		     
+
 		     for (edge2 = 0;
 			  isedge (domain2 = wfa->into [state2][label][edge2]);
 			  edge2++)
@@ -262,10 +262,10 @@ compute_ip_states_state (unsigned from, unsigned to,
 /*****************************************************************************
 
 				private code
-  
+
 *****************************************************************************/
 
-static real_t 
+static real_t
 standard_ip_image_state (unsigned address, unsigned level, unsigned domain,
 			 const coding_t *c)
 /*
@@ -283,18 +283,18 @@ standard_ip_image_state (unsigned address, unsigned level, unsigned domain,
 
    if (level > c->options.images_level)
       error ("We cannot interpret a Level %d image.", level);
-   
+
    imageptr = &c->pixels [address * size_of_level (level)];
 
    stateptr = c->images_of_state [domain] + address_of_level (level);
-   
+
    for (i = size_of_level (level); i; i--)
       ip += *imageptr++ * *stateptr++;
 
    return ip;
 }
 
-static real_t 
+static real_t
 standard_ip_state_state (unsigned domain1, unsigned domain2, unsigned level,
 			 const coding_t *c)
 /*
@@ -315,7 +315,7 @@ standard_ip_state_state (unsigned domain1, unsigned domain2, unsigned level,
 
    state1ptr = c->images_of_state [domain1] + address_of_level (level);
    state2ptr = c->images_of_state [domain2] + address_of_level (level);
-   
+
    for (i = size_of_level (level); i; i--)
       ip += *state1ptr++ * *state2ptr++;
 
diff --git a/converter/other/fiasco/codec/prediction.c b/converter/other/fiasco/codec/prediction.c
index e78e5acc..c592baa5 100644
--- a/converter/other/fiasco/codec/prediction.c
+++ b/converter/other/fiasco/codec/prediction.c
@@ -1,9 +1,9 @@
 /*
- *  prediction.c:	Range image prediction with MC or ND	
+ *  prediction.c:	Range image prediction with MC or ND
  *
  *  Written by:		Ullrich Hafner
  *			Michael Unger
- *		
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -41,7 +41,7 @@
 /*****************************************************************************
 
 			     local variables
-  
+
 *****************************************************************************/
 
 typedef struct state_data
@@ -71,7 +71,7 @@ typedef struct state_data
 /*****************************************************************************
 
 				prototypes
-  
+
 *****************************************************************************/
 
 static real_t
@@ -90,9 +90,9 @@ restore_state_data (unsigned from, unsigned to, unsigned max_level,
 /*****************************************************************************
 
 				public code
-  
+
 *****************************************************************************/
- 
+
 real_t
 predict_range (real_t max_costs, real_t price, range_t *range, wfa_t *wfa,
 	       coding_t *c, unsigned band, int y_state, unsigned states,
@@ -124,11 +124,11 @@ predict_range (real_t max_costs, real_t price, range_t *range, wfa_t *wfa,
    rec_d_coeff_model  = c->d_coeff->model;
    rec_tree_model     = c->tree;
    rec_p_tree_model   = c->p_tree;
-   rec_states         = wfa->states;	
+   rec_states         = wfa->states;
    rec_pixels         = c->pixels;
    rec_state_data     = store_state_data (states, rec_states - 1,
 					  c->options.lc_max_level, wfa, c);
-   
+
    /*
     *  Restore probability models to the state before the recursive subdivision
     *  has been started.
@@ -141,14 +141,14 @@ predict_range (real_t max_costs, real_t price, range_t *range, wfa_t *wfa,
    c->coeff->model   	   = c->coeff->model_duplicate (c->coeff, coeff_model);
    c->d_coeff->model   	   = c->d_coeff->model_duplicate (c->d_coeff,
 							  d_coeff_model);
-   
+
    if (c->mt->frame_type == I_FRAME)
-      costs = nd_prediction (max_costs, price, band, y_state, range, wfa, c); 
+      costs = nd_prediction (max_costs, price, band, y_state, range, wfa, c);
    else
       costs = mc_prediction (max_costs, price, band, y_state, range, wfa, c);
-   
+
    c->pixels = rec_pixels;
-   
+
    if (costs < MAXCOSTS)
    {
       /*
@@ -187,25 +187,25 @@ predict_range (real_t max_costs, real_t price, range_t *range, wfa_t *wfa,
       c->d_domain_pool->model_free (c->d_domain_pool->model);
       c->coeff->model_free (c->coeff->model);
       c->d_coeff->model_free (c->d_coeff->model);
-      
+
       c->domain_pool->model   = rec_domain_model;
       c->d_domain_pool->model = rec_d_domain_model;
       c->coeff->model         = rec_coeff_model;
       c->d_coeff->model       = rec_d_coeff_model;
       c->tree                 = rec_tree_model;
       c->p_tree               = rec_p_tree_model;
-      
+
       range->prediction = NO;
-      
+
       if (wfa->states != states)
 	 remove_states (states, wfa);
       restore_state_data (states, rec_states - 1, c->options.lc_max_level,
 			  rec_state_data, wfa, c);
       costs = MAXCOSTS;
    }
- 
+
    return costs;
-} 
+}
 
 void
 clear_norms_table (unsigned level, const wfa_info_t *wi, motion_t *mt)
@@ -238,11 +238,11 @@ update_norms_table (unsigned level, const wfa_info_t *wi, motion_t *mt)
    unsigned  range_size = wi->half_pixel
 			  ? square (wi->search_range)
 			  : square (2 * wi->search_range);
-   
+
    if (level > wi->p_min_level)
    {
       unsigned index;			/* index of motion vector */
-      
+
       for (index = 0; index < range_size; index++)
 	 mt->mc_forward_norms [level][index]
 	    += mt->mc_forward_norms [level - 1][index];
@@ -256,7 +256,7 @@ update_norms_table (unsigned level, const wfa_info_t *wi, motion_t *mt)
 /*****************************************************************************
 
 				private code
-  
+
 *****************************************************************************/
 
 static real_t
@@ -273,7 +273,7 @@ mc_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
     *  If we are at the bottom level of the mc tree:
     *  Fill in the norms table
     */
-   if (prange.level == wfa->wfainfo->p_min_level) 
+   if (prange.level == wfa->wfainfo->p_min_level)
       fill_norms_table (prange.x, prange.y, prange.level, wfa->wfainfo, c->mt);
    /*
     *  Predict 'range' with motion compensation according to frame type.
@@ -283,19 +283,19 @@ mc_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
       find_P_frame_mc (mcpe, price, &prange, wfa->wfainfo, c->mt);
    else
       find_B_frame_mc (mcpe, price, &prange, wfa->wfainfo, c->mt);
-   
+
    costs = (prange.mv_tree_bits + prange.mv_coord_bits) * price;
-   
+
    if (costs < max_costs)		/* motion vector not too expensive */
    {
       unsigned  last_state;		/* last WFA state before recursion */
       real_t   *ipi [MAXSTATES];	/* inner products pointers */
       unsigned  state;
       real_t  	mvt, mvc;
-      
+
       c->pixels = Calloc (width * height, sizeof (real_t));
       cut_to_bintree (c->pixels, mcpe, width, height, 0, 0, width, height);
-   
+
       /*
        *  Approximate MCPE recursively.
        */
@@ -310,7 +310,7 @@ mc_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
 
       mvc = prange.mv_coord_bits;
       mvt = prange.mv_tree_bits;
-      
+
       prange.image           = 0;
       prange.address         = 0;
       prange.tree_bits       = 0;
@@ -329,7 +329,7 @@ mc_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
       if (costs < max_costs)		/* use motion compensation */
       {
 	 unsigned img, adr;		/* temp. values */
-	 
+
 	 img                  = range->image;
 	 adr                  = range->address;
 	 *range               = prange;
@@ -362,7 +362,7 @@ mc_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
    }
    else
       costs = MAXCOSTS;
-   
+
    Free (mcpe);
 
    return costs;
@@ -374,7 +374,7 @@ nd_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
 {
    real_t  costs;			/* current approximation costs */
    range_t lrange = *range;
-   
+
    /*
     *  Predict 'range' with DC component approximation
     */
@@ -397,11 +397,11 @@ nd_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
       lrange.weights_bits    = c->coeff->bits (&w, s, range->level, c->coeff);
    }
    costs = price * (lrange.weights_bits + lrange.nd_tree_bits);
-   
+
    /*
-    *  Recursive aproximation of difference image
+    *  Recursive approximation of difference image
     */
-   if (costs < max_costs)		
+   if (costs < max_costs)
    {
       unsigned  state;
       range_t  	rrange;			/* range: recursive subdivision */
@@ -418,14 +418,14 @@ nd_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
 	 unsigned  n;
 	 real_t *src, *dst;		/* pointers to image data */
 	 real_t w = - lrange.weight [0] * c->images_of_state [0][0];
-		     
-	 src = c->pixels + range->address * size_of_level (range->level); 
+
+	 src = c->pixels + range->address * size_of_level (range->level);
 	 dst = c->pixels = pixels = Calloc (width * height, sizeof (real_t));
 
 	 for (n = width * height; n; n--)
 	    *dst++ = *src++ + w;
       }
-      
+
       /*
        *  Approximate difference recursively.
        */
@@ -448,13 +448,13 @@ nd_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
 	    c->ip_images_state[state]
 	       = Calloc (size_of_tree (c->products_level), sizeof (real_t));
 	 }
-      
+
       compute_ip_images_state (rrange.image, rrange.address, rrange.level,
 			       1, 0, wfa, c);
-      
+
       costs += subdivide (max_costs - costs, band, y_state, &rrange, wfa, c,
 			  NO, YES);
-      
+
       Free (pixels);
 
       if (costs < max_costs && ischild (rrange.tree)) /* use prediction */
@@ -469,7 +469,7 @@ nd_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
 	 range->address          = adr;
 	 range->nd_tree_bits    += lrange.nd_tree_bits;
 	 range->nd_weights_bits += lrange.weights_bits;
-	 
+
 	 for (edge = 0; isedge (lrange.into [edge]); edge++)
 	 {
 	    range->into [edge]   = lrange.into [edge];
@@ -485,7 +485,7 @@ nd_prediction (real_t max_costs, real_t price, unsigned band, int y_state,
       }
       else
 	 costs = MAXCOSTS;
-      
+
       for (state = 0; state <= last_state; state++)
 	 if (need_image (state, wfa))
 	 {
@@ -515,9 +515,9 @@ store_state_data (unsigned from, unsigned to, unsigned max_level,
 
    if (to < from)
       return NULL;			/* nothing to do */
-   
+
    data = Calloc (to - from + 1, sizeof (state_data_t));
-   
+
    for (state = from; state <= to; state++)
    {
       sd = &data [state - from];
@@ -527,12 +527,12 @@ store_state_data (unsigned from, unsigned to, unsigned max_level,
       sd->domain_type        = wfa->domain_type [state];
       sd->images_of_state    = c->images_of_state [state];
       sd->inner_products     = c->ip_images_state [state];
-      
+
       wfa->domain_type [state]   = 0;
       c->images_of_state [state] = NULL;
       c->ip_images_state [state] = NULL;
-				   
-      for (label = 0; label < MAXLABELS; label++) 
+
+      for (label = 0; label < MAXLABELS; label++)
       {
 	 sd->tree [label]     	= wfa->tree [state][label];
 	 sd->y_state [label]  	= wfa->y_state [state][label];
@@ -542,11 +542,11 @@ store_state_data (unsigned from, unsigned to, unsigned max_level,
 	 sd->y [label]        	= wfa->y [state][label];
 	 sd->prediction [label] = wfa->prediction [state][label];
 
-	 memcpy (sd->weight [label], wfa->weight [state][label], 
+	 memcpy (sd->weight [label], wfa->weight [state][label],
 		 sizeof (real_t) * (MAXEDGES + 1));
-	 memcpy (sd->int_weight [label], wfa->int_weight [state][label], 
+	 memcpy (sd->int_weight [label], wfa->int_weight [state][label],
 		 sizeof (word_t) * (MAXEDGES + 1));
-	 memcpy (sd->into [label], wfa->into [state][label], 
+	 memcpy (sd->into [label], wfa->into [state][label],
 		 sizeof (word_t) * (MAXEDGES + 1));
 
 	 wfa->into [state][label][0] = NO_EDGE;
@@ -569,7 +569,7 @@ restore_state_data (unsigned from, unsigned to, unsigned max_level,
 		    state_data_t *data, wfa_t *wfa, coding_t *c)
 /*
  *  Restore all state data starting from state 'from'.
- *  
+ *
  *  No return value.
  */
 {
@@ -578,15 +578,15 @@ restore_state_data (unsigned from, unsigned to, unsigned max_level,
 
    if (to < from)
       return;				/* nothing to do */
-   
+
    for (state = from; state <= to; state++)
    {
       sd = &data [state - from];
-      
+
       wfa->final_distribution [state] = sd->final_distribution;
       wfa->level_of_state [state]     = sd->level_of_state;
       wfa->domain_type [state]        = sd->domain_type;
-      
+
       if (c->images_of_state [state] != NULL)
 	 Free (c->images_of_state [state]);
       c->images_of_state [state] = sd->images_of_state;
@@ -603,14 +603,14 @@ restore_state_data (unsigned from, unsigned to, unsigned max_level,
 	 wfa->x [state][label]        	= sd->x [label];
 	 wfa->y [state][label]        	= sd->y [label];
 	 wfa->prediction [state][label] = sd->prediction [label];
-	 
-	 memcpy (wfa->weight [state][label], sd->weight [label], 
+
+	 memcpy (wfa->weight [state][label], sd->weight [label],
 		 sizeof(real_t) * (MAXEDGES + 1));
-	 memcpy (wfa->int_weight [state][label], sd->int_weight [label], 
+	 memcpy (wfa->int_weight [state][label], sd->int_weight [label],
 		 sizeof(word_t) * (MAXEDGES + 1));
-	 memcpy (wfa->into [state][label], sd->into [label],  
+	 memcpy (wfa->into [state][label], sd->into [label],
 		 sizeof(word_t) * (MAXEDGES + 1));
-      }	 
+      }
       for (level = c->options.images_level + 1; level <= max_level;
 	   level++)
       {
diff --git a/converter/other/fiasco/codec/subdivide.c b/converter/other/fiasco/codec/subdivide.c
index 348f838a..3ddf1ffc 100644
--- a/converter/other/fiasco/codec/subdivide.c
+++ b/converter/other/fiasco/codec/subdivide.c
@@ -2,7 +2,7 @@
  *  subdivide.c:	Recursive subdivision of range images
  *
  *  Written by:		Ullrich Hafner
- *		
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -56,10 +56,10 @@ init_range (range_t *range, const image_t *image, unsigned band,
 /*****************************************************************************
 
 				public code
-  
+
 *****************************************************************************/
 
-real_t 
+real_t
 subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
 	   wfa_t *wfa, coding_t *c, bool_t prediction, bool_t delta)
 /*
@@ -71,7 +71,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
  *  If 'prediction' is TRUE then also test motion compensation or
  *  nondeterministic approximation.
  *  If 'delta' is TRUE then current range is already predicted.
- *  
+ *
  *  Return value:
  *	costs of the best approximation or MAXCOSTS if costs exceed 'max_costs'
  *
@@ -82,7 +82,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
  */
 {
    real_t    subdivide_costs;        /* Costs arising from approx. the current
-				       range with two childs */
+				       range with two children */
    real_t    lincomb_costs;          /* Costs arising from approx. the current
 				       range with a linear combination */
    int	     new_y_state [MAXLABELS];	/* Corresponding state of Y */
@@ -91,7 +91,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
    bool_t    try_nd;			/* YES: try ND prediction */
    unsigned  states;			/* Number of states before the
 					   recursive subdivision starts */
-   void     *domain_model;		/* copy of domain pool model */      
+   void     *domain_model;		/* copy of domain pool model */
    void     *d_domain_model;		/* copy of delta domain pool model */
    void     *lc_domain_model;		/* copy of domain pool model */
    void     *lc_d_domain_model;		/* copy of delta domain pool model */
@@ -103,17 +103,17 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
    tree_t    p_tree_model;		/* copy of pred. tree model */
    range_t   lrange;			/* range of lin. comb. approx. */
    range_t   rrange;			/* range of recursive approx. */
-   range_t   child [MAXLABELS];		/* new childs of the current range */
+   range_t   child [MAXLABELS];		/* new children of the current range */
    static unsigned percent = 0;		/* status of progress meter */
 
    if (wfa->wfainfo->level == range->level)
       percent = 0;
-   
+
    range->into [0] = NO_EDGE;		/* default approximation: empty */
    range->tree     = RANGE;
 
    if (range->level < 3)		/* Don't process small ranges */
-      return MAXCOSTS;	
+      return MAXCOSTS;
 
    /*
     *  If image permutation (tiling) is performed and the tiling level
@@ -123,7 +123,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
        && range->level == wfa->wfainfo->level - c->tiling->exponent)
    {
       unsigned width, height;		/* size of range (dummies)*/
-      
+
       if (c->tiling->vorder [range->global_address] < 0)
 	 return 0;			/* nothing to do */
       else
@@ -140,7 +140,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
     *  Check whether prediction is allowed or not
     *  mc == motion compensation, nd == nondeterminism
     */
-   try_mc = (prediction && c->mt->frame_type != I_FRAME			
+   try_mc = (prediction && c->mt->frame_type != I_FRAME
 	     && range->level >= wfa->wfainfo->p_min_level
 	     && range->level <= wfa->wfainfo->p_max_level
 	     && (range->x + width_of_level (range->level)
@@ -155,21 +155,21 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
    if (try_mc)
       clear_norms_table (range->level, wfa->wfainfo, c->mt);
 
-   
+
    /*
     *  Check if current range must be initialized. I.e. range pixels must
     *  be copied from entire image to bintree pixel buffer. Moreover,
     *  all inner products tables must be initialized.
     */
-   if (range->level == c->options.lc_max_level)	
+   if (range->level == c->options.lc_max_level)
       init_range (range, c->mt->original, band, wfa, c);
-   
+
    price = c->price;
-   if (band != Y)			
+   if (band != Y)
       price *= c->options.chroma_decrease; /* less quality for chroma bands */
 
    /*
-    *  Compute childs of corresponding state in Y band
+    *  Compute children of corresponding state in Y band
     */
    if (band != Y)			/* Cb and Cr bands only */
    {
@@ -183,7 +183,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
    }
    else
       new_y_state [0] = new_y_state [1] = RANGE;
-   
+
    /*
     *  Store contents of all models that may get modified during recursion
     */
@@ -193,8 +193,8 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
    d_coeff_model  = c->d_coeff->model_duplicate (c->d_coeff, c->d_coeff->model);
    tree_model     = c->tree;
    p_tree_model   = c->p_tree;
-   states         = wfa->states;	
-   
+   states         = wfa->states;
+
    /*
     *  First alternative of range approximation:
     *  Compute costs of linear combination.
@@ -208,10 +208,10 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
       lrange.weights_bits    = 0;
       lrange.mv_tree_bits    = try_mc ? 1 : 0; /* mc allowed but not used */
       lrange.mv_coord_bits   = 0;
-      lrange.nd_tree_bits    = 0;	
-      lrange.nd_weights_bits = 0;	
+      lrange.nd_tree_bits    = 0;
+      lrange.nd_weights_bits = 0;
       lrange.prediction	     = NO;
-      
+
       lincomb_costs
 	 = approximate_range (max_costs, price, c->options.max_elements,
 			      y_state, &lrange,
@@ -219,7 +219,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
 			      (delta ? c->d_coeff : c->coeff), wfa, c);
    }
    else
-      lincomb_costs = MAXCOSTS;		
+      lincomb_costs = MAXCOSTS;
 
    /*
     *  Store contents of models that have been modified
@@ -237,7 +237,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
    c->coeff->model         = c->coeff->model_duplicate (c->coeff, coeff_model);
    c->d_coeff->model       = c->d_coeff->model_duplicate (c->d_coeff,
 							  d_coeff_model);
-   
+
    /*
     *  Second alternative of range approximation:
     *  Compute costs of recursive subdivision.
@@ -245,8 +245,8 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
    if (range->level > c->options.lc_min_level) /* range is large enough */
    {
       unsigned label;
-      
-      memset (&child [0], 0, 2 * sizeof (range_t)); /* initialize childs */
+
+      memset (&child [0], 0, 2 * sizeof (range_t)); /* initialize children */
 
       /*
        *  Initialize a new range for recursive approximation
@@ -260,7 +260,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
       rrange.mv_coord_bits   = 0;
       rrange.nd_tree_bits    = try_nd ?
 			       tree_bits (CHILD, lrange.level, &c->p_tree): 0;
-      rrange.nd_weights_bits = 0;	
+      rrange.nd_weights_bits = 0;
       rrange.prediction	     = NO;
 
       /*
@@ -271,11 +271,11 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
 			 + rrange.matrix_bits + rrange.mv_tree_bits
 			 + rrange.mv_coord_bits + rrange.nd_tree_bits
 			 + rrange.nd_weights_bits) * price;
-      
-      for (label = 0; label < MAXLABELS; label++) 
+
+      for (label = 0; label < MAXLABELS; label++)
       {
 	 real_t remaining_costs;	/* upper limit for next recursion */
-	 
+
 	 child[label].image          = rrange.image * MAXLABELS + label + 1;
 	 child[label].address        = rrange.address * MAXLABELS + label;
 	 child[label].global_address = rrange.global_address * MAXLABELS
@@ -289,8 +289,8 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
 			  ? (rrange.y
 			     + label * height_of_level (rrange.level - 1))
 			  : rrange.y;
-	 
-	 /* 
+
+	 /*
 	  *  If necessary compute the inner products of the new states
 	  *  (generated during the recursive approximation of child [0])
 	  */
@@ -298,7 +298,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
 	    compute_ip_images_state (child[label].image, child[label].address,
 				     child[label].level, 1, states, wfa, c);
 	 /*
-	  *  Call subdivide() for both childs. 
+	  *  Call subdivide() for both children.
 	  *  Abort the recursion if 'subdivide_costs' exceed 'lincomb_costs'
 	  *  or 'max_costs'.
 	  */
@@ -315,10 +315,10 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
 	    fill_norms_table (child[label].x, child[label].y,
 			      child[label].level, wfa->wfainfo, c->mt);
 	 }
-	 
+
 	 if (try_mc)
 	    update_norms_table (rrange.level, wfa->wfainfo, c->mt);
-	 
+
 	 /*
 	  *  Update of progress meter
 	  */
@@ -327,7 +327,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
 	    if (c->options.progress_meter == FIASCO_PROGRESS_PERCENT)
 	    {
 	       unsigned	new_percent; 	/* new status of progress meter */
-	 
+
 	       new_percent = (child[label].global_address + 1) * 100.0
 			     / (1 << (wfa->wfainfo->level - child[label].level));
 	       if (new_percent > percent)
@@ -339,7 +339,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
 	    else if (c->options.progress_meter == FIASCO_PROGRESS_BAR)
 	    {
 	       unsigned	new_percent;	/* new status of progress meter */
-	 
+
 	       new_percent = (child[label].global_address + 1) * 50.0
 			     / (1 << (wfa->wfainfo->level
 				      - child[label].level));
@@ -349,15 +349,15 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
 	       }
 	    }
 	 }
-   
+
 	 /*
-	  *  If costs of subdivision exceed costs of linear combination 
+	  *  If costs of subdivision exceed costs of linear combination
 	  *  then abort recursion.
 	  */
-	 if (subdivide_costs >= MIN(lincomb_costs, max_costs)) 
+	 if (subdivide_costs >= MIN(lincomb_costs, max_costs))
 	 {
 	    subdivide_costs = MAXCOSTS;
-	    break; 
+	    break;
 	 }
 	 rrange.err             += child [label].err;
 	 rrange.tree_bits       += child [label].tree_bits;
@@ -379,8 +379,8 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
 
    /*
     *  Third alternative of range approximation:
-    *  Predict range via motion compensation or nondeterminism and 
-    *  approximate delta image. 
+    *  Predict range via motion compensation or nondeterminism and
+    *  approximate delta image.
     */
    if (try_mc || try_nd)		/* try prediction */
    {
@@ -403,7 +403,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
            c->d_coeff->model_free (d_coeff_model);
            c->coeff->model_free (lc_coeff_model);
            c->d_coeff->model_free (lc_d_coeff_model);
-	 
+
            return prediction_costs;
        }
    }
@@ -423,25 +423,25 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
       c->d_coeff->model_free (c->d_coeff->model);
       c->coeff->model_free (lc_coeff_model);
       c->d_coeff->model_free (lc_d_coeff_model);
-	 
+
       c->domain_pool->model   = domain_model;
       c->d_domain_pool->model = d_domain_model;
       c->coeff->model	      = coeff_model;
       c->d_coeff->model	      = d_coeff_model;
       c->tree                 = tree_model;
       c->p_tree               = p_tree_model;
-      
+
       if (wfa->states != states)
 	 remove_states (states, wfa);
 
       return MAXCOSTS;
    }
-   else if (lincomb_costs < subdivide_costs) 
+   else if (lincomb_costs < subdivide_costs)
    {
       /*
        *  Use the linear combination: The factors of the linear combination
        *  are stored already in 'range', so revert the probability models
-       *  only. 
+       *  only.
        */
       c->domain_pool->model_free (c->domain_pool->model);
       c->d_domain_pool->model_free (c->d_domain_pool->model);
@@ -452,7 +452,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
       c->d_coeff->model_free (c->d_coeff->model);
       c->coeff->model_free (coeff_model);
       c->d_coeff->model_free (d_coeff_model);
-      
+
       c->domain_pool->model   = lc_domain_model;
       c->d_domain_pool->model = lc_d_domain_model;
       c->coeff->model	      = lc_coeff_model;
@@ -461,7 +461,7 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
       c->p_tree               = p_tree_model;
 
       *range = lrange;
-      
+
       if (wfa->states != states)
 	 remove_states (states, wfa);
 
@@ -474,8 +474,8 @@ subdivide (real_t max_costs, unsigned band, int y_state, range_t *range,
        *  given in child[].
        *  Don't use state in linear combinations in any of the following cases:
        *  - if color component is Cb or Cr
-       *  - if level of state > tiling level 
-       *  - if state is (partially) outside image geometry 
+       *  - if level of state > tiling level
+       *  - if state is (partially) outside image geometry
        */
       if (band > Y
 	  || (c->tiling->exponent
@@ -545,7 +545,7 @@ cut_to_bintree (real_t *dst, const word_t *src,
 /*****************************************************************************
 
 				private code
-  
+
 *****************************************************************************/
 
 static void
@@ -558,7 +558,7 @@ init_new_state (bool_t auxiliary_state, bool_t delta, range_t *range,
  *  If flag 'delta' is set then state represents a delta image (prediction via
  *  nondeterminism or motion compensation).
  *  'range' the current range image,
- *   'child []' the left and right childs of 'range'.
+ *   'child []' the left and right children of 'range'.
  *
  *  No return value.
  *
@@ -583,11 +583,11 @@ init_new_state (bool_t auxiliary_state, bool_t delta, range_t *range,
    }
    else
       state_is_domain = NO;
-   
+
    range->into [0] = NO_EDGE;
    range->tree     = wfa->states;
-   
-   for (label = 0; label < MAXLABELS; label++) 
+
+   for (label = 0; label < MAXLABELS; label++)
    {
       wfa->tree [wfa->states][label]       = child [label].tree;
       wfa->y_state [wfa->states][label]    = y_state [label];
@@ -605,7 +605,7 @@ init_new_state (bool_t auxiliary_state, bool_t delta, range_t *range,
       warning ("Negative image norm: %f, %f", child [0].err, child [1].err);
 
 /*    state_is_domain = YES; */
-   
+
    append_state (!state_is_domain,
 		 compute_final_distribution (wfa->states, wfa),
 		 range->level, wfa, c);
@@ -621,13 +621,13 @@ init_range (range_t *range, const image_t *image, unsigned band,
  *  No return value.
  *
  *  Side effects:
- *	'c->pixels' are filled with pixel values of image block 
- *	'c->ip_images_state' are computed with respect to new image block 
+ *	'c->pixels' are filled with pixel values of image block
+ *	'c->ip_images_state' are computed with respect to new image block
  *	'range->address' and 'range->image' are initialized with zero
  */
 {
    unsigned state;
-   
+
    /*
     *  Clear already computed products
     */
@@ -640,7 +640,7 @@ init_range (range_t *range, const image_t *image, unsigned band,
 		   image->width, image->height,
 		   range->x, range->y, width_of_level (range->level),
 		   height_of_level (range->level));
-   
+
    range->address = range->image = 0;
    compute_ip_images_state (0, 0, range->level, 1, 0, wfa, c);
 }
diff --git a/converter/other/fiasco/codec/wfa.h b/converter/other/fiasco/codec/wfa.h
index 59020fc1..4e66ccbd 100644
--- a/converter/other/fiasco/codec/wfa.h
+++ b/converter/other/fiasco/codec/wfa.h
@@ -2,7 +2,7 @@
  *  wfa.h
  *
  *  Written by:		Ullrich Hafner
- *		
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -20,7 +20,7 @@
 #define MAXEDGES  5
 #define MAXSTATES 6000
 #define MAXLABELS 2			/* only bintree possible anymore */
-#define MAXLEVEL  22 
+#define MAXLEVEL  22
 
 #define FIASCO_BINFILE_RELEASE   2
 #define FIASCO_MAGIC	         "FIASCO" /* FIASCO magic number */
@@ -85,7 +85,7 @@ typedef struct wfa_info
    char	    *basis_name;		/* filename of the initial basis */
    char     *title;			/* title of FIASCO stream */
    char     *comment;			/* comment for FIASCO stream */
-   
+
    unsigned  max_states;		/* max. cardinality of domain pool */
    unsigned  chroma_max_states;		/* max. cardinality of domain pool for
 					   chroma band coding */
@@ -111,7 +111,7 @@ typedef struct wfa_info
 
 typedef struct wfa
 /*
- *  Used to store all informations and data structures of a WFA
+ *  Used to store all information and data structures of a WFA
  */
 {
    wfa_info_t	*wfainfo;		/* misc. information about the WFA */
diff --git a/converter/other/fiasco/doc/fiasco_c_options_new.3 b/converter/other/fiasco/doc/fiasco_c_options_new.3
index d873b642..a7a96409 100644
--- a/converter/other/fiasco/doc/fiasco_c_options_new.3
+++ b/converter/other/fiasco/doc/fiasco_c_options_new.3
@@ -407,11 +407,10 @@ during coding. The following types are available:
 
 .SH RETURN VALUES
 The function \fBfiasco_c_options_new()\fP returns a pointer to the
-newly allocated coder option object. If an error has been catched, a
+newly allocated coder option object. If an error has been caught, a
 NULL pointer is returned.
 
-All set functions return 1 on success and 0 if an error has been
-catched.  
+All set functions return 1 on success and 0 if an error has been caught.
 
 In case of an error, use the function fiasco_get_error_message(3) to
 get a string with the last error message of FIASCO.
diff --git a/converter/other/fiasco/doc/fiasco_coder.3 b/converter/other/fiasco/doc/fiasco_coder.3
index 9f2e0f8e..ce32bb4d 100644
--- a/converter/other/fiasco/doc/fiasco_coder.3
+++ b/converter/other/fiasco/doc/fiasco_coder.3
@@ -73,7 +73,7 @@ available to change the default values.
 
 .SH RETURN VALUE
 The function \fBfiasco_coder()\fP returns 1 if the FIASCO file has
-been successfully written. If an error has been catched during
+been successfully written. If an error has been caught during
 compression, 0 is returned - use the function
 fiasco_get_error_message(3) to get the last error message of FIASCO.
 
diff --git a/converter/other/fiasco/doc/fiasco_d_options_new.3 b/converter/other/fiasco/doc/fiasco_d_options_new.3
index d7f2181a..02feabb0 100644
--- a/converter/other/fiasco/doc/fiasco_d_options_new.3
+++ b/converter/other/fiasco/doc/fiasco_d_options_new.3
@@ -97,11 +97,11 @@ channel is only one half of the width and height of the luminance.
 
 .SH RETURN VALUES
 The function \fBfiasco_d_options_new()\fP returns a pointer to the
-newly allocated decoder option object. If an error has been catched, a
+newly allocated decoder option object. If an error has been caught, a
 NULL pointer is returned.
 
 All set functions return 1 on success and 0 if an error has been
-catched.  
+caught.  
 
 In case of an error, use the function fiasco_get_error_message(3) to
 get a string with the last error message of FIASCO.
diff --git a/converter/other/fiasco/doc/fiasco_decoder_new.3 b/converter/other/fiasco/doc/fiasco_decoder_new.3
index 5d1d0d08..2af44f43 100644
--- a/converter/other/fiasco/doc/fiasco_decoder_new.3
+++ b/converter/other/fiasco/doc/fiasco_decoder_new.3
@@ -125,37 +125,37 @@ store the internal state of the decoder.
 
 .SH RETURN VALUES
 The function \fBfiasco_decoder_new()\fP returns a pointer to the newly
-allocated decoder object. If an error has been catched, a NULL pointer
+allocated decoder object. If an error has been caught, a NULL pointer
 is returned.
 
 The function \fBfiasco_decoder_write_frame()\fP returns 1 if the file
 has been successfully written. Otherwise, the function returns 0.
 
 The function \fBfiasco_decoder_get_frame()\fP returns a pointer to the
-newly allocated FIASCO image object. If an error has been catched, a NULL
+newly allocated FIASCO image object. If an error has been caught, a NULL
 pointer is returned.
 
 The function \fBfiasco_decoder_get_length()\fP returns the number of
-frames of the FIASCO file. If an error has been catched, 0 is
+frames of the FIASCO file. If an error has been caught, 0 is
 returned. 
 
 The function \fBfiasco_decoder_get_rate()\fP returns the
 framerate (number of frames per second) of the FIASCO file. If an
-error has been catched, 0 is returned.
+error has been caught, 0 is returned.
 
 The function \fBfiasco_decoder_get_width()\fP returns the width of the
-decoded frames of the FIASCO file. If an error has been catched, 0 is
+decoded frames of the FIASCO file. If an error has been caught, 0 is
 returned.
 
 The function \fBfiasco_decoder_get_height()\fP returns the height of the
-decoded frames of the FIASCO file. If an error has been catched, 0 is
+decoded frames of the FIASCO file. If an error has been caught, 0 is
 returned.
 
 The function \fBfiasco_decoder_get_title()\fP returns an optional
-title of the FIASCO file. If an error has been catched, 0 is returned.
+title of the FIASCO file. If an error has been caught, 0 is returned.
 
 The function \fBfiasco_decoder_get_comment()\fP returns an optional
-comment of the FIASCO file. If an error has been catched, 0 is returned.
+comment of the FIASCO file. If an error has been caught, 0 is returned.
 
 The function \fBfiasco_decoder_is_color()\fP returns 0 if the decoded
 frames are grayscale images, otherwise a non-zero value is
diff --git a/converter/other/fiasco/doc/fiasco_get_error_message.3 b/converter/other/fiasco/doc/fiasco_get_error_message.3
index ce53e6d9..da32c94e 100644
--- a/converter/other/fiasco/doc/fiasco_get_error_message.3
+++ b/converter/other/fiasco/doc/fiasco_get_error_message.3
@@ -3,7 +3,7 @@
 
 .SH NAME
 .B  fiasco_get_error_message
-\- return string describing last error catched in FIASCO library
+\- return string describing last error caught in FIASCO library
 
 .SH SYNOPSIS
 .B #include <fiasco.h>
@@ -15,11 +15,11 @@
 
 .SH DESCRIPTION
 The \fBfiasco_get_error_message()\fP function returns a string
-describing the last error that has been catched in the FIASCO library.
+describing the last error that has been caught in the FIASCO library.
 
 .SH RETURN VALUE
 The function \fBfiasco_get_error_message()\fP returns the appropriate
-description string, or an empty string if no error has been catched so
+description string, or an empty string if no error has been caught so
 far.
 
 .SH "SEE ALSO"
diff --git a/converter/other/fiasco/doc/fiasco_image_new.3 b/converter/other/fiasco/doc/fiasco_image_new.3
index ac3297bf..e4701a14 100644
--- a/converter/other/fiasco/doc/fiasco_image_new.3
+++ b/converter/other/fiasco/doc/fiasco_image_new.3
@@ -61,14 +61,14 @@ the environment variable \fBFIASCO_IMAGES\fP.
 
 .SH RETURN VALUE
 The function \fBfiasco_image_new()\fP returns a pointer to the newly
-allocated image object. If an error has been catched, a NULL pointer
+allocated image object. If an error has been caught, a NULL pointer
 is returned.
 
 The function \fBfiasco_image_get_width()\fP returns the width of the
-image. If an error has been catched, 0 is returned.
+image. If an error has been caught, 0 is returned.
 
 The function \fBfiasco_image_get_height()\fP returns the height of the
-image. If an error has been catched, 0 is returned.
+image. If an error has been caught, 0 is returned.
 
 The function \fBfiasco_image_is_color()\fP returns 0 if the image
 object is a grayscale image, otherwise a non-zero value is returned.
diff --git a/converter/other/fiasco/doc/fiasco_options_new.3 b/converter/other/fiasco/doc/fiasco_options_new.3
index f26586a7..884876c7 100644
--- a/converter/other/fiasco/doc/fiasco_options_new.3
+++ b/converter/other/fiasco/doc/fiasco_options_new.3
@@ -416,11 +416,11 @@ during coding. The following types are available:
 
 .SH RETURN VALUES
 The function \fBfiasco_decoder_new()\fP returns a pointer to the newly
-allocated option object. If an error has been catched, a NULL pointer
+allocated option object. If an error has been caught, a NULL pointer
 is returned.
 
 All set functions return 1 on success and 0 if an error has been
-catched.  
+caught.  
 
 In case of an error, use the function fiasco_get_error_message(3) to
 get a string with the last error message of FIASCO.
diff --git a/converter/other/fiasco/doc/fiasco_renderer_new.3 b/converter/other/fiasco/doc/fiasco_renderer_new.3
index 8b5e47cd..54bbdbcf 100644
--- a/converter/other/fiasco/doc/fiasco_renderer_new.3
+++ b/converter/other/fiasco/doc/fiasco_renderer_new.3
@@ -97,7 +97,7 @@ fiasco_image_new(3).
 
 .SH RETURN VALUE
 The function \fBfiasco_renderer_new()\fP returns a pointer to the newly
-allocated renderer object. If an error has been catched, a NULL pointer
+allocated renderer object. If an error has been caught, a NULL pointer
 is returned.
 
 The function \fBfiasco_renderer_render()\fP returns 1 if the image
diff --git a/converter/other/fiasco/input/basis.c b/converter/other/fiasco/input/basis.c
index aa371ea1..e5ced0d0 100644
--- a/converter/other/fiasco/input/basis.c
+++ b/converter/other/fiasco/input/basis.c
@@ -1,8 +1,8 @@
 /*
- *  basis.c:		WFA initial basis files	
+ *  basis.c:		WFA initial basis files
  *
  *  Written by:		Ullrich Hafner
- *		
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -44,29 +44,29 @@ typedef struct
 /*****************************************************************************
 
 				prototypes
-  
+
 *****************************************************************************/
 
 static void
 small_init (basis_values_t *bv);
 
-static basis_file_t const basis_files[] = { 
+static basis_file_t const basis_files[] = {
     {"small.fco", small_init},
     {"small.wfa", small_init},
-    {NULL, NULL} 
+    {NULL, NULL}
 };
 
 /*****************************************************************************
 
 				public code
-  
+
 *****************************************************************************/
 
 bool_t
 get_linked_basis (const char *basis_name, wfa_t *wfa)
 /*
- *  Check wether given WFA initial basis 'basis_name' is already linked
- *  with the excecutable. If the basis is available then fill the 'wfa' struct
+ *  Check whether given WFA initial basis 'basis_name' is already linked
+ *  with the executable. If the basis is available then fill the 'wfa' struct
  *  according to the stored data, otherwise print a warning message.
  *
  *  Return value:
@@ -79,18 +79,18 @@ get_linked_basis (const char *basis_name, wfa_t *wfa)
    bool_t	  success = NO;		/* indicates if basis is found */
    unsigned	  n;			/* counter */
    basis_values_t bv;			/* basis values */
-   
+
    for (n = 0; basis_files [n].filename != NULL; n++)
       if (streq (basis_files [n].filename, basis_name))	/* basis is stored */
       {
-	 unsigned state, edge;		
-	 
+	 unsigned state, edge;
+
 	 (*basis_files [n].function) (&bv); /* initialize local variables */
 	 /*
 	  *  Generate WFA
 	  */
 	 wfa->basis_states = wfa->states = bv.states + 1;
-	 wfa->domain_type[0]             = USE_DOMAIN_MASK; 
+	 wfa->domain_type[0]             = USE_DOMAIN_MASK;
 	 wfa->final_distribution[0]      = 128;
 	 append_edge (0, 0, 1.0, 0, wfa);
 	 append_edge (0, 0, 1.0, 1, wfa);
@@ -105,13 +105,13 @@ get_linked_basis (const char *basis_name, wfa_t *wfa)
 	    append_edge (bv.transitions [edge][0], bv.transitions [edge][1],
 			 bv.transitions [edge][2], bv.transitions [edge][3],
 			 wfa);
-	 
+
 	 success = YES;
 	 break;
       }
 
    if (!success)
-      warning ("WFA initial basis '%s' isn't linked with the excecutable yet."
+      warning ("WFA initial basis '%s' isn't linked with the executable yet."
 	       "\nLoading basis from disk instead.", basis_name);
 
    return success;
@@ -120,7 +120,7 @@ get_linked_basis (const char *basis_name, wfa_t *wfa)
 /*****************************************************************************
 
 				private code
-  
+
 *****************************************************************************/
 
 /*****************************************************************************
@@ -141,3 +141,6 @@ small_init (basis_values_t *bv)
    bv->use_domain  = use_domain_small;
    bv->transitions = transitions_small;
 }
+
+
+
diff --git a/converter/other/fiasco/input/matrices.c b/converter/other/fiasco/input/matrices.c
index 388855ea..d20a27eb 100644
--- a/converter/other/fiasco/input/matrices.c
+++ b/converter/other/fiasco/input/matrices.c
@@ -2,7 +2,7 @@
  *  matrices.c:		Input of transition matrices
  *
  *  Written by:		Ullrich Hafner
- *  
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -34,7 +34,7 @@
 /*****************************************************************************
 
 				prototypes
-  
+
 *****************************************************************************/
 
 static unsigned
@@ -49,19 +49,19 @@ compute_y_state (int state, int y_state, wfa_t *wfa);
 /*****************************************************************************
 
 				public code
-  
+
 *****************************************************************************/
 
 unsigned
 read_matrices (wfa_t *wfa, bitfile_t *input)
-/* 
+/*
  *  Read transitions of WFA given from the stream 'input'.
  *
  *  Return value:
  *	number of edges
  *
  *  Side effects:
- *	'wfa->into' is filled with decoded values 
+ *	'wfa->into' is filled with decoded values
  */
 {
    unsigned total;			/* total number of edges in the WFA */
@@ -73,14 +73,14 @@ read_matrices (wfa_t *wfa, bitfile_t *input)
    total += delta_decoding (wfa, root_state, input);
    if (wfa->wfainfo->color)
       total += chroma_decoding (wfa, input);
-       
+
    return total;
 }
 
 /*****************************************************************************
 
 				private code
-  
+
 *****************************************************************************/
 
 static unsigned
@@ -94,7 +94,7 @@ delta_decoding (wfa_t *wfa, unsigned last_domain, bitfile_t *input)
  *	number of non-zero matrix elements (WFA edges)
  *
  *  Side effects:
- *	'wfa->into' is filled with decoded values 
+ *	'wfa->into' is filled with decoded values
  */
 {
    range_sort_t	 rs;			/* ranges are sorted as in the coder */
@@ -128,26 +128,26 @@ delta_decoding (wfa_t *wfa, unsigned last_domain, bitfile_t *input)
       arith_t  *decoder;
       model_t  *elements;
       unsigned 	max_edges = read_rice_code (3, input);
-      
+
       /*
        *  Get the probability array of the number of edges distribution
        *  and allocate the corresponding model.
        */
       {
 	 unsigned edge;
-	 
+
 	 for (edge = 0; edge <= max_edges; edge++)
 	    count [edge] = read_rice_code ((int) log2 (last_domain) - 2,
 					   input);
 	 elements = alloc_model (max_edges + 1, 0, 0, count);
       }
-      
+
       /*
        *  Get number of elements per matrix row
        */
       {
 	 unsigned row;
-      
+
 	 n_edges = Calloc (wfa->states, sizeof (unsigned));
 	 decoder = alloc_decoder (input);
 	 for (row = range = 0; range < rs.range_no; range++)
@@ -155,17 +155,17 @@ delta_decoding (wfa_t *wfa, unsigned last_domain, bitfile_t *input)
 	    {
 	       state = rs.range_state [range];
 	       label = rs.range_label [range];
-	       
+
 	       n_edges [row++]
 		  = decode_symbol (decoder, elements)
 		  - (isedge (wfa->into [state][label][0]) ? 1 : 0);
 	    }
-	 
+
 	 free_decoder (decoder);
 	 free_model (elements);
       }
    }
-   
+
    /*
     *  Get matrix elements
     */
@@ -177,18 +177,18 @@ delta_decoding (wfa_t *wfa, unsigned last_domain, bitfile_t *input)
       u_word_t *mapping_coder2     = Calloc (wfa->states, sizeof (word_t));
       bool_t	use_normal_domains = get_bit (input);
       bool_t	use_delta_domains  = get_bit (input);
-	  
+
       /*
        *  Generate array of states which are admitted domains.
        *  When coding intra frames 'mapping1' == 'mapping2' otherwise
-       *  'mapping1' is a list of 'normal' domains which are admitted for 
+       *  'mapping1' is a list of 'normal' domains which are admitted for
        *             coding intra blocks
        *  'mapping2' is a list of 'delta' domains which are admitted for
-       *             coding the motion compensated prediction error 
+       *             coding the motion compensated prediction error
        */
       {
 	 unsigned n1, n2, state;
-	    
+
 	 for (n1 = n2 = state = 0; state < wfa->states; state++)
 	 {
 	    mapping1 [n1] = state;
@@ -197,7 +197,7 @@ delta_decoding (wfa_t *wfa, unsigned last_domain, bitfile_t *input)
 		&& (state < wfa->basis_states
 		    || use_delta_domains || !wfa->delta_state [state]))
 	       n1++;
-	    
+
 	    mapping2 [n2] = state;
 	    mapping_coder2 [state] = n2;
 	    if (usedomain (state, wfa)
@@ -206,7 +206,7 @@ delta_decoding (wfa_t *wfa, unsigned last_domain, bitfile_t *input)
 	       n2++;
 	 }
       }
-	 
+
       for (row = 0, range = 0; range < rs.range_no; range++)
 	 if (!rs.range_subdivided [range])
 	 {
@@ -249,7 +249,7 @@ delta_decoding (wfa_t *wfa, unsigned last_domain, bitfile_t *input)
       Free (mapping2);
       Free (mapping_coder2);
    }
-      
+
    Free (n_edges);
    Free (rs.range_state);
    Free (rs.range_label);
@@ -265,12 +265,12 @@ column_0_decoding (wfa_t *wfa, unsigned last_row, bitfile_t *input)
  *  Read column 0 of the transition matrices of the 'wfa' which are coded
  *  with quasi arithmetic coding from stream 'input'.
  *  All rows from 'wfa->basis_states' up to 'last_row' are decoded.
- * 
+ *
  *  Return value:
  *	number of non-zero matrix elements (WFA edges)
  *
  *  Side effects:
- *	'wfa->into' is filled with decoded values 
+ *	'wfa->into' is filled with decoded values
  */
 {
    unsigned  row;			/* current matrix row */
@@ -294,9 +294,9 @@ column_0_decoding (wfa_t *wfa, unsigned last_row, bitfile_t *input)
       unsigned n;
       unsigned index;			/* probability index */
       unsigned exp;			/* current exponent */
-      
+
       prob = Calloc (1 << (MAX_PROB + 1), sizeof (unsigned));
-   
+
       for (index = 0, n = MIN_PROB; n <= MAX_PROB; n++)
 	 for (exp = 0; exp < 1U << n; exp++, index++)
 	    prob [index] = n;
@@ -304,12 +304,12 @@ column_0_decoding (wfa_t *wfa, unsigned last_row, bitfile_t *input)
 
    first = prob_ptr = new_prob_ptr = prob;
    last  = first + 1020;
-   
+
    is_leaf = wfa->tree [wfa->basis_states]; /* use pointer arithmetics ... */
 
    high = HIGH;				/* 1.0 */
    low  = LOW;				/* 0.0 */
-   code = get_bits (input, 16);		
+   code = get_bits (input, 16);
 
    /*
     *  Decode column 0 with a quasi arithmetic coder (QAC).
@@ -325,7 +325,7 @@ column_0_decoding (wfa_t *wfa, unsigned last_row, bitfile_t *input)
    for (row = wfa->basis_states; row <= last_row; row++)
    {
       unsigned count;			/* value in the current interval */
-      
+
       /*
        *  Read label 0 element
        */
@@ -397,7 +397,7 @@ column_0_decoding (wfa_t *wfa, unsigned last_row, bitfile_t *input)
    INPUT_BYTE_ALIGN (input);
 
    Free (prob);
-   
+
    return total;
 }
 
@@ -411,7 +411,7 @@ chroma_decoding (wfa_t *wfa, bitfile_t *input)
  *	number of non-zero matrix elements (WFA edges)
  *
  *  Side effects:
- *	'wfa->into' is filled with decoded values 
+ *	'wfa->into' is filled with decoded values
  */
 {
    unsigned  domain;			/* current domain, counter */
@@ -425,7 +425,7 @@ chroma_decoding (wfa_t *wfa, bitfile_t *input)
    u_word_t  low;			/* End of the current code range */
    u_word_t  code;			/* The present input code value */
    word_t   *y_domains;			/* domain images corresponding to Y */
-   int	     save_index;		/* YES: store current probabilty */
+   int	     save_index;		/* YES: store current probability */
 
    /*
     *  Compute the asymmetric probability array
@@ -436,9 +436,9 @@ chroma_decoding (wfa_t *wfa, bitfile_t *input)
       unsigned n;
       unsigned index;			/* probability index */
       unsigned exp;			/* current exponent */
-      
+
       prob = Calloc (1 << (MAX_PROB + 1), sizeof (unsigned));
-   
+
       for (index = 0, n = MIN_PROB; n <= MAX_PROB; n++)
 	 for (exp = 0; exp < 1U << n; exp++, index++)
 	    prob [index] = n;
@@ -454,7 +454,7 @@ chroma_decoding (wfa_t *wfa, bitfile_t *input)
    y_domains = compute_hits (wfa->basis_states,
 			     wfa->tree [wfa->tree [wfa->root_state][0]][0],
 			     wfa->wfainfo->chroma_max_states, wfa);
-   
+
    first = prob_ptr = new_prob_ptr = prob;
    last  = first + 1020;
 
@@ -554,7 +554,7 @@ chroma_decoding (wfa_t *wfa, bitfile_t *input)
 		    wfa->tree [wfa->tree [wfa->root_state][0]][0], wfa);
    compute_y_state (wfa->tree [wfa->tree [wfa->root_state][1]][0],
 		    wfa->tree [wfa->tree [wfa->root_state][0]][0], wfa);
-   
+
    first = prob_ptr = new_prob_ptr = prob;
 
    /*
@@ -566,7 +566,7 @@ chroma_decoding (wfa_t *wfa, bitfile_t *input)
     */
    {
       unsigned 	row;
-      
+
       for (row = wfa->tree [wfa->tree [wfa->root_state][0]][0] + 1;
 	   row < wfa->states; row++)
       {
@@ -629,7 +629,7 @@ compute_y_state (int state, int y_state, wfa_t *wfa)
  */
 {
    unsigned label;
-   
+
    for (label = 0; label < MAXLABELS; label++)
       if (isrange (y_state))
 	 wfa->y_state [state][label] = RANGE;
@@ -640,5 +640,7 @@ compute_y_state (int state, int y_state, wfa_t *wfa)
 	    compute_y_state (wfa->tree [state][label],
 			     wfa->y_state [state][label], wfa);
       }
-      
+
 }
+
+
diff --git a/converter/other/fiasco/input/mc.c b/converter/other/fiasco/input/mc.c
index 2d4a073d..afc0c1c3 100644
--- a/converter/other/fiasco/input/mc.c
+++ b/converter/other/fiasco/input/mc.c
@@ -1,9 +1,9 @@
 /*
- *  mc.c:	Input of motion compensation	
+ *  mc.c:	Input of motion compensation
  *
  *  written by: Michael Unger
  *		Ullrich Hafner
- *		
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -32,10 +32,10 @@
 /*****************************************************************************
 
 			     local variables
-  
+
 *****************************************************************************/
 
-typedef struct huff_node 
+typedef struct huff_node
 {
    int		     code_index;	/* leaf if index >= 0 */
    struct huff_node *left;		/* follow if '0' bit read */
@@ -46,7 +46,7 @@ typedef struct huff_node
 /*****************************************************************************
 
 				prototypes
-  
+
 *****************************************************************************/
 
 static void
@@ -64,7 +64,7 @@ create_huff_node (huff_node_t *hn, int bits_processed);
 /*****************************************************************************
 
 				public code
-  
+
 *****************************************************************************/
 
 void
@@ -90,7 +90,7 @@ read_mc (frame_type_e frame_type, wfa_t *wfa, bitfile_t *input)
 /*****************************************************************************
 
 				private code
-  
+
 *****************************************************************************/
 
 static void
@@ -114,8 +114,8 @@ decode_mc_tree (frame_type_e frame_type, unsigned max_state,
 
    /*
     *  Traverse tree in breadth first order (starting at level
-    *  'wfa->wfainfo->p_max_level'). Use a queue to store the childs
-    *  of each node ('last' is the next free queue element).  
+    *  'wfa->wfainfo->p_max_level'). Use a queue to store the children
+    *  of each node ('last' is the next free queue element).
     */
    queue = Calloc (MAXSTATES, sizeof (unsigned));
    for (last = 0, state = wfa->basis_states; state < max_state; state++)
@@ -126,7 +126,7 @@ decode_mc_tree (frame_type_e frame_type, unsigned max_state,
    {
       unsigned label;			/* current label */
       unsigned current;			/* current node to process */
-      
+
       for (current = 0; current < last; current++)
 	 for (label = 0; label < MAXLABELS; label++)
 	 {
@@ -147,7 +147,7 @@ decode_mc_tree (frame_type_e frame_type, unsigned max_state,
 	    if (wfa->mv_tree [state][label].type == NONE &&
 		!isrange (wfa->tree [state][label]) &&
 		wfa->level_of_state [state] - 1 >=
-		(int) wfa->wfainfo->p_min_level) 
+		(int) wfa->wfainfo->p_min_level)
 	       queue [last++] = wfa->tree [state][label]; /* append child  */
 	 }
    }
@@ -155,7 +155,7 @@ decode_mc_tree (frame_type_e frame_type, unsigned max_state,
    {
       unsigned label;			/* current label */
       unsigned current;			/* current node to process */
-      
+
       for (current = 0; current < last; current++)
 	 for (label = 0; label < MAXLABELS; label++)
 	 {
@@ -172,18 +172,18 @@ decode_mc_tree (frame_type_e frame_type, unsigned max_state,
 	       wfa->mv_tree[state][label].type = NONE;
 	    else if (get_bit (input))	/* 01  */
 	       wfa->mv_tree[state][label].type = INTERPOLATED;
-	    else if (get_bit (input))	/* 001 */ 
+	    else if (get_bit (input))	/* 001 */
 	       wfa->mv_tree[state][label].type = BACKWARD;
-	    else			/* 000 */ 
+	    else			/* 000 */
 	       wfa->mv_tree[state][label].type = FORWARD;
 	    if (wfa->mv_tree[state][label].type == NONE &&
 		!isrange (wfa->tree[state][label]) &&
 		wfa->level_of_state[state] - 1
-		>= (int) wfa->wfainfo->p_min_level) 
+		>= (int) wfa->wfainfo->p_min_level)
 	       queue[last++] = wfa->tree[state][label]; /* append child  */
 	 }
    }
-   
+
    INPUT_BYTE_ALIGN (input);
    Free (queue);
 }
@@ -205,10 +205,10 @@ decode_mc_coords (unsigned max_state, wfa_t *wfa, bitfile_t *input)
    unsigned	       state;		/* current state */
    mv_t		      *mv;		/* current motion vector */
    static huff_node_t *huff_mv_root = NULL; /* root of huffman tree */
- 
+
    if (huff_mv_root == NULL)
       huff_mv_root = create_huff_tree ();
-   
+
    for (state = wfa->basis_states; state < max_state; state++)
       for (label = 0; label < MAXLABELS; label++)
       {
@@ -220,12 +220,12 @@ decode_mc_coords (unsigned max_state, wfa_t *wfa, bitfile_t *input)
 	    case FORWARD:
 	       mv->fx = get_mv (1, huff_mv_root, input);
 	       mv->fy = get_mv (1, huff_mv_root, input);
-	       break;	    
-	    case BACKWARD:	    
+	       break;
+	    case BACKWARD:
 	       mv->bx = get_mv (1, huff_mv_root, input);
 	       mv->by = get_mv (1, huff_mv_root, input);
-	       break;	    
-	    case INTERPOLATED:   
+	       break;
+	    case INTERPOLATED:
 	       mv->fx = get_mv (1, huff_mv_root, input);
 	       mv->fy = get_mv (1, huff_mv_root, input);
 	       mv->bx = get_mv (1, huff_mv_root, input);
@@ -236,11 +236,11 @@ decode_mc_coords (unsigned max_state, wfa_t *wfa, bitfile_t *input)
 
    INPUT_BYTE_ALIGN (input);
 }
- 
+
 static int
 get_mv (int f_code, huff_node_t *hn, bitfile_t *input)
-/* 
- *  Decode next motion vector component in bitstream 
+/*
+ *  Decode next motion vector component in bitstream
  *  by traversing the huffman tree.
  */
 {
@@ -256,7 +256,7 @@ get_mv (int f_code, huff_node_t *hn, bitfile_t *input)
 	 hn = hn->left;
    }
    vlc_code = hn->code_index - 16;
-   if (vlc_code == 0 || f_code == 1) 
+   if (vlc_code == 0 || f_code == 1)
       return vlc_code;
 
    vlc_code_magnitude = abs (vlc_code) - 1;
@@ -265,7 +265,7 @@ get_mv (int f_code, huff_node_t *hn, bitfile_t *input)
    else
       residual = get_bits (input, f_code - 1);
    diffvec = (vlc_code_magnitude << (f_code - 1)) + residual + 1;
-   
+
    return vlc_code > 0 ? diffvec : - diffvec;
 }
 
@@ -277,7 +277,7 @@ create_huff_tree (void)
 {
    unsigned	i;
    huff_node_t *huff_root = Calloc (1, sizeof (huff_node_t));
-   
+
    /*
     *  The nodes' index set contains indices of all codewords that are
     *  still decodable by traversing further down from the node.
@@ -318,7 +318,7 @@ create_huff_node (huff_node_t *hn, int bits_processed)
       if (code_len == bits_processed)	/* generate leaf */
       {
 	 hn->code_index = ind;
-	 Free (hn->left); 
+	 Free (hn->left);
 	 Free (hn->right);
 	 return;
       }
@@ -332,3 +332,6 @@ create_huff_node (huff_node_t *hn, int bits_processed)
    create_huff_node (hn->left, bits_processed + 1);
    create_huff_node (hn->right, bits_processed + 1);
 }
+
+
+
diff --git a/converter/other/fiasco/input/nd.c b/converter/other/fiasco/input/nd.c
index 52d48e61..129a150e 100644
--- a/converter/other/fiasco/input/nd.c
+++ b/converter/other/fiasco/input/nd.c
@@ -1,8 +1,8 @@
 /*
- *  nd.c:		Input of prediction tree	
+ *  nd.c:		Input of prediction tree
  *
  *  Written by:		Ullrich Hafner
- *		
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -31,7 +31,7 @@
 /*****************************************************************************
 
 				prototypes
-  
+
 *****************************************************************************/
 
 static void
@@ -42,7 +42,7 @@ decode_nd_tree (wfa_t *wfa, bitfile_t *input);
 /*****************************************************************************
 
 				public code
-  
+
 *****************************************************************************/
 
 void
@@ -56,7 +56,7 @@ read_nd (wfa_t *wfa, bitfile_t *input)
  */
 {
    unsigned total = decode_nd_tree (wfa, input);
-   
+
    if (total > 0)
       decode_nd_coefficients (total, wfa, input);
 }
@@ -64,7 +64,7 @@ read_nd (wfa_t *wfa, bitfile_t *input)
 /*****************************************************************************
 
 				private code
-  
+
 *****************************************************************************/
 
 static unsigned
@@ -106,7 +106,7 @@ decode_nd_tree (wfa_t *wfa, bitfile_t *input)
    {
       unsigned label;
 
-      if (wfa->level_of_state [next] > wfa->wfainfo->p_max_level + 1) 
+      if (wfa->level_of_state [next] > wfa->wfainfo->p_max_level + 1)
       {
 	 /*
 	  *  Nondetermismn is not allowed at levels larger than
@@ -114,7 +114,7 @@ decode_nd_tree (wfa_t *wfa, bitfile_t *input)
 	  */
 	 for (label = 0; label < MAXLABELS; label++)
 	    if (ischild (state = wfa->tree [next][label]))
-	       queue_append (queue, &state); /* continue with childs */
+	       queue_append (queue, &state); /* continue with children */
       }
       else if (wfa->level_of_state [next] > wfa->wfainfo->p_min_level)
       {
@@ -123,7 +123,7 @@ decode_nd_tree (wfa_t *wfa, bitfile_t *input)
 	    {
 	       unsigned count;		/* Current interval count */
 	       unsigned range;		/* Current interval range */
-	       
+
 	       count = (((code - low) + 1) * sum1 - 1) / ((high - low) + 1);
 	       if (count < sum0)
 	       {
@@ -192,7 +192,7 @@ decode_nd_tree (wfa_t *wfa, bitfile_t *input)
 static void
 decode_nd_coefficients (unsigned total, wfa_t *wfa, bitfile_t *input)
 /*
- *  Read #'total' weights of nondeterministic part of 'wfa'  
+ *  Read #'total' weights of nondeterministic part of 'wfa'
  *  of given 'input' stream.
  *  'frame' gives the current frame number.
  *
@@ -204,24 +204,24 @@ decode_nd_coefficients (unsigned total, wfa_t *wfa, bitfile_t *input)
 {
    unsigned *coefficients;		/* array of factors to encode */
    unsigned *ptr;			/* pointer to current factor */
-   
+
    /*
     *  Decode array of coefficients stored with arithmetic coding
     */
    {
       const int	scaling  = 50;		/* scaling factor of prob. model */
       unsigned  c_symbols = 1 << (wfa->wfainfo->dc_rpf->mantissa_bits + 1);
-      
+
       ptr = coefficients = decode_array (input, NULL, &c_symbols, 1,
 					 total, scaling);
    }
-   
+
    /*
     *  Fill 'wfa->weights' with decoded coefficients
     */
    {
       unsigned state, label;
-      
+
       for (state = wfa->basis_states; state < wfa->states; state++)
 	 for (label = 0; label < MAXLABELS; label++)
 	    if (ischild (wfa->tree [state][label])
@@ -235,3 +235,6 @@ decode_nd_coefficients (unsigned total, wfa_t *wfa, bitfile_t *input)
    }
    Free (coefficients);
 }
+
+
+
diff --git a/converter/other/fiasco/input/read.c b/converter/other/fiasco/input/read.c
index 9f4ac993..c3aa77a8 100644
--- a/converter/other/fiasco/input/read.c
+++ b/converter/other/fiasco/input/read.c
@@ -2,7 +2,7 @@
  *  read.c:		Input of WFA files
  *
  *  Written by:		Ullrich Hafner
- *  
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -47,7 +47,7 @@
 /*****************************************************************************
 
 				prototypes
-  
+
 *****************************************************************************/
 
 static void
@@ -57,7 +57,7 @@ read_tiling (tiling_t *tiling, unsigned image_width, unsigned image_height,
 /*****************************************************************************
 
 				public code
-  
+
 *****************************************************************************/
 
 bitfile_t *
@@ -69,14 +69,14 @@ open_wfa (const char *filename, wfa_info_t *wi)
  *	Pointer to input stream (fileposition: first WFA frame)
  *
  *  Side effects:
- *	The values of the header of 'filename' are copied to 'wfainfo'. 
+ *	The values of the header of 'filename' are copied to 'wfainfo'.
  *
  */
 {
    bitfile_t *input;			/* pointer to WFA bitfile */
-   
+
    assert (filename && wi);
-   
+
    wi->wfa_name = strdup (filename);
 
    /*
@@ -85,16 +85,16 @@ open_wfa (const char *filename, wfa_info_t *wi)
    {
       unsigned 	n;
       const char     *str;
-      
+
       if (!(input = open_bitfile (filename, "FIASCO_DATA", READ_ACCESS)))
           file_error (filename);
-   
+
       for (str = FIASCO_MAGIC, n = strlen (FIASCO_MAGIC); n; n--)
           if (get_bits (input, 8) != (unsigned) *str++)
               error ("Input file %s is not a valid FIASCO file!", filename);
       get_bits (input, 8);		/* fetch newline */
    }
-   
+
    /*
     *  Read WFA header information
     */
@@ -102,13 +102,13 @@ open_wfa (const char *filename, wfa_info_t *wi)
       char	      basis_name [MAXSTRLEN]; /* temp. buffer */
       const unsigned  rice_k = 8; 	/* parameter of Rice Code */
       char     	     *str    = basis_name;
-      
+
       while ((*str++ = get_bits (input, 8)) != 0
 	     && str < basis_name + MAXSTRLEN)
 	 ;
       if (str == basis_name + MAXSTRLEN)
 	 error ("Input file %s is not a valid FIASCO file!", filename);
-      
+
       {
 	 wi->release = read_rice_code (rice_k, input);
 
@@ -121,12 +121,12 @@ open_wfa (const char *filename, wfa_info_t *wi)
       if (wi->release > 1)
       {
 	 header_type_e type;
-	 
+
 	 while ((type = read_rice_code (rice_k, input)) != HEADER_END)
 	 {
 	    char     buffer [MAXSTRLEN];
 	    unsigned n = 0;
-	    
+
 	    switch (type)
 	    {
 	       case HEADER_TITLE:
@@ -157,7 +157,7 @@ open_wfa (const char *filename, wfa_info_t *wi)
       {
 	 unsigned lx = log2 (wi->width - 1) + 1;
 	 unsigned ly = log2 (wi->height - 1) + 1;
-      
+
 	 wi->level = MAX(lx, ly) * 2 - ((ly == lx + 1) ? 1 : 0);
       }
       wi->chroma_max_states = wi->color ? read_rice_code (rice_k, input) : -1;
@@ -176,14 +176,14 @@ open_wfa (const char *filename, wfa_info_t *wi)
 	 mantissa = get_bits (input, 3) + 2;
 	 range    = get_bits (input, 2);
 	 wi->rpf  = alloc_rpf (mantissa, range);
-	 
+
 	 if (get_bit (input))		/* different DC model */
 	 {
 	    mantissa   = get_bits (input, 3) + 2;
 	    range      = get_bits (input, 2);
 	    wi->dc_rpf = alloc_rpf (mantissa, range);
 	 }
-	 else				/* use same model for DC coefficents */
+	 else				/* use same model for DC coefficients */
 	    wi->dc_rpf = alloc_rpf (wi->rpf->mantissa_bits,
 				    wi->rpf->range_e);
 
@@ -196,7 +196,7 @@ open_wfa (const char *filename, wfa_info_t *wi)
 	 else
 	    wi->d_rpf = alloc_rpf (wi->rpf->mantissa_bits,
 				   wi->rpf->range_e);
-	 
+
 	 if (get_bit (input))		/* different DC delta model */
 	 {
 	    mantissa  	 = get_bits (input, 3) + 2;
@@ -216,7 +216,7 @@ open_wfa (const char *filename, wfa_info_t *wi)
 	 wi->B_as_past_ref = get_bit (input) ? YES : NO;
       }
    }
-   
+
    INPUT_BYTE_ALIGN (input);
 
    return input;
@@ -246,10 +246,10 @@ read_basis (const char *filename, wfa_t *wfa)
 	 Free (wfa->wfainfo->basis_name);
       wfa->wfainfo->basis_name = strdup (filename);
    }
-   
+
    if (get_linked_basis (filename, wfa))
-      return;				/* basis is linked with excecutable */
-   
+      return;				/* basis is linked with executable */
+
    /*
     *  Check whether 'wfa_name' is a regular ASCII WFA initial basis file
     */
@@ -258,19 +258,19 @@ read_basis (const char *filename, wfa_t *wfa)
 
       if (!(input = open_file (filename, "FIASCO_DATA", READ_ACCESS)))
 	 file_error(filename);
-      
+
       if (fscanf (input, MAXSTRLEN_SCANF, magic) != 1)
 	 error ("Format error: ASCII FIASCO initial basis file %s", filename);
-      else if (strneq (FIASCO_BASIS_MAGIC, magic))
+      else if (!streq (FIASCO_BASIS_MAGIC, magic))
 	 error ("Input file %s is not an ASCII FIASCO initial basis!",
 		filename);
    }
-   
+
    /*
     *  WFA ASCII format:
     *
     *  Note: State 0 is assumed to be the constant function f(x, y) = 128.
-    *        Don't define any transitions of state 0 in an initial basis. 
+    *        Don't define any transitions of state 0 in an initial basis.
     *
     *  Header:
     *   type		|description
@@ -307,14 +307,14 @@ read_basis (const char *filename, wfa_t *wfa)
       /*
        *  State 0 is assumed to be the constant function f(x, y) = 128.
        */
-      wfa->domain_type [0]        = USE_DOMAIN_MASK; 
+      wfa->domain_type [0]        = USE_DOMAIN_MASK;
       wfa->final_distribution [0] = 128;
       wfa->states 		  = wfa->basis_states;
       wfa->basis_states++;
 
       append_edge (0, 0, 1.0, 0, wfa);
       append_edge (0, 0, 1.0, 1, wfa);
-   
+
       for (state = 1; state < wfa->basis_states; state++)
 	 wfa->domain_type [state]
 	    = read_int (input) ? USE_DOMAIN_MASK : AUXILIARY_MASK;
@@ -343,7 +343,7 @@ read_basis (const char *filename, wfa_t *wfa)
 	 }
       }
    }
-   
+
    fclose (input);
 }
 
@@ -353,7 +353,7 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input)
  *  Read next WFA frame of the WFA stream 'input'.
  *  WFA header information has to be already present in the 'wfainfo' struct.
  *  (i.e. open_wfa must be called first!)
- *  
+ *
  *  No return value.
  *
  *  Side effects:
@@ -364,9 +364,9 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input)
 {
    tiling_t tiling;			/* tiling information */
    unsigned frame_number;		/* current frame number */
-   
+
    assert (wfa && input);
-   
+
    /*
     *  Frame header information
     */
@@ -382,16 +382,16 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input)
    {
       INPUT_BYTE_ALIGN (input);
    }
-   
+
    /*
-    *  Read image tiling info 
+    *  Read image tiling info
     */
    if (get_bit (input))			/* tiling performed ? */
       read_tiling (&tiling, wfa->wfainfo->width, wfa->wfainfo->height,
 		   wfa->wfainfo->level, input);
    else
       tiling.exponent = 0;
-   
+
    INPUT_BYTE_ALIGN (input);
 
    read_tree (wfa, &tiling, input);
@@ -402,7 +402,7 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input)
     */
    {
       unsigned state;
-   
+
       for (state = wfa->basis_states; state < wfa->states; state++)
 	 if ((!wfa->wfainfo->color
 	      || (int) state <= wfa->tree [wfa->tree [wfa->root_state][0]][0])
@@ -420,7 +420,7 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input)
 	 else
 	    wfa->domain_type [state] = 0;
    }
-   
+
    if (tiling.exponent)
       Free (tiling.vorder);
 
@@ -431,12 +431,12 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input)
       read_mc (wfa->frame_type, wfa, input);
 
    locate_delta_images (wfa);
-   
+
    /*
     *  Read linear combinations (coefficients and indices)
     */
    {
-      unsigned edges = read_matrices (wfa, input); 
+      unsigned edges = read_matrices (wfa, input);
 
       if (edges)
 	 read_weights (edges, wfa, input);
@@ -447,7 +447,7 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input)
     */
    {
       unsigned state;
-   
+
       for (state = wfa->basis_states; state <= wfa->states; state++)
 	 wfa->final_distribution[state]
 	    = compute_final_distribution (state, wfa);
@@ -459,7 +459,7 @@ read_next_wfa (wfa_t *wfa, bitfile_t *input)
 /*****************************************************************************
 
 				private code
-  
+
 *****************************************************************************/
 
 static void
@@ -468,14 +468,14 @@ read_tiling (tiling_t *tiling, unsigned image_width, unsigned image_height,
 /*
  *  Read image tiling information from the given file 'input'
  *  and store parameters in struct 'tiling'.
- *  
+ *
  *  No return value.
  */
 {
    const unsigned rice_k = 8;		/* parameter of Rice Code */
-   
+
    tiling->exponent = read_rice_code (rice_k, input);
-   
+
    if (get_bit (input))			/* variance order */
    {
       unsigned tile;			/* current image tile */
@@ -487,7 +487,7 @@ read_tiling (tiling_t *tiling, unsigned image_width, unsigned image_height,
       {
 	 locate_subimage (image_level, image_level - tiling->exponent, tile,
 			  &x0, &y0, &width, &height);
-	 if (x0 < image_width && y0 < image_height) 
+	 if (x0 < image_width && y0 < image_height)
 	    tiling->vorder [tile] = get_bits (input, tiling->exponent);
 	 else
 	    tiling->vorder [tile] = -1;
@@ -500,3 +500,6 @@ read_tiling (tiling_t *tiling, unsigned image_width, unsigned image_height,
 		      tiling->exponent, get_bit (input) ? YES : NO);
    }
 }
+
+
+
diff --git a/converter/other/fiasco/input/tree.c b/converter/other/fiasco/input/tree.c
index 0ac2b6ae..74ceeb68 100644
--- a/converter/other/fiasco/input/tree.c
+++ b/converter/other/fiasco/input/tree.c
@@ -2,7 +2,7 @@
  *  tree.c:		Input of bintree partitioning
  *
  *  Written by:		Ullrich Hafner
- *		
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -31,7 +31,7 @@
 /*****************************************************************************
 
 				prototypes
-  
+
 *****************************************************************************/
 
 static unsigned
@@ -39,14 +39,14 @@ restore_depth_first_order (unsigned src_state, unsigned level, unsigned x,
 			   unsigned y, unsigned *dst_state,
 			   word_t (*bfo_tree)[MAXLABELS],
 			   wfa_t *wfa, tiling_t *tiling);
-static void 
+static void
 decode_tree (bitfile_t *input, byte_t *data, unsigned n_data, unsigned scaling,
 	     u_word_t sum0, u_word_t sum1);
 
 /*****************************************************************************
 
 				public code
-  
+
 *****************************************************************************/
 
 void
@@ -64,7 +64,7 @@ read_tree (wfa_t *wfa, tiling_t *tiling, bitfile_t *input)
 {
    byte_t *bitstring;			/* the encoded data */
    word_t (*bfo_tree)[MAXLABELS];	/* node numbers in BFO */
-      
+
    /*
     *  Read WFA tree stored in breadth first order
     */
@@ -75,7 +75,7 @@ read_tree (wfa_t *wfa, tiling_t *tiling, bitfile_t *input)
       bitstring = Calloc (total, sizeof (byte_t));
       decode_tree (input, bitstring, total, scale, 1, 11);
    }
-   
+
    /*
     *  Generate tree using a breadth first traversal
     */
@@ -84,7 +84,7 @@ read_tree (wfa_t *wfa, tiling_t *tiling, bitfile_t *input)
       unsigned 	state;
       unsigned 	label;
       byte_t   *buffer = bitstring;	/* pointer to decoded data */
-      
+
       bfo_tree = Calloc (wfa->states * MAXLABELS, sizeof (word_t));
       for (state = 0, next = 1; state < next; state++)
 	 for (label = 0; label < MAXLABELS; label++)
@@ -110,7 +110,7 @@ read_tree (wfa_t *wfa, tiling_t *tiling, bitfile_t *input)
 /*****************************************************************************
 
 				private code
-  
+
 *****************************************************************************/
 
 static unsigned
@@ -119,13 +119,13 @@ restore_depth_first_order (unsigned src_state, unsigned level, unsigned x,
 			   word_t (*bfo_tree)[MAXLABELS],
 			   wfa_t *wfa, tiling_t *tiling)
 /*
- *  Map state 'src_state' (breadth first order) 
+ *  Map state 'src_state' (breadth first order)
  *  to state '*dst_state' (depth first order)
  *  Add a tree edge 'state' --> 'child' with label and weight 1.0
  *  if required.
  *  'x', 'y' give the coordinates of the current state in the 'color' image
- *  of size 'image_level'. 'tiling' defines the image partitioning. 
- *  
+ *  of size 'image_level'. 'tiling' defines the image partitioning.
+ *
  *  Return value:
  *	new node number in depth first order
  *
@@ -134,8 +134,8 @@ restore_depth_first_order (unsigned src_state, unsigned level, unsigned x,
  *      are filled with decoded values.
  */
 {
-   unsigned newx [MAXLABELS];		/* x coordinate of childs */
-   unsigned newy [MAXLABELS];		/* y coordinate of childs */
+   unsigned newx [MAXLABELS];		/* x coordinate of children */
+   unsigned newy [MAXLABELS];		/* y coordinate of children */
    unsigned x0, y0;			/* NW corner of image tile */
    unsigned width, height;		/* size of image tile */
 
@@ -145,7 +145,7 @@ restore_depth_first_order (unsigned src_state, unsigned level, unsigned x,
    if (tiling->exponent && level == wfa->wfainfo->level - tiling->exponent)
    {
       unsigned tile;
-      
+
       for (tile = 0; tile < 1U << tiling->exponent; tile++)
       {
 	 locate_subimage (wfa->wfainfo->level, level, tile,
@@ -159,7 +159,7 @@ restore_depth_first_order (unsigned src_state, unsigned level, unsigned x,
       }
    }
    /*
-    *  Coordinates of childs 0 and 1
+    *  Coordinates of children 0 and 1
     */
    if (wfa->wfainfo->color && level == wfa->wfainfo->level + 1)
       newx[0] = newy[0] = newx[1] = newy[1] = 0;
@@ -170,12 +170,12 @@ restore_depth_first_order (unsigned src_state, unsigned level, unsigned x,
       newx[1] = level & 1 ? x : x + width_of_level (level - 1);
       newy[1] = level & 1 ? y + height_of_level (level - 1) : y;
    }
-   
+
    /*
     *  Remap node numbers
     */
    {
-      int      child [MAXLABELS];	/* childs of current node (state) */
+      int      child [MAXLABELS];	/* children of current node (state) */
       int      domain;			/* current domain */
       unsigned label;
 
@@ -196,17 +196,17 @@ restore_depth_first_order (unsigned src_state, unsigned level, unsigned x,
       }
       wfa->level_of_state [*dst_state] = level;
    }
-   
+
    return (*dst_state)++;
-}	
+}
 
 /****************************************************************************
 
                  Binary adaptive arithmetic compression
- 
+
 ****************************************************************************/
 
-static void 
+static void
 decode_tree (bitfile_t *input, byte_t *data, unsigned n_data, unsigned scaling,
 	     u_word_t sum0, u_word_t sum1)
 /*
@@ -235,11 +235,11 @@ decode_tree (bitfile_t *input, byte_t *data, unsigned n_data, unsigned scaling,
    low  = 0;
    high = 0xffff;
 
-   for (n = n_data; n; n--) 
+   for (n = n_data; n; n--)
    {
       unsigned count;			/* Current interval count */
       unsigned range;			/* Current interval range */
-      
+
       count = (((code - low) + 1) * sum1 - 1) / ((high - low) + 1);
       if (count < sum0)
       {
diff --git a/converter/other/fiasco/lib/arith.c b/converter/other/fiasco/lib/arith.c
index 825d4757..e61e753e 100644
--- a/converter/other/fiasco/lib/arith.c
+++ b/converter/other/fiasco/lib/arith.c
@@ -2,7 +2,7 @@
  *  arith.c:		Adaptive arithmetic coding and decoding
  *
  *  Written by:		Ullrich Hafner
- *  
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -27,7 +27,7 @@
 /******************************************************************************
 
 				public code
-  
+
 ******************************************************************************/
 
 arith_t *
@@ -35,7 +35,7 @@ alloc_encoder (bitfile_t *output)
 /*
  *  Arithmetic coder constructor:
  *  Initialize the arithmetic coder.
- *  
+ *
  *  Return value:
  *	A pointer to the new coder structure
  */
@@ -43,7 +43,7 @@ alloc_encoder (bitfile_t *output)
    arith_t *arith = Calloc (1, sizeof (arith_t));
 
    assert (output);
-   
+
    arith->low       = LOW;
    arith->high      = HIGH;
    arith->underflow = 0;
@@ -58,7 +58,7 @@ free_encoder (arith_t *arith)
  *  Arithmetic encoder destructor.
  *  Flush the arithmetic coder. Append all remaining bits to the
  *  output stream. Append zero bits to get the output file byte aligned.
- *  
+ *
  *  No return value.
  */
 {
@@ -66,14 +66,14 @@ free_encoder (arith_t *arith)
    u_word_t   high;			/* end of the current code range    */
    u_word_t   underflow;		/* number of underflow bits pending */
    bitfile_t *output;
-   
+
    assert (arith);
 
    low       = arith->low;
    high      = arith->high;
    underflow = arith->underflow;
    output    = arith->file;
-   
+
    low = high;
 
    RESCALE_OUTPUT_INTERVAL;
@@ -92,7 +92,7 @@ encode_symbol (unsigned symbol, arith_t *arith, model_t *model)
  *
  *  The model is updated after encoding the symbol (if necessary the
  *  symbol counts are rescaled).
- *  
+ *
  *  Return value:
  *	information content of the encoded symbol.
  *
@@ -110,7 +110,7 @@ encode_symbol (unsigned symbol, arith_t *arith, model_t *model)
    u_word_t   high;			/* end of the current code range    */
    u_word_t   underflow;		/* number of underflow bits pending */
    bitfile_t *output;			/* output file */
-   
+
    assert (model && arith);
 
    /*
@@ -122,7 +122,7 @@ encode_symbol (unsigned symbol, arith_t *arith, model_t *model)
    output    = arith->file;
 
    assert (high > low);
-   
+
    if (model->order > 0)		/* order-'n' model*/
    {
       unsigned power;			/* multiplicator */
@@ -134,10 +134,10 @@ encode_symbol (unsigned symbol, arith_t *arith, model_t *model)
        */
       power = 1;			/* multiplicator */
       index = 0;			/* address of prob. model */
-	 
-      for (i = 0; i < model->order; i++) /* genarate a M-nary number */
+
+      for (i = 0; i < model->order; i++) /* generate a M-nary number */
       {
-	 index += model->context [i] * power;	
+	 index += model->context [i] * power;
 	 power *= model->symbols;
       }
 
@@ -160,9 +160,9 @@ encode_symbol (unsigned symbol, arith_t *arith, model_t *model)
    range = (high - low) + 1;
    high  = low + (u_word_t) ((range * high_count) / scale - 1);
    low   = low + (u_word_t) ((range * low_count) / scale);
-   
+
    RESCALE_OUTPUT_INTERVAL;
-   
+
    if (model->scale > 0)		/* adaptive model */
    {
       unsigned i;
@@ -189,7 +189,7 @@ encode_symbol (unsigned symbol, arith_t *arith, model_t *model)
    arith->low  	    = low;
    arith->high 	    = high;
    arith->underflow = underflow;
-   
+
    return - log2 ((high_count - low_count) / (real_t) scale);
 }
 
@@ -214,21 +214,21 @@ encode_array (bitfile_t *output, const unsigned *data, const unsigned *context,
 
    assert (output && c_symbols && data);
    assert (n_context == 1 || context);
-   
+
    /*
     *  Allocate probability models, start with uniform distribution
     */
    totals = Calloc (n_context, sizeof (u_word_t *));
    {
       unsigned c;
-      
+
       for (c = 0; c < n_context; c++)
       {
 	 unsigned i;
-      
+
 	 totals [c]    = Calloc (c_symbols [c] + 1, sizeof (u_word_t));
 	 totals [c][0] = 0;
-      
+
 	 for (i = 0; i < c_symbols [c]; i++)
 	    totals [c][i + 1] = totals [c][i] + 1;
       }
@@ -242,7 +242,7 @@ encode_array (bitfile_t *output, const unsigned *data, const unsigned *context,
       u_word_t high 	 = 0xffff;	/* End of the current code range */
       u_word_t underflow = 0;		/* Number of underflow bits pending */
       unsigned n;
-      
+
       for (n = 0; n < n_data; n++)
       {
 	 u_word_t low_count;		/* lower bound of 'symbol' interval */
@@ -253,8 +253,8 @@ encode_array (bitfile_t *output, const unsigned *data, const unsigned *context,
 	 int	  c;			/* context of current data symbol */
 
 	 d = data [n];
-	 c = n_context > 1 ? context [n] : 0; 
-      
+	 c = n_context > 1 ? context [n] : 0;
+
 	 scale	    = totals [c][c_symbols [c]];
 	 low_count  = totals [c][d];
 	 high_count = totals [c][d + 1];
@@ -266,7 +266,7 @@ encode_array (bitfile_t *output, const unsigned *data, const unsigned *context,
 	 high  = low + (u_word_t) ((range * high_count) / scale - 1);
 	 low   = low + (u_word_t) ((range * low_count) / scale);
 	 RESCALE_OUTPUT_INTERVAL;
-      
+
 	 /*
 	  *  Update probability models
 	  */
@@ -275,7 +275,7 @@ encode_array (bitfile_t *output, const unsigned *data, const unsigned *context,
 
 	    for (i = d + 1; i < c_symbols [c] + 1; i++)
 	       totals [c][i]++;
-	 
+
 	    if (totals [c][c_symbols [c]] > scaling) /* scaling */
 	       for (i = 1; i < c_symbols [c] + 1; i++)
 	       {
@@ -292,7 +292,7 @@ encode_array (bitfile_t *output, const unsigned *data, const unsigned *context,
       RESCALE_OUTPUT_INTERVAL;
       OUTPUT_BYTE_ALIGN (output);
    }
-   
+
    /*
     *  Cleanup ...
     */
@@ -310,16 +310,16 @@ alloc_decoder (bitfile_t *input)
  *  Arithmetic decoder constructor:
  *  Initialize the arithmetic decoder with the first
  *  16 input bits from the stream 'input'.
- *  
+ *
  *  Return value:
  *	A pointer to the new decoder structure
  */
 
 {
    arith_t *arith = Calloc (1, sizeof (arith_t));
-   
+
    assert (input);
-   
+
    arith->low  = LOW;
    arith->high = HIGH;
    arith->code = get_bits (input, 16);
@@ -333,8 +333,8 @@ free_decoder (arith_t *arith)
 /*
  *  Arithmetic decoder destructor:
  *  Flush the arithmetic decoder, i.e., read bits to get the input
- *  file byte aligned. 
- *  
+ *  file byte aligned.
+ *
  *  No return value.
  *
  *  Side effects:
@@ -354,8 +354,8 @@ decode_symbol (arith_t *arith, model_t *model)
  *  Decode the next symbol - the state of the arithmetic decoder
  *  is given in 'arith'. Read refinement bits from the stream 'input'
  *  and use the given probability 'model'. Update the probability model after
- *  deconding the symbol (if necessary also rescale the symbol counts).
- *  
+ *  decoding the symbol (if necessary also rescale the symbol counts).
+ *
  *  Return value:
  *	decoded symbol
  *
@@ -375,7 +375,7 @@ decode_symbol (arith_t *arith, model_t *model)
    bitfile_t *input;			/* input file */
 
    assert (arith && model);
-   
+
    /*
     * Get interval values
     */
@@ -385,22 +385,22 @@ decode_symbol (arith_t *arith, model_t *model)
    input = arith->file;
 
    assert (high > low);
-   
+
    if (model->order > 0)		/* order-'n' model */
    {
       unsigned power;			/* multiplicator */
       unsigned i;
-      
+
       /*
        *  Compute index of the probability model to use.
        *  See init_model() for more details.
        */
       power = 1;			/* multiplicator */
       index = 0;			/* address of prob. model */
-	 
-      for (i = 0; i < model->order; i++) /* genarate a m-nary number */
+
+      for (i = 0; i < model->order; i++) /* generate a m-nary number */
       {
-	 index += model->context[i] * power;	
+	 index += model->context[i] * power;
 	 power *= model->symbols;
       }
 
@@ -420,7 +420,7 @@ decode_symbol (arith_t *arith, model_t *model)
    if (model->order > 0)		/* order-'n' model */
    {
       unsigned i;
-      
+
       for (i = 0; i < model->order - 1; i++)
 	 model->context [i] = model->context [i + 1];
       model->context [i] = symbol;
@@ -432,15 +432,15 @@ decode_symbol (arith_t *arith, model_t *model)
    {
       u_word_t low_count;		/* lower bound of 'symbol' interval */
       u_word_t high_count;		/* upper bound of 'symbol' interval */
-      
+
       low_count  = model->totals [index + symbol];
       high_count = model->totals [index + symbol + 1];
       high       = low + (u_word_t) ((range * high_count) / scale - 1 );
       low        = low + (u_word_t) ((range * low_count) / scale );
    }
-   
+
    RESCALE_INPUT_INTERVAL;
-   
+
    if (model->scale > 0)		/* adaptive model */
    {
       unsigned i;
@@ -460,7 +460,7 @@ decode_symbol (arith_t *arith, model_t *model)
 	 }
       }
    }
-   
+
    /*
     *  Store interval values
     */
@@ -488,28 +488,28 @@ decode_array (bitfile_t *input, const unsigned *context,
 {
    unsigned  *data;			/* array to store decoded symbols */
    u_word_t **totals;			/* probability model */
-   
+
    if (n_context < 1)
       n_context = 1;			/* always use one context */
    assert (input && c_symbols);
    assert (n_context == 1 || context);
 
    data = Calloc (n_data, sizeof (unsigned));
-   
+
    /*
     *  Allocate probability models, start with uniform distribution
     */
    totals = Calloc (n_context, sizeof (u_word_t *));
    {
       unsigned c;
-      
+
       for (c = 0; c < n_context; c++)
       {
 	 unsigned i;
-      
+
 	 totals [c]    = Calloc (c_symbols [c] + 1, sizeof (u_word_t));
 	 totals [c][0] = 0;
-      
+
 	 for (i = 0; i < c_symbols [c]; i++)
 	    totals [c][i + 1] = totals [c][i] + 1;
       }
@@ -523,8 +523,8 @@ decode_array (bitfile_t *input, const unsigned *context,
       u_word_t low  = 0;		/* Start of the current code range */
       u_word_t high = 0xffff;		/* End of the current code range */
       unsigned n;
-      
-      for (n = 0; n < n_data; n++) 
+
+      for (n = 0; n < n_data; n++)
       {
 	 u_word_t scale;		/* range of all 'm' symbol intervals */
 	 u_word_t low_count;		/* lower bound of 'symbol' interval */
@@ -534,13 +534,13 @@ decode_array (bitfile_t *input, const unsigned *context,
 	 unsigned d;			/* current data symbol */
 	 unsigned c;			/* context of current data symbol */
 
-	 c = n_context > 1 ? context [n] : 0; 
+	 c = n_context > 1 ? context [n] : 0;
 
 	 assert (high > low);
 	 scale = totals [c][c_symbols [c]];
 	 range = (high - low) + 1;
 	 count = (((code - low) + 1 ) * scale - 1) / range;
-      
+
 	 for (d = c_symbols [c]; count < totals [c][d]; d--) /* next symbol */
 	    ;
 	 low_count  = totals [c][d];
@@ -558,7 +558,7 @@ decode_array (bitfile_t *input, const unsigned *context,
 
 	    for (i = d + 1; i < c_symbols [c] + 1; i++)
 	       totals [c][i]++;
-	 
+
 	    if (totals [c][c_symbols [c]] > scaling) /* scaling */
 	       for (i = 1; i < c_symbols [c] + 1; i++)
 	       {
@@ -577,12 +577,12 @@ decode_array (bitfile_t *input, const unsigned *context,
     */
    {
       unsigned c;
-      
+
       for (c = 0; c < n_context; c++)
 	 Free (totals [c]);
       Free (totals);
    }
-   
+
    return data;
 }
 
@@ -600,10 +600,10 @@ alloc_model (unsigned m, unsigned scale, unsigned n, unsigned *totals)
  *
  *  Return value:
  *	a pointer to the new probability model structure.
- *  
+ *
  *  Note: We recommend a small size of the alphabet because no escape codes
  *  are used to encode/decode previously unseen symbols.
- *  
+ *
  */
 {
    model_t  *model;			/* new probability model */
@@ -621,7 +621,7 @@ alloc_model (unsigned m, unsigned scale, unsigned n, unsigned *totals)
    model->order   = n;
    model->context = n > 0 ? Calloc (n, sizeof (unsigned)) : NULL;
    /*
-    *  Allocate memory for the probabilty model.
+    *  Allocate memory for the probability model.
     *  Each of the m^n different contexts requires its own probability model.
     */
    for (num = 1, i = 0; i < model->order; i++)
@@ -644,17 +644,17 @@ alloc_model (unsigned m, unsigned scale, unsigned n, unsigned *totals)
        */
       power = 1;			/* multiplicator */
       index = 0;			/* address of prob. model */
-	 
-      for (i = 0; i < model->order; i++)	/* genarate a m-nary number */
+
+      for (i = 0; i < model->order; i++)	/* generate a m-nary number */
       {
-	 index += model->context[i] * power;	
+	 index += model->context[i] * power;
 	 power *= model->symbols;
       }
 
       index *= model->symbols + 1;	/* size of each model is m + 1 */
 
       model->totals [index + 0] = 0;	/* always zero */
-	 
+
       for (i = 1; i <= model->symbols; i++) /* prob of each symbol is 1/m or
 					       as given in totals */
 	 model->totals[index + i] = model->totals [index + i - 1]
@@ -667,14 +667,14 @@ alloc_model (unsigned m, unsigned scale, unsigned n, unsigned *totals)
 	 {
 	    dec = NO;
 	    model->context[i]++;
-	    if (model->context[i] >= model->symbols) 
+	    if (model->context[i] >= model->symbols)
 	    {
 	       /* change previous context */
 	       model->context[i] = 0;
 	       if (i > 0)		/* there's still a context remaining */
 		  dec = YES;
 	       else
-		  cont = NO;		/* all context models initilized */
+		  cont = NO;		/* all context models initialized */
 	    }
 	 }
    }
diff --git a/converter/other/fiasco/lib/bit-io.c b/converter/other/fiasco/lib/bit-io.c
index f69343e6..04716f05 100644
--- a/converter/other/fiasco/lib/bit-io.c
+++ b/converter/other/fiasco/lib/bit-io.c
@@ -1,12 +1,12 @@
 /*
- *  bit-io.c:       Buffered and bit oriented file I/O 
+ *  bit-io.c:       Buffered and bit oriented file I/O
  *
  *  Written by:     Ullrich Hafner
- *  
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
- 
+
 /*
  *  $Date: 2000/06/14 20:49:37 $
  *  $Author: hafner $
@@ -35,7 +35,7 @@
 /*****************************************************************************
 
                  local constants
-  
+
 *****************************************************************************/
 
 static const unsigned BUFFER_SIZE = 16350;
@@ -48,7 +48,7 @@ static const unsigned mask[] = {0x0001, 0x0002, 0x0004, 0x0008,
 /*****************************************************************************
 
                 public code
-  
+
 *****************************************************************************/
 
 FILE *
@@ -57,7 +57,7 @@ open_file (const char *filename, const char *env_var, openmode_e mode)
  *  Try to open file 'filename' with mode 'mode' (READ_ACCESS, WRITE_ACCESS).
  *  Scan the current directory first and then cycle through the
  *  path given in the environment variable 'env_var', if set.
- * 
+ *
  *  Return value:
  *  Pointer to open file on success, else NULL.
  */
@@ -81,42 +81,42 @@ open_file (const char *filename, const char *env_var, openmode_e mode)
     {
         if (mode == READ_ACCESS)
             return stdin;
-        else 
+        else
             return stdout;
     }
-   
+
     /*
      *  Try to open 'readonly' file in the current directory
      */
     if (mode == READ_ACCESS && (fp = fopen (filename, read_mode)))
-        return fp; 
+        return fp;
 
     if (mode == WRITE_ACCESS && strchr (filename, '/')) /* contains path */
         return fopen (filename, write_mode);
-   
+
     /*
      *  Get value of environment variable 'env_var', if set
      *  else use DEFAULT_PATH ("./")
      */
     if (env_var != NULL)
         env_path = getenv (env_var);
-    if (env_path == NULL) 
+    if (env_path == NULL)
         env_path = strdup (DEFAULT_PATH);
     else
         env_path = strdup (env_path);
-   
+
     /*
      *  Try to open file in the directory given by the environment
-     *  variable env_var - individual path components are separated by PATH_SEP 
+     *  variable env_var - individual path components are separated by PATH_SEP
      */
     path = strtok (env_path, PATH_SEP);
-    do 
+    do
     {
-        if (ext_filename) 
+        if (ext_filename)
             Free (ext_filename);
         ext_filename =  Calloc (strlen (path) + strlen (filename) + 2,
                                 sizeof (char));
-        strcpy (ext_filename, path); 
+        strcpy (ext_filename, path);
         if (*(ext_filename + strlen (ext_filename) - 1) != '/')
             strcat (ext_filename, "/");
         strcat (ext_filename, filename);
@@ -125,7 +125,7 @@ open_file (const char *filename, const char *env_var, openmode_e mode)
     while (fp == NULL && (path = strtok (NULL, PATH_SEP)) != NULL);
 
     Free (env_path);
-   
+
     return fp;
 }
 
@@ -143,7 +143,7 @@ open_bitfile (const char *filename, const char *env_var, openmode_e mode)
  */
 {
     bitfile_t *bitfile = Calloc (1, sizeof (bitfile_t));
-   
+
     bitfile->file = open_file (filename, env_var, mode);
 
     if (bitfile->file == NULL)
@@ -164,8 +164,8 @@ open_bitfile (const char *filename, const char *env_var, openmode_e mode)
         bitfile->filename = filename ? strdup (filename) : strdup ("(stdout)");
     }
     else
-        error ("Unknow file access mode '%d'.", mode);
-   
+        error ("Unknown file access mode '%d'.", mode);
+
     bitfile->bits_processed = 0;
     bitfile->buffer         = Calloc (BUFFER_SIZE, sizeof (byte_t));
     bitfile->ptr            = bitfile->buffer;
@@ -187,7 +187,7 @@ get_bit (bitfile_t *bitfile)
  */
 {
     assert (bitfile);
-   
+
     if (!bitfile->bitpos--)      /* use next byte ? */
     {
         bitfile->ptr++;
@@ -226,7 +226,7 @@ get_bits (bitfile_t *bitfile, unsigned bits)
  */
 {
     unsigned value = 0;          /* input value */
-   
+
     while (bits--)
         value = (unsigned) (value << 1) | get_bit (bitfile);
 
@@ -235,7 +235,7 @@ get_bits (bitfile_t *bitfile, unsigned bits)
 
 void
 put_bit (bitfile_t *bitfile, unsigned value)
-/*     
+/*
  *  Put the bit 'value' to the bitfile buffer.
  *  The buffer is written to the file 'bitfile->file' if the number of
  *  buffer bytes exceeds 'BUFFER_SIZE'.
@@ -247,7 +247,7 @@ put_bit (bitfile_t *bitfile, unsigned value)
  */
 {
     assert (bitfile);
-   
+
     if (!bitfile->bitpos--)      /* use next byte ? */
     {
         bitfile->ptr++;
@@ -265,7 +265,7 @@ put_bit (bitfile_t *bitfile, unsigned value)
         }
         bitfile->bitpos = 7;
     }
-   
+
     if (value)
         *bitfile->ptr |= mask [bitfile->bitpos];
 
@@ -274,7 +274,7 @@ put_bit (bitfile_t *bitfile, unsigned value)
 
 void
 put_bits (bitfile_t *bitfile, unsigned value, unsigned bits)
-/*     
+/*
  *  Put #'bits' bits of integer 'value' to the bitfile buffer 'bitfile'.
  *
  *  No return value.
@@ -292,7 +292,7 @@ close_bitfile (bitfile_t *bitfile)
 /*
  *  Bitfile destructor:
  *  Close 'bitfile', if 'bitfile->mode' == WRITE_ACCESS write bit buffer
- *  to disk. 
+ *  to disk.
  *
  *  No return value.
  *
@@ -301,7 +301,7 @@ close_bitfile (bitfile_t *bitfile)
  */
 {
     assert (bitfile);
-   
+
     if (bitfile->mode == WRITE_ACCESS)
     {
         unsigned bytes = fwrite (bitfile->buffer, sizeof (byte_t),
diff --git a/converter/other/fiasco/lib/image.c b/converter/other/fiasco/lib/image.c
index a700fe88..705a56aa 100644
--- a/converter/other/fiasco/lib/image.c
+++ b/converter/other/fiasco/lib/image.c
@@ -2,7 +2,7 @@
  *  image.c:        Input and output of PNM images.
  *
  *  Written by:     Ullrich Hafner
- *      
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -31,7 +31,7 @@
 /*****************************************************************************
 
                 prototypes
-  
+
 *****************************************************************************/
 
 static void
@@ -40,7 +40,7 @@ init_chroma_tables (void);
 /*****************************************************************************
 
                 local variables
-  
+
 *****************************************************************************/
 static int *Cr_r_tab = NULL;
 static int *Cr_g_tab = NULL;
@@ -50,7 +50,7 @@ static int *Cb_b_tab = NULL;
 /*****************************************************************************
 
                 public code
-  
+
 *****************************************************************************/
 
 static fiasco_image_t *
@@ -197,7 +197,7 @@ cast_image (fiasco_image_t *image)
    image_t *this = (image_t *) image->private;
    if (this)
    {
-      if (!streq (this->id, "IFIASCO"))
+      if (!STRSEQ(this->id, "IFIASCO"))
       {
      set_error (_("Parameter `image' doesn't match required type."));
      return NULL;
@@ -240,7 +240,7 @@ alloc_image (unsigned width, unsigned height, bool_t color, format_e format)
    image->color       = color;
    image->format      = format;
    image->reference_count = 1;
-   
+
    STRSCPY(image->id, "IFIASCO");
 
    for (band = first_band (color); band <= last_band (color); band++)
@@ -249,7 +249,7 @@ alloc_image (unsigned width, unsigned height, bool_t color, format_e format)
                     sizeof (word_t));
       else
      image->pixels [band] = Calloc (width * height, sizeof (word_t));
-   
+
    return image;
 }
 
@@ -266,7 +266,7 @@ clone_image (image_t *image)
    image_t *new = alloc_image (image->width, image->height, image->color,
                    image->format);
    color_e band;
-   
+
    for (band = first_band (new->color); band <= last_band (new->color); band++)
       if (new->format == FORMAT_4_2_0 && band != Y)
       {
@@ -314,7 +314,7 @@ free_image (image_t *image)
 }
 
 
-static void 
+static void
 read_image_data(image_t * const image, FILE *input, const bool_t color,
                 const int width, const int height, const xelval maxval,
                 const int format) {
@@ -336,27 +336,27 @@ read_image_data(image_t * const image, FILE *input, const bool_t color,
 
    xelrow = pnm_allocrow(width);
 
-   i = 0; 
+   i = 0;
    for (row = 0; row < height; row++) {
        int col;
        pnm_readpnmrow(input, xelrow, width, maxval, format);
        for (col = 0; col < width; col++) {
            if (color) {
-               image->pixels[Y][i] = 
-                   coeff_lu_r * PPM_GETR(xelrow[col]) 
+               image->pixels[Y][i] =
+                   coeff_lu_r * PPM_GETR(xelrow[col])
                    + coeff_lu_g * PPM_GETG(xelrow[col])
                    + coeff_lu_b * PPM_GETB(xelrow[col]) - 2048;
-               image->pixels[Cb][i] = 
-                   coeff_cb_r * PPM_GETR(xelrow[col]) 
+               image->pixels[Cb][i] =
+                   coeff_cb_r * PPM_GETR(xelrow[col])
                    + coeff_cb_g * PPM_GETG(xelrow[col])
                    + coeff_cb_b * PPM_GETB(xelrow[col]);
-               image->pixels[Cr][i] = 
-                   coeff_cr_r * PPM_GETR(xelrow[col]) 
+               image->pixels[Cr][i] =
+                   coeff_cr_r * PPM_GETR(xelrow[col])
                    + coeff_cr_g * PPM_GETG(xelrow[col])
                    + coeff_cr_b * PPM_GETB(xelrow[col]);
 
                i++;
-           } else 
+           } else
                image->pixels[GRAY][i++] =
                    PNM_GET1(xelrow[col]) * 4095 / maxval - 2048;
        }
@@ -434,7 +434,7 @@ void
 write_image (const char *image_name, const image_t *image)
 /*
  *  Write given 'image' data to the file 'image_name'.
- *  
+ *
  *  No return value.
  */
 {
@@ -446,13 +446,13 @@ write_image (const char *image_name, const image_t *image)
    unsigned *gray_clip;         /* clipping table */
 
    assert (image && image_name);
-   
+
    if (image->format == FORMAT_4_2_0)
    {
       warning ("We cannot write images in 4:2:0 format.");
       return;
    }
-   
+
    if (image_name == NULL)
        output = stdout;
    else if (streq(image_name, "-"))
@@ -466,7 +466,7 @@ write_image (const char *image_name, const image_t *image)
    init_chroma_tables ();
 
    format = image->color ? PPM_TYPE : PGM_TYPE;
-   
+
    pnm_writepnminit(output, image->width, image->height, 255, format, 0);
 
    xelrow = pnm_allocrow(image->width);
@@ -481,18 +481,18 @@ write_image (const char *image_name, const image_t *image)
                cbval = image->pixels[Cb][i] / 16;
                crval = image->pixels[Cr][i] / 16;
 
-               PPM_ASSIGN(xelrow[col], 
+               PPM_ASSIGN(xelrow[col],
                           gray_clip[yval + Cr_r_tab[crval]],
                           gray_clip[yval + Cr_g_tab[crval] + Cb_g_tab [cbval]],
                           gray_clip[yval + Cb_b_tab[cbval]]);
 
            } else
                /* The 16 below should be 4095/255 = 16.0588 */
-               PNM_ASSIGN1(xelrow[col], 
+               PNM_ASSIGN1(xelrow[col],
                            gray_clip[image->pixels[GRAY][i]/16+128]);
            i++;
        }
-       pnm_writepnmrow(output, xelrow, 
+       pnm_writepnmrow(output, xelrow,
                        image->width, 255, format, 0);
    }
    pnm_freerow(xelrow);
@@ -511,7 +511,7 @@ same_image_type (const image_t *img1, const image_t *img2)
  */
 {
    assert (img1 && img2);
-   
+
    return ((img1->width == img2->width)
        && (img1->height == img2->height)
        && (img1->color == img2->color)
@@ -521,7 +521,7 @@ same_image_type (const image_t *img1, const image_t *img2)
 /*****************************************************************************
 
                 private code
-  
+
 *****************************************************************************/
 
 static void
@@ -547,21 +547,21 @@ init_chroma_tables (void)
 
       Cr_r_tab[i] =  1.4022 * crval + 0.5;
       Cr_g_tab[i] = -0.7145 * crval + 0.5;
-      Cb_g_tab[i] = -0.3456 * cbval + 0.5; 
+      Cb_g_tab[i] = -0.3456 * cbval + 0.5;
       Cb_b_tab[i] =  1.7710 * cbval + 0.5;
    }
    for (i = 0; i < 256; i++)
    {
       Cr_r_tab[i] = Cr_r_tab[256];
       Cr_g_tab[i] = Cr_g_tab[256];
-      Cb_g_tab[i] = Cb_g_tab[256]; 
+      Cb_g_tab[i] = Cb_g_tab[256];
       Cb_b_tab[i] = Cb_b_tab[256];
    }
    for (i = 512; i < 768; i++)
    {
       Cr_r_tab[i] = Cr_r_tab[511];
       Cr_g_tab[i] = Cr_g_tab[511];
-      Cb_g_tab[i] = Cb_g_tab[511]; 
+      Cb_g_tab[i] = Cb_g_tab[511];
       Cb_b_tab[i] = Cb_b_tab[511];
    }
 
diff --git a/converter/other/fiasco/lib/image.h b/converter/other/fiasco/lib/image.h
index a87a3c05..c3c5f0df 100644
--- a/converter/other/fiasco/lib/image.h
+++ b/converter/other/fiasco/lib/image.h
@@ -29,7 +29,7 @@ typedef struct image
  *  Image data
  */
 {
-   char      id [7];
+   char      id [8];         /* NUL-terminated "IFIASCO" */
    unsigned  reference_count;
    unsigned  width;			/* Width of the image */
    unsigned  height;			/* Height of the image */
diff --git a/converter/other/fiasco/lib/macros.h b/converter/other/fiasco/lib/macros.h
index 0bc80e7c..2f404a74 100644
--- a/converter/other/fiasco/lib/macros.h
+++ b/converter/other/fiasco/lib/macros.h
@@ -34,8 +34,6 @@
   
 *****************************************************************************/
 
-#define streq(str1, str2)	(strcmp ((str1), (str2)) == 0)
-#define strneq(str1, str2)	(strcmp ((str1), (str2)) != 0)
 #define square(x)		((x) * (x))
 #define first_band(color)	((unsigned) ((color) ? Y  : GRAY))
 #define last_band(color)        ((unsigned) ((color) ? Cr : GRAY))
diff --git a/converter/other/fiasco/output/mc.c b/converter/other/fiasco/output/mc.c
index d048bef5..170a2648 100644
--- a/converter/other/fiasco/output/mc.c
+++ b/converter/other/fiasco/output/mc.c
@@ -1,9 +1,9 @@
 /*
- *  mc.c:		Output of motion compensation	
+ *  mc.c:		Output of motion compensation
  *
  *  Written by:		Michael Unger
  *			Ullrich Hafner
- *		
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -30,7 +30,7 @@
 /*****************************************************************************
 
 			     local variables
-  
+
 *****************************************************************************/
 
 static unsigned p_frame_codes [4][2] =
@@ -39,7 +39,7 @@ static unsigned p_frame_codes [4][2] =
  *  NONE,  FORWARD
  */
 {
-   {1, 1}, {0, 1}, {0, 0}, {0, 0} 
+   {1, 1}, {0, 1}, {0, 0}, {0, 0}
 };
 
 static unsigned b_frame_codes [4][2] =
@@ -48,7 +48,7 @@ static unsigned b_frame_codes [4][2] =
  *  NONE,  FORWARD,  BACKWARD, INTERPOLATED
  */
 {
-   {1, 1}, {000, 3}, {001, 3}, {01, 2} 
+   {1, 1}, {000, 3}, {001, 3}, {01, 2}
 };
 
 enum vlc_e {CODE = 0, BITS = 1};
@@ -56,7 +56,7 @@ enum vlc_e {CODE = 0, BITS = 1};
 /*****************************************************************************
 
 				prototypes
-  
+
 *****************************************************************************/
 
 static void
@@ -68,7 +68,7 @@ encode_mc_coords (unsigned max_state, const wfa_t *wfa, bitfile_t *output);
 /*****************************************************************************
 
 				public code
-  
+
 *****************************************************************************/
 
 void
@@ -85,7 +85,7 @@ write_mc (frame_type_e frame_type, const wfa_t *wfa, bitfile_t *output)
 /*****************************************************************************
 
 				private code
-  
+
 *****************************************************************************/
 
 static void
@@ -108,22 +108,22 @@ encode_mc_tree (unsigned max_state, frame_type_e frame_type, const wfa_t *wfa,
    mc_type_e type;			/* type of motion compensation */
    unsigned	     (*mc_tree_codes)[2]; /* pointer to VLC table */
    unsigned  bits  = bits_processed (output); /* number of bits used */
-   
+
    if (frame_type == P_FRAME)
       mc_tree_codes = p_frame_codes;	/* binary code */
-   else 
+   else
       mc_tree_codes = b_frame_codes;	/* variable length code */
-   
+
    /*
     *  Traverse tree in breadth first order (starting at
-    *  level 'wfa->p_max_level'). Use a queue to store the childs
-    *  of each node ('last' is the next free queue element).  
+    *  level 'wfa->p_max_level'). Use a queue to store the children
+    *  of each node ('last' is the next free queue element).
     */
 
    for (last = 0, state = wfa->basis_states; state < max_state; state++)
       if (wfa->level_of_state [state] - 1 == (int) wfa->wfainfo->p_max_level)
 	 queue [last++] = state;	/* init level = 'mc_max_level' */
-   
+
    for (current = 0; current < last; current++)
       for (label = 0; label < MAXLABELS; label++)
       {
@@ -145,7 +145,7 @@ encode_mc_tree (unsigned max_state, frame_type_e frame_type, const wfa_t *wfa,
 	     wfa->level_of_state [state] - 1 >=
 	     (int) wfa->wfainfo->p_min_level)
 	    queue [last++] = wfa->tree [state][label]; /* append child */
-	 
+
       }
 
    OUTPUT_BYTE_ALIGN (output);
@@ -174,16 +174,16 @@ encode_mc_coords (unsigned max_state, const wfa_t *wfa, bitfile_t *output)
    unsigned  itotal = 0;		/* #interpolated decisions */
    unsigned  bits   = bits_processed (output); /* number of bits used */
    unsigned  sr     = wfa->wfainfo->search_range; /* search range */
-   
+
    for (level = wfa->wfainfo->p_max_level;
 	level >= wfa->wfainfo->p_min_level; level--)
       level_count [level] = 0;
-   
+
    for (state = wfa->basis_states; state < max_state; state++)
       for (label = 0; label < MAXLABELS; label++)
       {
 	 mv_t *mv = &wfa->mv_tree[state][label]; /* motion vector info */
-	 
+
 	 if (mv->type != NONE)
 	 {
 	    level_count [wfa->level_of_state [state] - 1]++;
@@ -229,14 +229,14 @@ encode_mc_coords (unsigned max_state, const wfa_t *wfa, bitfile_t *output)
       }
 
    OUTPUT_BYTE_ALIGN (output);
-   
+
    debug_message ("Motion compensation: %d forward, %d backward, "
 		  "%d interpolated", ftotal, btotal, itotal);
 
    for (level = wfa->wfainfo->p_max_level;
 	level >= wfa->wfainfo->p_min_level; level--)
       debug_message ("Level %d: %d motion vectors", level, level_count[level]);
-   
+
    {
       unsigned  total = ftotal * 2 + btotal * 2 + itotal * 4;
 
diff --git a/converter/other/fiasco/output/nd.c b/converter/other/fiasco/output/nd.c
index 65a85467..b1dd6746 100644
--- a/converter/other/fiasco/output/nd.c
+++ b/converter/other/fiasco/output/nd.c
@@ -1,8 +1,8 @@
 /*
- *  nd.c:		Output of prediction tree	
+ *  nd.c:		Output of prediction tree
  *
  *  Written by:		Ullrich Hafner
- *		
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -32,7 +32,7 @@
 /*****************************************************************************
 
 				prototypes
-  
+
 *****************************************************************************/
 
 static unsigned
@@ -43,7 +43,7 @@ encode_nd_coefficients (unsigned total, const wfa_t *wfa, bitfile_t *output);
 /*****************************************************************************
 
 				public code
-  
+
 *****************************************************************************/
 
 void
@@ -56,7 +56,7 @@ write_nd (const wfa_t *wfa, bitfile_t *output)
  */
 {
    unsigned total = encode_nd_tree (wfa, output);
-   
+
    if (total > 0)
       encode_nd_coefficients (total, wfa, output);
 }
@@ -64,13 +64,13 @@ write_nd (const wfa_t *wfa, bitfile_t *output)
 /*****************************************************************************
 
 				private code
-  
+
 *****************************************************************************/
 
 static unsigned
 encode_nd_tree (const wfa_t *wfa, bitfile_t *output)
 /*
- *  Write prediction tree of 'wfa' to given stream 'output'. 
+ *  Write prediction tree of 'wfa' to given stream 'output'.
  *
  *  No return value.
  */
@@ -85,7 +85,7 @@ encode_nd_tree (const wfa_t *wfa, bitfile_t *output)
    unsigned  bits = bits_processed (output);
 
    used = not_used = 0;
-   
+
    /*
     *  Initialize arithmetic coder
     */
@@ -94,18 +94,18 @@ encode_nd_tree (const wfa_t *wfa, bitfile_t *output)
    underflow = 0;
    sum0      = 1;
    sum1      = 11;
-   
+
    queue = alloc_queue (sizeof (int));
    state = wfa->root_state;
    queue_append (queue, &state);
-   
+
    /*
     *  Traverse the WFA tree in breadth first order (using a queue).
     */
    while (queue_remove (queue, &next))
    {
       unsigned label;
-      
+
       if (wfa->level_of_state [next] > wfa->wfainfo->p_max_level + 1)
       {
 	 /*
@@ -114,7 +114,7 @@ encode_nd_tree (const wfa_t *wfa, bitfile_t *output)
 	  */
 	 for (label = 0; label < MAXLABELS; label++)
 	    if (ischild (state = wfa->tree [next][label]))
-	       queue_append (queue, &state); /* continue with childs */
+	       queue_append (queue, &state); /* continue with children */
       }
       else if (wfa->level_of_state [next] > wfa->wfainfo->p_min_level)
       {
@@ -126,7 +126,7 @@ encode_nd_tree (const wfa_t *wfa, bitfile_t *output)
 	       if (isedge (wfa->into [next][label][0])) /* prediction used */
 	       {
 		  used++;
-		  
+
 		  /*
 		   *  Encode a '1' symbol
 		   */
@@ -134,12 +134,12 @@ encode_nd_tree (const wfa_t *wfa, bitfile_t *output)
 		  low   = low + (u_word_t) ((range * sum0) / sum1);
 		  RESCALE_OUTPUT_INTERVAL;
 	       }
-	       else			/* no predict., continue with childs */
+	       else			/* no predict., continue with children */
 	       {
 		  not_used++;
 		  if (wfa->level_of_state [state] > wfa->wfainfo->p_min_level)
 		     queue_append (queue, &state);
-		  
+
 		  /*
 		   *  Encode a '0' symbol
 		   */
@@ -162,7 +162,7 @@ encode_nd_tree (const wfa_t *wfa, bitfile_t *output)
 		     sum1 = sum0 + 1;
 	       }
 	    }
-	 
+
       }
    }
    free_queue (queue);
@@ -178,7 +178,7 @@ encode_nd_tree (const wfa_t *wfa, bitfile_t *output)
 		  used, not_used);
    {
       unsigned total = used + not_used;
-      
+
       debug_message ("nd-tree:      %5d bits. (%5d symbols => %5.2f bps)",
 		     bits_processed (output) - bits, total,
 		     total > 0 ? ((bits_processed (output) - bits) /
@@ -205,7 +205,7 @@ encode_nd_coefficients (unsigned total, const wfa_t *wfa, bitfile_t *output)
       unsigned *ptr;			/* pointer to current factor */
       unsigned	state, label, edge;
       word_t	domain;
-      
+
       ptr = coefficients  = Calloc (total, sizeof (unsigned));
 
       for (state = wfa->basis_states; state < wfa->states; state++)
@@ -232,7 +232,7 @@ encode_nd_coefficients (unsigned total, const wfa_t *wfa, bitfile_t *output)
 	 encode_array (output, coefficients, NULL, &c_symbols, 1,
 		       total, scaling);
       }
-      
+
       debug_message ("nd-factors:   %5d bits. (%5d symbols => %5.2f bps)",
 		     bits_processed (output) - bits, total,
 		     total ? ((bits_processed (output) - bits)
diff --git a/converter/other/fiasco/output/tree.c b/converter/other/fiasco/output/tree.c
index 2eae2df9..55080a51 100644
--- a/converter/other/fiasco/output/tree.c
+++ b/converter/other/fiasco/output/tree.c
@@ -2,7 +2,7 @@
  *  tree.c:		Output of bintree partitioning
  *
  *  Written by:		Ullrich Hafner
- *		
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -30,7 +30,7 @@
 /*****************************************************************************
 
 				prototypes
-  
+
 *****************************************************************************/
 
 static void
@@ -40,7 +40,7 @@ encode_tree (bitfile_t *output, const byte_t *data, unsigned n_data,
 /*****************************************************************************
 
 				public code
-  
+
 *****************************************************************************/
 
 void
@@ -64,9 +64,9 @@ write_tree (const wfa_t *wfa, bitfile_t *output)
 
    /*
     *  Traverse tree in breadth first order. Use a queue to store
-    *  the childs of each node ('last' is the next free queue element).
+    *  the children of each node ('last' is the next free queue element).
     *  The first element ('current') of this queue will get the new parent
-    *  node. 
+    *  node.
     */
    tree_string = Calloc (MAXSTATES * MAXLABELS, sizeof (byte_t));
    queue [0] = wfa->root_state;
@@ -83,7 +83,7 @@ write_tree (const wfa_t *wfa, bitfile_t *output)
    if (total != (wfa->states - wfa->basis_states) * MAXLABELS)
       error ("total [%d] != (states - basis_states) * 2 [%d]", total,
 	     (wfa->states - wfa->basis_states) * MAXLABELS);
-   
+
    {
       unsigned scale = total / 20 ;
 
@@ -91,7 +91,7 @@ write_tree (const wfa_t *wfa, bitfile_t *output)
    }
 
    Free (tree_string);
-   
+
    debug_message ("tree:         %5d bits. (%5d symbols => %5.2f bps)",
 		  bits_processed (output) - bits, total,
 		  total > 0 ? ((bits_processed (output) - bits)
@@ -101,7 +101,7 @@ write_tree (const wfa_t *wfa, bitfile_t *output)
 /*****************************************************************************
 
 				private code
-  
+
 *****************************************************************************/
 
 static void
@@ -128,7 +128,7 @@ encode_tree (bitfile_t *output, const byte_t *data, unsigned n_data,
    for (n = n_data; n; n--)
    {
       unsigned range;			/* Current interval range */
-      
+
       if (!*data++)
       {
 	 /*
diff --git a/converter/other/fiasco/params.c b/converter/other/fiasco/params.c
index 7d0b84ab..29f52afc 100644
--- a/converter/other/fiasco/params.c
+++ b/converter/other/fiasco/params.c
@@ -3,7 +3,7 @@
  *
  *  Written by:		Stefan Frank
  *			Ullrich Hafner
- *		
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
@@ -28,7 +28,7 @@
 
 #include <stdlib.h>
 #include <string.h>
- 
+
 #include <getopt.h>			/* system or ../lib */
 
 #include "pm_c_util.h"
@@ -47,7 +47,7 @@
 /*****************************************************************************
 
 				prototypes
-  
+
 *****************************************************************************/
 
 static void
@@ -56,7 +56,7 @@ static int
 get_parameter_index (const param_t *params, const char *search_string);
 static void
 set_parameter (param_t *parameter, const char *value);
-static void 
+static void
 usage (const param_t *params, const char *progname, const char *synopsis,
        const char *comment, const char *non_opt_string,
        bool_t show_all_options, const char *sys_file_name,
@@ -65,17 +65,17 @@ usage (const param_t *params, const char *progname, const char *synopsis,
 /*****************************************************************************
 
 				public code
-  
+
 *****************************************************************************/
 
 int
-parseargs (param_t *usr_params, 
-           int argc, char **argv, 
+parseargs (param_t *usr_params,
+           int argc, char **argv,
            const char *synopsis,
-           const char *comment, 
-           const char *non_opt_string, 
+           const char *comment,
+           const char *non_opt_string,
            const char *path,
-           const char *sys_file_name, 
+           const char *sys_file_name,
            const char *usr_file_name)
 /*
  *  Perform the command line parsing.
@@ -95,7 +95,7 @@ parseargs (param_t *usr_params,
  *
  *  Side effects:
  *	the elements of ARGV are permuted
- *      usr_params [].value is modified 
+ *      usr_params [].value is modified
  */
 {
    extern int optind;			/* index in ARGV of the 1st element
@@ -146,7 +146,7 @@ parseargs (param_t *usr_params,
     */
    {
        param_t *p;
-      
+
        for (p = usr_params; p->name != NULL; p++)
        {
            set_parameter (p, p->default_value);
@@ -155,7 +155,7 @@ parseargs (param_t *usr_params,
        }
 
       sys_params = detailed_help ? detailed_sys_params : short_sys_params;
-      
+
       for (p = sys_params; p->name != NULL; p++)
           set_parameter (p, p->default_value);
    }
@@ -210,12 +210,12 @@ parseargs (param_t *usr_params,
       int	     optchar;		/* found option character */
 
       /*
-       *  Build short option string for getopt_long (). 
+       *  Build short option string for getopt_long ().
        */
       {
 	 param_t *p;			/* counter */
 	 char	 *ptr_optstr;		/* pointer to position in string */
-	 
+
 	 ptr_optstr = optstr;
 	 for (p = params; p->name != NULL; p++)
 	    if (p->optchar != '\0')
@@ -231,13 +231,13 @@ parseargs (param_t *usr_params,
 	    }
 	 *ptr_optstr = '\0';
       }
-      
+
       /*
-       *  Build long option string for getopt_long (). 
+       *  Build long option string for getopt_long ().
        */
       {
 	 int i;
-	 
+
 	 long_options = calloc (n1 + n2 + 1, sizeof (struct option));
 	 if (!long_options)
 	    error ("Out of memory.");
@@ -264,15 +264,15 @@ parseargs (param_t *usr_params,
 	    long_options [i].val     = 0;
 	 }
       }
-      
+
       /*
-       *  Parse comand line
+       *  Parse command line
        */
       while ((optchar = getopt_long (argc, argv, optstr, long_options,
 				     &option_index)) != EOF)
       {
 	 int param_index = -1;
-	 
+
 	 switch (optchar)
 	 {
 	    case 0:
@@ -303,7 +303,7 @@ parseargs (param_t *usr_params,
 	    default:
 	       {
 		  int i;
-		  
+
 		  for (i = 0; params [i].name != NULL; i++)
 		     if (params [i].optchar == optchar)
 		     {
@@ -350,7 +350,7 @@ parseargs (param_t *usr_params,
 
       free (long_options);
    }
-   
+
    /*
     *  Read config-file if specified by option -f
     */
@@ -361,7 +361,7 @@ parseargs (param_t *usr_params,
       if ((filename = (char *) parameter_value (params, "config")) != NULL)
       {
 	 FILE *parameter_file;		/* input file */
-	 
+
 	 warning ("Options set in file `%s' will override"
 		  " command line options.", filename);
 	 parameter_file = open_file (filename, NULL, READ_ACCESS);
@@ -379,10 +379,10 @@ parseargs (param_t *usr_params,
 
    memcpy (usr_params, params, n1 * sizeof (param_t)); /* fill user struct */
    free (sys_path);
-   
+
    return optind;
 }
- 
+
 void *
 parameter_value (const param_t *params, const char *name)
 /*
@@ -399,7 +399,7 @@ parameter_value (const param_t *params, const char *name)
 
    if (params [pind].type == PSTR || params [pind].type == POSTR)
       return (void *) params [pind].value.s;
-      
+
    return (void *) &(params [pind].value);
 }
 
@@ -414,7 +414,7 @@ ask_and_set (param_t *params, const char *name, const char *msg)
  *  Side effects:
  *	'params ['name'].value' is changed
  */
-{ 
+{
    char answer [MAXSTRLEN];
    int  index = get_parameter_index (params, name);
 
@@ -423,7 +423,7 @@ ask_and_set (param_t *params, const char *name, const char *msg)
 
    if (msg)
       fprintf (stderr, "%s\n", msg);
-  
+
    switch (params [index].type)
    {
       case PFLAG:			/* Unusual, at least. */
@@ -439,7 +439,7 @@ ask_and_set (param_t *params, const char *name, const char *msg)
       default:
 	 error ("Invalid parameter type for %s", name);
    }
-} 
+}
 
 void
 write_parameters (const param_t *params, FILE *output)
@@ -483,7 +483,7 @@ write_parameters (const param_t *params, FILE *output)
 /*****************************************************************************
 
 				private code
-  
+
 *****************************************************************************/
 
 static void
@@ -498,7 +498,7 @@ set_parameter (param_t *parameter, const char *value)
  */
 {
    assert (parameter);
-   
+
    switch (parameter->type)
    {
       case PFLAG:
@@ -516,7 +516,7 @@ set_parameter (param_t *parameter, const char *value)
 	    {
 	       long int	data;
 	       char	*endptr;
-	    
+
 	       data = strtol (value, &endptr, 0);
 	       if (*endptr != '\0' || endptr == value)
 		  warning ("Invalid value `%s' converted to %d",
@@ -531,7 +531,7 @@ set_parameter (param_t *parameter, const char *value)
 	 {
 	    long int  data;
 	    char     *endptr;
-	    
+
 	    data = strtol (value, &endptr, 0);
 	    if (*endptr != '\0' || endptr == value)
 	       warning ("Invalid value `%s' converted to %d",
@@ -543,7 +543,7 @@ set_parameter (param_t *parameter, const char *value)
 	 {
 	    double	data;
 	    char	*endptr;
-	    
+
 	    data = strtod (value, &endptr);
 	    if (*endptr != '\0' || endptr == value)
 	       warning ("Invalid value `%s' converted to %f",
@@ -555,7 +555,7 @@ set_parameter (param_t *parameter, const char *value)
       case POSTR:
 	 parameter->value.s = value ? strdup (value) : NULL;
 	 break;
-      default:				
+      default:
 	 error ("Invalid parameter type for %s", parameter->name);
    }
 }
@@ -606,7 +606,7 @@ read_parameter_file (param_t *params, FILE *file)
       char *name;			/* parameter name */
       char *value;			/* parameter value */
       int   pind;			/* current argument number */
-      
+
       b = strchr (buffer, '#');
       if (b != NULL)			/* Strip comments. */
 	 *b = '\0';
@@ -619,7 +619,7 @@ read_parameter_file (param_t *params, FILE *file)
       /*
        *  Extract value of parameter
        */
-      for (value = b + 1; ISSPACE (*value); value++) 
+      for (value = b + 1; ISSPACE (*value); value++)
 	 ;				/* Delete leading spaces */
 
       for (b = value + strlen (value) - 1; b >= value && ISSPACE (*b); b--)
@@ -628,7 +628,7 @@ read_parameter_file (param_t *params, FILE *file)
       /*
        *  Extract parameter name
        */
-      for (name = buffer; ISSPACE (*name); name++) 
+      for (name = buffer; ISSPACE (*name); name++)
 	 ;				/* Delete leading spaces */
 
       for (b = name + strlen (name) - 1; b >= name && ISSPACE (*b); b--)
@@ -637,21 +637,21 @@ read_parameter_file (param_t *params, FILE *file)
       pind = get_parameter_index (params, name);
       if (pind >= 0)
 	 set_parameter (&params [pind], value);
-      
+
       n++;
    }
-}   
+}
 
 
 
-static void 
+static void
 usage (const param_t *params, const char *progname, const char *synopsis,
        const char *comment, const char *non_opt_string,
        bool_t show_all_options, const char *sys_file_name,
        const char *usr_file_name)
 /*
  *  Generates and prints command line description from param_t struct 'params'.
- *  'progname' is the name of the excecutable, 'synopsis' a short program
+ *  'progname' is the name of the executable, 'synopsis' a short program
  *  description, and 'comment' some more advice.
  *  If flag 'show_all_options' is set then print also options that are not
  *  associated with a short option character.
@@ -662,7 +662,7 @@ usage (const param_t *params, const char *progname, const char *synopsis,
 {
     int	  i;
     size_t width = 0;
-   
+
     fprintf (stderr, "Usage: %s [OPTION]...%s\n", progname,
              non_opt_string ? non_opt_string : " ");
     if (synopsis != NULL)
@@ -683,7 +683,7 @@ usage (const param_t *params, const char *progname, const char *synopsis,
             else
                 width = MAX(width, (strlen (params [i].name)) - 1);
         }
-   
+
     for (i = 0; params [i].name != NULL; i++)
         if (params [i].optchar != '\0' || show_all_options)
         {
@@ -691,7 +691,7 @@ usage (const param_t *params, const char *progname, const char *synopsis,
                 fprintf (stderr, "  -%c, --", params [i].optchar);
             else
                 fprintf (stderr, "      --");
-	 
+
             if (params [i].type == POSTR)
                 fprintf (stderr, "%s=[%s]%-*s  ", params [i].name,
                          params [i].argument_name,
@@ -707,7 +707,7 @@ usage (const param_t *params, const char *progname, const char *synopsis,
                          (unsigned)(width + 1), params [i].name);
 
             fprintf (stderr, params [i].use, params [i].argument_name);
-	 
+
             switch (params [i].type)
             {
             case PFLAG:
diff --git a/converter/other/fiasco/pnmtofiasco.c b/converter/other/fiasco/pnmtofiasco.c
index e2656c71..9f63e7a1 100644
--- a/converter/other/fiasco/pnmtofiasco.c
+++ b/converter/other/fiasco/pnmtofiasco.c
@@ -2,11 +2,11 @@
  *  cwfa.c:     FIASCO coder
  *
  *  Written by:     Ullrich Hafner
- *      
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
- 
+
 /*
  *  $Date: 2000/10/28 17:39:29 $
  *  $Author: hafner $
@@ -33,7 +33,7 @@
 /*****************************************************************************
 
                  local variables
-  
+
 *****************************************************************************/
 
 static param_t params [] =
@@ -107,7 +107,7 @@ static param_t params [] =
    "Set domain pool of r-lc to `%s'."},
   {"coeff", "NAME", '\0', PSTR, {0}, "adaptive",
    "Set coefficients model to `%s'."},
-  /*  DELTA APPROXIATION  */
+  /*  DELTA APPROXIMATION  */
   {"d-domain-pool", "NAME", '\0', PSTR, {0}, "rle",
    "Set domain pool of d-lc to `%s'."},
   {"d-coeff", "NAME", '\0', PSTR, {0}, "adaptive",
@@ -132,36 +132,36 @@ static param_t params [] =
    "Smooth frames by factor `%s' (0.5 - 1.0)"},
   {"reference-frame", "FILE", '\0', PSTR, {0}, NULL,
    "Use PPM/PGM image `%s' as reference frame."},
-#endif  
+#endif
   {NULL, NULL, 0, PSTR, {0}, NULL, NULL }
 };
 
 /*****************************************************************************
 
                 prototypes
-  
+
 *****************************************************************************/
 
-static void 
+static void
 checkargs (int argc, char **argv, char const ***image_template,
        char **wfa_name, float *quality, fiasco_c_options_t **options);
 
 /*****************************************************************************
 
                 public code
-  
+
 *****************************************************************************/
- 
-int 
+
+int
 main (int argc, char **argv)
 {
    char const         **image_template; /* template for input image files */
    char                *wfa_name;   /* filename of output WFA */
    float            quality;    /* approximation quality */
    fiasco_c_options_t  *options;    /* additional coder options */
-   
+
    pnm_init(&argc, argv);
-   
+
    init_error_handling (argv [0]);
 
    checkargs (argc, argv, &image_template, &wfa_name, &quality, &options);
@@ -179,10 +179,10 @@ main (int argc, char **argv)
 /*****************************************************************************
 
                 private code
-  
+
 *****************************************************************************/
 
-static void 
+static void
 checkargs (int argc, char **argv, char const ***image_template,
            char **wfa_name, float *quality, fiasco_c_options_t **options)
 /*
@@ -191,7 +191,7 @@ checkargs (int argc, char **argv, char const ***image_template,
  *  Return value:
  *  1 on success
  *  0 otherwise
- *  
+ *
  *
  *  Side effects:
  *  'image_template', 'wfa_name', 'quality' and 'options' are set.
@@ -200,7 +200,7 @@ checkargs (int argc, char **argv, char const ***image_template,
     int   optind;            /* last processed commandline param */
     char *image_name;            /* filename given by option '--input_name' */
     int   i;             /* counter */
-   
+
     optind = parseargs (params, argc, argv,
                         "Compress raw PPM/PGM image FILEs to a FIASCO file.",
                         "With no image FILE, or if FILE is -, "
@@ -220,7 +220,7 @@ checkargs (int argc, char **argv, char const ***image_template,
     /*
      *  Default options ...
      */
-    image_name = (char *) parameter_value (params, "image-name"); 
+    image_name = (char *) parameter_value (params, "image-name");
     *wfa_name  = (char *) parameter_value (params, "output-name");
     for (;;)
     {
@@ -233,7 +233,7 @@ checkargs (int argc, char **argv, char const ***image_template,
         ask_and_set (params, "quality",
                      "Please enter coding quality 'q' ('q' > 0): ");
     }
-   
+
     if (optind < argc)           /* Additional command line param */
     {
         if (image_name)
@@ -260,7 +260,7 @@ checkargs (int argc, char **argv, char const ***image_template,
      */
     {
         *options = fiasco_c_options_new ();
-      
+
         {
             char *pattern = (char *) parameter_value (params, "pattern");
 
@@ -270,7 +270,7 @@ checkargs (int argc, char **argv, char const ***image_template,
 
         {
             char *basis = (char *) parameter_value (params, "basis-name");
-     
+
             if (!fiasco_c_options_set_basisfile (*options, basis))
                 error (fiasco_get_error_message ());
         }
@@ -278,41 +278,41 @@ checkargs (int argc, char **argv, char const ***image_template,
         {
             int   n = * (int *) parameter_value (params, "chroma-dictionary");
             float q = * (float *) parameter_value (params, "chroma-qfactor");
-      
+
             if (!fiasco_c_options_set_chroma_quality (*options, q, MAX(0, n)))
                 error (fiasco_get_error_message ());
         }
-      
+
         {
             int n = *((int *) parameter_value (params, "smooth"));
-     
+
             if (!fiasco_c_options_set_smoothing (*options, MAX(0, n)))
                 error (fiasco_get_error_message ());
         }
-      
+
         {
             int n = * (int *) parameter_value (params, "progress-meter");
-            fiasco_progress_e type = (n < 0) ? 
+            fiasco_progress_e type = (n < 0) ?
                 FIASCO_PROGRESS_NONE : (fiasco_progress_e) n;
-      
+
             if (!fiasco_c_options_set_progress_meter (*options, type))
                 error (fiasco_get_error_message ());
         }
-      
+
         {
             char *t = (char *) parameter_value (params, "title");
-     
+
             if (strlen (t) > 0 && !fiasco_c_options_set_title (*options, t))
                 error (fiasco_get_error_message ());
         }
-      
+
         {
             char *c = (char *) parameter_value (params, "comment");
 
             if (strlen (c) > 0 && !fiasco_c_options_set_comment (*options, c))
                 error (fiasco_get_error_message ());
         }
-      
+
         {
             fiasco_tiling_e method = FIASCO_TILING_VARIANCE_DSC;
             int   e  = * (int *) parameter_value (params, "tiling-exponent");
@@ -332,7 +332,7 @@ checkargs (int argc, char **argv, char const ***image_template,
             if (!fiasco_c_options_set_tiling (*options, method, MAX(0, e)))
                 error (fiasco_get_error_message ());
         }
-      
+
         {
             int M/*  = * (int *) parameter_value (params, "max-level") */;
             int m/*  = * (int *) parameter_value (params, "min-level") */;
@@ -354,7 +354,7 @@ checkargs (int argc, char **argv, char const ***image_template,
                 m = 4;
                 N = 5;
             }
-     
+
             if (!fiasco_c_options_set_optimizations (*options, m, M, N,
                                                      MAX(0, D), o))
                 error (fiasco_get_error_message ());
@@ -363,7 +363,7 @@ checkargs (int argc, char **argv, char const ***image_template,
             int M = * (int *) parameter_value (params, "max-level");
             int m = * (int *) parameter_value (params, "min-level");
             int p = * (int *) parameter_value (params, "prediction");
-     
+
             if (!fiasco_c_options_set_prediction (*options,
                                                   p, MAX(0, m), MAX(0, M)))
                 error (fiasco_get_error_message ());
@@ -374,7 +374,7 @@ checkargs (int argc, char **argv, char const ***image_template,
             int   m    = * (int *)  parameter_value(params, "rpf-mantissa");
             int   dc_m = * (int *)  parameter_value(params, "dc-rpf-mantissa");
             fiasco_rpf_range_e range, dc_range;
-     
+
             if (r < 1)
                 range = FIASCO_RPF_RANGE_0_75;
             else if (r < 1.5)
@@ -383,7 +383,7 @@ checkargs (int argc, char **argv, char const ***image_template,
                 range = FIASCO_RPF_RANGE_1_50;
             else
                 range = FIASCO_RPF_RANGE_2_00;
-        
+
             if (dc_r < 1)
                 dc_range = FIASCO_RPF_RANGE_0_75;
             else if (dc_r < 1.5)
@@ -392,7 +392,7 @@ checkargs (int argc, char **argv, char const ***image_template,
                 dc_range = FIASCO_RPF_RANGE_1_50;
             else
                 dc_range = FIASCO_RPF_RANGE_2_00;
-        
+
             if (!fiasco_c_options_set_quantization (*options,
                                                     MAX(0, m), range,
                                                     MAX(0, dc_m), dc_range))
@@ -402,4 +402,7 @@ checkargs (int argc, char **argv, char const ***image_template,
         if (fiasco_get_verbosity () == FIASCO_ULTIMATE_VERBOSITY)
             write_parameters (params, stderr);
     }
-}   
+}
+
+
+
diff --git a/converter/other/fitstopnm.c b/converter/other/fitstopnm.c
index e7de4311..804d4ae9 100644
--- a/converter/other/fitstopnm.c
+++ b/converter/other/fitstopnm.c
@@ -44,6 +44,7 @@
 #include <string.h>
 #include <float.h>
 #include <assert.h>
+#include <stdbool.h>
 
 #include "pm_config.h"
 #include "pm_c_util.h"
@@ -74,12 +75,12 @@ struct CmdlineInfo {
 
 
 
-static void 
-parseCommandLine(int argc, const char ** argv, 
+static void
+parseCommandLine(int argc, const char ** argv,
                  struct CmdlineInfo * const cmdlineP) {
 /* --------------------------------------------------------------------------
    Parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -140,7 +141,7 @@ parseCommandLine(int argc, const char ** argv,
         cmdlineP->inputFileName = "-";
     else {
         cmdlineP->inputFileName = argv[1];
-        
+
         if (argc-1 > 1)
             pm_error("Too many arguments (%u).  The only non-option argument "
                      "is the input file name.", argc-1);
@@ -150,29 +151,25 @@ parseCommandLine(int argc, const char ** argv,
 
 
 
-struct FITS_Header {
-  int simple;       /* basic format or not */
-  int bitpix;
-      /* number of bits per pixel, positive for integer, negative 
-         for floating point
-      */
-  int naxis;        /* number of axes */
-  int naxis1;       /* number of points on axis 1 */
-  int naxis2;       /* number of points on axis 2 */
-  int naxis3;       /* number of points on axis 3 */
-  double datamin;   /* min # (Physical value!) */
-  double datamax;   /* max #     "       "     */
-  double bzer;      /* Physical value = Array value*bscale + bzero */
-  double bscale;
-};
-
-
 typedef enum {
     VF_CHAR, VF_SHORT, VF_LONG, VF_FLOAT, VF_DOUBLE
-} valFmt;
+} ValFmt;
+
+struct FITS_Header {
+    bool simple;      /* basic format */
+    ValFmt valFmt;    /* format of values -- bits per pixel, integer/float */
+    unsigned int naxis;  /* number of axes */
+    unsigned int naxis1;       /* number of points on axis 1 */
+    unsigned int naxis2;       /* number of points on axis 2 */
+    unsigned int naxis3;       /* number of points on axis 3 */
+    double datamin;   /* min # (Physical value!) */
+    double datamax;   /* max #     "       "     */
+    double bzer;      /* Physical value = Array value*bscale + bzero */
+    double bscale;
+};
 
-struct fitsRasterInfo {
-    valFmt valFmt;
+struct FitsRasterInfo {
+    ValFmt valFmt;
     double bzer;
     double bscale;
 };
@@ -296,7 +293,7 @@ readFitsDouble(FILE *   const ifP,
 
 
 
-static valFmt
+static ValFmt
 valFmtFromBitpix(int const bitpix) {
 /*----------------------------------------------------------------------------
    Return the format of a "value" in the FITS file, given the value
@@ -323,7 +320,7 @@ valFmtFromBitpix(int const bitpix) {
 
 static void
 readVal(FILE *   const ifP,
-        valFmt   const fmt,
+        ValFmt   const fmt,
         double * const vP) {
 
     switch (fmt) {
@@ -334,15 +331,15 @@ readVal(FILE *   const ifP,
     case VF_SHORT:
         readFitsShort(ifP, vP);
         break;
-      
+
     case VF_LONG:
         readFitsLong(ifP, vP);
         break;
-      
+
     case VF_FLOAT:
         readFitsFloat(ifP, vP);
         break;
-      
+
     case VF_DOUBLE:
         readFitsDouble(ifP, vP);
         break;
@@ -364,46 +361,129 @@ readCard(FILE * const ifP,
 
 
 
+
+static void
+processNaxisN(unsigned int   const n,
+              int            const value,
+              bool           const gotNaxis,
+              unsigned int   const naxis,
+              bool *         const gotNaxisNP,
+              unsigned int * const naxisNP) {
+
+    if (*gotNaxisNP)
+        pm_error("Invalid FITS header: two NAXIS%u keywords", n);
+    else {
+        *gotNaxisNP = true;
+
+        if (!gotNaxis)
+            pm_error("Invalid FITS header: NAXIS must precede NAXIS%u", n);
+        else if (naxis < n)
+            pm_error("Invalid FITS header: NAXIS%u for image with "
+                     "only %u axes", n, naxis);
+        else if (value < 0)
+            pm_error("Invalid NAXIS%u value %d in FITS header:  "
+                     "Must not be negative", n, value);
+        else
+            *naxisNP = value;
+    }
+}
+
+
+
 static void
 readFitsHeader(FILE *               const ifP,
                struct FITS_Header * const hP) {
 
-    int seenEnd;
-  
-    seenEnd = 0;
+
+    bool gotEmpty, gotSimple, gotNaxis, gotN1, gotN2, gotN3, gotBitpix, gotEnd;
+
+    gotEmpty  = false;  /* initial value */    
+    gotSimple = false;  /* initial value */
+    gotNaxis  = false;  /* initial value */
+    gotN1     = false;  /* initial value */
+    gotN2     = false;  /* initial value */
+    gotN3     = false;  /* initial value */
+    gotBitpix = false;  /* initial value */
+    gotEnd    = false;  /* initial value */
+
     /* Set defaults */
-    hP->simple  = 0;
     hP->bzer    = 0.0;
     hP->bscale  = 1.0;
     hP->datamin = - DBL_MAX;
     hP->datamax = DBL_MAX;
-  
-    while (!seenEnd) {
+
+    while (!gotEnd) {
         unsigned int i;
 
         for (i = 0; i < 36; ++i) {
             char buf[81];
             char c;
+            int n;
 
             readCard(ifP, buf); /* Reads into first 80 elements of buf[] */
-    
+
             buf[80] = '\0'; /* Make ASCIIZ string */
 
-            if (sscanf(buf, "SIMPLE = %c", &c) == 1) {
+            if (sscanf(buf, " %c", &c) < 1) {
+                gotEmpty = true;
+            } else if (sscanf(buf, "SIMPLE = %c", &c) == 1) {
+                if (gotSimple)
+                    pm_error("FITS header has two SIMPLE keywords");
+                gotSimple = true;
                 if (c == 'T' || c == 't')
-                    hP->simple = 1;
-            } else if (sscanf(buf, "BITPIX = %d", &(hP->bitpix)) == 1);
-            else if (sscanf(buf, "NAXIS = %d", &(hP->naxis)) == 1);
-            else if (sscanf(buf, "NAXIS1 = %d", &(hP->naxis1)) == 1);
-            else if (sscanf(buf, "NAXIS2 = %d", &(hP->naxis2)) == 1);
-            else if (sscanf(buf, "NAXIS3 = %d", &(hP->naxis3)) == 1);
-            else if (sscanf(buf, "DATAMIN = %lf", &(hP->datamin)) == 1);
-            else if (sscanf(buf, "DATAMAX = %lf", &(hP->datamax)) == 1);
-            else if (sscanf(buf, "BZERO = %lf", &(hP->bzer)) == 1);
-            else if (sscanf(buf, "BSCALE = %lf", &(hP->bscale)) == 1);
-            else if (strncmp(buf, "END ", 4 ) == 0) seenEnd = 1;
+                    hP->simple = true;
+                else if (c == 'F' || c == 'f')
+                    hP->simple = false;
+                else
+                    pm_error("Invalid SIMPLE value '%c'.  Only 'T' and 'F' "
+                             "are recognized", c);
+            } else if (sscanf(buf, "BITPIX = %d", &n) == 1) {
+                if (gotBitpix)
+                    pm_error("FITS header has two NAXIS keywords");
+                gotBitpix = true;
+                hP->valFmt = valFmtFromBitpix(n);
+            } else if (sscanf(buf, "NAXIS = %d", &n) == 1) {
+                gotNaxis = true;
+                if (n < 0)
+                    pm_error("Invalid value %d for NAXIS in FITS header.  "
+                             "Value must not be negative", n);
+                else
+                    hP->naxis = n;
+            } else if (sscanf(buf, "NAXIS1 = %d", &n) == 1) {
+                processNaxisN(1, n, gotNaxis, hP->naxis, &gotN1, &hP->naxis1);
+            } else if (sscanf(buf, "NAXIS2 = %d", &n) == 1) {
+                processNaxisN(2, n, gotNaxis, hP->naxis, &gotN2, &hP->naxis2);
+            } else if (sscanf(buf, "NAXIS3 = %d", &n) == 1) {
+                processNaxisN(3, n, gotNaxis, hP->naxis, &gotN3, &hP->naxis3);
+            } else if (sscanf(buf, "DATAMIN = %lf", &(hP->datamin)) == 1) {
+            } else if (sscanf(buf, "DATAMAX = %lf", &(hP->datamax)) == 1) {
+            } else if (sscanf(buf, "BZERO = %lf", &(hP->bzer)) == 1) {
+            } else if (sscanf(buf, "BSCALE = %lf", &(hP->bscale)) == 1) {
+            } else if (strncmp(buf, "END ", 4 ) == 0) {
+                gotEnd = true;
+                if (gotEmpty == true)
+                    pm_message("Blank card(s) were encountered before "
+			       "END in header");
+            }
         }
     }
+    if (!gotSimple)
+        pm_error("FITS header missing the SIMPLE keyword");
+    if (!gotBitpix)
+        pm_error("FITS header missing the BITPIX keyword");
+    if (!gotNaxis)
+        pm_error("FITS header missing the NAXIS keyword");
+
+    if (hP->naxis > 3)
+        pm_error("FITS file has %u axes; this program can handle "
+                 "no more than 3", hP->naxis);
+
+    if (hP->naxis > 0 && !gotN1)
+        pm_error("FITS header missing NAXIS1 keyword");
+    if (hP->naxis > 1 && !gotN2)
+        pm_error("FITS header missing NAXIS1 keyword");
+    if (hP->naxis > 2 && !gotN3)
+        pm_error("FITS header missing NAXIS3 keyword");
 }
 
 
@@ -424,7 +504,7 @@ interpretPlanes(struct FITS_Header const fitsHeader,
         if (imageRequest) {
             if (imageRequest > fitsHeader.naxis3)
                 pm_error("Only %u plane%s in this file.  "
-                         "You requested image %u", 
+                         "You requested image %u",
                          fitsHeader.naxis3, fitsHeader.naxis3 > 1 ? "s" : "",
                          imageRequest);
             else {
@@ -449,7 +529,7 @@ interpretPlanes(struct FITS_Header const fitsHeader,
         }
     }
     if (verbose) {
-        
+
         pm_message("FITS stream is %smultiplane", *multiplaneP ? "" : "not ");
         pm_message("We will take image %u (1 is first) of %u "
                    "in the FITS stream",
@@ -464,7 +544,7 @@ scanImageForMinMax(FILE *       const ifP,
                    unsigned int const images,
                    int          const cols,
                    int          const rows,
-                   valFmt       const valFmt,
+                   ValFmt       const valFmt,
                    double       const bscale,
                    double       const bzer,
                    unsigned int const imagenum,
@@ -479,7 +559,7 @@ scanImageForMinMax(FILE *       const ifP,
     unsigned int image;
     pm_filepos rasterPos;
     double fmaxval;
-    
+
     pm_tell2(ifP, &rasterPos, sizeof(rasterPos));
 
     pm_message("Scanning file for scaling parameters");
@@ -557,7 +637,7 @@ computeMinMax(FILE *             const ifP,
     if (datamin == -DBL_MAX || datamax == DBL_MAX) {
         double scannedDatamin, scannedDatamax;
         scanImageForMinMax(ifP, images, cols, rows,
-                           valFmtFromBitpix(h.bitpix), h.bscale, h.bzer,
+                           h.valFmt, h.bscale, h.bzer,
                            imagenum, multiplane,
                            &scannedDatamin, &scannedDatamax);
 
@@ -574,12 +654,12 @@ computeMinMax(FILE *             const ifP,
 
 static xelval
 determineMaxval(struct CmdlineInfo const cmdline,
-                valFmt             const valFmt,
+                ValFmt             const valFmt,
                 double             const datamax,
                 double             const datamin) {
 
     xelval retval;
-                
+
     if (cmdline.omaxvalSpec)
         retval = cmdline.omaxval;
     else {
@@ -615,11 +695,11 @@ convertPgmRaster(FILE *                const ifP,
                  xelval                const maxval,
                  unsigned int          const desiredImage,
                  unsigned int          const imageCount,
-                 struct fitsRasterInfo const rasterInfo,
+                 struct FitsRasterInfo const rasterInfo,
                  double                const scale,
                  double                const datamin,
                  xel **                const xels) {
-        
+
     /* Note: the FITS specification does not give the association between
        file position and image position (i.e. is the first pixel in the
        file the top left, bottom left, etc.).  We use the common sense,
@@ -651,7 +731,7 @@ convertPgmRaster(FILE *                const ifP,
                 }
             }
         }
-    } 
+    }
 }
 
 
@@ -661,7 +741,7 @@ convertPpmRaster(FILE *                const ifP,
                  unsigned int          const cols,
                  unsigned int          const rows,
                  xelval                const maxval,
-                 struct fitsRasterInfo const rasterInfo,
+                 struct FitsRasterInfo const rasterInfo,
                  double                const scale,
                  double                const datamin,
                  xel **                const xels) {
@@ -711,7 +791,7 @@ convertRaster(FILE *                const ifP,
               bool                  const multiplane,
               unsigned int          const desiredImage,
               unsigned int          const imageCount,
-              struct fitsRasterInfo const rasterInfo,
+              struct FitsRasterInfo const rasterInfo,
               double                const scale,
               double                const datamin) {
 
@@ -746,7 +826,7 @@ main(int argc, const char * argv[]) {
     double scale;
     double datamin, datamax;
     struct FITS_Header fitsHeader;
-    struct fitsRasterInfo rasterInfo;
+    struct FitsRasterInfo rasterInfo;
 
     unsigned int imageCount;
     unsigned int desiredImage;
@@ -757,15 +837,15 @@ main(int argc, const char * argv[]) {
         /* This is a one-image multiplane stream; 'desiredImage'
            is undefined
         */
-  
+
     pm_proginit(&argc, argv);
-  
+
     parseCommandLine(argc, argv, &cmdline);
 
     ifP = pm_openr(cmdline.inputFileName);
 
     readFitsHeader(ifP, &fitsHeader);
-  
+
     if (!fitsHeader.simple)
         pm_error("FITS file is not in simple format, can't read");
 
@@ -777,7 +857,7 @@ main(int argc, const char * argv[]) {
 
     rasterInfo.bscale = fitsHeader.bscale;
     rasterInfo.bzer   = fitsHeader.bzer;
-    rasterInfo.valFmt = valFmtFromBitpix(fitsHeader.bitpix);
+    rasterInfo.valFmt = fitsHeader.valFmt;
 
     interpretPlanes(fitsHeader, cmdline.image, cmdline.verbose,
                     &imageCount, &multiplane, &desiredImage);
diff --git a/converter/other/gemtopnm.c b/converter/other/gemtopnm.c
index d862213f..6bbfcc05 100644
--- a/converter/other/gemtopnm.c
+++ b/converter/other/gemtopnm.c
@@ -25,7 +25,7 @@
  *
  * 92/07/11 Johann Haider
  * Changed to read from stdin if file is omitted
- * Changed to handle line length not a multipe of 8
+ * Changed to handle line length not a multiple of 8
  *
  * 94/01/31 Andreas Schwab (schwab@ls5.informatik.uni-dortmund.de)
  * Changed to remove architecture dependency and conform to
diff --git a/converter/other/giftopnm.c b/converter/other/giftopnm.c
index e2d5923d..470c85b7 100644
--- a/converter/other/giftopnm.c
+++ b/converter/other/giftopnm.c
@@ -867,7 +867,7 @@ termStack(struct Stack * const stackP) {
 
    What we call 'dataWidth', others call the "minimum code size," which is a
    misnomer, because the minimum code size in a stream must be at least one
-   more than 'dataWidth', to accomodate the clear and end codes.
+   more than 'dataWidth', to accommmodate the clear and end codes.
 -----------------------------------------------------------------------------*/
 
 static int const maxLzwCodeCt = (1<<MAX_LZW_BITS);
@@ -1722,7 +1722,7 @@ readImageData(FILE *       const ifP,
         pm_error("Invalid data width (bits for a true data item) "
                  "in image data: %u.  "
                  "Maximum allowable code size in GIF is %u, "
-                 "and a code has to be wide enough to accomodate both "
+                 "and a code has to be wide enough to accommodate both "
                  "all possible data values and two control codes",
                  lzwDataWidth, MAX_LZW_BITS);
 
diff --git a/converter/other/infotopam.c b/converter/other/infotopam.c
index f2e35827..24c4d776 100644
--- a/converter/other/infotopam.c
+++ b/converter/other/infotopam.c
@@ -99,7 +99,7 @@ typedef struct IconInfo_ {
 typedef struct IconHeader_ { /* 20 bytes */
     unsigned char pad0[4];        /* Padding (always seems to be zero) */
     unsigned char iconWidth[2];   /* Width (usually equal to Gadget width) */
-    unsigned char iconHeight[2];  
+    unsigned char iconHeight[2];
     /* Height (usually equal to Gadget height -1) */
     unsigned char bpp[2];         /* Bits per pixel */
     unsigned char pad1[10];       /* ??? */
@@ -134,7 +134,7 @@ parseCommandLine( int              argc,
     unsigned int numColorArgs,  /* Number of arguments for overriding colors */
         colorIdx,      /* Color index */
         i;             /* Argument index */
-    const char  * const colors[4] = { 
+    const char  * const colors[4] = {
         /* Pixel colors based on original Amiga colors */
         "#0055AA",    /*   Blue      0,  85, 170 */
         "#FFFFFF",    /*   White   255, 255, 255 */
@@ -147,7 +147,7 @@ parseCommandLine( int              argc,
     optStruct3    opt;
     unsigned int  option_def_index;
     unsigned int numColorsSpec, forceColorSpec, selectedSpec;
-  
+
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     /* Set command line options */
@@ -166,7 +166,7 @@ parseCommandLine( int              argc,
     infoP->depth = 0;
     infoP->icon = NULL;
     for ( colorIdx = 0; colorIdx < 4; colorIdx++ )
-        infoP->colors[colorIdx] = 
+        infoP->colors[colorIdx] =
             ppm_parsecolor( (char*) colors[colorIdx], 0xFF );
 
     /* Initialize option structure */
@@ -258,7 +258,7 @@ getDiskObject( IconInfo * const infoP ) {
 
 
 
-static void 
+static void
 getIconHeader(IconInfo * const infoP) {
 /*-------------------------------------------------------------------------
  * Get fields from icon header portion of info file
@@ -277,7 +277,7 @@ getIconHeader(IconInfo * const infoP) {
                  "Only read 0x%X of 0x%X bytes",
                  infoP->name, (unsigned)bytesRead, (unsigned)sizeof(ihead));
 
-    /* Get icon width, heigh, and bitplanes */
+    /* Get icon width, height, and bitplanes */
     infoP->width  = (ihead.iconWidth[0]  << 8) + ihead.iconWidth[1];
     infoP->height = (ihead.iconHeight[0] << 8) + ihead.iconHeight[1];
     infoP->depth  = (ihead.bpp[0]        << 8) + ihead.bpp[1];
@@ -299,7 +299,7 @@ addBitplane(unsigned char * const icon,
 -----------------------------------------------------------------------------*/
     unsigned int i;
     unsigned int j;
-    
+
     for (i = j = 0; i < bpsize; ++i, j += 8) {
         icon[j+0] = (icon[j+0] << 1) | ((buff[i] >> 0) & 0x01);
         icon[j+1] = (icon[j+1] << 1) | ((buff[i] >> 1) & 0x01);
@@ -317,7 +317,7 @@ addBitplane(unsigned char * const icon,
 static void
 readIconData(FILE *           const fileP,
              unsigned int     const width,
-             unsigned int     const height, 
+             unsigned int     const height,
              unsigned int     const depth,
              unsigned char ** const iconP) {
 /*-------------------------------------------------------------------------
@@ -330,7 +330,7 @@ readIconData(FILE *           const fileP,
     unsigned int const bpsize = height * (((width + 15) / 16) * 2);
         /* Bitplane size in bytes, with padding */
 
-  
+
     MALLOCARRAY(buff, bpsize);
     if ( buff == NULL )
         pm_error( "Cannot allocate memory to hold icon pixels" );
@@ -350,10 +350,10 @@ readIconData(FILE *           const fileP,
      * points to the next byte in buff to fill in.  When the inner
      * loop is done, bp points to the end of buff.
      *
-     * After reading in the entire bitplane, the second inner loop splits the 
-     * eight pixels in each byte of the bitplane into eight separate bytes in 
-     * the icon buffer.  The existing contents of each byte in icon are left 
-     * shifted by one to make room for the next bit. 
+     * After reading in the entire bitplane, the second inner loop splits the
+     * eight pixels in each byte of the bitplane into eight separate bytes in
+     * the icon buffer.  The existing contents of each byte in icon are left
+     * shifted by one to make room for the next bit.
      *
      * Each byte in the completed icon contains a value from 0 to
      * 2^depth (0 to 1 for depth of 1 and 0 to 3 for a depth of 3).
@@ -363,7 +363,7 @@ readIconData(FILE *           const fileP,
         /* Read bitplane into buffer */
         int toread;   /* Number of bytes left to read */
         unsigned char * buffp;    /* Buffer point for reading data */
-       
+
         toread = bpsize; buffp = &buff[0];
 
         while (toread > 0) {
@@ -378,7 +378,7 @@ readIconData(FILE *           const fileP,
                 pm_error("Premature end-of-file.  "
                          "Still have 0x%X bytes to read",
                          toread );
-            
+
             toread -= bytesRead;
             buffp  += bytesRead;
         }
@@ -542,3 +542,6 @@ main( int argc,
 
     return 0;
 }
+
+
+
diff --git a/converter/other/ipdb.c b/converter/other/ipdb.c
index 5e4dc82e..d524c7e9 100644
--- a/converter/other/ipdb.c
+++ b/converter/other/ipdb.c
@@ -23,15 +23,12 @@
 #define _XOPEN_SOURCE 500  /* Make sure strdup() is in string.h */
 #define _BSD_SOURCE   /* Ensure strdup() is in <string.h> */
 #include <assert.h>
-#include <time.h>
 #include <string.h>
 
 #include "mallocvar.h"
 #include "nstring.h"
-#include "ipdb.h"
-
-typedef uint32_t pilot_time_t;
 
+#include "ipdb.h"
 
 
 
@@ -49,7 +46,7 @@ imgPpb(IMAGE * const imgP) {
 
 
 unsigned int
-ipdb_img_ppb(IMAGE * const imgP) {
+ipdb_imgPpb(IMAGE * const imgP) {
 /*----------------------------------------------------------------------------
    Pixels per byte
 -----------------------------------------------------------------------------*/
@@ -59,7 +56,7 @@ ipdb_img_ppb(IMAGE * const imgP) {
 
 
 size_t
-ipdb_img_size(IMAGE * const imgP) {
+ipdb_imgSize(IMAGE * const imgP) {
 /*----------------------------------------------------------------------------
   Size (in bytes) of an image's data.
 -----------------------------------------------------------------------------*/
@@ -71,115 +68,97 @@ ipdb_img_size(IMAGE * const imgP) {
 /*
  * Return the start of row `r'.
  */
- uint8_t *
- ipdb_img_row(IMAGE *      const imgP,
-              unsigned int const row) {
-
-     return &imgP->data[(row) * imgP->width / imgPpb(imgP)];
- }
-
-
+uint8_t *
+ipdb_imgRow(IMAGE *      const imgP,
+            unsigned int const row) {
 
- #define img_row(i, r)   
-
- static pilot_time_t const unixepoch = (66*365+17)*24*3600;
-     /* The unix epoch in Mac time (the Mac epoch is 00:00 UTC 1904.01.01).
-        The 17 is the number of leap years.
-     */
-
- static const char * const errorDesc[] = {
-     /* E_BADCOLORS      */
-     "Invalid palette, only {0x00, 0x55, 0xAA, 0xFF} allowed.",
+    return &imgP->data[(row) * imgP->width / imgPpb(imgP)];
+}
 
-     /* E_NOTIMAGE       */
-     "Not an image file.",
 
-     /* E_IMAGETHERE     */
-     "Image record already present, logic error.",
 
-     /* E_IMAGENOTTHERE  */
-     "Image record required before text record, logic error.",
+static const char * const errorDesc[] = {
+    /* E_BADCOLORS      */
+    "Invalid palette, only {0x00, 0x55, 0xAA, 0xFF} allowed.",
 
-     /* E_TEXTTHERE      */
-     "Text record already present, logic error.",
+    /* E_NOTIMAGE       */
+    "Not an image file.",
 
-     /* E_NOTRECHDR      */
-     "Invalid record header encountered.",
+    /* E_IMAGETHERE     */
+    "Image record already present, logic error.",
 
-     /* E_UNKNOWNRECHDR  */
-     "Unknown record header.",
+    /* E_IMAGENOTTHERE  */
+    "Image record required before text record, logic error.",
 
-     /* E_TOOBIGG        */
-     "Image too big, maximum size approx. 640*400 gray pixels.",
+    /* E_TEXTTHERE      */
+    "Text record already present, logic error.",
 
-     /* E_TOOBIGM        */
-     "Image too big, maximum size approx. 640*800 monochrome pixels.",
- };
+    /* E_NOTRECHDR      */
+    "Invalid record header encountered.",
 
+    /* E_UNKNOWNRECHDR  */
+    "Unknown record header.",
 
+    /* E_TOOBIGG        */
+    "Image too big, maximum size approx. 640*400 gray pixels.",
 
- const char *
- ipdb_err(int const e) {
+    /* E_TOOBIGM        */
+    "Image too big, maximum size approx. 640*800 monochrome pixels.",
+};
 
-     if (e < 0)
-         return e >= E_LAST ? errorDesc[-e - 1] : "unknown error";
-     else
-         return strerror(e);
- }
 
 
+const char *
+ipdb_err(int const e) {
 
- static void
- rechdr_free(RECHDR * const recP) {
+    if (e < 0)
+        return e >= E_LAST ? errorDesc[-e - 1] : "unknown error";
+    else
+        return strerror(e);
+}
 
-     if (recP) {
-         free(recP->extra);
-         free(recP);
-     }
- }
 
 
+static void
+rechdr_free(RECHDR * const recP) {
 
- void
- ipdb_image_free(IMAGE * const imgP) {
+    if (recP) {
+        free(recP->extra);
+        free(recP);
+    }
+}
 
-     if (imgP) {
-         rechdr_free(imgP->r);
-         free(imgP->data);
-         free(imgP);
-     }
- }
 
 
+void
+ipdb_imageFree(IMAGE * const imgP) {
 
- void
- ipdb_text_free(TEXT * const textP) {
+    if (imgP) {
+        rechdr_free(imgP->r);
+        free(imgP->data);
+        free(imgP);
+    }
+}
 
-     if (textP) {
-         rechdr_free(textP->r);
-         free(textP->data);
-         free(textP);
-     }
- }
 
 
+void
+ipdb_textFree(TEXT * const textP) {
 
- void
- ipdb_pdbhead_free(PDBHEAD * const headP) {
+    if (textP) {
+        rechdr_free(textP->r);
+        if (textP->data)
+            free(textP->data);
+        free(textP);
+    }
+}
 
-     free(headP);
- }
 
 
+void
+ipdb_pdbheadFree(PDBHEAD * const headP) {
 
- void
- ipdb_clear(IPDB * const pdbP) {
-     
-     if (pdbP) {
-         ipdb_image_free(pdbP->i);
-         ipdb_text_free(pdbP->t);
-         ipdb_pdbhead_free(pdbP->p);
-    }
+    free(headP);
 }
 
 
@@ -187,14 +166,22 @@ ipdb_img_size(IMAGE * const imgP) {
 void
 ipdb_free(IPDB * const pdbP) {
 
-    ipdb_clear(pdbP);
+    if (pdbP->i)
+        ipdb_imageFree(pdbP->i);
+
+    if (pdbP->t)
+        ipdb_textFree(pdbP->t);
+
+    if (pdbP->p)
+        ipdb_pdbheadFree(pdbP->p);
+
     free(pdbP);
 }
 
 
 
 PDBHEAD *
-ipdb_pdbhead_alloc(const char * const name) {
+ipdb_pdbheadAlloc() {
 
     PDBHEAD * pdbHeadP;
 
@@ -202,20 +189,6 @@ ipdb_pdbhead_alloc(const char * const name) {
 
     if (pdbHeadP) {
         MEMSZERO(pdbHeadP);
-
-        STRSCPY(pdbHeadP->name, name == NULL ? "unnamed" : name);
-
-        /*
-         * All of the Image Viewer pdb files that I've come across have
-         * 3510939142U (1997.08.16 14:38:22 UTC) here.  I don't know where
-         * this bizarre date comes from but the real date works fine so
-         * I'm using it.
-         */
-        pdbHeadP->ctime =
-            pdbHeadP->mtime = (pilot_time_t)time(NULL) + unixepoch;
-        
-        MEMSCPY(&pdbHeadP->type, IPDB_vIMG);
-        MEMSCPY(&pdbHeadP->id,   IPDB_View);
     }
     return pdbHeadP;
 }
@@ -223,7 +196,7 @@ ipdb_pdbhead_alloc(const char * const name) {
 
 
 static RECHDR *
-rechdr_alloc(int      const type,
+rechdrCreate(int      const type,
              uint32_t const offset) {
 
     /*
@@ -234,7 +207,7 @@ rechdr_alloc(int      const type,
     RECHDR  * recHdrP;
 
     MALLOCVAR(recHdrP);
-    
+
     if (recHdrP) {
         MEMSSET(recHdrP, 0);
 
@@ -255,10 +228,10 @@ rechdr_alloc(int      const type,
 
 
 IMAGE *
-ipdb_image_alloc(const char * const name,
-            int          const type,
-            int          const w,
-            int          const h) {
+ipdb_imageCreate(const char * const name,
+                 int          const type,
+                 int          const w,
+                 int          const h) {
 
     bool failed;
     IMAGE * imgP;
@@ -277,7 +250,7 @@ ipdb_image_alloc(const char * const name,
         imgP->width    = w;
         imgP->height   = h;
 
-        imgP->r = rechdr_alloc(IMG_REC, IMGOFFSET);
+        imgP->r = rechdrCreate(IMG_REC, IMGOFFSET);
 
         if (imgP->r) {
             if (w != 0 && h != 0) {
@@ -292,10 +265,10 @@ ipdb_image_alloc(const char * const name,
                 rechdr_free(imgP->r);
         } else
             failed = true;
-        
+
         if (failed)
-            ipdb_image_free(imgP);
-    } else 
+            ipdb_imageFree(imgP);
+    } else
         failed = true;
 
     return failed ? NULL : imgP;
@@ -304,7 +277,7 @@ ipdb_image_alloc(const char * const name,
 
 
 TEXT *
-ipdb_text_alloc(const char * const content) {
+ipdb_textAlloc(void) {
 
     TEXT * textP;
     bool failed;
@@ -320,22 +293,13 @@ ipdb_text_alloc(const char * const content) {
     if (textP) {
         MEMSZERO(textP);
 
-        textP->r = rechdr_alloc(TEXT_REC, 0);
+        textP->r = rechdrCreate(TEXT_REC, 0);
 
-        if (textP->r) {
-            if (content) {
-                textP->data = strdup(content);
-
-                if (!textP->data)
-                    failed = true;
-            }
-            if (failed)
-                rechdr_free(textP->r);
-        } else
+        if (textP->r == NULL)
             failed = true;
 
         if (failed)
-            ipdb_text_free(textP);
+            free(textP);
     } else
         failed = true;
 
@@ -345,7 +309,7 @@ ipdb_text_alloc(const char * const content) {
 
 
 IPDB *
-ipdb_alloc(const char * const name) {
+ipdb_alloc(void) {
 
     IPDB * pdbP;
     bool failed;
@@ -357,12 +321,11 @@ ipdb_alloc(const char * const name) {
     if (pdbP) {
         MEMSZERO(pdbP);
 
-        if (name) {
-            pdbP->p = ipdb_pdbhead_alloc(name);
+        pdbP->p = ipdb_pdbheadAlloc();
+
+        if (!pdbP->p)
+            failed = true;
 
-            if (!pdbP->p)
-                failed = true;
-        }
         if (failed)
             ipdb_free(pdbP);
     } else
@@ -383,3 +346,6 @@ ipdb_typeName(uint8_t const type) {
     default: return "???";
     }
 }
+
+
+
diff --git a/converter/other/ipdb.h b/converter/other/ipdb.h
index 6af5fc44..59e5d266 100644
--- a/converter/other/ipdb.h
+++ b/converter/other/ipdb.h
@@ -201,43 +201,40 @@ const char *
 ipdb_err(int error);
 
 size_t
-ipdb_img_size(IMAGE * const imgP);
+ipdb_imgSize(IMAGE * const imgP);
 
 unsigned int
-ipdb_img_ppb(IMAGE * const imgP);
+ipdb_imgPpb(IMAGE * const imgP);
 
 uint8_t *
-ipdb_img_row(IMAGE *      const imgP,
+ipdb_imgRow(IMAGE *      const imgP,
              unsigned int const row);
 
 void
 ipdb_free(IPDB *);
 
 IPDB *
-ipdb_alloc(const char *);
-
-void
-ipdb_clear(IPDB * const pdbP);
+ipdb_alloc(void);
 
 PDBHEAD *
-ipdb_pdbhead_alloc(const char * const name);
+ipdb_pdbheadAlloc(void);
 
 void
-ipdb_pdbhead_free(PDBHEAD * const headP);
+ipdb_pdbheadFree(PDBHEAD * const headP);
 
 IMAGE *
-ipdb_image_alloc(const char * const name,
+ipdb_imageCreate(const char * const name,
                  int          const type,
                  int          const w,
                  int          const h);
 
 void
-ipdb_image_free(IMAGE * const imgP);
+ipdb_imageFree(IMAGE * const imgP);
 
 void
-ipdb_text_free(TEXT * const textP);
+ipdb_textFree(TEXT * const textP);
 
 TEXT *
-ipdb_text_alloc(const char * const content);
+ipdb_textAlloc(void);
 
 #endif
diff --git a/converter/other/jbig/libjbig/include/jbig_ar.h b/converter/other/jbig/libjbig/include/jbig_ar.h
index d58b1ae0..ed5f2f86 100644
--- a/converter/other/jbig/libjbig/include/jbig_ar.h
+++ b/converter/other/jbig/libjbig/include/jbig_ar.h
@@ -14,7 +14,7 @@
 
 struct jbg_arenc_state {
   unsigned char st[4096];    /* probability status for contexts, MSB = MPS */
-  unsigned long c;                /* register C: base of coding intervall, *
+  unsigned long c;                /* register C: base of coding interval,  *
                                    * layout as in Table 23                 */
   unsigned long a;       /* register A: normalized size of coding interval */
   long sc;     /* number of buffered 0xff values that might still overflow */
@@ -30,7 +30,7 @@ struct jbg_arenc_state {
 
 struct jbg_ardec_state {
   unsigned char st[4096];    /* probability status for contexts, MSB = MPS */
-  unsigned long c;                /* register C: base of coding intervall, *
+  unsigned long c;                /* register C: base of coding interval,  *
                                    * layout as in Table 25                 */
   unsigned long a;       /* register A: normalized size of coding interval */
   unsigned char *pscd_ptr;               /* pointer to next PSCD data byte */
diff --git a/converter/other/jbig/libjbig/jbig.c b/converter/other/jbig/libjbig/jbig.c
index e8141070..cf24a93b 100644
--- a/converter/other/jbig/libjbig/jbig.c
+++ b/converter/other/jbig/libjbig/jbig.c
@@ -109,7 +109,7 @@ static const char *errmsg[] = {
  * The following three functions are the only places in this code, were
  * C library memory management functions are called. The whole JBIG
  * library has been designed in order to allow multi-threaded
- * execution. No static or global variables are used, so all fuctions
+ * execution. No static or global variables are used, so all functions
  * are fully reentrant. However if you want to use this multi-thread
  * capability and your malloc, realloc and free are not reentrant,
  * then simply add the necessary semaphores or mutex primitives below.
@@ -776,7 +776,7 @@ void jbg_enc_init(struct jbg_enc_state *s, unsigned long x, unsigned long y,
   assert(x > 0 && y > 0 && planes > 0 && planes < 256);
   s->xd = x;
   s->yd = y;
-  s->yd1 = y; /* This is the hight initially announced in BIH. To provoke
+  s->yd1 = y; /* This is the height initially announced in BIH. To provoke
                  generation of NEWLEN for T.85 compatibility tests,
                  overwrite with new value s->yd1 > s->yd  */
   s->planes = planes;
@@ -1106,7 +1106,7 @@ static void encode_sde(struct jbg_enc_state *s,
 	    if (!at_determined && j >= s->mx && j < hx-2) {
 	      p = (line_h1 & 0x100) != 0; /* current pixel value */
 	      c[0] += ((line_h2 & 0x4000) != 0) == p; /* default position */
-	      assert(!(((line_h2 >> 6) ^ line_h1) & 0x100) ==
+	      assert((!(((line_h2 >> 6) ^ line_h1) & 0x100)) ==
 		     (((line_h2 & 0x4000) != 0) == p));
 	      for (t = 5; t <= s->mx && t <= j; t++) {
 		o = (j - t) - (j & ~7L);
@@ -1151,7 +1151,7 @@ static void encode_sde(struct jbg_enc_state *s,
 	    if (!at_determined && j >= s->mx && j < hx-2) {
 	      p = (line_h1 & 0x100) != 0; /* current pixel value */
 	      c[0] += ((line_h2 & 0x4000) != 0) == p; /* default position */
-	      assert(!(((line_h2 >> 6) ^ line_h1) & 0x100) ==
+	      assert((!(((line_h2 >> 6) ^ line_h1) & 0x100)) ==
 		     (((line_h2 & 0x4000) != 0) == p));
 	      for (t = 3; t <= s->mx && t <= j; t++) {
 		o = (j - t) - (j & ~7L);
@@ -3240,7 +3240,7 @@ static unsigned char *jbg_next_pscdms(unsigned char *p, size_t len)
  * depends on the fact that section 6.2.6.2 of ITU-T T.82 says that a
  * NEWLEN marker segment "could refer to a line in the immediately
  * preceding stripe due to an unexpected termination of the image or
- * the use of only such stripe". ITU-T.85 explicitely suggests the
+ * the use of only such stripe". ITU-T.85 explicitly suggests the
  * use of this for fax machines that start transmission before having
  * encountered the end of the page. None of this is necessary for
  * BIEs produced by JBIG-KIT, which normally does not use NEWLEN.
diff --git a/converter/other/jpeg2000/Makefile b/converter/other/jpeg2000/Makefile
index 6e5af8e7..9c8729ac 100644
--- a/converter/other/jpeg2000/Makefile
+++ b/converter/other/jpeg2000/Makefile
@@ -46,8 +46,8 @@ endif
 
 BINARIES = $(PORTBINARIES)
 
-OBJECTS = $(BINARIES:%=%.o)
-MERGE_OBJECTS = $(BINARIES:%=%.o2) 
+OBJECTS = $(BINARIES:%=%.o) libjasper_compat.o
+MERGE_OBJECTS = $(BINARIES:%=%.o2) libjasper_compat.o2
 ifeq ($(JASPERLIB),$(INTERNAL_JASPERLIB))
   # MERGE_OBJECTS contains relative paths, so $(INTERNAL_JASPERLIB) had better
   # be relative to the current directory.
@@ -63,7 +63,7 @@ include $(SRCDIR)/common.mk
 
 LIBOPTS = $(shell $(LIBOPT) $(JASPERLIB_USE))
 
-$(BINARIES): %: %.o $(JASPERLIB_DEP) $(LIBOPT)
+$(BINARIES): %: %.o libjasper_compat.o $(JASPERLIB_DEP) $(LIBOPT)
 $(BINARIES): LDFLAGS_TARGET = $(LIBOPTS) $(JASPERDEPLIBS)
 
 $(INTERNAL_JASPERLIB): $(BUILDDIR)/$(SUBDIR)/libjasper FORCE
diff --git a/converter/other/jpeg2000/jpeg2ktopam.c b/converter/other/jpeg2000/jpeg2ktopam.c
index b507f56e..bda0de2e 100644
--- a/converter/other/jpeg2000/jpeg2ktopam.c
+++ b/converter/other/jpeg2000/jpeg2ktopam.c
@@ -29,11 +29,9 @@
 
 #include "libjasper_compat.h"
 
-enum compmode {COMPMODE_INTEGER, COMPMODE_REAL};
 
-enum progression {PROG_LRCP, PROG_RLCP, PROG_RPCL, PROG_PCRL, PROG_CPRL};
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
@@ -44,15 +42,15 @@ struct cmdlineInfo {
 
 
 static void
-parseCommandLine(int argc, char ** argv,
-                 struct cmdlineInfo * const cmdlineP) {
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that many of the strings that this function returns in the
    *cmdlineP structure are actually in the supplied argv array.  And
    sometimes, one of these strings is actually just a suffix of an entry
    in argv!
 -----------------------------------------------------------------------------*/
-    optEntry *option_def;
+    optEntry * option_def;
     optStruct3 opt;
 
     unsigned int debuglevelSpec;
@@ -71,7 +69,7 @@ parseCommandLine(int argc, char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
+    pm_optParseOptions3(&argc, (char**)argv, opt, sizeof(opt), 0);
 
     if (!debuglevelSpec)
         cmdlineP->debuglevel = 0;
@@ -84,6 +82,7 @@ parseCommandLine(int argc, char ** argv,
         pm_error("Too many arguments.  The only argument accepted\n"
                  "is the input file specification");
 
+    free(option_def);
 }
 
 
@@ -114,9 +113,11 @@ static void
 readJ2k(const char *   const inputFilename,
         jas_image_t ** const jasperPP) {
 
+    const char * const options = "";
+
     jas_image_t * jasperP;
     jas_stream_t * instreamP;
-    const char * options;
+    const char * error;
 
     if (streq(inputFilename, "-")) {
         /* The input image is to be read from standard input. */
@@ -131,13 +132,10 @@ readJ2k(const char *   const inputFilename,
 
     validateJ2k(instreamP);
 
-    options = "";
-
-    jasperP = jas_image_decode(instreamP, jas_image_getfmt(instreamP),
-                               (char*)options);
-    if (jasperP == NULL)
-        pm_error("Unable to interpret JPEG-2000 input.  "
-                 "The Jasper library jas_image_decode() subroutine failed.");
+    pmjas_image_decode(instreamP, jas_image_getfmt(instreamP), options,
+                       &jasperP, &error);
+    if (error)
+        pm_error("Unable to interpret JPEG-2000 input.  %s", error);
 
     jas_stream_close(instreamP);
 
@@ -483,9 +481,9 @@ convertToPamPnm(struct pam *  const outpamP,
 
 
 int
-main(int argc, char **argv)
+main(int argc, const char **argv)
 {
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     struct pam outpam;
     int * jasperCmpt;  /* malloc'ed */
        /* jaspercmpt[P] is the component number for use with the
@@ -493,7 +491,7 @@ main(int argc, char **argv)
        */
     jas_image_t * jasperP;
 
-    pnm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
diff --git a/converter/other/jpeg2000/libjasper/base/jas_image.c b/converter/other/jpeg2000/libjasper/base/jas_image.c
index 5c2822be..c6f984c1 100644
--- a/converter/other/jpeg2000/libjasper/base/jas_image.c
+++ b/converter/other/jpeg2000/libjasper/base/jas_image.c
@@ -126,6 +126,8 @@
 #include <assert.h>
 #include <ctype.h>
 
+#include "netpbm/nstring.h"
+
 #include "jasper/jas_math.h"
 #include "jasper/jas_image.h"
 #include "jasper/jas_malloc.h"
@@ -379,22 +381,47 @@ static void jas_image_cmpt_destroy(jas_image_cmpt_t *cmpt)
 * Load and save operations.
 \*****************************************************************************/
 
-jas_image_t *jas_image_decode(jas_stream_t *in, int fmt, char *optstr)
-{
+void
+pmjas_image_decode(jas_stream_t * const in,
+				   int            const fmtArg,
+				   const char *   const optstr,
+				   jas_image_t ** const imagePP,
+				   const char **  const errorP) {
+/*----------------------------------------------------------------------------
+  Create an image from a stream in some specified format
+-----------------------------------------------------------------------------*/
 	jas_image_fmtinfo_t *fmtinfo;
+	int fmt;
 
 	/* If possible, try to determine the format of the input data. */
-	if (fmt < 0) {
+	if (fmtArg < 0) {
 		if ((fmt = jas_image_getfmt(in)) < 0) {
-			return 0;
+			pm_asprintf(errorP, "jas_image_getfmt failed");
+			return;
 		}
-	}
+	} else
+		fmt = fmtArg;
+
 	if (!(fmtinfo = jas_image_lookupfmtbyid(fmt))) {
-		return 0;
+		pm_asprintf(errorP, "jas_image_lookupfmtbyid of format %d failed",
+					fmt);
+		return;
+	}
+	{
+		const char * error;
+
+		(*fmtinfo->ops.decode)(in, optstr, imagePP, &error);
+		if (error) {
+			pm_asprintf(errorP, "decoder failed.  %s", error);
+			pm_strfree(error);
+		} else {
+			*errorP = NULL;
+		}
 	}
-	return (fmtinfo->ops.decode) ? (*fmtinfo->ops.decode)(in, optstr) : 0;
 }
 
+
+
 int jas_image_encode(jas_image_t *image, jas_stream_t *out, int fmt, char *optstr)
 {
 	jas_image_fmtinfo_t *fmtinfo;
@@ -648,7 +675,7 @@ int jas_image_fmtfromname(char *name)
 		return -1;
 	}
 	++ext;
-	/* Try to find a format that uses this extension. */	
+	/* Try to find a format that uses this extension. */
 	for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i,
 	  ++fmtinfo) {
 		/* Do we have a match? */
@@ -659,25 +686,28 @@ int jas_image_fmtfromname(char *name)
 	return -1;
 }
 
-/******************************************************************************\
+/*****************************************************************************\
 * Miscellaneous operations.
-\******************************************************************************/
+\*****************************************************************************/
 
-uint_fast32_t jas_image_rawsize(jas_image_t *image)
-{
-	uint_fast32_t rawsize;
-	uint_fast32_t cmptno;
-	jas_image_cmpt_t *cmpt;
+uint_fast32_t
+jas_image_rawsize(jas_image_t * const imageP) {
+/*----------------------------------------------------------------------------
+   The raw size of the image, i.e. the number of bytes the raster of the image
+   would take if just represented simply, with no compression.
+-----------------------------------------------------------------------------*/
+    uint_fast32_t rawsize;
+    uint_fast32_t cmptno;
 
-	rawsize = 0;
-	for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno) {
-		cmpt = image->cmpts_[cmptno];
-		rawsize += (cmpt->width_ * cmpt->height_ * cmpt->prec_ +
-		  7) / 8;
-	}
-	return rawsize;
+    for (cmptno = 0, rawsize = 0; cmptno < imageP->numcmpts_; ++cmptno) {
+        jas_image_cmpt_t * const cmptP = imageP->cmpts_[cmptno];
+        rawsize += (cmptP->width_ * cmptP->height_ * cmptP->prec_ + 7) / 8;
+    }
+    return rawsize;
 }
 
+
+
 void jas_image_delcmpt(jas_image_t *image, uint_fast16_t cmptno)
 {
 	if (cmptno >= image->numcmpts_) {
diff --git a/converter/other/jpeg2000/libjasper/base/jas_stream.c b/converter/other/jpeg2000/libjasper/base/jas_stream.c
index 24f835ed..a4b3a27c 100644
--- a/converter/other/jpeg2000/libjasper/base/jas_stream.c
+++ b/converter/other/jpeg2000/libjasper/base/jas_stream.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,10 +106,11 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
+#define _DEFAULT_SOURCE /* New name for SVID & BSD source defines */
 #define _SVID_SOURCE
     /* Make sure P_tmpdir is defined in GNU libc 2.0.7 (_XOPEN_SOURCE 500
        does it in other libc's).  pm_config.h defines TMPDIR as P_tmpdir
@@ -276,7 +277,7 @@ jas_stream_t *jas_stream_memopen(char *buf, int bufsize)
 		obj->len_ = 0;
 	}
 	obj->pos_ = 0;
-	
+
 	return stream;
 }
 
@@ -409,7 +410,7 @@ jas_stream_t *jas_stream_tmpfile()
         */
         jmp_buf jmpbuf;
         int rc;
-        
+
         rc = setjmp(jmpbuf);
         if (rc == 0) {
             pm_setjmpbuf(&jmpbuf);
diff --git a/converter/other/jpeg2000/libjasper/include/jasper/jas_image.h b/converter/other/jpeg2000/libjasper/include/jasper/jas_image.h
index 6e914efd..20170986 100644
--- a/converter/other/jpeg2000/libjasper/include/jasper/jas_image.h
+++ b/converter/other/jpeg2000/libjasper/include/jasper/jas_image.h
@@ -300,7 +300,10 @@ typedef struct {
 
 typedef struct {
 
-	jas_image_t *(*decode)(jas_stream_t *in, char *opts);
+	void (*decode)(jas_stream_t * const in,
+				   const char *   const opts,
+				   jas_image_t ** const imagePP,
+				   const char **  const errorP);
 	/* Decode image data from a stream. */
 
 	int (*encode)(jas_image_t *image, jas_stream_t *out, char *opts);
@@ -442,8 +445,14 @@ void jas_image_destroy(jas_image_t *image);
   any compression. */
 uint_fast32_t jas_image_rawsize(jas_image_t *image);
 
-/* Create an image from a stream in some specified format. */
-jas_image_t *jas_image_decode(jas_stream_t *in, int fmt, char *optstr);
+#define JAS_HAVE_PMJAS_IMAGE_DECODE
+
+void
+pmjas_image_decode(jas_stream_t * const in,
+				   int            const fmt,
+				   const char *   const optstr,
+				   jas_image_t ** const imagePP,
+				   const char **  const errorP);
 
 /* Write an image to a stream in a specified format. */
 int jas_image_encode(jas_image_t *image, jas_stream_t *out, int fmt,
@@ -567,14 +576,22 @@ int bmp_validate(jas_stream_t *in);
 
 #if !defined(EXCLUDE_JP2_CAPABILITY)
 /* Format-dependent operations for JP2 capability. */
-jas_image_t *jp2_decode(jas_stream_t *in, char *optstr);
+void
+jp2_decode(jas_stream_t * const in,
+		   const char *   const optstr,
+		   jas_image_t ** const imagePP,
+		   const char **  const errorP);
 int jp2_encode(jas_image_t *image, jas_stream_t *out, char *optstr);
 int jp2_validate(jas_stream_t *in);
 #endif
 
 #if !defined(EXCLUDE_JPC_CAPABILITY)
 /* Format-dependent operations for JPEG-2000 code stream capability. */
-jas_image_t *jpc_decode(jas_stream_t *in, char *optstr);
+void
+jpc_decode(jas_stream_t * const in,
+           const char *   const optstr,
+           jas_image_t ** const imagePP,
+           const char **  const errorP);
 int jpc_encode(jas_image_t *image, jas_stream_t *out, char *optstr);
 int jpc_validate(jas_stream_t *in);
 #endif
diff --git a/converter/other/jpeg2000/libjasper/jp2/jp2_dec.c b/converter/other/jpeg2000/libjasper/jp2/jp2_dec.c
index 4036f0f2..e8d71b0a 100644
--- a/converter/other/jpeg2000/libjasper/jp2/jp2_dec.c
+++ b/converter/other/jpeg2000/libjasper/jp2/jp2_dec.c
@@ -117,6 +117,8 @@
 #include "jasper/jas_malloc.h"
 #include "jasper/jas_version.h"
 
+#include "netpbm/nstring.h"
+
 #include "jp2_cod.h"
 #include "jp2_dec.h"
 
@@ -271,8 +273,11 @@ fromiccpcs(int cs) {
 
 
 
-jas_image_t *
-jp2_decode(jas_stream_t *in, char *optstr) {
+void
+jp2_decode(jas_stream_t * const in,
+           const char *   const optstr,
+           jas_image_t ** const imagePP,
+           const char **  const errorP) {
 
     jp2_box_t *box;
     int found;
@@ -295,32 +300,34 @@ jp2_decode(jas_stream_t *in, char *optstr) {
     image = 0;
 
     if (!(dec = jp2_dec_create())) {
-        goto error;
+        pm_asprintf(errorP, "jp2_dec_create failed");
+        goto cleanup;
     }
 
     /* Get the first box.  This should be a JP box. */
     if (!(box = jp2_box_get(in))) {
-        jas_eprintf("error: cannot get box\n");
-        goto error;
+        pm_asprintf(errorP, "cannot get box");
+        goto cleanup;
     }
     if (box->type != JP2_BOX_JP) {
-        jas_eprintf("error: expecting signature box\n");
-        goto error;
+        pm_asprintf(errorP, "expecting signature box");
+        goto cleanup;
     }
     if (box->data.jp.magic != JP2_JP_MAGIC) {
-        jas_eprintf("incorrect magic number\n");
-        goto error;
+        pm_asprintf(errorP, "incorrect magic number");
+        goto cleanup;
     }
     jp2_box_destroy(box);
     box = 0;
 
     /* Get the second box.  This should be a FTYP box. */
     if (!(box = jp2_box_get(in))) {
-        goto error;
+        pm_asprintf(errorP, "cannot get second box");
+        goto cleanup;
     }
     if (box->type != JP2_BOX_FTYP) {
-        jas_eprintf("expecting file type box\n");
-        goto error;
+        pm_asprintf(errorP, "expecting file type box");
+        goto cleanup;
     }
     jp2_box_destroy(box);
     box = 0;
@@ -329,7 +336,7 @@ jp2_decode(jas_stream_t *in, char *optstr) {
     found = 0;
     while ((box = jp2_box_get(in))) {
         if (jas_getdbglevel() >= 1) {
-            fprintf(stderr, "box type %s\n", box->info->name);
+            jas_eprintf("box type '%s'\n", box->info->name);
         }
         switch (box->type) {
         case JP2_BOX_JP2C:
@@ -382,19 +389,24 @@ jp2_decode(jas_stream_t *in, char *optstr) {
     }
 
     if (!found) {
-        jas_eprintf("error: no code stream found\n");
-        goto error;
+        pm_asprintf(errorP, "no code stream found");
+        goto cleanup;
     }
 
-    if (!(dec->image = jpc_decode(in, optstr))) {
-        jas_eprintf("error: cannot decode code stream\n");
-        goto error;
+    {
+        const char * decodeError;
+        jpc_decode(in, optstr, &dec->image, &decodeError);
+        if (decodeError) {
+            pm_asprintf(errorP, "cannot decode code stream.  %s", decodeError);
+            pm_strfree(decodeError);
+            goto cleanup;
+        }
     }
 
     /* An IHDR box must be present. */
     if (!dec->ihdr) {
-        jas_eprintf("error: missing IHDR box\n");
-        goto error;
+        pm_asprintf(errorP, "missing IHDR box");
+        goto cleanup;
     }
 
     /* Does the number of components indicated in the IHDR box match
@@ -405,8 +417,8 @@ jp2_decode(jas_stream_t *in, char *optstr) {
 
     /* At least one component must be present. */
     if (!jas_image_numcmpts(dec->image)) {
-        jas_eprintf("error: no components\n");
-        goto error;
+        pm_asprintf(errorP, "no components");
+        goto cleanup;
     }
 
     /* Determine if all components have the same data type. */
@@ -428,15 +440,15 @@ jp2_decode(jas_stream_t *in, char *optstr) {
 
     /* Can we handle the compression type? */
     if (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) {
-        jas_eprintf("error: not capable of this compression type\n");
-        goto error;
+        pm_asprintf(errorP, "not capable of this compression type");
+        goto cleanup;
     }
 
     if (dec->bpcc) {
         /* Is the number of components indicated in the BPCC box
           consistent with the code stream data? */
         if (dec->bpcc->data.bpcc.numcmpts != jas_image_numcmpts(
-          dec->image)) {
+                dec->image)) {
             jas_eprintf("warning: number of components mismatch\n");
         }
         /* Is the component data type information indicated in the BPCC
@@ -455,8 +467,8 @@ jp2_decode(jas_stream_t *in, char *optstr) {
 
     /* A COLR box must be present. */
     if (!dec->colr) {
-        jas_eprintf("error: no COLR box\n");
-        goto error;
+        pm_asprintf(errorP, "no COLR box");
+        goto cleanup;
     }
 
     switch (dec->colr->data.colr.method) {
@@ -502,14 +514,14 @@ jp2_decode(jas_stream_t *in, char *optstr) {
             /* Is the component number reasonable? */
             if (dec->cmap->data.cmap.ents[i].cmptno >=
                 jas_image_numcmpts(dec->image)) {
-                jas_eprintf("error: invalid component number in CMAP box\n");
-                goto error;
+                pm_asprintf(errorP, "invalid component number in CMAP box");
+                goto cleanup;
             }
             /* Is the LUT index reasonable? */
             if (dec->cmap->data.cmap.ents[i].pcol >=
                 dec->pclr->data.pclr.numchans) {
-                jas_eprintf("error: invalid CMAP LUT index\n");
-                goto error;
+                pm_asprintf(errorP, "invalid CMAP LUT index");
+                goto cleanup;
             }
         }
     }
@@ -517,8 +529,8 @@ jp2_decode(jas_stream_t *in, char *optstr) {
     /* Allocate space for the channel-number to component-number LUT. */
     dec->chantocmptlut = jas_malloc(dec->numchans * sizeof(uint_fast16_t));
     if (!dec->chantocmptlut) {
-        jas_eprintf("error: no memory\n");
-        goto error;
+        pm_asprintf(errorP, "no memory");
+        goto cleanup;
     }
 
     if (!dec->cmap) {
@@ -564,8 +576,8 @@ jp2_decode(jas_stream_t *in, char *optstr) {
                 }
 #endif
             } else {
-                jas_eprintf("error: invalid MTYP in CMAP box\n");
-                goto error;
+                pm_asprintf(errorP, "invalid MTYP in CMAP box");
+                goto cleanup;
             }
         }
     }
@@ -604,8 +616,8 @@ jp2_decode(jas_stream_t *in, char *optstr) {
 
     /* Ensure that some components survived. */
     if (!jas_image_numcmpts(dec->image)) {
-        jas_eprintf("error: no components\n");
-        goto error;
+        pm_asprintf(errorP, "no components");
+        goto cleanup;
     }
 
     /* Prevent the image from being destroyed later. */
@@ -614,16 +626,17 @@ jp2_decode(jas_stream_t *in, char *optstr) {
 
     jp2_dec_destroy(dec);
 
-    return image;
+    *imagePP = image;
+    *errorP = NULL;
+    return;
 
-error:
+cleanup:
     if (box) {
         jp2_box_destroy(box);
     }
     if (dec) {
         jp2_dec_destroy(dec);
     }
-    return 0;
 }
 
 
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_dec.c b/converter/other/jpeg2000/libjasper/jpc/jpc_dec.c
index 4d4dfc50..140169ec 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_dec.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_dec.c
@@ -114,15 +114,13 @@
  * $Id$
  */
 
-/*****************************************************************************\
-* Includes.
-\*****************************************************************************/
-
 #include <stdio.h>
 #include <stdlib.h>
+#include <stdbool.h>
 #include <assert.h>
 
 #include "pm.h"
+#include "netpbm/nstring.h"
 
 #include "jasper/jas_types.h"
 #include "jasper/jas_math.h"
@@ -164,7 +162,10 @@ typedef struct {
     /* The states in which this type of marker segment can be
       validly encountered. */
 
-    int (*action)(jpc_dec_t *dec, jpc_ms_t *ms);
+    void (*action)(jpc_dec_t *   const dec,
+                   jpc_ms_t *    const ms,
+                   bool *        const doneP,
+                   const char ** const errorP);
     /* The action to take upon encountering this type of marker segment. */
 
 } jpc_dec_mstabent_t;
@@ -223,119 +224,263 @@ static void jpc_dec_cp_destroy(jpc_dec_cp_t *cp);
 static int jpc_dec_cp_setfrompoc(jpc_dec_cp_t *cp, jpc_poc_t *poc, int reset);
 static int jpc_pi_addpchgfrompoc(jpc_pi_t *pi, jpc_poc_t *poc);
 
-static int jpc_dec_decode(jpc_dec_t *dec);
 static jpc_dec_t *jpc_dec_create(jpc_dec_importopts_t *impopts, jas_stream_t *in);
 static void jpc_dec_destroy(jpc_dec_t *dec);
 static void jpc_dequantize(jas_matrix_t *x, jpc_fix_t absstepsize);
 static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps);
 static jpc_fix_t jpc_calcabsstepsize(int stepsize, int numbits);
-static int jpc_dec_tiledecode(jpc_dec_t *dec, jpc_dec_tile_t *tile);
 static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile);
 static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile);
-static int jpc_dec_process_soc(jpc_dec_t *dec, jpc_ms_t *ms);
-static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms);
-static int jpc_dec_process_sod(jpc_dec_t *dec, jpc_ms_t *ms);
-static int jpc_dec_process_eoc(jpc_dec_t *dec, jpc_ms_t *ms);
-static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms);
-static int jpc_dec_process_cod(jpc_dec_t *dec, jpc_ms_t *ms);
-static int jpc_dec_process_coc(jpc_dec_t *dec, jpc_ms_t *ms);
-static int jpc_dec_process_rgn(jpc_dec_t *dec, jpc_ms_t *ms);
-static int jpc_dec_process_qcd(jpc_dec_t *dec, jpc_ms_t *ms);
-static int jpc_dec_process_qcc(jpc_dec_t *dec, jpc_ms_t *ms);
-static int jpc_dec_process_poc(jpc_dec_t *dec, jpc_ms_t *ms);
-static int jpc_dec_process_ppm(jpc_dec_t *dec, jpc_ms_t *ms);
-static int jpc_dec_process_ppt(jpc_dec_t *dec, jpc_ms_t *ms);
-static int jpc_dec_process_com(jpc_dec_t *dec, jpc_ms_t *ms);
-static int jpc_dec_process_unk(jpc_dec_t *dec, jpc_ms_t *ms);
-static int jpc_dec_process_crg(jpc_dec_t *dec, jpc_ms_t *ms);
-static int jpc_dec_parseopts(char *optstr, jpc_dec_importopts_t *opts);
 
-/******************************************************************************\
-* Global data.
-\******************************************************************************/
 
-jpc_dec_mstabent_t jpc_dec_mstab[] = {
-    {JPC_MS_SOC, JPC_MHSOC, jpc_dec_process_soc},
-    {JPC_MS_SOT, JPC_MH | JPC_TPHSOT, jpc_dec_process_sot},
-    {JPC_MS_SOD, JPC_TPH, jpc_dec_process_sod},
-    {JPC_MS_EOC, JPC_TPHSOT, jpc_dec_process_eoc},
-    {JPC_MS_SIZ, JPC_MHSIZ, jpc_dec_process_siz},
-    {JPC_MS_COD, JPC_MH | JPC_TPH, jpc_dec_process_cod},
-    {JPC_MS_COC, JPC_MH | JPC_TPH, jpc_dec_process_coc},
-    {JPC_MS_RGN, JPC_MH | JPC_TPH, jpc_dec_process_rgn},
-    {JPC_MS_QCD, JPC_MH | JPC_TPH, jpc_dec_process_qcd},
-    {JPC_MS_QCC, JPC_MH | JPC_TPH, jpc_dec_process_qcc},
-    {JPC_MS_POC, JPC_MH | JPC_TPH, jpc_dec_process_poc},
-    {JPC_MS_TLM, JPC_MH, 0},
-    {JPC_MS_PLM, JPC_MH, 0},
-    {JPC_MS_PLT, JPC_TPH, 0},
-    {JPC_MS_PPM, JPC_MH, jpc_dec_process_ppm},
-    {JPC_MS_PPT, JPC_TPH, jpc_dec_process_ppt},
-    {JPC_MS_SOP, 0, 0},
-    {JPC_MS_CRG, JPC_MH, jpc_dec_process_crg},
-    {JPC_MS_COM, JPC_MH | JPC_TPH, jpc_dec_process_com},
-    {0, JPC_MH | JPC_TPH, jpc_dec_process_unk}
-};
 
-/*****************************************************************************\
-* The main entry point for the JPEG-2000 decoder.
-\*****************************************************************************/
+static void
+jpc_dec_tiledecode(jpc_dec_t *      const dec,
+                   jpc_dec_tile_t * const tile,
+                   const char **    const errorP) {
 
-jas_image_t *jpc_decode(jas_stream_t *in, char *optstr)
-{
-    jpc_dec_importopts_t opts;
-    jpc_dec_t *dec;
-    jas_image_t *image;
+    int i;
+    int j;
+    jpc_dec_tcomp_t *tcomp;
+    jpc_dec_rlvl_t *rlvl;
+    jpc_dec_band_t *band;
+    int compno;
+    int rlvlno;
+    int bandno;
+    int adjust;
+    int v;
+    jpc_dec_ccp_t *ccp;
+    jpc_dec_cmpt_t *cmpt;
+    const char * error;
 
-    dec = 0;
+    jpc_dec_decodecblks(dec, tile, &error);
 
-    if (jpc_dec_parseopts(optstr, &opts)) {
-        goto error;
+    if (error) {
+        pm_asprintf(errorP, "jpc_dec_decodecblks failed.  %s", error);
+        return;
     }
 
-    jpc_initluts();
+    /* Perform dequantization. */
+    for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
+         ++compno, ++tcomp) {
+        ccp = &tile->cp->ccps[compno];
+        for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls;
+             ++rlvlno, ++rlvl) {
+            if (!rlvl->bands) {
+                continue;
+            }
+            for (bandno = 0, band = rlvl->bands;
+                 bandno < rlvl->numbands; ++bandno, ++band) {
+                if (!band->data) {
+                    continue;
+                }
+                jpc_undo_roi(band->data, band->roishift, ccp->roishift -
+                             band->roishift, band->numbps);
+                if (tile->realmode) {
+                    jas_matrix_asl(band->data, JPC_FIX_FRACBITS);
+                    jpc_dequantize(band->data, band->absstepsize);
+                }
 
-    if (!(dec = jpc_dec_create(&opts, in))) {
-        goto error;
+            }
+        }
     }
 
-    /* Do most of the work. */
-    if (jpc_dec_decode(dec)) {
-        goto error;
+    /* Apply an inverse wavelet transform if necessary. */
+    for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
+         ++compno, ++tcomp) {
+        ccp = &tile->cp->ccps[compno];
+        jpc_tsfb_synthesize(tcomp->tsfb,
+                            ((ccp->qmfbid ==
+                              JPC_COX_RFT) ? JPC_TSFB_RITIMODE : 0),
+                            tcomp->data);
     }
 
-    if (jas_image_numcmpts(dec->image) >= 3) {
-        jas_image_setcolorspace(dec->image, JAS_IMAGE_CS_RGB);
-        jas_image_setcmpttype(dec->image, 0,
-          JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_RGB_R));
-        jas_image_setcmpttype(dec->image, 1,
-          JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_RGB_G));
-        jas_image_setcmpttype(dec->image, 2,
-          JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_RGB_B));
-    } else {
-        jas_image_setcolorspace(dec->image, JAS_IMAGE_CS_GRAY);
-        jas_image_setcmpttype(dec->image, 0,
-          JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_GRAY_Y));
+
+    /* Apply an inverse intercomponent transform if necessary. */
+    switch (tile->cp->mctid) {
+    case JPC_MCT_RCT:
+        assert(dec->numcomps == 3);
+        jpc_irct(tile->tcomps[0].data, tile->tcomps[1].data,
+                 tile->tcomps[2].data);
+        break;
+    case JPC_MCT_ICT:
+        assert(dec->numcomps == 3);
+        jpc_iict(tile->tcomps[0].data, tile->tcomps[1].data,
+                 tile->tcomps[2].data);
+        break;
     }
 
-    /* Save the return value. */
-    image = dec->image;
+    /* Perform rounding and convert to integer values. */
+    if (tile->realmode) {
+        for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
+             ++compno, ++tcomp) {
+            for (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) {
+                for (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) {
+                    v = jas_matrix_get(tcomp->data, i, j);
+                    v = jpc_fix_round(v);
+                    jas_matrix_set(tcomp->data, i, j, jpc_fixtoint(v));
+                }
+            }
+        }
+    }
 
-    /* Stop the image from being discarded. */
-    dec->image = 0;
+    /* Perform level shift. */
+    for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <
+             dec->numcomps; ++compno, ++tcomp, ++cmpt) {
+        adjust = cmpt->sgnd ? 0 : (1 << (cmpt->prec - 1));
+        for (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) {
+            for (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) {
+                *jas_matrix_getref(tcomp->data, i, j) += adjust;
+            }
+        }
+    }
 
-    /* Destroy decoder. */
-    jpc_dec_destroy(dec);
+    /* Perform clipping. */
+    for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <
+             dec->numcomps; ++compno, ++tcomp, ++cmpt) {
+        jpc_fix_t mn;
+        jpc_fix_t mx;
+        mn = cmpt->sgnd ? (-(1 << (cmpt->prec - 1))) : (0);
+        mx = cmpt->sgnd ? ((1 << (cmpt->prec - 1)) - 1) : ((1 <<
+                                                            cmpt->prec) - 1);
+        jas_matrix_clip(tcomp->data, mn, mx);
+    }
 
-    return image;
+    /* XXX need to free tsfb struct */
 
-error:
-    if (dec) {
-        jpc_dec_destroy(dec);
+    /* Write the data for each component of the image. */
+    for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <
+             dec->numcomps; ++compno, ++tcomp, ++cmpt) {
+        if (jas_image_writecmpt(dec->image, compno, tcomp->xstart -
+                                JPC_CEILDIV(dec->xstart, cmpt->hstep),
+                                tcomp->ystart -
+                                JPC_CEILDIV(dec->ystart, cmpt->vstep),
+                                jas_matrix_numcols(
+                                    tcomp->data),
+                                jas_matrix_numrows(tcomp->data),
+                                tcomp->data)) {
+            pm_asprintf(errorP, "write component failed");
+            return;
+        }
     }
-    return 0;
+    *errorP = NULL;
 }
 
+
+
+static void
+jpc_dec_process_sod(jpc_dec_t *   const dec,
+                    jpc_ms_t *    const ms,
+                    bool *        const doneP,
+                    const char ** const errorP) {
+
+    jpc_dec_tile_t *tile;
+    int pos;
+
+    if (!(tile = dec->curtile)) {
+        pm_asprintf(errorP, "No current tile");
+        return;
+    }
+
+    if (!tile->partno) {
+        if (!jpc_dec_cp_isvalid(tile->cp)) {
+            pm_asprintf(errorP, "CP is not valid");
+            return;
+        }
+        if (jpc_dec_cp_prepare(tile->cp)) {
+            pm_asprintf(errorP, "fpc_dec_cp_prepare failed");
+            return;
+        }
+        if (jpc_dec_tileinit(dec, tile)) {
+            pm_asprintf(errorP, "jpc_dec_tileinit failed");
+            return;
+        }
+    }
+
+    /* Are packet headers stored in the main header or tile-part header? */
+    if (dec->pkthdrstreams) {
+        /* Get the stream containing the packet header data for this
+          tile-part. */
+        if (!(tile->pkthdrstream = jpc_streamlist_remove(dec->pkthdrstreams, 0))) {
+            pm_asprintf(errorP, "jpc_streamlist_remove failed");
+            return;
+        }
+    }
+
+    if (tile->pptstab) {
+        if (!tile->pkthdrstream) {
+            if (!(tile->pkthdrstream = jas_stream_memopen(0, 0))) {
+                pm_asprintf(errorP, "jas_stream_memopen failed");
+                return;
+            }
+        }
+        pos = jas_stream_tell(tile->pkthdrstream);
+        jas_stream_seek(tile->pkthdrstream, 0, SEEK_END);
+        if (jpc_pptstabwrite(tile->pkthdrstream, tile->pptstab)) {
+            pm_asprintf(errorP, "jpc_pptstabwrite failed");
+            return;
+        }
+        jas_stream_seek(tile->pkthdrstream, pos, SEEK_SET);
+        jpc_ppxstab_destroy(tile->pptstab);
+        tile->pptstab = 0;
+    }
+
+    if (jas_getdbglevel() >= 10) {
+        jpc_dec_dump(dec, stderr);
+    }
+
+    if (jpc_dec_decodepkts(dec, (tile->pkthdrstream) ? tile->pkthdrstream :
+      dec->in, dec->in)) {
+        pm_asprintf(errorP, "jpc_dec_decodepkts failed");
+        return;
+    }
+
+    /* Gobble any unconsumed tile data. */
+    if (dec->curtileendoff > 0) {
+        uint_fast32_t curoff;
+        uint_fast32_t n;
+        curoff = jas_stream_getrwcount(dec->in);
+        if (curoff < dec->curtileendoff) {
+            n = dec->curtileendoff - curoff;
+            pm_message("warning: ignoring trailing garbage (%lu bytes)",
+                       (unsigned long) n);
+
+            while (n-- > 0) {
+                if (jas_stream_getc(dec->in) == EOF) {
+                    pm_asprintf(errorP, "read error");
+                    return;
+                }
+            }
+        } else if (curoff > dec->curtileendoff) {
+            pm_message("warning: not enough tile data (%lu bytes)",
+                       (unsigned long) curoff - dec->curtileendoff);
+        }
+    }
+
+    if (tile->numparts > 0 && tile->partno == tile->numparts - 1) {
+        const char * error;
+        jpc_dec_tiledecode(dec, tile, &error);
+        if (error) {
+            pm_asprintf(errorP, "jpc_dec_tiledecode failed.  %s", error);
+            pm_strfree(error);
+            return;
+        }
+        jpc_dec_tilefini(dec, tile);
+    }
+
+    dec->curtile = 0;
+
+    /* Increment the expected tile-part number. */
+    ++tile->partno;
+
+    /* We should expect to encounter a SOT marker segment next. */
+    dec->state = JPC_TPHSOT;
+
+    *errorP = NULL;
+}
+
+
+
 typedef enum {
     OPT_MAXLYRS,
     OPT_MAXPKTS,
@@ -349,7 +494,8 @@ jas_taginfo_t decopts[] = {
     {-1, 0}
 };
 
-static int jpc_dec_parseopts(char *optstr, jpc_dec_importopts_t *opts)
+static int
+jpc_dec_parseopts(const char *optstr, jpc_dec_importopts_t *opts)
 {
     jas_tvparser_t *tvp;
 
@@ -374,8 +520,8 @@ static int jpc_dec_parseopts(char *optstr, jpc_dec_importopts_t *opts)
             opts->maxpkts = atoi(jas_tvparser_getval(tvp));
             break;
         default:
-            fprintf(stderr, "warning: ignoring invalid option %s\n",
-              jas_tvparser_gettag(tvp));
+            pm_message("warning: ignoring invalid option %s",
+                       jas_tvparser_gettag(tvp));
             break;
         }
     }
@@ -385,79 +531,14 @@ static int jpc_dec_parseopts(char *optstr, jpc_dec_importopts_t *opts)
     return 0;
 }
 
-/******************************************************************************\
-* Code for table-driven code stream decoder.
-\******************************************************************************/
-
-static jpc_dec_mstabent_t *jpc_dec_mstab_lookup(uint_fast16_t id)
-{
-    jpc_dec_mstabent_t *mstabent;
-    for (mstabent = jpc_dec_mstab; mstabent->id != 0; ++mstabent) {
-        if (mstabent->id == id) {
-            break;
-        }
-    }
-    return mstabent;
-}
-
-static int jpc_dec_decode(jpc_dec_t *dec)
-{
-    jpc_ms_t *ms;
-    jpc_dec_mstabent_t *mstabent;
-    int ret;
-    jpc_cstate_t *cstate;
-
-    if (!(cstate = jpc_cstate_create())) {
-        return -1;
-    }
-    dec->cstate = cstate;
-
-    /* Initially, we should expect to encounter a SOC marker segment. */
-    dec->state = JPC_MHSOC;
-
-    for (;;) {
-
-        /* Get the next marker segment in the code stream. */
-        if (!(ms = jpc_getms(dec->in, cstate))) {
-            fprintf(stderr, "cannot get marker segment\n");
-            return -1;
-        }
-
-        mstabent = jpc_dec_mstab_lookup(ms->id);
-        assert(mstabent);
-
-        /* Ensure that this type of marker segment is permitted
-          at this point in the code stream. */
-        if (!(dec->state & mstabent->validstates)) {
-            fprintf(stderr, "unexpected marker segment type\n");
-            jpc_ms_destroy(ms);
-            return -1;
-        }
-
-        /* Process the marker segment. */
-        if (mstabent->action) {
-            ret = (*mstabent->action)(dec, ms);
-        } else {
-            /* No explicit action is required. */
-            ret = 0;
-        }
-
-        /* Destroy the marker segment. */
-        jpc_ms_destroy(ms);
-
-        if (ret < 0) {
-            return -1;
-        } else if (ret > 0) {
-            break;
-        }
 
-    }
 
-    return 0;
-}
+static void
+jpc_dec_process_crg(jpc_dec_t *   const dec,
+                    jpc_ms_t *    const ms,
+                    bool *        const doneP,
+                    const char ** const errorP) {
 
-static int jpc_dec_process_crg(jpc_dec_t *dec, jpc_ms_t *ms)
-{
     /* Ignore the information in the CRG marker segment for now.
        This information serves no useful purpose for decoding anyhow.
        Some other parts of the code need to be changed if these lines
@@ -475,19 +556,33 @@ static int jpc_dec_process_crg(jpc_dec_t *dec, jpc_ms_t *ms)
         cmpt->vsubstep = crg->comps[cmptno].voff;
     }
 #endif
-    return 0;
+    *doneP = false;
+    *errorP = NULL;
 }
 
-static int jpc_dec_process_soc(jpc_dec_t *dec, jpc_ms_t *ms)
-{
+
+
+static void
+jpc_dec_process_soc(jpc_dec_t *   const dec,
+                    jpc_ms_t *    const ms,
+                    bool *        const doneP,
+                    const char ** const errorP) {
+
     /* We should expect to encounter a SIZ marker segment next. */
     dec->state = JPC_MHSIZ;
 
-    return 0;
+    *doneP = false;
+    *errorP = NULL;
 }
 
-static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms)
-{
+
+
+static void
+jpc_dec_process_sot(jpc_dec_t *   const dec,
+                    jpc_ms_t *    const ms,
+                    bool *        const doneP,
+                    const char ** const errorP) {
+
     jpc_dec_tile_t *tile;
     jpc_sot_t *sot = &ms->parms.sot;
     jas_image_cmptparm_t *compinfos;
@@ -512,8 +607,9 @@ static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms)
         }
 
         if (!(dec->image = jas_image_create(dec->numcomps, compinfos,
-          JAS_IMAGE_CS_UNKNOWN))) {
-            return -1;
+                                            JAS_IMAGE_CS_UNKNOWN))) {
+            pm_asprintf(errorP, "jas_image_create failed");
+            return;
         }
         jas_free(compinfos);
 
@@ -538,18 +634,20 @@ static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms)
     }
 
     if (sot->tileno > dec->numtiles) {
-        fprintf(stderr, "invalid tile number in SOT marker segment\n");
-        return -1;
+        pm_asprintf(errorP, "invalid tile number in SOT marker segment");
+        return;
     }
     /* Set the current tile. */
     dec->curtile = &dec->tiles[sot->tileno];
     tile = dec->curtile;
     /* Ensure that this is the expected part number. */
     if (sot->partno != tile->partno) {
-        return -1;
+        pm_asprintf(errorP, "Unexpected part number");
+        return;
     }
     if (tile->numparts > 0 && sot->partno >= tile->numparts) {
-        return -1;
+        pm_asprintf(errorP, "part number greater than number of parts");
+        return;
     }
     if (!tile->numparts && sot->numparts > 0) {
         tile->numparts = sot->numparts;
@@ -563,7 +661,8 @@ static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms)
         tile->state = JPC_TILE_ACTIVE;
         assert(!tile->cp);
         if (!(tile->cp = jpc_dec_cp_copy(dec->cp))) {
-            return -1;
+            pm_asprintf(errorP, "jpc_dec_cp_copy failed");
+            return;
         }
         jpc_dec_cp_resetflags(dec->cp);
         break;
@@ -581,107 +680,11 @@ static int jpc_dec_process_sot(jpc_dec_t *dec, jpc_ms_t *ms)
       segments next. */
     dec->state = JPC_TPH;
 
-    return 0;
+    *doneP = false;
+    *errorP = NULL;
 }
 
-static int jpc_dec_process_sod(jpc_dec_t *dec, jpc_ms_t *ms)
-{
-    jpc_dec_tile_t *tile;
-    int pos;
-
-    if (!(tile = dec->curtile)) {
-        return -1;
-    }
-
-    if (!tile->partno) {
-        if (!jpc_dec_cp_isvalid(tile->cp)) {
-            return -1;
-        }
-        if (jpc_dec_cp_prepare(tile->cp)) {
-            return -1;
-        }
-        if (jpc_dec_tileinit(dec, tile)) {
-            return -1;
-        }
-    }
-
-    /* Are packet headers stored in the main header or tile-part header? */
-    if (dec->pkthdrstreams) {
-        /* Get the stream containing the packet header data for this
-          tile-part. */
-        if (!(tile->pkthdrstream = jpc_streamlist_remove(dec->pkthdrstreams, 0))) {
-            return -1;
-        }
-    }
-
-    if (tile->pptstab) {
-        if (!tile->pkthdrstream) {
-            if (!(tile->pkthdrstream = jas_stream_memopen(0, 0))) {
-                return -1;
-            }
-        }
-        pos = jas_stream_tell(tile->pkthdrstream);
-        jas_stream_seek(tile->pkthdrstream, 0, SEEK_END);
-        if (jpc_pptstabwrite(tile->pkthdrstream, tile->pptstab)) {
-            return -1;
-        }
-        jas_stream_seek(tile->pkthdrstream, pos, SEEK_SET);
-        jpc_ppxstab_destroy(tile->pptstab);
-        tile->pptstab = 0;
-    }
-
-    if (jas_getdbglevel() >= 10) {
-        jpc_dec_dump(dec, stderr);
-    }
-
-    if (jpc_dec_decodepkts(dec, (tile->pkthdrstream) ? tile->pkthdrstream :
-      dec->in, dec->in)) {
-        fprintf(stderr, "jpc_dec_decodepkts failed\n");
-        return -1;
-    }
-
-    /* Gobble any unconsumed tile data. */
-    if (dec->curtileendoff > 0) {
-        uint_fast32_t curoff;
-        uint_fast32_t n;
-        curoff = jas_stream_getrwcount(dec->in);
-        if (curoff < dec->curtileendoff) {
-            n = dec->curtileendoff - curoff;
-            fprintf(stderr,
-              "warning: ignoring trailing garbage (%lu bytes)\n",
-              (unsigned long) n);
-
-            while (n-- > 0) {
-                if (jas_stream_getc(dec->in) == EOF) {
-                    fprintf(stderr, "read error\n");
-                    return -1;
-                }
-            }
-        } else if (curoff > dec->curtileendoff) {
-            fprintf(stderr,
-              "warning: not enough tile data (%lu bytes)\n",
-              (unsigned long) curoff - dec->curtileendoff);
-        }
-
-    }
-
-    if (tile->numparts > 0 && tile->partno == tile->numparts - 1) {
-        if (jpc_dec_tiledecode(dec, tile)) {
-            return -1;
-        }
-        jpc_dec_tilefini(dec, tile);
-    }
-
-    dec->curtile = 0;
-
-    /* Increment the expected tile-part number. */
-    ++tile->partno;
-
-    /* We should expect to encounter a SOT marker segment next. */
-    dec->state = JPC_TPHSOT;
 
-    return 0;
-}
 
 static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile)
 {
@@ -1059,136 +1062,25 @@ if (!prc->cblks) {
     return 0;
 }
 
-static int jpc_dec_tiledecode(jpc_dec_t *dec, jpc_dec_tile_t *tile)
-{
-    int i;
-    int j;
-    jpc_dec_tcomp_t *tcomp;
-    jpc_dec_rlvl_t *rlvl;
-    jpc_dec_band_t *band;
-    int compno;
-    int rlvlno;
-    int bandno;
-    int adjust;
-    int v;
-    jpc_dec_ccp_t *ccp;
-    jpc_dec_cmpt_t *cmpt;
 
-    if (jpc_dec_decodecblks(dec, tile)) {
-        fprintf(stderr, "jpc_dec_decodecblks failed\n");
-        return -1;
-    }
 
-    /* Perform dequantization. */
-    for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
-      ++compno, ++tcomp) {
-        ccp = &tile->cp->ccps[compno];
-        for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls;
-          ++rlvlno, ++rlvl) {
-            if (!rlvl->bands) {
-                continue;
-            }
-            for (bandno = 0, band = rlvl->bands;
-              bandno < rlvl->numbands; ++bandno, ++band) {
-                if (!band->data) {
-                    continue;
-                }
-                jpc_undo_roi(band->data, band->roishift, ccp->roishift -
-                  band->roishift, band->numbps);
-                if (tile->realmode) {
-                    jas_matrix_asl(band->data, JPC_FIX_FRACBITS);
-                    jpc_dequantize(band->data, band->absstepsize);
-                }
+static void
+jpc_dec_process_eoc(jpc_dec_t *   const dec,
+                    jpc_ms_t *    const ms,
+                    bool *        const doneP,
+                    const char ** const errorP) {
 
-            }
-        }
-    }
-
-    /* Apply an inverse wavelet transform if necessary. */
-    for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
-      ++compno, ++tcomp) {
-        ccp = &tile->cp->ccps[compno];
-        jpc_tsfb_synthesize(tcomp->tsfb, ((ccp->qmfbid ==
-          JPC_COX_RFT) ? JPC_TSFB_RITIMODE : 0), tcomp->data);
-    }
-
-
-    /* Apply an inverse intercomponent transform if necessary. */
-    switch (tile->cp->mctid) {
-    case JPC_MCT_RCT:
-        assert(dec->numcomps == 3);
-        jpc_irct(tile->tcomps[0].data, tile->tcomps[1].data,
-          tile->tcomps[2].data);
-        break;
-    case JPC_MCT_ICT:
-        assert(dec->numcomps == 3);
-        jpc_iict(tile->tcomps[0].data, tile->tcomps[1].data,
-          tile->tcomps[2].data);
-        break;
-    }
-
-    /* Perform rounding and convert to integer values. */
-    if (tile->realmode) {
-        for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
-          ++compno, ++tcomp) {
-            for (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) {
-                for (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) {
-                    v = jas_matrix_get(tcomp->data, i, j);
-                    v = jpc_fix_round(v);
-                    jas_matrix_set(tcomp->data, i, j, jpc_fixtoint(v));
-                }
-            }
-        }
-    }
-
-    /* Perform level shift. */
-    for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <
-      dec->numcomps; ++compno, ++tcomp, ++cmpt) {
-        adjust = cmpt->sgnd ? 0 : (1 << (cmpt->prec - 1));
-        for (i = 0; i < jas_matrix_numrows(tcomp->data); ++i) {
-            for (j = 0; j < jas_matrix_numcols(tcomp->data); ++j) {
-                *jas_matrix_getref(tcomp->data, i, j) += adjust;
-            }
-        }
-    }
-
-    /* Perform clipping. */
-    for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <
-      dec->numcomps; ++compno, ++tcomp, ++cmpt) {
-        jpc_fix_t mn;
-        jpc_fix_t mx;
-        mn = cmpt->sgnd ? (-(1 << (cmpt->prec - 1))) : (0);
-        mx = cmpt->sgnd ? ((1 << (cmpt->prec - 1)) - 1) : ((1 <<
-          cmpt->prec) - 1);
-        jas_matrix_clip(tcomp->data, mn, mx);
-    }
-
-    /* XXX need to free tsfb struct */
-
-    /* Write the data for each component of the image. */
-    for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno <
-      dec->numcomps; ++compno, ++tcomp, ++cmpt) {
-        if (jas_image_writecmpt(dec->image, compno, tcomp->xstart -
-          JPC_CEILDIV(dec->xstart, cmpt->hstep), tcomp->ystart -
-          JPC_CEILDIV(dec->ystart, cmpt->vstep), jas_matrix_numcols(
-          tcomp->data), jas_matrix_numrows(tcomp->data), tcomp->data)) {
-            fprintf(stderr, "write component failed\n");
-            return -4;
-        }
-    }
-
-    return 0;
-}
-
-static int jpc_dec_process_eoc(jpc_dec_t *dec, jpc_ms_t *ms)
-{
     int tileno;
     jpc_dec_tile_t *tile;
     for (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,
       ++tile) {
         if (tile->state == JPC_TILE_ACTIVE) {
-            if (jpc_dec_tiledecode(dec, tile)) {
-                return -1;
+            const char * error;
+            jpc_dec_tiledecode(dec, tile, &error);
+            if (error) {
+                pm_asprintf(errorP, "jpc_dec_tiledecode failed.  %s", error);
+                pm_strfree(error);
+                return;
             }
         }
         jpc_dec_tilefini(dec, tile);
@@ -1197,11 +1089,17 @@ static int jpc_dec_process_eoc(jpc_dec_t *dec, jpc_ms_t *ms)
     /* We are done processing the code stream. */
     dec->state = JPC_MT;
 
-    return 1;
+    *doneP = true;
 }
 
-static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)
-{
+
+
+static void
+jpc_dec_process_siz(jpc_dec_t *   const dec,
+                    jpc_ms_t *    const ms,
+                    bool *        const doneP,
+                    const char ** const errorP) {
+
     jpc_siz_t *siz = &ms->parms.siz;
     uint_fast16_t compno;
     uint_fast32_t tileno;
@@ -1221,11 +1119,13 @@ static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)
     dec->tileyoff = siz->tileyoff;
     dec->numcomps = siz->numcomps;
     if (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) {
-        return -1;
+        pm_asprintf(errorP, "jpc_dec_cp_create failed");
+        return;
     }
 
     if (!(dec->cmpts = jas_malloc(dec->numcomps * sizeof(jpc_dec_cmpt_t)))) {
-        return -1;
+        pm_asprintf(errorP, "jas_malloc failed");
+        return;
     }
 
     for (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno,
@@ -1248,7 +1148,8 @@ static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)
     dec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight);
     dec->numtiles = dec->numhtiles * dec->numvtiles;
     if (!(dec->tiles = jas_malloc(dec->numtiles * sizeof(jpc_dec_tile_t)))) {
-        return -1;
+        pm_asprintf(errorP, "jas_malloc failed");
+        return;
     }
 
     for (tileno = 0, tile = dec->tiles;
@@ -1280,9 +1181,10 @@ static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)
         tile->pkthdrstreampos = 0;
         tile->pptstab = 0;
         tile->cp = 0;
-        if (!(tile->tcomps = jas_malloc(dec->numcomps *
-          sizeof(jpc_dec_tcomp_t)))) {
-            return -1;
+        tile->tcomps = jas_malloc(dec->numcomps * sizeof(jpc_dec_tcomp_t));
+        if (!tile->tcomps) {
+            pm_asprintf(errorP, "jas_malloc failed");
+            return;
         }
         for (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps;
           compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) {
@@ -1302,11 +1204,18 @@ static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)
       or an SOT marker segment next. */
     dec->state = JPC_MH;
 
-    return 0;
+    *doneP = false;
+    *errorP = NULL;
 }
 
-static int jpc_dec_process_cod(jpc_dec_t *dec, jpc_ms_t *ms)
-{
+
+
+static void
+jpc_dec_process_cod(jpc_dec_t *   const dec,
+                    jpc_ms_t *    const ms,
+                    bool *        const doneP,
+                    const char ** const errorP) {
+
     jpc_cod_t *cod = &ms->parms.cod;
     jpc_dec_tile_t *tile;
 
@@ -1316,26 +1225,34 @@ static int jpc_dec_process_cod(jpc_dec_t *dec, jpc_ms_t *ms)
         break;
     case JPC_TPH:
         if (!(tile = dec->curtile)) {
-            return -1;
+            pm_asprintf(errorP, "No current tile");
+            return;
         }
         if (tile->partno != 0) {
-            return -1;
+            pm_asprintf(errorP, "part number is not zero");
+            return;
         }
         jpc_dec_cp_setfromcod(tile->cp, cod);
         break;
     }
-    return 0;
+    *doneP = false;
+    *errorP = NULL;
 }
 
-static int jpc_dec_process_coc(jpc_dec_t *dec, jpc_ms_t *ms)
-{
+
+
+static void
+jpc_dec_process_coc(jpc_dec_t *   const dec,
+                    jpc_ms_t *    const ms,
+                    bool *        const doneP,
+                    const char ** const errorP) {
+
     jpc_coc_t *coc = &ms->parms.coc;
     jpc_dec_tile_t *tile;
 
     if (coc->compno > dec->numcomps) {
-        fprintf(stderr,
-          "invalid component number in COC marker segment\n");
-        return -1;
+        pm_asprintf(errorP, "invalid component number in COC marker segment");
+        return;
     }
     switch (dec->state) {
     case JPC_MH:
@@ -1343,26 +1260,34 @@ static int jpc_dec_process_coc(jpc_dec_t *dec, jpc_ms_t *ms)
         break;
     case JPC_TPH:
         if (!(tile = dec->curtile)) {
-            return -1;
+            pm_asprintf(errorP, "No current tile");
+            return;
         }
         if (tile->partno > 0) {
-            return -1;
+            pm_asprintf(errorP, "Part number is not zero");
+            return;
         }
         jpc_dec_cp_setfromcoc(tile->cp, coc);
         break;
     }
-    return 0;
+    *doneP = false;
+    *errorP = NULL;
 }
 
-static int jpc_dec_process_rgn(jpc_dec_t *dec, jpc_ms_t *ms)
-{
+
+
+static void
+jpc_dec_process_rgn(jpc_dec_t *   const dec,
+                    jpc_ms_t *    const ms,
+                    bool *        const doneP,
+                    const char ** const errorP) {
+
     jpc_rgn_t *rgn = &ms->parms.rgn;
     jpc_dec_tile_t *tile;
 
     if (rgn->compno > dec->numcomps) {
-        fprintf(stderr,
-          "invalid component number in RGN marker segment\n");
-        return -1;
+        pm_asprintf(errorP, "invalid component number in RGN marker segment");
+        return;
     }
     switch (dec->state) {
     case JPC_MH:
@@ -1370,20 +1295,29 @@ static int jpc_dec_process_rgn(jpc_dec_t *dec, jpc_ms_t *ms)
         break;
     case JPC_TPH:
         if (!(tile = dec->curtile)) {
-            return -1;
+            pm_asprintf(errorP, "No current tile");
+            return;
         }
         if (tile->partno > 0) {
-            return -1;
+            pm_asprintf(errorP, "Part number is not zero");
+            return;
         }
         jpc_dec_cp_setfromrgn(tile->cp, rgn);
         break;
     }
 
-    return 0;
+    *doneP = false;
+    *errorP = NULL;
 }
 
-static int jpc_dec_process_qcd(jpc_dec_t *dec, jpc_ms_t *ms)
-{
+
+
+static void
+jpc_dec_process_qcd(jpc_dec_t *   const dec,
+                    jpc_ms_t *    const ms,
+                    bool *        const doneP,
+                    const char ** const errorP) {
+
     jpc_qcd_t *qcd = &ms->parms.qcd;
     jpc_dec_tile_t *tile;
 
@@ -1393,26 +1327,34 @@ static int jpc_dec_process_qcd(jpc_dec_t *dec, jpc_ms_t *ms)
         break;
     case JPC_TPH:
         if (!(tile = dec->curtile)) {
-            return -1;
+            pm_asprintf(errorP, "No current tile");
+            return;
         }
         if (tile->partno > 0) {
-            return -1;
+            pm_asprintf(errorP, "Part number is not zero");
+            return;
         }
         jpc_dec_cp_setfromqcd(tile->cp, qcd);
         break;
     }
-    return 0;
+    *doneP = false;
+    *errorP = NULL;
 }
 
-static int jpc_dec_process_qcc(jpc_dec_t *dec, jpc_ms_t *ms)
-{
+
+
+static void
+jpc_dec_process_qcc(jpc_dec_t *   const dec,
+                    jpc_ms_t *    const ms,
+                    bool *        const doneP,
+                    const char ** const errorP) {
+
     jpc_qcc_t *qcc = &ms->parms.qcc;
     jpc_dec_tile_t *tile;
 
     if (qcc->compno > dec->numcomps) {
-        fprintf(stderr,
-          "invalid component number in QCC marker segment\n");
-        return -1;
+        pm_asprintf(errorP, "invalid component number in QCC marker segment");
+        return;
     }
     switch (dec->state) {
     case JPC_MH:
@@ -1420,69 +1362,98 @@ static int jpc_dec_process_qcc(jpc_dec_t *dec, jpc_ms_t *ms)
         break;
     case JPC_TPH:
         if (!(tile = dec->curtile)) {
-            return -1;
+            pm_asprintf(errorP, "No current tile");
+            return;
         }
         if (tile->partno > 0) {
-            return -1;
+            pm_asprintf(errorP, "Part number is not zero");
+            return;
         }
         jpc_dec_cp_setfromqcc(tile->cp, qcc);
         break;
     }
-    return 0;
+    *doneP = false;
+    *errorP = NULL;
 }
 
-static int jpc_dec_process_poc(jpc_dec_t *dec, jpc_ms_t *ms)
-{
+
+
+static void
+jpc_dec_process_poc(jpc_dec_t *   const dec,
+                    jpc_ms_t *    const ms,
+                    bool *        const doneP,
+                    const char ** const errorP) {
+
     jpc_poc_t *poc = &ms->parms.poc;
     jpc_dec_tile_t *tile;
     switch (dec->state) {
     case JPC_MH:
         if (jpc_dec_cp_setfrompoc(dec->cp, poc, 1)) {
-            return -1;
+            pm_asprintf(errorP, "jpc_dec_cp_setfrompoc failed");
+            return;
         }
         break;
     case JPC_TPH:
         if (!(tile = dec->curtile)) {
-            return -1;
+            pm_asprintf(errorP, "No current tile");
+            return;
         }
         if (!tile->partno) {
             if (jpc_dec_cp_setfrompoc(tile->cp, poc, (!tile->partno))) {
-                return -1;
+                pm_asprintf(errorP, "jpc_dec_cp_setfrompoc failed");
+                return;
             }
         } else {
             jpc_pi_addpchgfrompoc(tile->pi, poc);
         }
         break;
     }
-    return 0;
+    *doneP = false;
+    *errorP = NULL;
 }
 
-static int jpc_dec_process_ppm(jpc_dec_t *dec, jpc_ms_t *ms)
-{
+
+
+static void
+jpc_dec_process_ppm(jpc_dec_t *   const dec,
+                    jpc_ms_t *    const ms,
+                    bool *        const doneP,
+                    const char ** const errorP) {
+
     jpc_ppm_t *ppm = &ms->parms.ppm;
     jpc_ppxstabent_t *ppmstabent;
 
     if (!dec->ppmstab) {
         if (!(dec->ppmstab = jpc_ppxstab_create())) {
-            return -1;
+            pm_asprintf(errorP, "jpc_ppxstab_create failed");
+            return;
         }
     }
 
     if (!(ppmstabent = jpc_ppxstabent_create())) {
-        return -1;
+        pm_asprintf(errorP, "jpc_ppxstabent_create failed");
+        return;
     }
     ppmstabent->ind = ppm->ind;
     ppmstabent->data = ppm->data;
     ppm->data = 0;
     ppmstabent->len = ppm->len;
     if (jpc_ppxstab_insert(dec->ppmstab, ppmstabent)) {
-        return -1;
+        pm_asprintf(errorP, "jpc_ppxstab_insert failed");
+        return;
     }
-    return 0;
+    *doneP = false;
+    *errorP = NULL;
 }
 
-static int jpc_dec_process_ppt(jpc_dec_t *dec, jpc_ms_t *ms)
-{
+
+
+static void
+jpc_dec_process_ppt(jpc_dec_t *   const dec,
+                    jpc_ms_t *    const ms,
+                    bool *        const doneP,
+                    const char ** const errorP) {
+
     jpc_ppt_t *ppt = &ms->parms.ppt;
     jpc_dec_tile_t *tile;
     jpc_ppxstabent_t *pptstabent;
@@ -1490,34 +1461,55 @@ static int jpc_dec_process_ppt(jpc_dec_t *dec, jpc_ms_t *ms)
     tile = dec->curtile;
     if (!tile->pptstab) {
         if (!(tile->pptstab = jpc_ppxstab_create())) {
-            return -1;
+            pm_asprintf(errorP, "jpc_ppxstab_create failed");
+            return;
         }
     }
     if (!(pptstabent = jpc_ppxstabent_create())) {
-        return -1;
+        pm_asprintf(errorP, "jpc_ppxstabent_create failed");
+        return;
     }
     pptstabent->ind = ppt->ind;
     pptstabent->data = ppt->data;
     ppt->data = 0;
     pptstabent->len = ppt->len;
     if (jpc_ppxstab_insert(tile->pptstab, pptstabent)) {
-        return -1;
+        pm_asprintf(errorP, "jpc_ppxstab_insert failed.");
+        return;
     }
-    return 0;
+    *doneP = false;
+    *errorP = NULL;
 }
 
-static int jpc_dec_process_com(jpc_dec_t *dec, jpc_ms_t *ms)
-{
-    return 0;
+
+
+static void
+jpc_dec_process_com(jpc_dec_t *   const dec,
+                    jpc_ms_t *    const ms,
+                    bool *        const doneP,
+                    const char ** const errorP) {
+
+    *doneP = false;
+    *errorP = NULL;
 }
 
-static int jpc_dec_process_unk(jpc_dec_t *dec, jpc_ms_t *ms)
-{
-    fprintf(stderr, "warning: ignoring unknown marker segment\n");
+
+
+static void
+jpc_dec_process_unk(jpc_dec_t *   const dec,
+                    jpc_ms_t *    const ms,
+                    bool *        const doneP,
+                    const char ** const errorP) {
+
+    pm_message("warning: ignoring unknown marker segment");
     jpc_ms_dump(ms, stderr);
-    return 0;
+
+    *doneP = false;
+    *errorP = NULL;
 }
 
+
+
 /******************************************************************************\
 *
 \******************************************************************************/
@@ -2370,3 +2362,168 @@ void jpc_ppxstabent_destroy(jpc_ppxstabent_t *ent)
     }
     jas_free(ent);
 }
+
+
+
+jpc_dec_mstabent_t jpc_dec_mstab[] = {
+    {JPC_MS_SOC, JPC_MHSOC, jpc_dec_process_soc},
+    {JPC_MS_SOT, JPC_MH | JPC_TPHSOT, jpc_dec_process_sot},
+    {JPC_MS_SOD, JPC_TPH, jpc_dec_process_sod},
+    {JPC_MS_EOC, JPC_TPHSOT, jpc_dec_process_eoc},
+    {JPC_MS_SIZ, JPC_MHSIZ, jpc_dec_process_siz},
+    {JPC_MS_COD, JPC_MH | JPC_TPH, jpc_dec_process_cod},
+    {JPC_MS_COC, JPC_MH | JPC_TPH, jpc_dec_process_coc},
+    {JPC_MS_RGN, JPC_MH | JPC_TPH, jpc_dec_process_rgn},
+    {JPC_MS_QCD, JPC_MH | JPC_TPH, jpc_dec_process_qcd},
+    {JPC_MS_QCC, JPC_MH | JPC_TPH, jpc_dec_process_qcc},
+    {JPC_MS_POC, JPC_MH | JPC_TPH, jpc_dec_process_poc},
+    {JPC_MS_TLM, JPC_MH, 0},
+    {JPC_MS_PLM, JPC_MH, 0},
+    {JPC_MS_PLT, JPC_TPH, 0},
+    {JPC_MS_PPM, JPC_MH, jpc_dec_process_ppm},
+    {JPC_MS_PPT, JPC_TPH, jpc_dec_process_ppt},
+    {JPC_MS_SOP, 0, 0},
+    {JPC_MS_CRG, JPC_MH, jpc_dec_process_crg},
+    {JPC_MS_COM, JPC_MH | JPC_TPH, jpc_dec_process_com},
+    {0, JPC_MH | JPC_TPH, jpc_dec_process_unk}
+};
+
+
+
+static jpc_dec_mstabent_t *jpc_dec_mstab_lookup(uint_fast16_t id)
+{
+    jpc_dec_mstabent_t *mstabent;
+    for (mstabent = jpc_dec_mstab; mstabent->id != 0; ++mstabent) {
+        if (mstabent->id == id) {
+            break;
+        }
+    }
+    return mstabent;
+}
+
+
+
+static void
+jpc_dec_decode(jpc_dec_t *   const dec,
+               const char ** const errorP) {
+
+    jpc_ms_t *ms;
+    jpc_dec_mstabent_t *mstabent;
+    bool done;
+    jpc_cstate_t *cstate;
+
+    if (!(cstate = jpc_cstate_create())) {
+        pm_asprintf(errorP, "jpc_cstate_create failed");
+        return;
+    }
+    dec->cstate = cstate;
+
+    /* Initially, we should expect to encounter a SOC marker segment. */
+    dec->state = JPC_MHSOC;
+
+    *errorP = NULL;   /* initial value */
+
+    for (;;) {
+
+        /* Get the next marker segment in the code stream. */
+        if (!(ms = jpc_getms(dec->in, cstate))) {
+            pm_asprintf(errorP, "cannot get marker segment");
+            return;
+        }
+
+        mstabent = jpc_dec_mstab_lookup(ms->id);
+        assert(mstabent);
+
+        /* Ensure that this type of marker segment is permitted
+          at this point in the code stream. */
+        if (!(dec->state & mstabent->validstates)) {
+            pm_asprintf(errorP, "unexpected marker segment type");
+            jpc_ms_destroy(ms);
+            return;
+        }
+
+        /* Process the marker segment. */
+        if (mstabent->action) {
+            (*mstabent->action)(dec, ms, &done, errorP);
+        } else {
+            /* No explicit action is required. */
+            *errorP = NULL;
+            done = false;
+        }
+
+        /* Destroy the marker segment. */
+        jpc_ms_destroy(ms);
+
+        if (*errorP) {
+            return;
+        } else if (done) {
+            break;
+        }
+    }
+}
+
+
+
+/*****************************************************************************\
+* The main entry point for the JPEG-2000 decoder.
+\*****************************************************************************/
+
+void
+jpc_decode(jas_stream_t * const in,
+           const char *   const optstr,
+           jas_image_t ** const imagePP,
+           const char **  const errorP) {
+
+    jpc_dec_importopts_t opts;
+    jpc_dec_t *dec;
+    jas_image_t *image;
+    const char * error;
+
+    if (jpc_dec_parseopts(optstr, &opts)) {
+        pm_asprintf(errorP, "jpc_dec_parseopts failed");
+        return;
+    }
+
+    jpc_initluts();
+
+    dec = jpc_dec_create(&opts, in);
+
+    if (!dec) {
+        pm_asprintf(errorP, "jpc_dec_create failed");
+    } else {
+        /* Do most of the work. */
+        jpc_dec_decode(dec, &error);
+        if (error) {
+            pm_asprintf(errorP, "jpc_dec_decode failed.  %s", error);
+            pm_strfree(error);
+        } else {
+            if (jas_image_numcmpts(dec->image) >= 3) {
+                jas_image_setcolorspace(dec->image, JAS_IMAGE_CS_RGB);
+                jas_image_setcmpttype(dec->image, 0,
+                                      JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_RGB_R));
+                jas_image_setcmpttype(dec->image, 1,
+                                      JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_RGB_G));
+                jas_image_setcmpttype(dec->image, 2,
+                                      JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_RGB_B));
+            } else {
+                jas_image_setcolorspace(dec->image, JAS_IMAGE_CS_GRAY);
+                jas_image_setcmpttype(dec->image, 0,
+                                      JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_GRAY_Y));
+            }
+
+            /* Save the return value. */
+            image = dec->image;
+
+            /* Stop the image from being discarded. */
+            dec->image = 0;
+
+            *imagePP = image;
+
+            *errorP = NULL;
+        }
+        jpc_dec_destroy(dec);
+    }
+}
+
+
+
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_dec.h b/converter/other/jpeg2000/libjasper/jpc/jpc_dec.h
index 02c5553d..fe0e9616 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_dec.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_dec.h
@@ -236,7 +236,7 @@ typedef struct {
 
 } jpc_dec_ccp_t;
 
-/* Coding paramters. */
+/* Coding parameters. */
 
 typedef struct {
 
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_enc.c b/converter/other/jpeg2000/libjasper/jpc/jpc_enc.c
index 9db41ca2..0c77a94e 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_enc.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_enc.c
@@ -69,7 +69,6 @@ static void prc_destroy(jpc_enc_prc_t *prcs);
 static jpc_enc_cblk_t *cblk_create(jpc_enc_cblk_t *cblk, jpc_enc_cp_t *cp,
   jpc_enc_prc_t *prc);
 static void cblk_destroy(jpc_enc_cblk_t *cblks);
-int ratestrtosize(const char *s, uint_fast32_t rawsize, uint_fast32_t *size);
 static void pass_destroy(jpc_enc_pass_t *pass);
 void jpc_enc_dump(jpc_enc_t *enc);
 
@@ -78,17 +77,8 @@ void jpc_enc_dump(jpc_enc_t *enc);
 \*****************************************************************************/
 
 void quantize(jas_matrix_t *data, jpc_fix_t stepsize);
-static int jpc_enc_encodemainhdr(jpc_enc_t *enc);
-static int jpc_enc_encodemainbody(jpc_enc_t *enc);
-int jpc_enc_encodetiledata(jpc_enc_t *enc);
 jpc_enc_t *jpc_enc_create(jpc_enc_cp_t *cp, jas_stream_t *out, jas_image_t *image);
 void jpc_enc_destroy(jpc_enc_t *enc);
-static int jpc_enc_encodemainhdr(jpc_enc_t *enc);
-static int jpc_enc_encodemainbody(jpc_enc_t *enc);
-int jpc_enc_encodetiledata(jpc_enc_t *enc);
-int setins(int numvalues, jpc_flt_t *values, jpc_flt_t value);
-static jpc_enc_cp_t *cp_create(char *optstr, jas_image_t *image);
-void jpc_enc_cp_destroy(jpc_enc_cp_t *cp);
 
 
 
@@ -143,7 +133,6 @@ typedef enum {
     OPT_NUMGBITS,
     OPT_RATE,
     OPT_ILYRRATES,
-    OPT_JP2OVERHEAD
 } optid_t;
 
 jas_taginfo_t encopts[] = {
@@ -173,7 +162,6 @@ jas_taginfo_t encopts[] = {
     {OPT_NUMGBITS, "numgbits"},
     {OPT_RATE, "rate"},
     {OPT_ILYRRATES, "ilyrrates"},
-    {OPT_JP2OVERHEAD, "_jp2overhead"},
     {-1, 0}
 };
 
@@ -230,72 +218,46 @@ trace(const char * const fmt, ...) {
 
 
 
-int
-jpc_encode(jas_image_t *image, jas_stream_t *out, char *optstr) {
-
-    jpc_enc_t *enc;
-    jpc_enc_cp_t *cp;
-
-    enc = 0;
-    cp = 0;
-
-    jpc_initluts();
-
-    if (!(cp = cp_create(optstr, image))) {
-        fprintf(stderr, "invalid JP encoder options\n");
-        goto error;
-    }
-
-    if (!(enc = jpc_enc_create(cp, out, image))) {
-        goto error;
-    }
-    cp = 0;
+/*****************************************************************************\
+* Option parsing code.
+\*****************************************************************************/
 
-    /* Encode the main header. */
-    if (jpc_enc_encodemainhdr(enc)) {
-        goto error;
-    }
+static void
+ratestrtosize(const char *    const s,
+              uint_fast32_t   const rawsize,
+              uint_fast32_t * const sizeP) {
 
-    /* Encode the main body.  This constitutes most of the encoding work. */
-    if (jpc_enc_encodemainbody(enc)) {
-        goto error;
-    }
+    if (strchr(s, 'B')) {
+        *sizeP = atoi(s);
+    } else {
+        jpc_flt_t const f = atof(s);
 
-    /* Write EOC marker segment. */
-    if (!(enc->mrk = jpc_ms_create(JPC_MS_EOC))) {
-        goto error;
-    }
-    if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
-        fprintf(stderr, "cannot write EOI marker\n");
-        goto error;
+        if (f < 0) {
+            *sizeP = 0;
+        } else if (f > 1.0) {
+            *sizeP = rawsize + 1;
+        } else {
+            *sizeP = f * rawsize;
+        }
     }
-    jpc_ms_destroy(enc->mrk);
-    enc->mrk = 0;
+}
 
-    if (jas_stream_flush(enc->out)) {
-        goto error;
-    }
 
-    jpc_enc_destroy(enc);
 
-    return 0;
+static void
+cp_destroy(jpc_enc_cp_t *cp) {
 
-error:
-    if (cp) {
-        jpc_enc_cp_destroy(cp);
-    }
-    if (enc) {
-        jpc_enc_destroy(enc);
+    if (cp->ccps) {
+        if (cp->tcp.ilyrrates) {
+            jas_free(cp->tcp.ilyrrates);
+        }
+        jas_free(cp->ccps);
     }
-    return -1;
+    jas_free(cp);
 }
 
 
 
-/*****************************************************************************\
-* Option parsing code.
-\*****************************************************************************/
-
 static jpc_enc_cp_t *
 cp_create(char *optstr, jas_image_t *image) {
 
@@ -314,7 +276,6 @@ cp_create(char *optstr, jas_image_t *image) {
     uint_fast16_t prcwidthexpn;
     uint_fast16_t prcheightexpn;
     bool enablemct;
-    uint_fast32_t jp2overhead;
     uint_fast16_t lyrno;
     uint_fast32_t hsteplcm;
     uint_fast32_t vsteplcm;
@@ -332,7 +293,6 @@ cp_create(char *optstr, jas_image_t *image) {
     prcwidthexpn = 15;
     prcheightexpn = 15;
     enablemct = true;
-    jp2overhead = 0;
 
     cp->ccps = 0;
     cp->debug = 0;
@@ -380,6 +340,10 @@ cp_create(char *optstr, jas_image_t *image) {
 
     cp->rawsize = jas_image_rawsize(image);
     cp->totalsize = UINT_FAST32_MAX;
+        /* Set default value, the special value that means size is unlimited
+           (so lossless coding is called for).  To be overridden if user
+           specified
+        */
 
     tcp = &cp->tcp;
     tcp->csty = 0;
@@ -492,12 +456,8 @@ cp_create(char *optstr, jas_image_t *image) {
             cp->tccp.numgbits = atoi(jas_tvparser_getval(tvp));
             break;
         case OPT_RATE:
-            if (ratestrtosize(jas_tvparser_getval(tvp), cp->rawsize,
-              &cp->totalsize)) {
-                fprintf(stderr,
-                  "ignoring bad rate specifier %s\n",
-                  jas_tvparser_getval(tvp));
-            }
+            ratestrtosize(jas_tvparser_getval(tvp), cp->rawsize,
+                          &cp->totalsize);
             break;
         case OPT_ILYRRATES:
             if (jpc_atoaf(jas_tvparser_getval(tvp), &numilyrrates,
@@ -505,13 +465,10 @@ cp_create(char *optstr, jas_image_t *image) {
                 fprintf(stderr,
                         "warning: invalid intermediate layer rates specifier "
                         "ignored (%s)\n",
-                  jas_tvparser_getval(tvp));
+                        jas_tvparser_getval(tvp));
             }
             break;
 
-        case OPT_JP2OVERHEAD:
-            jp2overhead = atoi(jas_tvparser_getval(tvp));
-            break;
         default:
             fprintf(stderr, "warning: ignoring invalid option %s\n",
              jas_tvparser_gettag(tvp));
@@ -522,11 +479,6 @@ cp_create(char *optstr, jas_image_t *image) {
     jas_tvparser_destroy(tvp);
     tvp = 0;
 
-    if (cp->totalsize != UINT_FAST32_MAX) {
-        cp->totalsize = (cp->totalsize > jp2overhead) ?
-          (cp->totalsize - jp2overhead) : 0;
-    }
-
     if (cp->imgareatlx == UINT_FAST32_MAX) {
         cp->imgareatlx = 0;
     } else {
@@ -697,20 +649,28 @@ cp_create(char *optstr, jas_image_t *image) {
         /* The intermediate layers rates must increase monotonically. */
         for (lyrno = 0; lyrno + 2 < tcp->numlyrs; ++lyrno) {
             if (tcp->ilyrrates[lyrno] >= tcp->ilyrrates[lyrno + 1]) {
-                fprintf(stderr,
-                        "intermediate layer rates must increase "
-                        "monotonically\n");
+                pm_message("Compression rate for Layer %u (%f) "
+                           "is not greater than that for Layer %u (%f).  "
+                           "Rates must increase at every layer",
+                           (unsigned)(lyrno+1),
+                           jpc_fixtodbl(tcp->ilyrrates[lyrno + 1]),
+                           (unsigned)lyrno,
+                           jpc_fixtodbl(tcp->ilyrrates[lyrno]));
                 goto error;
             }
         }
         /* The intermediate layer rates must be less than the overall rate. */
         if (cp->totalsize != UINT_FAST32_MAX) {
             for (lyrno = 0; lyrno < tcp->numlyrs - 1; ++lyrno) {
-                if (jpc_fixtodbl(tcp->ilyrrates[lyrno]) >
-                    ((double) cp->totalsize) / cp->rawsize) {
-                    fprintf(stderr,
-                            "warning: intermediate layer rates must be "
-                            "less than overall rate\n");
+                double const thisLyrRate = jpc_fixtodbl(tcp->ilyrrates[lyrno]);
+                double const completeRate =
+                    ((double) cp->totalsize) / cp->rawsize;
+                if (thisLyrRate > completeRate) {
+                    pm_message(
+                        "Compression rate for Layer %u is %f, "
+                        "which is greater than the rate for the complete "
+                        "image (%f)",
+                        (unsigned)lyrno, thisLyrRate, completeRate);
                     goto error;
                 }
             }
@@ -732,118 +692,17 @@ error:
         jas_tvparser_destroy(tvp);
     }
     if (cp) {
-        jpc_enc_cp_destroy(cp);
-    }
-    return 0;
-}
-
-
-
-void
-jpc_enc_cp_destroy(jpc_enc_cp_t *cp) {
-
-    if (cp->ccps) {
-        if (cp->tcp.ilyrrates) {
-            jas_free(cp->tcp.ilyrrates);
-        }
-        jas_free(cp->ccps);
-    }
-    jas_free(cp);
-}
-
-
-
-int
-ratestrtosize(const char *s, uint_fast32_t rawsize, uint_fast32_t *size) {
-
-    char *cp;
-    jpc_flt_t f;
-
-    /* Note: This function must not modify output size on failure. */
-    if ((cp = strchr(s, 'B'))) {
-        *size = atoi(s);
-    } else {
-        f = atof(s);
-        if (f < 0) {
-            *size = 0;
-        } else if (f > 1.0) {
-            *size = rawsize + 1;
-        } else {
-            *size = f * rawsize;
-        }
-    }
-    return 0;
-}
-
-/*****************************************************************************\
-* Encoder constructor and destructor.
-\*****************************************************************************/
-
-jpc_enc_t *
-jpc_enc_create(jpc_enc_cp_t *cp, jas_stream_t *out, jas_image_t *image) {
-
-    jpc_enc_t *enc;
-
-    enc = 0;
-
-    if (!(enc = jas_malloc(sizeof(jpc_enc_t)))) {
-        goto error;
-    }
-
-    enc->image = image;
-    enc->out = out;
-    enc->cp = cp;
-    enc->cstate = 0;
-    enc->tmpstream = 0;
-    enc->mrk = 0;
-    enc->curtile = 0;
-
-    if (!(enc->cstate = jpc_cstate_create())) {
-        goto error;
-    }
-    enc->len = 0;
-    enc->mainbodysize = 0;
-
-    return enc;
-
-error:
-
-    if (enc) {
-        jpc_enc_destroy(enc);
+        cp_destroy(cp);
     }
     return 0;
 }
 
 
 
-void
-jpc_enc_destroy(jpc_enc_t *enc) {
-
-    /* The image object (i.e., enc->image) and output stream object
-       (i.e., enc->out) are created outside of the encoder.
-       Therefore, they must not be destroyed here.
-    */
-
-    if (enc->curtile) {
-        jpc_enc_tile_destroy(enc->curtile);
-    }
-    if (enc->cp) {
-        jpc_enc_cp_destroy(enc->cp);
-    }
-    if (enc->cstate) {
-        jpc_cstate_destroy(enc->cstate);
-    }
-    if (enc->tmpstream) {
-        jas_stream_close(enc->tmpstream);
-    }
-
-    jas_free(enc);
-}
-
-
-
 static int
-jpc_enc_encodemainhdr(jpc_enc_t *enc) {
+encodemainhdr(jpc_enc_t *enc) {
+
+    uint_fast32_t const maintlrlen = 2;
 
     jpc_siz_t *siz;
     jpc_cod_t *cod;
@@ -961,7 +820,7 @@ jpc_enc_encodemainhdr(jpc_enc_t *enc) {
                   (analgain + 1)), bandinfo->synenergywt);
             } else {
                 absstepsize = jpc_inttofix(1);
-            }   
+            }
             cp->ccps[cmptno].stepsizes[bandno] =
               jpc_abstorelstepsize(absstepsize,
               cp->ccps[cmptno].prec + analgain);
@@ -1038,61 +897,32 @@ jpc_enc_encodemainhdr(jpc_enc_t *enc) {
         enc->mrk = 0;
     }
 
-#define MAINTLRLEN  2
     mainhdrlen = jas_stream_getrwcount(enc->out) - startoff;
     enc->len += mainhdrlen;
     if (enc->cp->totalsize != UINT_FAST32_MAX) {
-        uint_fast32_t overhead;
-        overhead = mainhdrlen + MAINTLRLEN;
-        enc->mainbodysize = (enc->cp->totalsize >= overhead) ?
-          (enc->cp->totalsize - overhead) : 0;
-    } else {
-        enc->mainbodysize = UINT_FAST32_MAX;
-    }
-
-    return 0;
-}
-
-
-
-int
-jpc_enc_encodetiledata(jpc_enc_t *enc) {
-
-    assert(enc->tmpstream);
-    if (jpc_enc_encpkts(enc, enc->tmpstream)) {
-        return -1;
-    }
-    return 0;
-}
-
-
-
-void
-quantize(jas_matrix_t *data, jpc_fix_t stepsize) {
+        uint_fast32_t const overhead = mainhdrlen + maintlrlen;
 
-    int i;
-    int j;
-    jpc_fix_t t;
-
-    if (stepsize == jpc_inttofix(1)) {
-        return;
-    }
-
-    for (i = 0; i < jas_matrix_numrows(data); ++i) {
-        for (j = 0; j < jas_matrix_numcols(data); ++j) {
-            t = jas_matrix_get(data, i, j);
+        if (overhead > enc->cp->totalsize) {
+            pm_message("Requested limit on image size of %u bytes "
+                       "is not possible because it is less than "
+                       "the image metadata size (%u bytes)",
+                       (unsigned)enc->cp->totalsize, (unsigned)overhead);
+            return -1;
+        }
+        enc->mainbodysize = enc->cp->totalsize - overhead;
+        /* This has never actually worked.  'totalsize' is supposed to be
+           the total all-in, so if you request total size 200, you should
+           get an output file 200 bytes or smaller; but we see 209 bytes.
+           Furthermore, at 194 bytes, we get a warning that an empty layer
+           is generated, which probably is actually an error.
 
-{
-    if (t < 0) {
-        t = jpc_fix_neg(jpc_fix_div(jpc_fix_neg(t), stepsize));
+           We should fix this some day.
+        */
     } else {
-        t = jpc_fix_div(t, stepsize);
+        enc->mainbodysize = UINT_FAST32_MAX;
     }
-}
 
-            jas_matrix_set(data, i, j, t);
-        }
-    }
+    return 0;
 }
 
 
@@ -1166,12 +996,12 @@ calcrdslopes(jpc_enc_cblk_t *cblk) {
 
 static void
 traceLayerSizes(const uint_fast32_t * const lyrSizes,
-                unsigned int          const layerCt) {
+                uint_fast32_t         const layerCt) {
 
     if (jas_getdbglevel() > 0) {
-        unsigned int i;
+        uint_fast32_t i;
         for (i = 0; i < layerCt; ++i) {
-            fprintf(stderr, "Layer %u size = ", i);
+            fprintf(stderr, "Layer %u size = ", (unsigned)i);
 
             if (lyrSizes[i] == UINT_FAST32_MAX)
                 fprintf(stderr, "Unlimited");
@@ -1189,48 +1019,28 @@ computeLayerSizes(jpc_enc_t *      const encP,
                   jpc_enc_tile_t * const tileP,
                   jpc_enc_cp_t *   const cpP,
                   double           const rho,
-                  long             const tilehdrlen,
-                  const char **    const errorP) {
+                  long             const tilehdrlen) {
 
     /* Note that in allowed sizes, UINT_FAST32_MAX is a special value meaning
        "unlimited".
     */
 
-    unsigned int const lastLyrno = tileP->numlyrs - 1;
+    uint_fast32_t const lastLyrno = tileP->numlyrs - 1;
 
-    unsigned int lyrno;
+    uint_fast32_t lyrno;
 
     assert(tileP->numlyrs > 0);
 
     for (lyrno = 0; lyrno < lastLyrno; ++lyrno) {
-        tileP->lyrsizes[lyrno] = tileP->rawsize * jpc_fixtodbl(
-            cpP->tcp.ilyrrates[lyrno]);
+        tileP->lyrsizes[lyrno] =
+            MAX(tileP->rawsize *
+                jpc_fixtodbl(cpP->tcp.ilyrrates[lyrno]),
+                tilehdrlen + 1) - tilehdrlen;
     }
 
     tileP->lyrsizes[lastLyrno] =
-        (cpP->totalsize != UINT_FAST32_MAX) ?
-        (rho * encP->mainbodysize) : UINT_FAST32_MAX;
-
-
-    /* Subtract 'tilehdrlen' from every layer. */
-
-    for (lyrno = 0; lyrno < tileP->numlyrs; ++lyrno) {
-        if (tileP->lyrsizes[lyrno] != UINT_FAST32_MAX) {
-            if (tilehdrlen <= tileP->lyrsizes[lyrno]) {
-                tileP->lyrsizes[lyrno] -= tilehdrlen;
-            } else {
-                tileP->lyrsizes[lyrno] = 0;
-            }
-        }
-    }
-
-    if (tileP->lyrsizes[lastLyrno] < 1)
-        pm_asprintf(errorP, "Cannot make image that small (%u bytes).  "
-                    "Even with pixels compressed as far as possible, metadata "
-                    "would exceed the limit",
-                    (unsigned)cpP->totalsize);
-    else
-        *errorP = NULL;
+        (cpP->totalsize == UINT_FAST32_MAX) ?
+        UINT_FAST32_MAX : (rho * encP->mainbodysize);
 
     traceLayerSizes(tileP->lyrsizes, tileP->numlyrs);
 }
@@ -1313,8 +1123,8 @@ trace_layeringinfo(jpc_enc_t * const encP) {
 
 static void
 validateCumlensIncreases(const uint_fast32_t * const cumlens,
-                         unsigned int          const numlyrs) {
-    unsigned int lyrno;
+                         uint_fast32_t          const numlyrs) {
+    uint_fast32_t lyrno;
 
     for (lyrno = 1; lyrno < numlyrs - 1; ++lyrno) {
         if (cumlens[lyrno - 1] > cumlens[lyrno]) {
@@ -1404,7 +1214,7 @@ findMinMaxRDSlopeValues(jpc_enc_tile_t * const tileP,
 static void
 performTier2CodingOneLayer(jpc_enc_t *      const encP,
                            jpc_enc_tile_t * const tileP,
-                           unsigned int     const lyrno,
+                           uint_fast32_t     const lyrno,
                            jas_stream_t *   const outP,
                            const char **    const errorP) {
 /*----------------------------------------------------------------------------
@@ -1444,9 +1254,9 @@ performTier2CodingOneLayer(jpc_enc_t *      const encP,
 static void
 assignHighSlopePassesToLayer(jpc_enc_t *      const encP,
                              jpc_enc_tile_t * const tileP,
-                             unsigned int     const lyrno,
-                             bool             const haveThresh,
-                             jpc_flt_t        const thresh) {
+                             uint_fast32_t     const lyrno,
+                             bool              const haveThresh,
+                             jpc_flt_t         const thresh) {
 /*----------------------------------------------------------------------------
   Assign all passes with R-D slopes greater than or equal to 'thresh' to layer
   'lyrno' and the rest to no layer.
@@ -1505,8 +1315,7 @@ assignHighSlopePassesToLayer(jpc_enc_t *      const encP,
                                         for (; passP != endpassesP; ++passP) {
                                             passP->lyrno = -1;
                                         }
-                                    
-                                    }   
+                                    }
                                 }
                             }
                         }
@@ -1522,7 +1331,7 @@ assignHighSlopePassesToLayer(jpc_enc_t *      const encP,
 static void
 doLayer(jpc_enc_t *      const encP,
         jpc_enc_tile_t * const tileP,
-        unsigned int     const lyrno,
+        uint_fast32_t    const lyrno,
         uint_fast32_t    const allowedSize,
         jpc_flt_t        const mnrdslope,
         jpc_flt_t        const mxrdslope,
@@ -1550,7 +1359,7 @@ doLayer(jpc_enc_t *      const encP,
         long pos;
         jpc_flt_t lo;
         jpc_flt_t hi;
-        unsigned int numiters;
+        uint_fast32_t numiters;
 
         lo = mnrdslope;  /* initial value */
         hi = mxrdslope;  /* initial value */
@@ -1559,52 +1368,46 @@ doLayer(jpc_enc_t *      const encP,
         goodThresh = 0;     /* initial value */
 
         do {
-            if (allowedSize == UINT_FAST32_MAX) {
-                /* There's no rate constraint (This can be true of the last
-                   layer, e.g. for lossless coding). */
-                goodThresh = -1;
-                haveGoodThresh = true;
-            } else {
-                jpc_flt_t const thresh = (lo + hi) / 2;
-
-                int rc;
-                long oldpos;
-
-                /* Save the tier 2 coding state. */
-                jpc_save_t2state(encP);
-                oldpos = jas_stream_tell(outP);
-                assert(oldpos >= 0);
-
-                assignHighSlopePassesToLayer(encP, tileP, lyrno, true, thresh);
-
-                performTier2CodingOneLayer(encP, tileP, lyrno, outP, errorP);
-
-                if (!*errorP) {
-                    pos = jas_stream_tell(outP);
-
-                    /* Check the rate constraint. */
-                    assert(pos >= 0);
-                    if (pos > allowedSize) {
-                        /* The rate is too high. */
-                        lo = thresh;
-                    } else if (pos <= allowedSize) {
-                        /* The rate is low enough, so try higher. */
-                        hi = thresh;
-                        if (!haveGoodThresh || thresh < goodThresh) {
-                            goodThresh = thresh;
-                            haveGoodThresh = true;
-                        }
+            jpc_flt_t const thresh = (lo + hi) / 2;
+
+            int rc;
+            long oldpos;
+
+            /* Save the tier 2 coding state. */
+            jpc_save_t2state(encP);
+            oldpos = jas_stream_tell(outP);
+            assert(oldpos >= 0);
+
+            assignHighSlopePassesToLayer(encP, tileP, lyrno, true, thresh);
+
+            performTier2CodingOneLayer(encP, tileP, lyrno, outP, errorP);
+
+            if (!*errorP) {
+                pos = jas_stream_tell(outP);
+
+                /* Check the rate constraint. */
+                assert(pos >= 0);
+                if (pos > allowedSize) {
+                    /* The rate is too high. */
+                    lo = thresh;
+                } else if (pos <= allowedSize) {
+                    /* The rate is low enough, so try higher. */
+                    hi = thresh;
+                    if (!haveGoodThresh || thresh < goodThresh) {
+                        goodThresh = thresh;
+                        haveGoodThresh = true;
                     }
                 }
-                /* Restore the tier 2 coding state. */
-                jpc_restore_t2state(encP);
-                rc = jas_stream_seek(outP, oldpos, SEEK_SET);
-                if (rc < 0)
-                    abort();
-
-                trace("iter %u: allowedlen=%08ld actuallen=%08ld thresh=%f",
-                      numiters, allowedSize, pos, thresh);
             }
+            /* Restore the tier 2 coding state. */
+            jpc_restore_t2state(encP);
+            rc = jas_stream_seek(outP, oldpos, SEEK_SET);
+            if (rc < 0)
+                abort();
+
+            trace("iter %u: allowedlen=%08ld actuallen=%08ld thresh=%f",
+                  numiters, allowedSize, pos, thresh);
+
             ++numiters;
         } while (lo < hi - 1e-3 && numiters < 32 && !*errorP);
     }
@@ -1625,10 +1428,10 @@ doLayer(jpc_enc_t *      const encP,
 
 
 static void
-performTier2Coding(jpc_enc_t *     const encP,
-                   unsigned int    const numlyrs,
-                   uint_fast32_t * const cumlens,
-                   const char **   const errorP) {
+performTier2Coding(jpc_enc_t *      const encP,
+                   uint_fast32_t    const numlyrs,
+                   uint_fast32_t *  const cumlens,
+                   const char **    const errorP) {
 /*----------------------------------------------------------------------------
    Encode in 'numlyrs' layers, such that at each layer L, the size is
    cumlens[L].
@@ -1636,7 +1439,7 @@ performTier2Coding(jpc_enc_t *     const encP,
     jpc_enc_tile_t * const tileP = encP->curtile;
 
     jas_stream_t * outP;
-    unsigned int lyrno;
+    uint_fast32_t lyrno;
     jpc_flt_t mnrdslope;
     jpc_flt_t mxrdslope;
 
@@ -1669,6 +1472,562 @@ performTier2Coding(jpc_enc_t *     const encP,
 
 
 
+
+
+static void
+encodeTileBody(jpc_enc_t *   const encoderP,
+               long          const tilehdrlen,
+               const char ** const errorP) {
+/*----------------------------------------------------------------------------
+   Encode the body of encoder *encoderP's current tile, writing the encoded
+   result to the encoder's output stream.
+
+   Assume the tile header is already in that stream, and its length is
+   'tilehdrlen'.
+-----------------------------------------------------------------------------*/
+    jpc_enc_tile_t * const tileP = encoderP->curtile;
+    jpc_enc_cp_t *   const cp    = encoderP->cp;
+
+    int rc;
+
+    rc = jpc_enc_enccblks(encoderP);
+    if (rc != 0)
+        pm_asprintf(errorP, "jpc_enc_enccblks() failed");
+    else {
+        double const rho =
+            (double) (tileP->brx - tileP->tlx) * (tileP->bry - tileP->tly) /
+            ((cp->refgrdwidth - cp->imgareatlx) * (cp->refgrdheight -
+                                                   cp->imgareatly));
+        const char * error;
+
+        tileP->rawsize = cp->rawsize * rho;
+
+        computeLayerSizes(encoderP, tileP, cp, rho, tilehdrlen);
+
+        performTier2Coding(encoderP, tileP->numlyrs, tileP->lyrsizes, &error);
+
+        if (error) {
+            pm_asprintf(errorP, "Tier 2 coding failed.  %s", error);
+            pm_strfree(error);
+        } else {
+            int rc;
+
+            rc = jpc_enc_encpkts(encoderP, encoderP->tmpstream);
+            if (rc != 0)
+                pm_asprintf(errorP, "jpc_enc_encpkts() failed\n");
+            else
+                *errorP = NULL;
+        }
+    }
+}
+
+
+
+static void
+quantizeBand(jpc_enc_band_t * const bandP,
+             jpc_enc_tile_t * const tileP,
+             jpc_enc_cp_t *   const cp,
+             int              const prec,
+             int              const tccp_numgbits,
+             int *            const numgbitsP) {
+
+    if (bandP->data) {
+        int actualnumbps;
+        uint_fast32_t y;
+        jpc_fix_t mxmag;
+
+        for (y = 0, actualnumbps = 0, mxmag = 0;
+             y < jas_matrix_numrows(bandP->data);
+             ++y) {
+            uint_fast32_t x;
+
+            for (x = 0; x < jas_matrix_numcols(bandP->data); ++x)
+                mxmag = MAX(mxmag, abs(jas_matrix_get(bandP->data, y, x)));
+        }
+        if (tileP->intmode)
+            actualnumbps = jpc_firstone(mxmag) + 1;
+        else
+            actualnumbps = jpc_firstone(mxmag) + 1 - JPC_FIX_FRACBITS;
+
+        *numgbitsP = actualnumbps - (prec - 1 + bandP->analgain);
+
+        if (!tileP->intmode) {
+            bandP->absstepsize =
+                jpc_fix_div(
+                    jpc_inttofix(1 << (bandP->analgain + 1)),
+                    bandP->synweight);
+        } else {
+            bandP->absstepsize = jpc_inttofix(1);
+        }
+        bandP->stepsize = jpc_abstorelstepsize(
+            bandP->absstepsize, prec + bandP->analgain);
+        /* I couldn't figure out what the calculation with tccp_numgbits and
+           stepsize does (or even what a step size is), but there is an
+           assertion elsewhere than the number here is at least at large as
+           the 'numbps' value for every code block, which means
+           'actualnumbps'.  In practice, we saw that not be true, so we added
+           the code to make 'actualnumbps' the floor here in hopes that would
+           fix the problem.  But with the change, the image that caused the
+           assertion failure produces incorrect output.  22.11.07
+        */
+        bandP->numbps =
+            MAX(actualnumbps,
+                tccp_numgbits + JPC_QCX_GETEXPN(bandP->stepsize) - 1);
+
+        if (!tileP->intmode && bandP->data)
+            quantize(bandP->data, bandP->absstepsize);
+    } else
+        *numgbitsP = 0;
+}
+
+
+
+static int
+encodemainbody(jpc_enc_t *enc) {
+
+    int tileno;
+    int i;
+    jpc_sot_t *sot;
+    int rlvlno;
+    jpc_qcc_t *qcc;
+    jpc_cod_t *cod;
+    int adjust;
+    int j;
+    int absbandno;
+    long tilehdrlen;
+    long tilelen;
+    jpc_enc_tile_t *tile;
+    jpc_enc_cp_t *cp;
+    int samestepsizes;
+    jpc_enc_ccp_t *ccps;
+    jpc_enc_tccp_t *tccp;
+    int mingbits; /* Minimum number of guard bits needed */
+    const char * error;
+
+    cp = enc->cp;
+
+    for (tileno = 0; tileno < cp->numtiles; ++tileno) {
+        uint_fast16_t cmptno;
+
+        enc->curtile = jpc_enc_tile_create(enc->cp, enc->image, tileno);
+        if (!enc->curtile)
+            abort();
+
+        tile = enc->curtile;
+
+        if (jas_getdbglevel() >= 10) {
+            jpc_enc_dump(enc);
+        }
+
+        for (cmptno = 0; cmptno < tile->numtcmpts; ++cmptno) {
+
+            jpc_enc_tcmpt_t * const comp = &tile->tcmpts[cmptno];
+
+            if (!cp->ccps[cmptno].sgnd) {
+                adjust = 1 << (cp->ccps[cmptno].prec - 1);
+                for (i = 0; i < jas_matrix_numrows(comp->data); ++i) {
+                    for (j = 0; j < jas_matrix_numcols(comp->data); ++j) {
+                        *jas_matrix_getref(comp->data, i, j) -= adjust;
+                    }
+                }
+            }
+        }
+
+        if (!tile->intmode) {
+            uint_fast16_t cmptno;
+            for (cmptno = 0; cmptno < tile->numtcmpts; ++cmptno) {
+                jpc_enc_tcmpt_t * const comp = &tile->tcmpts[cmptno];
+                jas_matrix_asl(comp->data, JPC_FIX_FRACBITS);
+            }
+        }
+
+        switch (tile->mctid) {
+        case JPC_MCT_RCT:
+            assert(jas_image_numcmpts(enc->image) == 3);
+            jpc_rct(tile->tcmpts[0].data, tile->tcmpts[1].data,
+                    tile->tcmpts[2].data);
+            break;
+        case JPC_MCT_ICT:
+            assert(jas_image_numcmpts(enc->image) == 3);
+            jpc_ict(tile->tcmpts[0].data, tile->tcmpts[1].data,
+                    tile->tcmpts[2].data);
+            break;
+        default:
+            break;
+        }
+
+        for (i = 0; i < jas_image_numcmpts(enc->image); ++i) {
+            jpc_enc_tcmpt_t * const comp = &tile->tcmpts[i];
+            jpc_tsfb_analyze(comp->tsfb,
+                             ((comp->qmfbid == JPC_COX_RFT) ?
+                              JPC_TSFB_RITIMODE : 0), comp->data);
+
+        }
+
+        for (cmptno = 0; cmptno < tile->numtcmpts; ++cmptno) {
+
+            jpc_enc_tcmpt_t * const comp = &tile->tcmpts[cmptno];
+
+            mingbits = 0;
+            absbandno = 0;
+            /* All bands must have a corresponding quantizer step size,
+               even if they contain no samples and are never coded. */
+            /* Some bands may not be hit by the loop below, so we must
+               initialize all of the step sizes to a sane value. */
+            memset(comp->stepsizes, 0, sizeof(comp->stepsizes));
+            for (rlvlno = 0; rlvlno < comp->numrlvls; ++rlvlno) {
+                jpc_enc_rlvl_t * const lvl = &comp->rlvls[rlvlno];
+
+                unsigned int bandno;
+
+                if (!lvl->bands) {
+                    absbandno += rlvlno ? 3 : 1;
+                    continue;
+                }
+                for (bandno = 0; bandno < lvl->numbands; ++bandno) {
+                    jpc_enc_band_t * const band = &lvl->bands[bandno];
+
+                    int numgbits;
+
+                    quantizeBand(band, tile, cp,
+                                 cp->ccps[cmptno].prec,
+                                 cp->tccp.numgbits,
+                                 &numgbits);
+
+                    mingbits = MAX(mingbits, numgbits);
+
+                    comp->stepsizes[absbandno] = band->stepsize;
+
+                    ++absbandno;
+                }
+            }
+
+            assert(JPC_FIX_FRACBITS >= JPC_NUMEXTRABITS);
+            if (!tile->intmode) {
+                jas_matrix_divpow2(comp->data,
+                                   JPC_FIX_FRACBITS - JPC_NUMEXTRABITS);
+            } else {
+                jas_matrix_asl(comp->data, JPC_NUMEXTRABITS);
+            }
+        }
+
+        if (mingbits > cp->tccp.numgbits) {
+            fprintf(stderr, "error: too few guard bits (need at least %d)\n",
+                    mingbits);
+            return -1;
+        }
+
+        enc->tmpstream = jas_stream_memopen(0, 0);
+        if (!enc->tmpstream) {
+            fprintf(stderr, "cannot open tmp file\n");
+            return -1;
+        }
+
+        /* Write the tile header. */
+        enc->mrk = jpc_ms_create(JPC_MS_SOT);
+        if (!enc->mrk)
+            return -1;
+        sot = &enc->mrk->parms.sot;
+        sot->len = 0;
+        sot->tileno = tileno;
+        sot->partno = 0;
+        sot->numparts = 1;
+        if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
+            fprintf(stderr, "cannot write SOT marker\n");
+            return -1;
+        }
+        jpc_ms_destroy(enc->mrk);
+        enc->mrk = 0;
+
+/************************************************************************/
+/************************************************************************/
+/************************************************************************/
+
+        tccp = &cp->tccp;
+        for (cmptno = 0; cmptno < cp->numcmpts; ++cmptno) {
+            jpc_enc_tcmpt_t * const comp = &tile->tcmpts[cmptno];
+            jpc_enc_tcmpt_t * const comp0 = &tile->tcmpts[0];
+
+            if (comp->numrlvls != tccp->maxrlvls) {
+                if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) {
+                    return -1;
+                }
+                /* XXX = this is not really correct. we are using comp #0's
+                   precint sizes and other characteristics */
+                cod = &enc->mrk->parms.cod;
+                cod->compparms.csty = 0;
+                cod->compparms.numdlvls = comp0->numrlvls - 1;
+                cod->prg = tile->prg;
+                cod->numlyrs = tile->numlyrs;
+                cod->compparms.cblkwidthval =
+                    JPC_COX_CBLKSIZEEXPN(comp0->cblkwidthexpn);
+                cod->compparms.cblkheightval =
+                    JPC_COX_CBLKSIZEEXPN(comp0->cblkheightexpn);
+                cod->compparms.cblksty = comp0->cblksty;
+                cod->compparms.qmfbid = comp0->qmfbid;
+                cod->mctrans = (tile->mctid != JPC_MCT_NONE);
+                for (i = 0; i < comp0->numrlvls; ++i) {
+                    cod->compparms.rlvls[i].parwidthval =
+                        comp0->rlvls[i].prcwidthexpn;
+                    cod->compparms.rlvls[i].parheightval =
+                        comp0->rlvls[i].prcheightexpn;
+                }
+                if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
+                    return -1;
+                }
+                jpc_ms_destroy(enc->mrk);
+                enc->mrk = 0;
+            }
+        }
+
+        for (cmptno = 0; cmptno < cp->numcmpts; ++cmptno) {
+            jpc_enc_tcmpt_t * const comp = &tile->tcmpts[cmptno];
+
+            ccps = &cp->ccps[cmptno];
+            if (ccps->numstepsizes == comp->numstepsizes) {
+                unsigned int bandno;
+                samestepsizes = 1;
+                for (bandno = 0; bandno < ccps->numstepsizes; ++bandno) {
+                    if (ccps->stepsizes[bandno] != comp->stepsizes[bandno]) {
+                        samestepsizes = 0;
+                        break;
+                    }
+                }
+            } else {
+                samestepsizes = 0;
+            }
+            if (!samestepsizes) {
+                if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) {
+                    return -1;
+                }
+                qcc = &enc->mrk->parms.qcc;
+                qcc->compno = cmptno;
+                qcc->compparms.numguard = cp->tccp.numgbits;
+                qcc->compparms.qntsty = (comp->qmfbid == JPC_COX_INS) ?
+                    JPC_QCX_SEQNT : JPC_QCX_NOQNT;
+                qcc->compparms.numstepsizes = comp->numstepsizes;
+                qcc->compparms.stepsizes = comp->stepsizes;
+                if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
+                    return -1;
+                }
+                qcc->compparms.stepsizes = 0;
+                jpc_ms_destroy(enc->mrk);
+                enc->mrk = 0;
+            }
+        }
+
+        /* Write a SOD marker to indicate the end of the tile header. */
+        if (!(enc->mrk = jpc_ms_create(JPC_MS_SOD))) {
+            return -1;
+        }
+        if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
+            fprintf(stderr, "cannot write SOD marker\n");
+            return -1;
+        }
+        jpc_ms_destroy(enc->mrk);
+        enc->mrk = 0;
+        tilehdrlen = jas_stream_getrwcount(enc->tmpstream);
+
+/************************************************************************/
+/************************************************************************/
+/************************************************************************/
+
+        encodeTileBody(enc, tilehdrlen, &error);
+            /* Encodes current tile; writes to output file */
+
+        if (error) {
+            fprintf(stderr, "Failed to encode body of tile %u.  %s\n",
+                    tileno, error);
+            pm_strfree(error);
+            return -1;
+        }
+        tilelen = jas_stream_tell(enc->tmpstream);
+
+        if (jas_stream_seek(enc->tmpstream, 6, SEEK_SET) < 0) {
+            return -1;
+        }
+        jpc_putuint32(enc->tmpstream, tilelen);
+
+        if (jas_stream_seek(enc->tmpstream, 0, SEEK_SET) < 0) {
+            return -1;
+        }
+        if (jpc_putdata(enc->out, enc->tmpstream, -1)) {
+            return -1;
+        }
+        enc->len += tilelen;
+
+        jas_stream_close(enc->tmpstream);
+        enc->tmpstream = 0;
+
+        jpc_enc_tile_destroy(enc->curtile);
+        enc->curtile = 0;
+
+    }
+
+    return 0;
+}
+
+
+
+int
+jpc_encode(jas_image_t *image, jas_stream_t *out, char *optstr) {
+
+    jpc_enc_t *enc;
+    jpc_enc_cp_t *cp;
+
+    enc = 0;
+    cp = 0;
+
+    jpc_initluts();
+
+    if (!(cp = cp_create(optstr, image))) {
+        fprintf(stderr, "invalid JP encoder options\n");
+        goto error;
+    }
+
+    if (!(enc = jpc_enc_create(cp, out, image))) {
+        goto error;
+    }
+    cp = 0;
+
+    /* Encode the main header. */
+    if (encodemainhdr(enc)) {
+        goto error;
+    }
+
+    /* Encode the main body.  This constitutes most of the encoding work. */
+    if (encodemainbody(enc)) {
+        goto error;
+    }
+
+    /* Write EOC marker segment. */
+    if (!(enc->mrk = jpc_ms_create(JPC_MS_EOC))) {
+        goto error;
+    }
+    if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
+        fprintf(stderr, "cannot write EOI marker\n");
+        goto error;
+    }
+    jpc_ms_destroy(enc->mrk);
+    enc->mrk = 0;
+
+    if (jas_stream_flush(enc->out)) {
+        goto error;
+    }
+
+    jpc_enc_destroy(enc);
+
+    return 0;
+
+error:
+    if (cp) {
+        cp_destroy(cp);
+    }
+    if (enc) {
+        jpc_enc_destroy(enc);
+    }
+    return -1;
+}
+
+
+
+/*****************************************************************************\
+* Encoder constructor and destructor.
+\*****************************************************************************/
+
+jpc_enc_t *
+jpc_enc_create(jpc_enc_cp_t *cp, jas_stream_t *out, jas_image_t *image) {
+
+    jpc_enc_t *enc;
+
+    enc = 0;
+
+    if (!(enc = jas_malloc(sizeof(jpc_enc_t)))) {
+        goto error;
+    }
+
+    enc->image = image;
+    enc->out = out;
+    enc->cp = cp;
+    enc->cstate = 0;
+    enc->tmpstream = 0;
+    enc->mrk = 0;
+    enc->curtile = 0;
+
+    if (!(enc->cstate = jpc_cstate_create())) {
+        goto error;
+    }
+    enc->len = 0;
+    enc->mainbodysize = 0;
+
+    return enc;
+
+error:
+
+    if (enc) {
+        jpc_enc_destroy(enc);
+    }
+    return 0;
+}
+
+
+
+void
+jpc_enc_destroy(jpc_enc_t *enc) {
+
+    /* The image object (i.e., enc->image) and output stream object
+       (i.e., enc->out) are created outside of the encoder.
+       Therefore, they must not be destroyed here.
+    */
+
+    if (enc->curtile) {
+        jpc_enc_tile_destroy(enc->curtile);
+    }
+    if (enc->cp) {
+        cp_destroy(enc->cp);
+    }
+    if (enc->cstate) {
+        jpc_cstate_destroy(enc->cstate);
+    }
+    if (enc->tmpstream) {
+        jas_stream_close(enc->tmpstream);
+    }
+
+    jas_free(enc);
+}
+
+
+
+void
+quantize(jas_matrix_t *data, jpc_fix_t stepsize) {
+
+    int i;
+    int j;
+    jpc_fix_t t;
+
+    if (stepsize == jpc_inttofix(1)) {
+        return;
+    }
+
+    for (i = 0; i < jas_matrix_numrows(data); ++i) {
+        for (j = 0; j < jas_matrix_numcols(data); ++j) {
+            t = jas_matrix_get(data, i, j);
+
+{
+    if (t < 0) {
+        t = jpc_fix_neg(jpc_fix_div(jpc_fix_neg(t), stepsize));
+    } else {
+        t = jpc_fix_div(t, stepsize);
+    }
+}
+
+            jas_matrix_set(data, i, j, t);
+        }
+    }
+}
+
+
+
 /*****************************************************************************\
 * Tile constructors and destructors.
 \*****************************************************************************/
@@ -2227,7 +2586,7 @@ prc_create(jpc_enc_prc_t *prc, jpc_enc_cp_t *cp, jpc_enc_band_t *band) {
         }
 
         prc->cblks = jas_malloc(prc->numcblks * sizeof(jpc_enc_cblk_t));
-        
+
         if (!prc->cblks)
             goto error;
         for (cblkno = 0, cblk = prc->cblks;
@@ -2445,9 +2804,9 @@ jpc_enc_dump(jpc_enc_t *enc) {
                      prcno < rlvl->numprcs;
                      ++prcno, ++prc) {
                     fprintf(stderr, "        prc %5d %5d %5d %5d (%5d %5d)\n",
-                            (int)prc->tlx, (int)prc->tly, 
+                            (int)prc->tlx, (int)prc->tly,
                             (int)prc->brx, (int)prc->bry,
-                            (int)(prc->brx - prc->tlx), 
+                            (int)(prc->brx - prc->tlx),
                             (int)(prc->bry - prc->tly));
                     if (!prc->cblks) {
                         continue;
@@ -2468,352 +2827,6 @@ jpc_enc_dump(jpc_enc_t *enc) {
 
 
 
-static int
-jpc_enc_encodemainbody(jpc_enc_t *enc) {
-
-    int tileno;
-    int i;
-    jpc_sot_t *sot;
-    jpc_enc_tcmpt_t *comp;
-    jpc_enc_tcmpt_t *endcomps;
-    jpc_enc_band_t *band;
-    jpc_enc_band_t *endbands;
-    jpc_enc_rlvl_t *lvl;
-    int rlvlno;
-    jpc_qcc_t *qcc;
-    jpc_cod_t *cod;
-    int adjust;
-    int j;
-    int absbandno;
-    long tilehdrlen;
-    long tilelen;
-    jpc_enc_tile_t *tile;
-    jpc_enc_cp_t *cp;
-    double rho;
-    uint_fast16_t cmptno;
-    int samestepsizes;
-    jpc_enc_ccp_t *ccps;
-    jpc_enc_tccp_t *tccp;
-    int bandno;
-    uint_fast32_t x;
-    uint_fast32_t y;
-    int mingbits;
-    int actualnumbps;
-    jpc_fix_t mxmag;
-    jpc_fix_t mag;
-    int numgbits;
-    const char * error;
-
-    cp = enc->cp;
-
-    for (tileno = 0; tileno < cp->numtiles; ++tileno) {
-        enc->curtile = jpc_enc_tile_create(enc->cp, enc->image, tileno);
-        if (!enc->curtile)
-            abort();
-
-        tile = enc->curtile;
-
-        if (jas_getdbglevel() >= 10) {
-            jpc_enc_dump(enc);
-        }
-
-        endcomps = &tile->tcmpts[tile->numtcmpts];
-        for (cmptno = 0, comp = tile->tcmpts;
-             cmptno < tile->numtcmpts;
-             ++cmptno, ++comp) {
-            if (!cp->ccps[cmptno].sgnd) {
-                adjust = 1 << (cp->ccps[cmptno].prec - 1);
-                for (i = 0; i < jas_matrix_numrows(comp->data); ++i) {
-                    for (j = 0; j < jas_matrix_numcols(comp->data); ++j) {
-                        *jas_matrix_getref(comp->data, i, j) -= adjust;
-                    }
-                }
-            }
-        }
-
-        if (!tile->intmode) {
-            endcomps = &tile->tcmpts[tile->numtcmpts];
-            for (comp = tile->tcmpts; comp != endcomps; ++comp) {
-                jas_matrix_asl(comp->data, JPC_FIX_FRACBITS);
-            }
-        }
-
-        switch (tile->mctid) {
-        case JPC_MCT_RCT:
-            assert(jas_image_numcmpts(enc->image) == 3);
-            jpc_rct(tile->tcmpts[0].data, tile->tcmpts[1].data,
-                    tile->tcmpts[2].data);
-            break;
-        case JPC_MCT_ICT:
-            assert(jas_image_numcmpts(enc->image) == 3);
-            jpc_ict(tile->tcmpts[0].data, tile->tcmpts[1].data,
-                    tile->tcmpts[2].data);
-            break;
-        default:
-            break;
-        }
-
-        for (i = 0; i < jas_image_numcmpts(enc->image); ++i) {
-            comp = &tile->tcmpts[i];
-            jpc_tsfb_analyze(comp->tsfb,
-                             ((comp->qmfbid == JPC_COX_RFT) ?
-                              JPC_TSFB_RITIMODE : 0), comp->data);
-
-        }
-
-        endcomps = &tile->tcmpts[tile->numtcmpts];
-        for (cmptno = 0, comp = tile->tcmpts;
-             comp != endcomps;
-             ++cmptno, ++comp) {
-            mingbits = 0;
-            absbandno = 0;
-            /* All bands must have a corresponding quantizer step size,
-               even if they contain no samples and are never coded. */
-            /* Some bands may not be hit by the loop below, so we must
-               initialize all of the step sizes to a sane value. */
-            memset(comp->stepsizes, 0, sizeof(comp->stepsizes));
-            for (rlvlno = 0, lvl = comp->rlvls;
-                 rlvlno < comp->numrlvls;
-                 ++rlvlno, ++lvl) {
-                if (!lvl->bands) {
-                    absbandno += rlvlno ? 3 : 1;
-                    continue;
-                }
-                endbands = &lvl->bands[lvl->numbands];
-                for (band = lvl->bands; band != endbands; ++band) {
-                    if (!band->data) {
-                        ++absbandno;
-                        continue;
-                    }
-                    actualnumbps = 0;
-                    mxmag = 0;
-                    for (y = 0; y < jas_matrix_numrows(band->data); ++y) {
-                        for (x = 0; x < jas_matrix_numcols(band->data); ++x) {
-                            mag = abs(jas_matrix_get(band->data, y, x));
-                            if (mag > mxmag) {
-                                mxmag = mag;
-                            }
-                        }
-                    }
-                    if (tile->intmode) {
-                        actualnumbps =
-                            jpc_firstone(mxmag) + 1;
-                    } else {
-                        actualnumbps =
-                            jpc_firstone(mxmag) + 1 - JPC_FIX_FRACBITS;
-                    }
-                    numgbits = actualnumbps - (cp->ccps[cmptno].prec - 1 +
-                                               band->analgain);
-                    if (numgbits > mingbits) {
-                        mingbits = numgbits;
-                    }
-                    if (!tile->intmode) {
-                        band->absstepsize =
-                            jpc_fix_div(
-                                jpc_inttofix(1 << (band->analgain + 1)),
-                                band->synweight);
-                    } else {
-                        band->absstepsize = jpc_inttofix(1);
-                    }
-                    band->stepsize = jpc_abstorelstepsize(
-                        band->absstepsize, cp->ccps[cmptno].prec +
-                        band->analgain);
-                    band->numbps = cp->tccp.numgbits +
-                        JPC_QCX_GETEXPN(band->stepsize) - 1;
-
-                    if ((!tile->intmode) && band->data) {
-                        quantize(band->data, band->absstepsize);
-                    }
-
-                    comp->stepsizes[absbandno] = band->stepsize;
-                    ++absbandno;
-                }
-            }
-
-            assert(JPC_FIX_FRACBITS >= JPC_NUMEXTRABITS);
-            if (!tile->intmode) {
-                jas_matrix_divpow2(comp->data,
-                                   JPC_FIX_FRACBITS - JPC_NUMEXTRABITS);
-            } else {
-                jas_matrix_asl(comp->data, JPC_NUMEXTRABITS);
-            }
-        }
-
-        if (mingbits > cp->tccp.numgbits) {
-            fprintf(stderr, "error: too few guard bits (need at least %d)\n",
-                    mingbits);
-            return -1;
-        }
-
-        enc->tmpstream = jas_stream_memopen(0, 0);
-        if (!enc->tmpstream) {
-            fprintf(stderr, "cannot open tmp file\n");
-            return -1;
-        }
-
-        /* Write the tile header. */
-        enc->mrk = jpc_ms_create(JPC_MS_SOT);
-        if (!enc->mrk)
-            return -1;
-        sot = &enc->mrk->parms.sot;
-        sot->len = 0;
-        sot->tileno = tileno;
-        sot->partno = 0;
-        sot->numparts = 1;
-        if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
-            fprintf(stderr, "cannot write SOT marker\n");
-            return -1;
-        }
-        jpc_ms_destroy(enc->mrk);
-        enc->mrk = 0;
-
-/************************************************************************/
-/************************************************************************/
-/************************************************************************/
-
-        tccp = &cp->tccp;
-        for (cmptno = 0; cmptno < cp->numcmpts; ++cmptno) {
-            comp = &tile->tcmpts[cmptno];
-            if (comp->numrlvls != tccp->maxrlvls) {
-                if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) {
-                    return -1;
-                }
-                /* XXX = this is not really correct. we are using comp #0's
-                   precint sizes and other characteristics */
-                comp = &tile->tcmpts[0];
-                cod = &enc->mrk->parms.cod;
-                cod->compparms.csty = 0;
-                cod->compparms.numdlvls = comp->numrlvls - 1;
-                cod->prg = tile->prg;
-                cod->numlyrs = tile->numlyrs;
-                cod->compparms.cblkwidthval =
-                    JPC_COX_CBLKSIZEEXPN(comp->cblkwidthexpn);
-                cod->compparms.cblkheightval =
-                    JPC_COX_CBLKSIZEEXPN(comp->cblkheightexpn);
-                cod->compparms.cblksty = comp->cblksty;
-                cod->compparms.qmfbid = comp->qmfbid;
-                cod->mctrans = (tile->mctid != JPC_MCT_NONE);
-                for (i = 0; i < comp->numrlvls; ++i) {
-                    cod->compparms.rlvls[i].parwidthval =
-                        comp->rlvls[i].prcwidthexpn;
-                    cod->compparms.rlvls[i].parheightval =
-                        comp->rlvls[i].prcheightexpn;
-                }
-                if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
-                    return -1;
-                }
-                jpc_ms_destroy(enc->mrk);
-                enc->mrk = 0;
-            }
-        }
-
-        for (cmptno = 0, comp = tile->tcmpts;
-             cmptno < cp->numcmpts;
-             ++cmptno, ++comp) {
-            ccps = &cp->ccps[cmptno];
-            if (ccps->numstepsizes == comp->numstepsizes) {
-                samestepsizes = 1;
-                for (bandno = 0; bandno < ccps->numstepsizes; ++bandno) {
-                    if (ccps->stepsizes[bandno] != comp->stepsizes[bandno]) {
-                        samestepsizes = 0;
-                        break;
-                    }
-                }
-            } else {
-                samestepsizes = 0;
-            }
-            if (!samestepsizes) {
-                if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) {
-                    return -1;
-                }
-                qcc = &enc->mrk->parms.qcc;
-                qcc->compno = cmptno;
-                qcc->compparms.numguard = cp->tccp.numgbits;
-                qcc->compparms.qntsty = (comp->qmfbid == JPC_COX_INS) ?
-                    JPC_QCX_SEQNT : JPC_QCX_NOQNT;
-                qcc->compparms.numstepsizes = comp->numstepsizes;
-                qcc->compparms.stepsizes = comp->stepsizes;
-                if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
-                    return -1;
-                }
-                qcc->compparms.stepsizes = 0;
-                jpc_ms_destroy(enc->mrk);
-                enc->mrk = 0;
-            }
-        }
-
-        /* Write a SOD marker to indicate the end of the tile header. */
-        if (!(enc->mrk = jpc_ms_create(JPC_MS_SOD))) {
-            return -1;
-        }
-        if (jpc_putms(enc->tmpstream, enc->cstate, enc->mrk)) {
-            fprintf(stderr, "cannot write SOD marker\n");
-            return -1;
-        }
-        jpc_ms_destroy(enc->mrk);
-        enc->mrk = 0;
-        tilehdrlen = jas_stream_getrwcount(enc->tmpstream);
-
-/************************************************************************/
-/************************************************************************/
-/************************************************************************/
-
-        if (jpc_enc_enccblks(enc)) {
-            abort();
-            return -1;
-        }
-
-        cp = enc->cp;
-        rho = (double) (tile->brx - tile->tlx) * (tile->bry - tile->tly) /
-            ((cp->refgrdwidth - cp->imgareatlx) * (cp->refgrdheight -
-                                                   cp->imgareatly));
-        tile->rawsize = cp->rawsize * rho;
-
-        computeLayerSizes(enc, tile, cp, rho, tilehdrlen, &error);
-        
-        if (!error) {
-            int rc;
-            performTier2Coding(enc, tile->numlyrs, tile->lyrsizes, &error);
-
-            rc =  jpc_enc_encodetiledata(enc);
-            if (rc != 0)
-                pm_asprintf(&error, "jpc_enc_encodetiledata() failed\n");
-        }
-
-        if (error) {
-            fprintf(stderr, "%s\n", error);
-            pm_strfree(error);
-            return -1;
-        }
-
-        tilelen = jas_stream_tell(enc->tmpstream);
-
-        if (jas_stream_seek(enc->tmpstream, 6, SEEK_SET) < 0) {
-            return -1;
-        }
-        jpc_putuint32(enc->tmpstream, tilelen);
-
-        if (jas_stream_seek(enc->tmpstream, 0, SEEK_SET) < 0) {
-            return -1;
-        }
-        if (jpc_putdata(enc->out, enc->tmpstream, -1)) {
-            return -1;
-        }
-        enc->len += tilelen;
-
-        jas_stream_close(enc->tmpstream);
-        enc->tmpstream = 0;
-
-        jpc_enc_tile_destroy(enc->curtile);
-        enc->curtile = 0;
-
-    }
-
-    return 0;
-}
-
-
-
 /*
  * Copyright (c) 1999-2000 Image Power, Inc. and the University of
  *   British Columbia.
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_enc.h b/converter/other/jpeg2000/libjasper/jpc/jpc_enc.h
index cfd754c9..86a8e59c 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_enc.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_enc.h
@@ -145,7 +145,7 @@
 * Coding parameters types.
 \******************************************************************************/
 
-/* Per-component coding paramters. */
+/* Per-component coding parameters. */
 
 typedef struct {
 
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_math.c b/converter/other/jpeg2000/libjasper/jpc/jpc_math.c
index 01e3611e..a884ed4d 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_math.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_math.c
@@ -50,6 +50,8 @@ jpc_firstone(int_fast32_t const arg) {
 /*---------------------------------------------------------------------------- 
   Calculate the bit position of the first leading one in a nonnegative
   integer.
+
+  LSB is bit position 0.  Iff there are no ones, return -1.
 -----------------------------------------------------------------------------*/
 	int n;
     int x;
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_mqenc.c b/converter/other/jpeg2000/libjasper/jpc/jpc_mqenc.c
index 3f6122e3..54472481 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_mqenc.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_mqenc.c
@@ -6,14 +6,14 @@
  */
 
 /* __START_OF_JASPER_LICENSE__
- * 
+ *
  * JasPer Software License
- * 
+ *
  * IMAGE POWER JPEG-2000 PUBLIC LICENSE
  * ************************************
- * 
+ *
  * GRANT:
- * 
+ *
  * Permission is hereby granted, free of charge, to any person (the "User")
  * obtaining a copy of this software and associated documentation, to deal
  * in the JasPer Software without restriction, including without limitation
@@ -21,22 +21,22 @@
  * and/or sell copies of the JasPer Software (in source and binary forms),
  * and to permit persons to whom the JasPer Software is furnished to do so,
  * provided further that the License Conditions below are met.
- * 
+ *
  * License Conditions
  * ******************
- * 
+ *
  * A.  Redistributions of source code must retain the above copyright notice,
  * and this list of conditions, and the following disclaimer.
- * 
+ *
  * B.  Redistributions in binary form must reproduce the above copyright
  * notice, and this list of conditions, and the following disclaimer in
  * the documentation and/or other materials provided with the distribution.
- * 
+ *
  * C.  Neither the name of Image Power, Inc. nor any other contributor
  * (including, but not limited to, the University of British Columbia and
  * Michael David Adams) may be used to endorse or promote products derived
  * from this software without specific prior written permission.
- * 
+ *
  * D.  User agrees that it shall not commence any action against Image Power,
  * Inc., the University of British Columbia, Michael David Adams, or any
  * other contributors (collectively "Licensors") for infringement of any
@@ -56,17 +56,17 @@
  * trade dress, or service mark rights); and (v) divisions, continuations,
  * renewals, reissues and extensions of the foregoing (as and to the extent
  * applicable) now existing, hereafter filed, issued or acquired.
- * 
+ *
  * E.  If User commences an infringement action against any Licensor(s) then
  * such Licensor(s) shall have the right to terminate User's license and
  * all sublicenses that have been granted hereunder by User to other parties.
- * 
+ *
  * F.  This software is for use only in hardware or software products that
  * are compliant with ISO/IEC 15444-1 (i.e., JPEG-2000 Part 1).  No license
  * or right to this Software is granted for products that do not comply
  * with ISO/IEC 15444-1.  The JPEG-2000 Part 1 standard can be purchased
  * from the ISO.
- * 
+ *
  * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE.
  * NO USE OF THE JASPER SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
  * THIS DISCLAIMER.  THE JASPER SOFTWARE IS PROVIDED BY THE LICENSORS AND
@@ -106,7 +106,7 @@
  * TECHNOLOGY OR PRODUCTS FOR HIGH RISK ACTIVITIES AND WILL ENSURE THAT ITS
  * CUSTOMERS AND END-USERS OF ITS PRODUCTS ARE PROVIDED WITH A COPY OF THE
  * NOTICE SPECIFIED IN THIS SECTION.
- * 
+ *
  * __END_OF_JASPER_LICENSE__
  */
 
@@ -223,7 +223,7 @@
 }
 
 /******************************************************************************\
-* Local function protoypes.
+* Local function prototypes.
 \******************************************************************************/
 
 static void jpc_mqenc_setbits(jpc_mqenc_t *mqenc);
@@ -439,3 +439,6 @@ int jpc_mqenc_dump(jpc_mqenc_t *mqenc, FILE *out)
             (unsigned)(*mqenc->curctx)->qeval);
     return 0;
 }
+
+
+
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_t1dec.c b/converter/other/jpeg2000/libjasper/jpc/jpc_t1dec.c
index 01a54ea8..b6c5e14f 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_t1dec.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_t1dec.c
@@ -124,6 +124,8 @@
 #include <stdlib.h>
 #include <assert.h>
 
+#include "netpbm/nstring.h"
+
 #include "jasper/jas_fix.h"
 #include "jasper/jas_stream.h"
 #include "jasper/jas_math.h"
@@ -138,817 +140,871 @@
 *
 \******************************************************************************/
 
-static int jpc_dec_decodecblk(jpc_dec_t *dec, jpc_dec_tile_t *tile, jpc_dec_tcomp_t *tcomp, jpc_dec_band_t *band,
-  jpc_dec_cblk_t *cblk, int dopartial, int maxlyrs);
-static int dec_sigpass(jpc_dec_t *dec, jpc_mqdec_t *mqdec, int bitpos, int orient,
-  int vcausalflag, jas_matrix_t *flags, jas_matrix_t *data);
-static int dec_rawsigpass(jpc_dec_t *dec, jpc_bitstream_t *in, int bitpos,
-  int vcausalflag, jas_matrix_t *flags, jas_matrix_t *data);
-static int dec_refpass(jpc_dec_t *dec, jpc_mqdec_t *mqdec, int bitpos, int vcausalflag,
-  jas_matrix_t *flags, jas_matrix_t *data);
-static int dec_rawrefpass(jpc_dec_t *dec, jpc_bitstream_t *in, int bitpos,
-  int vcausalflag, jas_matrix_t *flags, jas_matrix_t *data);
-static int dec_clnpass(jpc_dec_t *dec, jpc_mqdec_t *mqdec, int bitpos, int orient,
-  int vcausalflag, int segsymflag, jas_matrix_t *flags, jas_matrix_t *data);
-
 #if defined(DEBUG)
 static long t1dec_cnt = 0;
 #endif
 
 #if !defined(DEBUG)
-#define	JPC_T1D_GETBIT(mqdec, v, passtypename, symtypename) \
-	((v) = jpc_mqdec_getbit(mqdec))
+#define JPC_T1D_GETBIT(mqdec, v, passtypename, symtypename) \
+    ((v) = jpc_mqdec_getbit(mqdec))
 #else
-#define	JPC_T1D_GETBIT(mqdec, v, passtypename, symtypename) \
+#define JPC_T1D_GETBIT(mqdec, v, passtypename, symtypename) \
 { \
-	(v) = jpc_mqdec_getbit(mqdec); \
-	if (jas_getdbglevel() >= 100) { \
-		fprintf(stderr, "index = %ld; passtype = %s; symtype = %s; sym = %d\n", t1dec_cnt, passtypename, symtypename, v); \
-		++t1dec_cnt; \
-	} \
+    (v) = jpc_mqdec_getbit(mqdec); \
+    if (jas_getdbglevel() >= 100) { \
+        fprintf(stderr, "index = %ld; passtype = %s; symtype = %s; sym = %d\n", t1dec_cnt, passtypename, symtypename, v); \
+        ++t1dec_cnt; \
+    } \
 }
 #endif
-#define	JPC_T1D_GETBITNOSKEW(mqdec, v, passtypename, symtypename) \
-	JPC_T1D_GETBIT(mqdec, v, passtypename, symtypename)
+#define JPC_T1D_GETBITNOSKEW(mqdec, v, passtypename, symtypename) \
+    JPC_T1D_GETBIT(mqdec, v, passtypename, symtypename)
 
 #if !defined(DEBUG)
-#define	JPC_T1D_RAWGETBIT(bitstream, v, passtypename, symtypename) \
-	((v) = jpc_bitstream_getbit(bitstream))
+#define JPC_T1D_RAWGETBIT(bitstream, v, passtypename, symtypename) \
+    ((v) = jpc_bitstream_getbit(bitstream))
 #else
-#define	JPC_T1D_RAWGETBIT(bitstream, v, passtypename, symtypename) \
+#define JPC_T1D_RAWGETBIT(bitstream, v, passtypename, symtypename) \
 { \
-	(v) = jpc_bitstream_getbit(bitstream); \
-	if (jas_getdbglevel() >= 100) { \
-		fprintf(stderr, "index = %ld; passtype = %s; symtype = %s; sym = %d\n", t1dec_cnt, passtypename, symtypename, v); \
-		++t1dec_cnt; \
-	} \
+    (v) = jpc_bitstream_getbit(bitstream); \
+    if (jas_getdbglevel() >= 100) { \
+        fprintf(stderr, "index = %ld; passtype = %s; symtype = %s; sym = %d\n", t1dec_cnt, passtypename, symtypename, v); \
+        ++t1dec_cnt; \
+    } \
 }
 #endif
 
-/******************************************************************************\
-* Code.
-\******************************************************************************/
 
-int jpc_dec_decodecblks(jpc_dec_t *dec, jpc_dec_tile_t *tile)
-{
-	jpc_dec_tcomp_t *tcomp;
-	int compcnt;
-	jpc_dec_rlvl_t *rlvl;
-	int rlvlcnt;
-	jpc_dec_band_t *band;
-	int bandcnt;
-	jpc_dec_prc_t *prc;
-	int prccnt;
-	jpc_dec_cblk_t *cblk;
-	int cblkcnt;
-
-	for (compcnt = dec->numcomps, tcomp = tile->tcomps; compcnt > 0;
-	  --compcnt, ++tcomp) {
-		for (rlvlcnt = tcomp->numrlvls, rlvl = tcomp->rlvls;
-		  rlvlcnt > 0; --rlvlcnt, ++rlvl) {
-			if (!rlvl->bands) {
-				continue;
-			}
-			for (bandcnt = rlvl->numbands, band = rlvl->bands;
-			  bandcnt > 0; --bandcnt, ++band) {
-				if (!band->data) {
-					continue;
-				}
-				for (prccnt = rlvl->numprcs, prc = band->prcs;
-				  prccnt > 0; --prccnt, ++prc) {
-					if (!prc->cblks) {
-						continue;
-					}
-					for (cblkcnt = prc->numcblks,
-					  cblk = prc->cblks; cblkcnt > 0;
-					  --cblkcnt, ++cblk) {
-						if (jpc_dec_decodecblk(dec, tile, tcomp,
-						  band, cblk, 1, JPC_MAXLYRS)) {
-							return -1;
-						}
-					}
-				}
-
-			}
-		}
-	}
-
-	return 0;
-}
-
-static int jpc_dec_decodecblk(jpc_dec_t *dec, jpc_dec_tile_t *tile, jpc_dec_tcomp_t *tcomp, jpc_dec_band_t *band,
-  jpc_dec_cblk_t *cblk, int dopartial, int maxlyrs)
-{
-	jpc_dec_seg_t *seg;
-	int i;
-	int bpno;
-	int passtype;
-	int ret;
-	int compno;
-	int filldata;
-	int fillmask;
-	jpc_dec_ccp_t *ccp;
-
-	compno = tcomp - tile->tcomps;
-
-	if (!cblk->flags) {
-		/* Note: matrix is assumed to be zeroed */
-		if (!(cblk->flags = jas_matrix_create(jas_matrix_numrows(cblk->data) +
-		  2, jas_matrix_numcols(cblk->data) + 2))) {
-			return -1;
-		}
-	}
-
-	seg = cblk->segs.head;
-	while (seg && (seg != cblk->curseg || dopartial) && (maxlyrs < 0 ||
-	  seg->lyrno < maxlyrs)) {
-		assert(seg->numpasses >= seg->maxpasses || dopartial);
-		assert(seg->stream);
-		jas_stream_rewind(seg->stream);
-		jas_stream_setrwcount(seg->stream, 0);
-		if (seg->type == JPC_SEG_MQ) {
-			if (!cblk->mqdec) {
-				if (!(cblk->mqdec = jpc_mqdec_create(JPC_NUMCTXS, 0))) {
-					return -1;
-				}
-				jpc_mqdec_setctxs(cblk->mqdec, JPC_NUMCTXS, jpc_mqctxs);
-			}
-			jpc_mqdec_setinput(cblk->mqdec, seg->stream);
-			jpc_mqdec_init(cblk->mqdec);
-		} else {
-			assert(seg->type == JPC_SEG_RAW);
-			if (!cblk->nulldec) {
-				if (!(cblk->nulldec = jpc_bitstream_sopen(seg->stream, "r"))) {
-					assert(0);
-				}
-			}
-		}
-
-
-		for (i = 0; i < seg->numpasses; ++i) {
-			if (cblk->numimsbs > band->numbps) {
-				ccp = &tile->cp->ccps[compno];
-				if (ccp->roishift <= 0) {
-					fprintf(stderr, "warning: corrupt code stream\n");
-				} else {
-					if (cblk->numimsbs < ccp->roishift - band->numbps) {
-						fprintf(stderr, "warning: corrupt code stream\n");
-					}
-				}
-			}
-			bpno = band->roishift + band->numbps - 1 - (cblk->numimsbs +
-			  (seg->passno + i - cblk->firstpassno + 2) / 3);
-if (bpno < 0) {
-	goto premature_exit;
-}
-#if 1
-			passtype = (seg->passno + i + 2) % 3;
-#else
-			passtype = JPC_PASSTYPE(seg->passno + i + 2);
-#endif
-			assert(bpno >= 0 && bpno < 31);
-			switch (passtype) {
-			case JPC_SIGPASS:
-				ret = (seg->type == JPC_SEG_MQ) ? dec_sigpass(dec,
-				  cblk->mqdec, bpno, band->orient,
-				  (tile->cp->ccps[compno].cblkctx & JPC_COX_VSC) != 0,
-				  cblk->flags, cblk->data) :
-				  dec_rawsigpass(dec, cblk->nulldec, bpno,
-				  (tile->cp->ccps[compno].cblkctx & JPC_COX_VSC) != 0,
-				  cblk->flags, cblk->data);
-				break;
-			case JPC_REFPASS:
-				ret = (seg->type == JPC_SEG_MQ) ?
-				  dec_refpass(dec, cblk->mqdec, bpno,
-				  (tile->cp->ccps[compno].cblkctx & JPC_COX_VSC) != 0,
-				  cblk->flags, cblk->data) :
-				  dec_rawrefpass(dec, cblk->nulldec, bpno,
-				  (tile->cp->ccps[compno].cblkctx & JPC_COX_VSC) != 0,
-				  cblk->flags, cblk->data);
-				break;
-			case JPC_CLNPASS:
-				assert(seg->type == JPC_SEG_MQ);
-				ret = dec_clnpass(dec, cblk->mqdec, bpno,
-				  band->orient, (tile->cp->ccps[compno].cblkctx &
-				  JPC_COX_VSC) != 0, (tile->cp->ccps[compno].cblkctx &
-				  JPC_COX_SEGSYM) != 0, cblk->flags,
-				  cblk->data);
-				break;
-			default:
-				ret = -1;
-				break;
-			}
-			/* Do we need to reset after each coding pass? */
-			if (tile->cp->ccps[compno].cblkctx & JPC_COX_RESET) {
-				jpc_mqdec_setctxs(cblk->mqdec, JPC_NUMCTXS, jpc_mqctxs);
-			}
-
-			if (ret) {
-				fprintf(stderr, "coding pass failed passtype=%d segtype=%d\n", passtype, seg->type);
-				return -1;
-			}
-
-		}
-
-		if (seg->type == JPC_SEG_MQ) {
-/* Note: dont destroy mq decoder because context info will be lost */
-		} else {
-			assert(seg->type == JPC_SEG_RAW);
-			if (tile->cp->ccps[compno].cblkctx & JPC_COX_PTERM) {
-				fillmask = 0x7f;
-				filldata = 0x2a;
-			} else {
-				fillmask = 0;
-				filldata = 0;
-			}
-			if ((ret = jpc_bitstream_inalign(cblk->nulldec, fillmask,
-			  filldata)) < 0) {
-				return -1;
-			} else if (ret > 0) {
-				fprintf(stderr, "warning: bad termination pattern detected\n");
-			}
-			jpc_bitstream_close(cblk->nulldec);
-			cblk->nulldec = 0;
-		}
-
-		cblk->curseg = seg->next;
-		jpc_seglist_remove(&cblk->segs, seg);
-		jpc_seg_destroy(seg);
-		seg = cblk->curseg;
-	}
-
-	assert(dopartial ? (!cblk->curseg) : 1);
-
-premature_exit:
-	return 0;
-}
 
 /******************************************************************************\
 * Code for significance pass.
 \******************************************************************************/
 
-#define	jpc_sigpass_step(fp, frowstep, dp, bitpos, oneplushalf, orient, mqdec, vcausalflag) \
+#define jpc_sigpass_step(fp, frowstep, dp, bitpos, oneplushalf, orient, mqdec, vcausalflag) \
 { \
-	int f; \
-	int v; \
-	f = *(fp); \
-	if ((f & JPC_OTHSIGMSK) && !(f & (JPC_SIG | JPC_VISIT))) { \
-		jpc_mqdec_setcurctx((mqdec), JPC_GETZCCTXNO(f, (orient))); \
-		JPC_T1D_GETBIT((mqdec), v, "SIG", "ZC"); \
-		if (v) { \
-			jpc_mqdec_setcurctx((mqdec), JPC_GETSCCTXNO(f)); \
-			JPC_T1D_GETBIT((mqdec), v, "SIG", "SC"); \
-			v ^= JPC_GETSPB(f); \
-			JPC_UPDATEFLAGS4((fp), (frowstep), v, (vcausalflag)); \
-			*(fp) |= JPC_SIG; \
-			*(dp) = (v) ? (-(oneplushalf)) : (oneplushalf); \
-		} \
-		*(fp) |= JPC_VISIT; \
-	} \
+    int f; \
+    int v; \
+    f = *(fp); \
+    if ((f & JPC_OTHSIGMSK) && !(f & (JPC_SIG | JPC_VISIT))) { \
+        jpc_mqdec_setcurctx((mqdec), JPC_GETZCCTXNO(f, (orient))); \
+        JPC_T1D_GETBIT((mqdec), v, "SIG", "ZC"); \
+        if (v) { \
+            jpc_mqdec_setcurctx((mqdec), JPC_GETSCCTXNO(f)); \
+            JPC_T1D_GETBIT((mqdec), v, "SIG", "SC"); \
+            v ^= JPC_GETSPB(f); \
+            JPC_UPDATEFLAGS4((fp), (frowstep), v, (vcausalflag)); \
+            *(fp) |= JPC_SIG; \
+            *(dp) = (v) ? (-(oneplushalf)) : (oneplushalf); \
+        } \
+        *(fp) |= JPC_VISIT; \
+    } \
 }
 
-static int dec_sigpass(jpc_dec_t *dec, register jpc_mqdec_t *mqdec, int bitpos, int orient,
-  int vcausalflag, jas_matrix_t *flags, jas_matrix_t *data)
-{
-	int i;
-	int j;
-	int one;
-	int half;
-	int oneplushalf;
-	int vscanlen;
-	int width;
-	int height;
-	jpc_fix_t *fp;
-	int frowstep;
-	int fstripestep;
-	jpc_fix_t *fstripestart;
-	jpc_fix_t *fvscanstart;
-	jpc_fix_t *dp;
-	int drowstep;
-	int dstripestep;
-	jpc_fix_t *dstripestart;
-	jpc_fix_t *dvscanstart;
-	int k;
-
-	width = jas_matrix_numcols(data);
-	height = jas_matrix_numrows(data);
-	frowstep = jas_matrix_rowstep(flags);
-	drowstep = jas_matrix_rowstep(data);
-	fstripestep = frowstep << 2;
-	dstripestep = drowstep << 2;
-
-	one = 1 << bitpos;
-	half = one >> 1;
-	oneplushalf = one | half;
-
-	fstripestart = jas_matrix_getref(flags, 1, 1);
-	dstripestart = jas_matrix_getref(data, 0, 0);
-	for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
-	  dstripestart += dstripestep) {
-		fvscanstart = fstripestart;
-		dvscanstart = dstripestart;
-		vscanlen = JAS_MIN(i, 4);
-		for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
-			fp = fvscanstart;
-			dp = dvscanstart;
-			k = vscanlen;
-
-			/* Process first sample in vertical scan. */
-			jpc_sigpass_step(fp, frowstep, dp, bitpos, oneplushalf,
-			  orient, mqdec, vcausalflag);
-			if (--k <= 0) {
-				continue;
-			}
-			fp += frowstep;
-			dp += drowstep;
-
-			/* Process second sample in vertical scan. */
-			jpc_sigpass_step(fp, frowstep, dp, bitpos, oneplushalf,
-			  orient, mqdec, 0);
-			if (--k <= 0) {
-				continue;
-			}
-			fp += frowstep;
-			dp += drowstep;
-
-			/* Process third sample in vertical scan. */
-			jpc_sigpass_step(fp, frowstep, dp, bitpos, oneplushalf,
-			  orient, mqdec, 0);
-			if (--k <= 0) {
-				continue;
-			}
-			fp += frowstep;
-			dp += drowstep;
-
-			/* Process fourth sample in vertical scan. */
-			jpc_sigpass_step(fp, frowstep, dp, bitpos, oneplushalf,
-			  orient, mqdec, 0);
-		}
-	}
-	return 0;
+#define jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf, in, vcausalflag) \
+{ \
+    jpc_fix_t f = *(fp); \
+    jpc_fix_t v; \
+    if ((f & JPC_OTHSIGMSK) && !(f & (JPC_SIG | JPC_VISIT))) { \
+        JPC_T1D_RAWGETBIT(in, v, "SIG", "ZC"); \
+        if (v < 0) { \
+            return -1; \
+        } \
+        if (v) { \
+            JPC_T1D_RAWGETBIT(in, v, "SIG", "SC"); \
+            if (v < 0) { \
+                return -1; \
+            } \
+            JPC_UPDATEFLAGS4((fp), (frowstep), v, (vcausalflag)); \
+            *(fp) |= JPC_SIG; \
+            *(dp) = v ? (-oneplushalf) : (oneplushalf); \
+        } \
+        *(fp) |= JPC_VISIT; \
+    } \
 }
 
-#define	jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf, in, vcausalflag) \
-{ \
-	jpc_fix_t f = *(fp); \
-	jpc_fix_t v; \
-	if ((f & JPC_OTHSIGMSK) && !(f & (JPC_SIG | JPC_VISIT))) { \
-		JPC_T1D_RAWGETBIT(in, v, "SIG", "ZC"); \
-		if (v < 0) { \
-			return -1; \
-		} \
-		if (v) { \
-			JPC_T1D_RAWGETBIT(in, v, "SIG", "SC"); \
-			if (v < 0) { \
-				return -1; \
-			} \
-			JPC_UPDATEFLAGS4((fp), (frowstep), v, (vcausalflag)); \
-			*(fp) |= JPC_SIG; \
-			*(dp) = v ? (-oneplushalf) : (oneplushalf); \
-		} \
-		*(fp) |= JPC_VISIT; \
-	} \
+
+
+static int
+dec_sigpass(jpc_dec_t *dec, register jpc_mqdec_t *mqdec, int bitpos,
+            int orient,
+            int vcausalflag, jas_matrix_t *flags, jas_matrix_t *data)
+{
+    int i;
+    int j;
+    int one;
+    int half;
+    int oneplushalf;
+    int vscanlen;
+    int width;
+    int height;
+    jpc_fix_t *fp;
+    int frowstep;
+    int fstripestep;
+    jpc_fix_t *fstripestart;
+    jpc_fix_t *fvscanstart;
+    jpc_fix_t *dp;
+    int drowstep;
+    int dstripestep;
+    jpc_fix_t *dstripestart;
+    jpc_fix_t *dvscanstart;
+    int k;
+
+    width = jas_matrix_numcols(data);
+    height = jas_matrix_numrows(data);
+    frowstep = jas_matrix_rowstep(flags);
+    drowstep = jas_matrix_rowstep(data);
+    fstripestep = frowstep << 2;
+    dstripestep = drowstep << 2;
+
+    one = 1 << bitpos;
+    half = one >> 1;
+    oneplushalf = one | half;
+
+    fstripestart = jas_matrix_getref(flags, 1, 1);
+    dstripestart = jas_matrix_getref(data, 0, 0);
+    for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
+      dstripestart += dstripestep) {
+        fvscanstart = fstripestart;
+        dvscanstart = dstripestart;
+        vscanlen = JAS_MIN(i, 4);
+        for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+            fp = fvscanstart;
+            dp = dvscanstart;
+            k = vscanlen;
+
+            /* Process first sample in vertical scan. */
+            jpc_sigpass_step(fp, frowstep, dp, bitpos, oneplushalf,
+              orient, mqdec, vcausalflag);
+            if (--k <= 0) {
+                continue;
+            }
+            fp += frowstep;
+            dp += drowstep;
+
+            /* Process second sample in vertical scan. */
+            jpc_sigpass_step(fp, frowstep, dp, bitpos, oneplushalf,
+              orient, mqdec, 0);
+            if (--k <= 0) {
+                continue;
+            }
+            fp += frowstep;
+            dp += drowstep;
+
+            /* Process third sample in vertical scan. */
+            jpc_sigpass_step(fp, frowstep, dp, bitpos, oneplushalf,
+              orient, mqdec, 0);
+            if (--k <= 0) {
+                continue;
+            }
+            fp += frowstep;
+            dp += drowstep;
+
+            /* Process fourth sample in vertical scan. */
+            jpc_sigpass_step(fp, frowstep, dp, bitpos, oneplushalf,
+              orient, mqdec, 0);
+        }
+    }
+    return 0;
 }
 
-static int dec_rawsigpass(jpc_dec_t *dec, jpc_bitstream_t *in, int bitpos, int vcausalflag,
-  jas_matrix_t *flags, jas_matrix_t *data)
+
+
+static int
+dec_rawsigpass(jpc_dec_t *dec, jpc_bitstream_t *in, int bitpos,
+               int vcausalflag,
+               jas_matrix_t *flags, jas_matrix_t *data)
 {
-	int i;
-	int j;
-	int k;
-	int one;
-	int half;
-	int oneplushalf;
-	int vscanlen;
-	int width;
-	int height;
-	jpc_fix_t *fp;
-	int frowstep;
-	int fstripestep;
-	jpc_fix_t *fstripestart;
-	jpc_fix_t *fvscanstart;
-	jpc_fix_t *dp;
-	int drowstep;
-	int dstripestep;
-	jpc_fix_t *dstripestart;
-	jpc_fix_t *dvscanstart;
-
-	width = jas_matrix_numcols(data);
-	height = jas_matrix_numrows(data);
-	frowstep = jas_matrix_rowstep(flags);
-	drowstep = jas_matrix_rowstep(data);
-	fstripestep = frowstep << 2;
-	dstripestep = drowstep << 2;
-
-	one = 1 << bitpos;
-	half = one >> 1;
-	oneplushalf = one | half;
-
-	fstripestart = jas_matrix_getref(flags, 1, 1);
-	dstripestart = jas_matrix_getref(data, 0, 0);
-	for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
-	  dstripestart += dstripestep) {
-		fvscanstart = fstripestart;
-		dvscanstart = dstripestart;
-		vscanlen = JAS_MIN(i, 4);
-		for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
-			fp = fvscanstart;
-			dp = dvscanstart;
-			k = vscanlen;
-
-			/* Process first sample in vertical scan. */
-			jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf,
-			  in, vcausalflag);
-			if (--k <= 0) {
-				continue;
-			}
-			fp += frowstep;
-			dp += drowstep;
-
-			/* Process second sample in vertical scan. */
-			jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf,
-			  in, 0);
-			if (--k <= 0) {
-				continue;
-			}
-			fp += frowstep;
-			dp += drowstep;
-
-			/* Process third sample in vertical scan. */
-			jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf,
-			  in, 0);
-			if (--k <= 0) {
-				continue;
-			}
-			fp += frowstep;
-			dp += drowstep;
-
-			/* Process fourth sample in vertical scan. */
-			jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf,
-			  in, 0);
-
-		}
-	}
-	return 0;
+    int i;
+    int j;
+    int k;
+    int one;
+    int half;
+    int oneplushalf;
+    int vscanlen;
+    int width;
+    int height;
+    jpc_fix_t *fp;
+    int frowstep;
+    int fstripestep;
+    jpc_fix_t *fstripestart;
+    jpc_fix_t *fvscanstart;
+    jpc_fix_t *dp;
+    int drowstep;
+    int dstripestep;
+    jpc_fix_t *dstripestart;
+    jpc_fix_t *dvscanstart;
+
+    width = jas_matrix_numcols(data);
+    height = jas_matrix_numrows(data);
+    frowstep = jas_matrix_rowstep(flags);
+    drowstep = jas_matrix_rowstep(data);
+    fstripestep = frowstep << 2;
+    dstripestep = drowstep << 2;
+
+    one = 1 << bitpos;
+    half = one >> 1;
+    oneplushalf = one | half;
+
+    fstripestart = jas_matrix_getref(flags, 1, 1);
+    dstripestart = jas_matrix_getref(data, 0, 0);
+    for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
+      dstripestart += dstripestep) {
+        fvscanstart = fstripestart;
+        dvscanstart = dstripestart;
+        vscanlen = JAS_MIN(i, 4);
+        for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+            fp = fvscanstart;
+            dp = dvscanstart;
+            k = vscanlen;
+
+            /* Process first sample in vertical scan. */
+            jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf,
+              in, vcausalflag);
+            if (--k <= 0) {
+                continue;
+            }
+            fp += frowstep;
+            dp += drowstep;
+
+            /* Process second sample in vertical scan. */
+            jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf,
+              in, 0);
+            if (--k <= 0) {
+                continue;
+            }
+            fp += frowstep;
+            dp += drowstep;
+
+            /* Process third sample in vertical scan. */
+            jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf,
+              in, 0);
+            if (--k <= 0) {
+                continue;
+            }
+            fp += frowstep;
+            dp += drowstep;
+
+            /* Process fourth sample in vertical scan. */
+            jpc_rawsigpass_step(fp, frowstep, dp, oneplushalf,
+              in, 0);
+
+        }
+    }
+    return 0;
 }
 
+
+
 /******************************************************************************\
 * Code for refinement pass.
 \******************************************************************************/
 
-#define	jpc_refpass_step(fp, dp, poshalf, neghalf, mqdec, vcausalflag) \
+#define jpc_refpass_step(fp, dp, poshalf, neghalf, mqdec, vcausalflag) \
 { \
-	int v; \
-	int t; \
-	if (((*(fp)) & (JPC_SIG | JPC_VISIT)) == JPC_SIG) { \
-		jpc_mqdec_setcurctx((mqdec), JPC_GETMAGCTXNO(*(fp))); \
-		JPC_T1D_GETBITNOSKEW((mqdec), v, "REF", "MR"); \
-		t = (v ? (poshalf) : (neghalf)); \
-		*(dp) += (*(dp) < 0) ? (-t) : t; \
-		*(fp) |= JPC_REFINE; \
-	} \
+    int v; \
+    int t; \
+    if (((*(fp)) & (JPC_SIG | JPC_VISIT)) == JPC_SIG) { \
+        jpc_mqdec_setcurctx((mqdec), JPC_GETMAGCTXNO(*(fp))); \
+        JPC_T1D_GETBITNOSKEW((mqdec), v, "REF", "MR"); \
+        t = (v ? (poshalf) : (neghalf)); \
+        *(dp) += (*(dp) < 0) ? (-t) : t; \
+        *(fp) |= JPC_REFINE; \
+    } \
 }
 
-static int dec_refpass(jpc_dec_t *dec, register jpc_mqdec_t *mqdec, int bitpos,
-  int vcausalflag, jas_matrix_t *flags, jas_matrix_t *data)
+
+
+static int
+dec_refpass(jpc_dec_t *dec, register jpc_mqdec_t *mqdec, int bitpos,
+            int vcausalflag, jas_matrix_t *flags, jas_matrix_t *data)
 {
-	int i;
-	int j;
-	int vscanlen;
-	int width;
-	int height;
-	int one;
-	int poshalf;
-	int neghalf;
-	jpc_fix_t *fp;
-	int frowstep;
-	int fstripestep;
-	jpc_fix_t *fstripestart;
-	jpc_fix_t *fvscanstart;
-	jpc_fix_t *dp;
-	int drowstep;
-	int dstripestep;
-	jpc_fix_t *dstripestart;
-	jpc_fix_t *dvscanstart;
-	int k;
-
-	width = jas_matrix_numcols(data);
-	height = jas_matrix_numrows(data);
-	frowstep = jas_matrix_rowstep(flags);
-	drowstep = jas_matrix_rowstep(data);
-	fstripestep = frowstep << 2;
-	dstripestep = drowstep << 2;
-
-	one = 1 << bitpos;
-	poshalf = one >> 1;
-	neghalf = (bitpos > 0) ? (-poshalf) : (-1);
-
-	fstripestart = jas_matrix_getref(flags, 1, 1);
-	dstripestart = jas_matrix_getref(data, 0, 0);
-	for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
-	  dstripestart += dstripestep) {
-		fvscanstart = fstripestart;
-		dvscanstart = dstripestart;
-		vscanlen = JAS_MIN(i, 4);
-		for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
-			fp = fvscanstart;
-			dp = dvscanstart;
-			k = vscanlen;
-
-			/* Process first sample in vertical scan. */
-			jpc_refpass_step(fp, dp, poshalf, neghalf, mqdec,
-			  vcausalflag);
-			if (--k <= 0) {
-				continue;
-			}
-			fp += frowstep;
-			dp += drowstep;
-
-			/* Process second sample in vertical scan. */
-			jpc_refpass_step(fp, dp, poshalf, neghalf, mqdec, 0);
-			if (--k <= 0) {
-				continue;
-			}
-			fp += frowstep;
-			dp += drowstep;
-
-			/* Process third sample in vertical scan. */
-			jpc_refpass_step(fp, dp, poshalf, neghalf, mqdec, 0);
-			if (--k <= 0) {
-				continue;
-			}
-			fp += frowstep;
-			dp += drowstep;
-
-			/* Process fourth sample in vertical scan. */
-			jpc_refpass_step(fp, dp, poshalf, neghalf, mqdec, 0);
-		}
-	}
-
-	return 0;
+    int i;
+    int j;
+    int vscanlen;
+    int width;
+    int height;
+    int one;
+    int poshalf;
+    int neghalf;
+    jpc_fix_t *fp;
+    int frowstep;
+    int fstripestep;
+    jpc_fix_t *fstripestart;
+    jpc_fix_t *fvscanstart;
+    jpc_fix_t *dp;
+    int drowstep;
+    int dstripestep;
+    jpc_fix_t *dstripestart;
+    jpc_fix_t *dvscanstart;
+    int k;
+
+    width = jas_matrix_numcols(data);
+    height = jas_matrix_numrows(data);
+    frowstep = jas_matrix_rowstep(flags);
+    drowstep = jas_matrix_rowstep(data);
+    fstripestep = frowstep << 2;
+    dstripestep = drowstep << 2;
+
+    one = 1 << bitpos;
+    poshalf = one >> 1;
+    neghalf = (bitpos > 0) ? (-poshalf) : (-1);
+
+    fstripestart = jas_matrix_getref(flags, 1, 1);
+    dstripestart = jas_matrix_getref(data, 0, 0);
+    for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
+      dstripestart += dstripestep) {
+        fvscanstart = fstripestart;
+        dvscanstart = dstripestart;
+        vscanlen = JAS_MIN(i, 4);
+        for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+            fp = fvscanstart;
+            dp = dvscanstart;
+            k = vscanlen;
+
+            /* Process first sample in vertical scan. */
+            jpc_refpass_step(fp, dp, poshalf, neghalf, mqdec,
+              vcausalflag);
+            if (--k <= 0) {
+                continue;
+            }
+            fp += frowstep;
+            dp += drowstep;
+
+            /* Process second sample in vertical scan. */
+            jpc_refpass_step(fp, dp, poshalf, neghalf, mqdec, 0);
+            if (--k <= 0) {
+                continue;
+            }
+            fp += frowstep;
+            dp += drowstep;
+
+            /* Process third sample in vertical scan. */
+            jpc_refpass_step(fp, dp, poshalf, neghalf, mqdec, 0);
+            if (--k <= 0) {
+                continue;
+            }
+            fp += frowstep;
+            dp += drowstep;
+
+            /* Process fourth sample in vertical scan. */
+            jpc_refpass_step(fp, dp, poshalf, neghalf, mqdec, 0);
+        }
+    }
+
+    return 0;
 }
 
-#define	jpc_rawrefpass_step(fp, dp, poshalf, neghalf, in, vcausalflag) \
+#define jpc_rawrefpass_step(fp, dp, poshalf, neghalf, in, vcausalflag) \
 { \
-	jpc_fix_t v; \
-	jpc_fix_t t; \
-	if (((*(fp)) & (JPC_SIG | JPC_VISIT)) == JPC_SIG) { \
-		JPC_T1D_RAWGETBIT(in, v, "REF", "MAGREF"); \
-		if (v < 0) { \
-			return -1; \
-		} \
-		t = (v ? poshalf : neghalf); \
-		*(dp) += (*(dp) < 0) ? (-t) : t; \
-		*(fp) |= JPC_REFINE; \
-	} \
+    jpc_fix_t v; \
+    jpc_fix_t t; \
+    if (((*(fp)) & (JPC_SIG | JPC_VISIT)) == JPC_SIG) { \
+        JPC_T1D_RAWGETBIT(in, v, "REF", "MAGREF"); \
+        if (v < 0) { \
+            return -1; \
+        } \
+        t = (v ? poshalf : neghalf); \
+        *(dp) += (*(dp) < 0) ? (-t) : t; \
+        *(fp) |= JPC_REFINE; \
+    } \
 }
 
-static int dec_rawrefpass(jpc_dec_t *dec, jpc_bitstream_t *in, int bitpos, int vcausalflag,
-  jas_matrix_t *flags, jas_matrix_t *data)
+
+
+static int
+dec_rawrefpass(jpc_dec_t *dec, jpc_bitstream_t *in, int bitpos,
+               int vcausalflag,
+               jas_matrix_t *flags, jas_matrix_t *data)
 {
-	int i;
-	int j;
-	int k;
-	int vscanlen;
-	int width;
-	int height;
-	int one;
-	int poshalf;
-	int neghalf;
-	jpc_fix_t *fp;
-	int frowstep;
-	int fstripestep;
-	jpc_fix_t *fstripestart;
-	jpc_fix_t *fvscanstart;
-	jpc_fix_t *dp;
-	int drowstep;
-	int dstripestep;
-	jpc_fix_t *dstripestart;
-	jpc_fix_t *dvscanstart;
-
-	width = jas_matrix_numcols(data);
-	height = jas_matrix_numrows(data);
-	frowstep = jas_matrix_rowstep(flags);
-	drowstep = jas_matrix_rowstep(data);
-	fstripestep = frowstep << 2;
-	dstripestep = drowstep << 2;
-
-	one = 1 << bitpos;
-	poshalf = one >> 1;
-	neghalf = (bitpos > 0) ? (-poshalf) : (-1);
-
-	fstripestart = jas_matrix_getref(flags, 1, 1);
-	dstripestart = jas_matrix_getref(data, 0, 0);
-	for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
-	  dstripestart += dstripestep) {
-		fvscanstart = fstripestart;
-		dvscanstart = dstripestart;
-		vscanlen = JAS_MIN(i, 4);
-		for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
-			fp = fvscanstart;
-			dp = dvscanstart;
-			k = vscanlen;
-
-			/* Process first sample in vertical scan. */
-			jpc_rawrefpass_step(fp, dp, poshalf, neghalf, in,
-			  vcausalflag);
-			if (--k <= 0) {
-				continue;
-			}
-			fp += frowstep;
-			dp += drowstep;
-
-			/* Process second sample in vertical scan. */
-			jpc_rawrefpass_step(fp, dp, poshalf, neghalf, in, 0);
-			if (--k <= 0) {
-				continue;
-			}
-			fp += frowstep;
-			dp += drowstep;
-
-			/* Process third sample in vertical scan. */
-			jpc_rawrefpass_step(fp, dp, poshalf, neghalf, in, 0);
-			if (--k <= 0) {
-				continue;
-			}
-			fp += frowstep;
-			dp += drowstep;
-
-			/* Process fourth sample in vertical scan. */
-			jpc_rawrefpass_step(fp, dp, poshalf, neghalf, in, 0);
-		}
-	}
-	return 0;
+    int i;
+    int j;
+    int k;
+    int vscanlen;
+    int width;
+    int height;
+    int one;
+    int poshalf;
+    int neghalf;
+    jpc_fix_t *fp;
+    int frowstep;
+    int fstripestep;
+    jpc_fix_t *fstripestart;
+    jpc_fix_t *fvscanstart;
+    jpc_fix_t *dp;
+    int drowstep;
+    int dstripestep;
+    jpc_fix_t *dstripestart;
+    jpc_fix_t *dvscanstart;
+
+    width = jas_matrix_numcols(data);
+    height = jas_matrix_numrows(data);
+    frowstep = jas_matrix_rowstep(flags);
+    drowstep = jas_matrix_rowstep(data);
+    fstripestep = frowstep << 2;
+    dstripestep = drowstep << 2;
+
+    one = 1 << bitpos;
+    poshalf = one >> 1;
+    neghalf = (bitpos > 0) ? (-poshalf) : (-1);
+
+    fstripestart = jas_matrix_getref(flags, 1, 1);
+    dstripestart = jas_matrix_getref(data, 0, 0);
+    for (i = height; i > 0; i -= 4, fstripestart += fstripestep,
+      dstripestart += dstripestep) {
+        fvscanstart = fstripestart;
+        dvscanstart = dstripestart;
+        vscanlen = JAS_MIN(i, 4);
+        for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+            fp = fvscanstart;
+            dp = dvscanstart;
+            k = vscanlen;
+
+            /* Process first sample in vertical scan. */
+            jpc_rawrefpass_step(fp, dp, poshalf, neghalf, in,
+              vcausalflag);
+            if (--k <= 0) {
+                continue;
+            }
+            fp += frowstep;
+            dp += drowstep;
+
+            /* Process second sample in vertical scan. */
+            jpc_rawrefpass_step(fp, dp, poshalf, neghalf, in, 0);
+            if (--k <= 0) {
+                continue;
+            }
+            fp += frowstep;
+            dp += drowstep;
+
+            /* Process third sample in vertical scan. */
+            jpc_rawrefpass_step(fp, dp, poshalf, neghalf, in, 0);
+            if (--k <= 0) {
+                continue;
+            }
+            fp += frowstep;
+            dp += drowstep;
+
+            /* Process fourth sample in vertical scan. */
+            jpc_rawrefpass_step(fp, dp, poshalf, neghalf, in, 0);
+        }
+    }
+    return 0;
 }
 
+
+
 /******************************************************************************\
 * Code for cleanup pass.
 \******************************************************************************/
 
-#define	jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient, mqdec, flabel, plabel, vcausalflag) \
+#define jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient, mqdec, flabel, plabel, vcausalflag) \
 { \
-	int v; \
+    int v; \
 flabel \
-	if (!((f) & (JPC_SIG | JPC_VISIT))) { \
-		jpc_mqdec_setcurctx((mqdec), JPC_GETZCCTXNO((f), (orient))); \
-		JPC_T1D_GETBIT((mqdec), v, "CLN", "ZC"); \
-		if (v) { \
+    if (!((f) & (JPC_SIG | JPC_VISIT))) { \
+        jpc_mqdec_setcurctx((mqdec), JPC_GETZCCTXNO((f), (orient))); \
+        JPC_T1D_GETBIT((mqdec), v, "CLN", "ZC"); \
+        if (v) { \
 plabel \
-			/* Coefficient is significant. */ \
-			jpc_mqdec_setcurctx((mqdec), JPC_GETSCCTXNO(f)); \
-			JPC_T1D_GETBIT((mqdec), v, "CLN", "SC"); \
-			v ^= JPC_GETSPB(f); \
-			*(dp) = (v) ? (-(oneplushalf)) : (oneplushalf); \
-			JPC_UPDATEFLAGS4((fp), (frowstep), v, (vcausalflag)); \
-			*(fp) |= JPC_SIG; \
-		} \
-	} \
-	/* XXX - Is this correct?  Can aggregation cause some VISIT bits not to be reset?  Check. */ \
-	*(fp) &= ~JPC_VISIT; \
+            /* Coefficient is significant. */ \
+            jpc_mqdec_setcurctx((mqdec), JPC_GETSCCTXNO(f)); \
+            JPC_T1D_GETBIT((mqdec), v, "CLN", "SC"); \
+            v ^= JPC_GETSPB(f); \
+            *(dp) = (v) ? (-(oneplushalf)) : (oneplushalf); \
+            JPC_UPDATEFLAGS4((fp), (frowstep), v, (vcausalflag)); \
+            *(fp) |= JPC_SIG; \
+        } \
+    } \
+    /* XXX - Is this correct?  Can aggregation cause some VISIT bits not to be reset?  Check. */ \
+    *(fp) &= ~JPC_VISIT; \
 }
 
-static int dec_clnpass(jpc_dec_t *dec, register jpc_mqdec_t *mqdec, int bitpos, int orient,
-  int vcausalflag, int segsymflag, jas_matrix_t *flags, jas_matrix_t *data)
+static int
+dec_clnpass(jpc_dec_t *dec, register jpc_mqdec_t *mqdec, int bitpos,
+            int orient, int vcausalflag, int segsymflag, jas_matrix_t *flags,
+            jas_matrix_t *data)
 {
-	int i;
-	int j;
-	int k;
-	int vscanlen;
-	int v;
-	int half;
-	int runlen;
-	int f;
-	int width;
-	int height;
-	int one;
-	int oneplushalf;
-
-	jpc_fix_t *fp;
-	int frowstep;
-	int fstripestep;
-	jpc_fix_t *fstripestart;
-	jpc_fix_t *fvscanstart;
-
-	jpc_fix_t *dp;
-	int drowstep;
-	int dstripestep;
-	jpc_fix_t *dstripestart;
-	jpc_fix_t *dvscanstart;
-
-	one = 1 << bitpos;
-	half = one >> 1;
-	oneplushalf = one | half;
-
-	width = jas_matrix_numcols(data);
-	height = jas_matrix_numrows(data);
-
-	frowstep = jas_matrix_rowstep(flags);
-	drowstep = jas_matrix_rowstep(data);
-	fstripestep = frowstep << 2;
-	dstripestep = drowstep << 2;
-
-	fstripestart = jas_matrix_getref(flags, 1, 1);
-	dstripestart = jas_matrix_getref(data, 0, 0);
-	for (i = 0; i < height; i += 4, fstripestart += fstripestep,
-	  dstripestart += dstripestep) {
-		fvscanstart = fstripestart;
-		dvscanstart = dstripestart;
-		vscanlen = JAS_MIN(4, height - i);
-		for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
-			fp = fvscanstart;
-			if (vscanlen >= 4 && (!((*fp) & (JPC_SIG | JPC_VISIT |
-			  JPC_OTHSIGMSK))) && (fp += frowstep, !((*fp) & (JPC_SIG |
-			  JPC_VISIT | JPC_OTHSIGMSK))) && (fp += frowstep, !((*fp) &
-			  (JPC_SIG | JPC_VISIT | JPC_OTHSIGMSK))) && (fp += frowstep,
-			  !((*fp) & (JPC_SIG | JPC_VISIT | JPC_OTHSIGMSK)))) {
-
-				jpc_mqdec_setcurctx(mqdec, JPC_AGGCTXNO);
-				JPC_T1D_GETBIT(mqdec, v, "CLN", "AGG");
-				if (!v) {
-					continue;
-				}
-				jpc_mqdec_setcurctx(mqdec, JPC_UCTXNO);
-				JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "RL");
-				runlen = v;
-				JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "RL");
-				runlen = (runlen << 1) | v;
-				f = *(fp = fvscanstart + frowstep * runlen);
-				dp = dvscanstart + drowstep * runlen;
-				k = vscanlen - runlen;
-				switch (runlen) {
-				case 0:
-					goto clnpass_partial0;
-					break;
-				case 1:
-					goto clnpass_partial1;
-					break;
-				case 2:
-					goto clnpass_partial2;
-					break;
-				case 3:
-					goto clnpass_partial3;
-					break;
-				}
-			} else {
-				f = *(fp = fvscanstart);
-				dp = dvscanstart;
-				k = vscanlen;
-				goto clnpass_full0;
-			}
-
-			/* Process first sample in vertical scan. */
-			jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient,
-			  mqdec, clnpass_full0:, clnpass_partial0:,
-			  vcausalflag);
-			if (--k <= 0) {
-				continue;
-			}
-			fp += frowstep;
-			dp += drowstep;
-
-			/* Process second sample in vertical scan. */
-			f = *fp;
-			jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient,
-				mqdec, ;, clnpass_partial1:, 0);
-			if (--k <= 0) {
-				continue;
-			}
-			fp += frowstep;
-			dp += drowstep;
-
-			/* Process third sample in vertical scan. */
-			f = *fp;
-			jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient,
-				mqdec, ;, clnpass_partial2:, 0);
-			if (--k <= 0) {
-				continue;
-			}
-			fp += frowstep;
-			dp += drowstep;
-
-			/* Process fourth sample in vertical scan. */
-			f = *fp;
-			jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient,
-				mqdec, ;, clnpass_partial3:, 0);
-		}
-	}
-
-	if (segsymflag) {
-		int segsymval;
-		segsymval = 0;
-		jpc_mqdec_setcurctx(mqdec, JPC_UCTXNO);
-		JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "SEGSYM");
-		segsymval = (segsymval << 1) | (v & 1);
-		JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "SEGSYM");
-		segsymval = (segsymval << 1) | (v & 1);
-		JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "SEGSYM");
-		segsymval = (segsymval << 1) | (v & 1);
-		JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "SEGSYM");
-		segsymval = (segsymval << 1) | (v & 1);
-		if (segsymval != 0xa) {
-			fprintf(stderr, "warning: bad segmentation symbol\n");
-		}
-	}
-
-	return 0;
+    int i;
+    int j;
+    int k;
+    int vscanlen;
+    int v;
+    int half;
+    int runlen;
+    int f;
+    int width;
+    int height;
+    int one;
+    int oneplushalf;
+
+    jpc_fix_t *fp;
+    int frowstep;
+    int fstripestep;
+    jpc_fix_t *fstripestart;
+    jpc_fix_t *fvscanstart;
+
+    jpc_fix_t *dp;
+    int drowstep;
+    int dstripestep;
+    jpc_fix_t *dstripestart;
+    jpc_fix_t *dvscanstart;
+
+    one = 1 << bitpos;
+    half = one >> 1;
+    oneplushalf = one | half;
+
+    width = jas_matrix_numcols(data);
+    height = jas_matrix_numrows(data);
+
+    frowstep = jas_matrix_rowstep(flags);
+    drowstep = jas_matrix_rowstep(data);
+    fstripestep = frowstep << 2;
+    dstripestep = drowstep << 2;
+
+    fstripestart = jas_matrix_getref(flags, 1, 1);
+    dstripestart = jas_matrix_getref(data, 0, 0);
+    for (i = 0; i < height; i += 4, fstripestart += fstripestep,
+      dstripestart += dstripestep) {
+        fvscanstart = fstripestart;
+        dvscanstart = dstripestart;
+        vscanlen = JAS_MIN(4, height - i);
+        for (j = width; j > 0; --j, ++fvscanstart, ++dvscanstart) {
+            fp = fvscanstart;
+            if (vscanlen >= 4 && (!((*fp) & (JPC_SIG | JPC_VISIT |
+              JPC_OTHSIGMSK))) && (fp += frowstep, !((*fp) & (JPC_SIG |
+              JPC_VISIT | JPC_OTHSIGMSK))) && (fp += frowstep, !((*fp) &
+              (JPC_SIG | JPC_VISIT | JPC_OTHSIGMSK))) && (fp += frowstep,
+              !((*fp) & (JPC_SIG | JPC_VISIT | JPC_OTHSIGMSK)))) {
+
+                jpc_mqdec_setcurctx(mqdec, JPC_AGGCTXNO);
+                JPC_T1D_GETBIT(mqdec, v, "CLN", "AGG");
+                if (!v) {
+                    continue;
+                }
+                jpc_mqdec_setcurctx(mqdec, JPC_UCTXNO);
+                JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "RL");
+                runlen = v;
+                JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "RL");
+                runlen = (runlen << 1) | v;
+                f = *(fp = fvscanstart + frowstep * runlen);
+                dp = dvscanstart + drowstep * runlen;
+                k = vscanlen - runlen;
+                switch (runlen) {
+                case 0:
+                    goto clnpass_partial0;
+                    break;
+                case 1:
+                    goto clnpass_partial1;
+                    break;
+                case 2:
+                    goto clnpass_partial2;
+                    break;
+                case 3:
+                    goto clnpass_partial3;
+                    break;
+                }
+            } else {
+                f = *(fp = fvscanstart);
+                dp = dvscanstart;
+                k = vscanlen;
+                goto clnpass_full0;
+            }
+
+            /* Process first sample in vertical scan. */
+            jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient,
+              mqdec, clnpass_full0:, clnpass_partial0:,
+              vcausalflag);
+            if (--k <= 0) {
+                continue;
+            }
+            fp += frowstep;
+            dp += drowstep;
+
+            /* Process second sample in vertical scan. */
+            f = *fp;
+            jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient,
+                mqdec, ;, clnpass_partial1:, 0);
+            if (--k <= 0) {
+                continue;
+            }
+            fp += frowstep;
+            dp += drowstep;
+
+            /* Process third sample in vertical scan. */
+            f = *fp;
+            jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient,
+                mqdec, ;, clnpass_partial2:, 0);
+            if (--k <= 0) {
+                continue;
+            }
+            fp += frowstep;
+            dp += drowstep;
+
+            /* Process fourth sample in vertical scan. */
+            f = *fp;
+            jpc_clnpass_step(f, fp, frowstep, dp, oneplushalf, orient,
+                mqdec, ;, clnpass_partial3:, 0);
+        }
+    }
+
+    if (segsymflag) {
+        int segsymval;
+        segsymval = 0;
+        jpc_mqdec_setcurctx(mqdec, JPC_UCTXNO);
+        JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "SEGSYM");
+        segsymval = (segsymval << 1) | (v & 1);
+        JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "SEGSYM");
+        segsymval = (segsymval << 1) | (v & 1);
+        JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "SEGSYM");
+        segsymval = (segsymval << 1) | (v & 1);
+        JPC_T1D_GETBITNOSKEW(mqdec, v, "CLN", "SEGSYM");
+        segsymval = (segsymval << 1) | (v & 1);
+        if (segsymval != 0xa) {
+            fprintf(stderr, "warning: bad segmentation symbol\n");
+        }
+    }
+
+    return 0;
+}
+
+
+
+static void
+jpc_dec_decodecblk(jpc_dec_t *       const dec,
+                   jpc_dec_tile_t *  const tile,
+                   jpc_dec_tcomp_t * const tcomp,
+                   jpc_dec_band_t *  const band,
+                   jpc_dec_cblk_t *  const cblk,
+                   int               const dopartial,
+                   int               const maxlyrs,
+                   const char **     const errorP) {
+
+    jpc_dec_seg_t *seg;
+    int i;
+    int bpno;
+    int passtype;
+    int ret;
+    int compno;
+    int filldata;
+    int fillmask;
+    jpc_dec_ccp_t *ccp;
+
+    compno = tcomp - tile->tcomps;
+
+    if (!cblk->flags) {
+        /* Note: matrix is assumed to be zeroed */
+        unsigned int const nrow = jas_matrix_numrows(cblk->data) + 2;
+        unsigned int const ncol = jas_matrix_numcols(cblk->data) + 2;
+        cblk->flags = jas_matrix_create(nrow, ncol);
+        if (!cblk->flags) {
+            pm_asprintf(errorP, "Out of memory allocating a flags matrix of "
+                        "%u rows by %u columns", nrow, ncol);
+            return;
+        }
+    }
+
+    seg = cblk->segs.head;
+    while (seg && (seg != cblk->curseg || dopartial) && (maxlyrs < 0 ||
+      seg->lyrno < maxlyrs)) {
+        assert(seg->numpasses >= seg->maxpasses || dopartial);
+        assert(seg->stream);
+        jas_stream_rewind(seg->stream);
+        jas_stream_setrwcount(seg->stream, 0);
+        if (seg->type == JPC_SEG_MQ) {
+            if (!cblk->mqdec) {
+                if (!(cblk->mqdec = jpc_mqdec_create(JPC_NUMCTXS, 0))) {
+                    pm_asprintf(errorP, "jpc_mqdec_create failed");
+                    return;
+                }
+                jpc_mqdec_setctxs(cblk->mqdec, JPC_NUMCTXS, jpc_mqctxs);
+            }
+            jpc_mqdec_setinput(cblk->mqdec, seg->stream);
+            jpc_mqdec_init(cblk->mqdec);
+        } else {
+            assert(seg->type == JPC_SEG_RAW);
+            if (!cblk->nulldec) {
+                if (!(cblk->nulldec = jpc_bitstream_sopen(seg->stream, "r"))) {
+                    assert(0);
+                }
+            }
+        }
+
+
+        for (i = 0; i < seg->numpasses; ++i) {
+            if (cblk->numimsbs > band->numbps) {
+                ccp = &tile->cp->ccps[compno];
+                if (ccp->roishift <= 0) {
+                    fprintf(stderr, "warning: corrupt code stream\n");
+                } else {
+                    if (cblk->numimsbs < ccp->roishift - band->numbps) {
+                        fprintf(stderr, "warning: corrupt code stream\n");
+                    }
+                }
+            }
+            bpno = band->roishift + band->numbps - 1 - (cblk->numimsbs +
+              (seg->passno + i - cblk->firstpassno + 2) / 3);
+            if (bpno < 0) {
+                goto exit;
+            }
+#if 1
+            passtype = (seg->passno + i + 2) % 3;
+#else
+            passtype = JPC_PASSTYPE(seg->passno + i + 2);
+#endif
+            assert(bpno >= 0 && bpno < 31);
+            switch (passtype) {
+            case JPC_SIGPASS:
+                ret = (seg->type == JPC_SEG_MQ) ? dec_sigpass(dec,
+                  cblk->mqdec, bpno, band->orient,
+                  (tile->cp->ccps[compno].cblkctx & JPC_COX_VSC) != 0,
+                  cblk->flags, cblk->data) :
+                  dec_rawsigpass(dec, cblk->nulldec, bpno,
+                  (tile->cp->ccps[compno].cblkctx & JPC_COX_VSC) != 0,
+                  cblk->flags, cblk->data);
+                break;
+            case JPC_REFPASS:
+                ret = (seg->type == JPC_SEG_MQ) ?
+                  dec_refpass(dec, cblk->mqdec, bpno,
+                  (tile->cp->ccps[compno].cblkctx & JPC_COX_VSC) != 0,
+                  cblk->flags, cblk->data) :
+                  dec_rawrefpass(dec, cblk->nulldec, bpno,
+                  (tile->cp->ccps[compno].cblkctx & JPC_COX_VSC) != 0,
+                  cblk->flags, cblk->data);
+                break;
+            case JPC_CLNPASS:
+                assert(seg->type == JPC_SEG_MQ);
+                ret = dec_clnpass(dec, cblk->mqdec, bpno,
+                  band->orient, (tile->cp->ccps[compno].cblkctx &
+                  JPC_COX_VSC) != 0, (tile->cp->ccps[compno].cblkctx &
+                  JPC_COX_SEGSYM) != 0, cblk->flags,
+                  cblk->data);
+                break;
+            default:
+                ret = -1;
+                break;
+            }
+            /* Do we need to reset after each coding pass? */
+            if (tile->cp->ccps[compno].cblkctx & JPC_COX_RESET) {
+                jpc_mqdec_setctxs(cblk->mqdec, JPC_NUMCTXS, jpc_mqctxs);
+            }
+
+            if (ret) {
+                pm_asprintf(errorP,
+                            "coding pass failed passtype=%d segtype=%d",
+                            passtype, seg->type);
+                return;
+            }
+
+        }
+
+        if (seg->type == JPC_SEG_MQ) {
+            /* Note: dont destroy mq decoder because context info will be
+               lost
+            */
+        } else {
+            assert(seg->type == JPC_SEG_RAW);
+            if (tile->cp->ccps[compno].cblkctx & JPC_COX_PTERM) {
+                fillmask = 0x7f;
+                filldata = 0x2a;
+            } else {
+                fillmask = 0;
+                filldata = 0;
+            }
+            if ((ret = jpc_bitstream_inalign(cblk->nulldec, fillmask,
+              filldata)) < 0) {
+                pm_asprintf(errorP, "jpc_bitstream_inalign failed");
+                return;
+            } else if (ret > 0) {
+                pm_message("warning: bad termination pattern detected");
+            }
+            jpc_bitstream_close(cblk->nulldec);
+            cblk->nulldec = 0;
+        }
+
+        cblk->curseg = seg->next;
+        jpc_seglist_remove(&cblk->segs, seg);
+        jpc_seg_destroy(seg);
+        seg = cblk->curseg;
+    }
+
+    assert(dopartial ? (!cblk->curseg) : 1);
+
+exit:
+    *errorP = NULL;
 }
+
+
+
+void
+jpc_dec_decodecblks(jpc_dec_t *      const decP,
+                    jpc_dec_tile_t * const tileP,
+                    const char **    const errorP) {
+/*----------------------------------------------------------------------------
+  Decode all of the code blocks for a particular tile
+-----------------------------------------------------------------------------*/
+    unsigned int compcnt;
+    jpc_dec_tcomp_t * tcompP;
+
+    for (compcnt = 0, tcompP = tileP->tcomps;
+         compcnt < decP->numcomps;
+         ++compcnt, ++tcompP) {
+
+        unsigned int rlvlcnt;
+        jpc_dec_rlvl_t * rlvlP;
+
+        for (rlvlcnt = 0, rlvlP = tcompP->rlvls;
+             rlvlcnt < tcompP->numrlvls;
+             ++rlvlcnt, ++rlvlP) {
+
+            if (rlvlP->bands) {
+                unsigned int bandcnt;
+                jpc_dec_band_t * bandP;
+
+                for (bandcnt = 0, bandP = rlvlP->bands;
+                     bandcnt < rlvlP->numbands;
+                     ++bandcnt, ++bandP) {
+
+                    if (bandP->data) {
+                        unsigned int prccnt;
+                        jpc_dec_prc_t * prcP;
+
+                        for (prccnt = 0, prcP = bandP->prcs;
+                             prccnt < rlvlP->numprcs;
+                             ++prccnt, ++prcP) {
+
+                            if (prcP->cblks) {
+                                unsigned int cblkcnt;
+                                jpc_dec_cblk_t * cblkP;
+
+                                for (cblkcnt = 0, cblkP = prcP->cblks;
+                                     cblkcnt < prcP->numcblks;
+                                     ++cblkcnt, ++cblkP) {
+
+                                    const char * error;
+
+                                    jpc_dec_decodecblk(decP, tileP, tcompP,
+                                                       bandP, cblkP, 1,
+                                                       JPC_MAXLYRS, &error);
+                                    if (error) {
+                                        pm_asprintf(errorP,
+                                                    "jpc_dec_decodecblk "
+                                                    "failed on component %u, "
+                                                    "resolution level %u, "
+                                                    "band %u, prc %u, "
+                                                    "code block %u.  %s",
+                                                    compcnt, rlvlcnt, bandcnt,
+                                                    prccnt, cblkcnt, error);
+                                        pm_strfree(error);
+                                        return;
+                                    }
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+        }
+    }
+    *errorP = NULL;
+}
+
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_t1dec.h b/converter/other/jpeg2000/libjasper/jpc/jpc_t1dec.h
index e28a1f57..f8b3b342 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_t1dec.h
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_t1dec.h
@@ -119,19 +119,13 @@
 #ifndef JPC_T1DEC_H
 #define JPC_T1DEC_H
 
-/******************************************************************************\
-* Includes.
-\******************************************************************************/
-
 #include "jpc_dec.h"
 #include "jpc_mqdec.h"
 #include "jpc_t1cod.h"
 
-/******************************************************************************\
-* Functions.
-\******************************************************************************/
-
-/* Decode all of the code blocks for a particular tile. */
-int jpc_dec_decodecblks(jpc_dec_t *dec, jpc_dec_tile_t *tile);
+void
+jpc_dec_decodecblks(jpc_dec_t *      const decP,
+                    jpc_dec_tile_t * const tileP,
+                    const char **    const errorP);
 
 #endif
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_t1enc.c b/converter/other/jpeg2000/libjasper/jpc/jpc_t1enc.c
index e1af0f61..34b9738c 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_t1enc.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_t1enc.c
@@ -124,6 +124,8 @@
 #include <stdlib.h>
 #include <assert.h>
 
+#include "netpbm/nstring.h"
+
 #include "jasper/jas_fix.h"
 #include "jasper/jas_malloc.h"
 #include "jasper/jas_math.h"
@@ -149,74 +151,111 @@ static int jpc_encrawsigpass(jpc_bitstream_t *out, int bitpos, int,
 static int jpc_encrawrefpass(jpc_bitstream_t *out, int bitpos, int,
   jas_matrix_t *flags, jas_matrix_t *data, int term, long *nmsedec);
 
-/******************************************************************************\
+/*****************************************************************************\
 * Code for encoding code blocks.
-\******************************************************************************/
+\*****************************************************************************/
 
-/* Encode all of the code blocks associated with the current tile. */
-int jpc_enc_enccblks(jpc_enc_t *enc)
-{
-    jpc_enc_tcmpt_t *tcmpt;
-    jpc_enc_tcmpt_t *endcomps;
-    jpc_enc_rlvl_t *lvl;
-    jpc_enc_rlvl_t *endlvls;
-    jpc_enc_band_t *band;
-    jpc_enc_band_t *endbands;
-    jpc_enc_cblk_t *cblk;
-    jpc_enc_cblk_t *endcblks;
-    int i;
-    int j;
-    int mx;
-    int bmx;
-    int v;
-    jpc_enc_tile_t *tile;
-    uint_fast32_t prcno;
-    jpc_enc_prc_t *prc;
+static void
+encodeBlocksOfPrecinct(jpc_enc_prc_t *   const prcP,
+                       jpc_enc_band_t *  const bandP,
+                       jpc_enc_tcmpt_t * const tcmptP,
+                       jpc_enc_t *       const encoderP,
+                       const char **     const errorP) {
 
-    tile = enc->curtile;
+    if (prcP->cblks) {
+        int bmx;
+        uint_fast32_t cblkno;
 
-    endcomps = &tile->tcmpts[tile->numtcmpts];
-    for (tcmpt = tile->tcmpts; tcmpt != endcomps; ++tcmpt) {
-        endlvls = &tcmpt->rlvls[tcmpt->numrlvls];
-        for (lvl = tcmpt->rlvls; lvl != endlvls; ++lvl) {
-            if (!lvl->bands) {
-                continue;
-            }
-            endbands = &lvl->bands[lvl->numbands];
-            for (band = lvl->bands; band != endbands; ++band) {
-                if (!band->data) {
-                    continue;
+        for (cblkno = 0, bmx = 0; cblkno < prcP->numcblks; ++ cblkno) {
+            jpc_enc_cblk_t * const cblkP = &prcP->cblks[cblkno];
+
+            int mx;
+            uint_fast32_t row;
+
+            for (row = 0, mx = 0;
+                 row < jas_matrix_numrows(cblkP->data);
+                 ++row) {
+
+                uint_fast32_t col;
+
+                for (col = 0; col < jas_matrix_numcols(cblkP->data); ++col) {
+                    int const v = abs(jas_matrix_get(cblkP->data, row, col));
+                    if (v > mx)
+                        mx = v;
                 }
-                for (prcno = 0, prc = band->prcs; prcno < lvl->numprcs; ++prcno, ++prc) {
-                    if (!prc->cblks) {
-                        continue;
-                    }
-                    bmx = 0;
-                    endcblks = &prc->cblks[prc->numcblks];
-                    for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
-                        mx = 0;
-                        for (i = 0; i < jas_matrix_numrows(cblk->data); ++i) {
-                            for (j = 0; j < jas_matrix_numcols(cblk->data); ++j) {
-                                v = abs(jas_matrix_get(cblk->data, i, j));
-                                if (v > mx) {
-                                    mx = v;
-                                }
-                            }
-                        }
-                        if (mx > bmx) {
-                            bmx = mx;
-                        }
-                        cblk->numbps = JAS_MAX(jpc_firstone(mx) + 1 - JPC_NUMEXTRABITS, 0);
-                    }
+            }
+            if (mx > bmx)
+                bmx = mx;
 
-                    for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
-                        cblk->numimsbs = band->numbps - cblk->numbps;
-                        assert(cblk->numimsbs >= 0);
-                    }
+            cblkP->numbps = MAX(jpc_firstone(mx) + 1 - JPC_NUMEXTRABITS, 0);
+        }
+
+        for (cblkno = 0; cblkno < prcP->numcblks; ++ cblkno) {
+            jpc_enc_cblk_t * const cblkP = &prcP->cblks[cblkno];
 
-                    for (cblk = prc->cblks; cblk != endcblks; ++cblk) {
-                        if (jpc_enc_enccblk(enc, cblk->stream, tcmpt, band, cblk)) {
-                            return -1;
+            assert(cblkP->numbps <= bandP->numbps);
+        }
+
+        for (cblkno = 0, *errorP = NULL;
+             cblkno < prcP->numcblks && !*errorP;
+             ++ cblkno) {
+
+            jpc_enc_cblk_t * const cblkP = &prcP->cblks[cblkno];
+
+            int rc;
+
+            rc = jpc_enc_enccblk(encoderP,
+                                 cblkP->stream, tcmptP, bandP, cblkP);
+            if (rc != 0)
+                pm_asprintf(errorP, "Encoding failed on code block %u "
+                            "of %u", (unsigned)cblkno,
+                            (unsigned)prcP->numcblks);
+        }
+    } else
+        *errorP = NULL;
+}
+
+
+
+int
+jpc_enc_enccblks(jpc_enc_t * const encoderP) {
+/*----------------------------------------------------------------------------
+  Encode all of the code blocks associated with the current tile.
+-----------------------------------------------------------------------------*/
+    jpc_enc_tile_t * const tileP = encoderP->curtile;
+
+    uint_fast32_t cmptno;
+
+    for (cmptno = 0; cmptno < tileP->numtcmpts; ++cmptno) {
+        jpc_enc_tcmpt_t * const tcmptP = &tileP->tcmpts[cmptno];
+
+        unsigned int lvlno;
+        for (lvlno = 0; lvlno < tcmptP->numrlvls; ++ lvlno) {
+            jpc_enc_rlvl_t * const lvlP = &tcmptP->rlvls[lvlno];
+
+            if (lvlP->bands) {
+                uint_fast32_t bandno;
+
+                for (bandno = 0; bandno < lvlP->numbands; ++bandno) {
+                    jpc_enc_band_t * const bandP = &lvlP->bands[bandno];
+
+                    if (bandP->data) {
+                        uint_fast32_t prcno;
+
+                        for (prcno = 0; prcno < lvlP->numprcs; ++prcno) {
+
+                            const char * error;
+
+                            encodeBlocksOfPrecinct(&bandP->prcs[prcno],
+                                                   bandP,
+                                                   tcmptP,
+                                                   encoderP,
+                                                   &error);
+
+                            if (error) {
+                                pm_strfree(error);
+                                return -1;
+                            }
                         }
                     }
                 }
@@ -226,6 +265,8 @@ int jpc_enc_enccblks(jpc_enc_t *enc)
     return 0;
 }
 
+
+
 static int getthebyte(jas_stream_t *in, long off)
 {
     int c;
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_util.c b/converter/other/jpeg2000/libjasper/jpc/jpc_util.c
index fede2bef..e6e3942a 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_util.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_util.c
@@ -114,9 +114,9 @@
  * $Id$
  */
 
-/******************************************************************************\
+/*****************************************************************************\
 * Includes
-\******************************************************************************/
+\*****************************************************************************/
 
 #include <assert.h>
 #include <stdio.h>
@@ -133,21 +133,21 @@
 #include "jpc_flt.h"
 #include "jpc_util.h"
 
-/******************************************************************************\
+/*****************************************************************************\
 * Miscellaneous Functions
-\******************************************************************************/
+\*****************************************************************************/
 
-int jpc_atoaf(const char *s, int *numvalues, double **values)
-{
-	static char delim[] = ", \t\n";
+static unsigned int
+countOfTokens(const char * const s,
+			  const char * const delim) {
+
+	unsigned int n;
 	char buf[4096];
-	int n;
-	double *vs;
-	char *cp;
+	const char * cp;
 
 	strncpy(buf, s, sizeof(buf));
 	buf[sizeof(buf) - 1] = '\0';
-	n = 0;
+	n = 0;  /* initial value */
 	if ((cp = strtok(buf, delim))) {
 		++n;
 		while ((cp = strtok(0, delim))) {
@@ -156,32 +156,57 @@ int jpc_atoaf(const char *s, int *numvalues, double **values)
 			}
 		}
 	}
+	return n;
+}
+
+
+
+int
+jpc_atoaf(const char * const s,
+		  int *        const numvaluesP,
+		  double **    const valuesP) {
+/*----------------------------------------------------------------------------
+   Parse a string like "3.2,9,-5".  Return as *numvaluesP the number of
+   values in the string and as *valuesP a malloced array of the values.
 
-	if (n) {
-		if (!(vs = jas_malloc(n * sizeof(double)))) {
+   But if the string is empty (*numvaluesP is zero), return *valuesP NULL.
+
+   Delimiters can be comma as in the example or space, tab, or newline.
+-----------------------------------------------------------------------------*/
+	char const delim[] = ", \t\n";
+
+	unsigned int const valueCt = countOfTokens(s, delim);
+
+	if (valueCt > 0) {
+		unsigned int i;
+		double * vs;
+		const char * cp;
+		char buf[4096];
+
+		if (!(vs = jas_malloc(valueCt * sizeof(double)))) {
 			return -1;
 		}
 
 		strncpy(buf, s, sizeof(buf));
 		buf[sizeof(buf) - 1] = '\0';
-		n = 0;
+		i = 0;
 		if ((cp = strtok(buf, delim))) {
-			vs[n] = atof(cp);
-			++n;
+			vs[i] = atof(cp);
+			++i;
 			while ((cp = strtok(0, delim))) {
 				if (cp[0] != '\0') {
-					vs[n] = atof(cp);
-					++n;
+					vs[i] = atof(cp);
+					++i;
 				}
 			}
 		}
+		assert(i == valueCt);
+		*numvaluesP = valueCt;
+		*valuesP    = vs;
 	} else {
-		vs = 0;
+		*valuesP    = NULL;
+		*numvaluesP = 0;
 	}
-
-	*numvalues = n;
-	*values = vs;
-
 	return 0;
 }
 
diff --git a/converter/other/jpeg2000/libjasper_compat.c b/converter/other/jpeg2000/libjasper_compat.c
new file mode 100644
index 00000000..101820a3
--- /dev/null
+++ b/converter/other/jpeg2000/libjasper_compat.c
@@ -0,0 +1,26 @@
+#include "netpbm/nstring.h"
+
+#include "jasper/jasper.h"
+#include "jasper/jas_image.h"
+
+#ifndef JAS_HAVE_PMJAS_IMAGE_DECODE
+
+void
+pmjas_image_decode(jas_stream_t * const in,
+                   int            const fmtArg,
+                   const char *   const optstr,
+                   jas_image_t ** const imagePP,
+                   const char **  const errorP) {
+
+    jas_image_t * const jasperP = jas_image_decode(in, fmtArg, optstr);
+
+    if (jasperP) {
+        *imagePP = jasperP;
+        *errorP  = errorP;
+    } else {
+        pm_asprintf(errorP, "Failed.  Details may have been written to "
+                    "Standard Error");
+    }
+}
+
+#endif
diff --git a/converter/other/jpeg2000/libjasper_compat.h b/converter/other/jpeg2000/libjasper_compat.h
index 401144a3..103b1d09 100644
--- a/converter/other/jpeg2000/libjasper_compat.h
+++ b/converter/other/jpeg2000/libjasper_compat.h
@@ -1,12 +1,18 @@
 /* Here's some stuff to create backward compatibility with older Jasper
    libraries.  Unfortunately, new versions of the Jasper library are not
    backward compatible with old applications.
+
+   This also makes the programs compatible with both distributed Jasper
+   libraries and the Netpbm fork of Jasper distributed with Netpbm.
 */
 /* The color space thing got more complex between Version 1.600 and
    1.701.  For example, it now allows for multiple kinds of RGB, whereas
    in 1.600 RGB meant SRGB.  As part of that change, names changed
    from "colorspace" to "clrspc".
 */
+#include "jasper/jasper.h"
+#include "jasper/jas_image.h"
+
 #if defined(jas_image_setcolorspace)
 /* Old style color space */
 #define jas_image_setclrspc jas_image_setcolorspace
@@ -22,3 +28,32 @@
 #define JAS_CLRSPC_FAM_UNKNOWN JAS_IMAGE_CS_UNKNOWN
 
 #endif
+
+
+#ifndef JAS_HAVE_PMJAS_IMAGE_DECODE
+
+/* The Netpbm version of jas_image_decode (pmjas_image_decode) returns a
+   description of the problem when it fails and does not molest Standard
+   Error.  Real libjasper just indicates that it failed, after writing some
+   explanation (but not as much as the Netpbm version returns) to Standard
+   Error.
+*/
+void
+pmjas_image_decode(jas_stream_t * const in,
+                   int            const fmtArg,
+                   const char *   const optstr,
+                   jas_image_t ** const imagePP,
+                   const char **  const errorP) {
+
+    jas_image_t * const jasperP = jas_image_decode(in, fmtArg, optstr);
+
+    if (jasperP) {
+        *imagePP = jasperP;
+        *errorP  = NULL;
+    } else {
+        pm_asprintf(errorP, "Failed.  Details may have been written to "
+                    "Standard Error");
+    }
+}
+
+#endif
diff --git a/converter/other/jpeg2000/pamtojpeg2k.c b/converter/other/jpeg2000/pamtojpeg2k.c
index a886c390..8f7409c0 100644
--- a/converter/other/jpeg2000/pamtojpeg2k.c
+++ b/converter/other/jpeg2000/pamtojpeg2k.c
@@ -35,7 +35,7 @@ enum compmode {COMPMODE_INTEGER, COMPMODE_REAL};
 
 enum progression {PROG_LRCP, PROG_RLCP, PROG_RPCL, PROG_PCRL, PROG_CPRL};
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
@@ -53,6 +53,8 @@ struct cmdlineInfo {
     enum compmode compmode;
     unsigned int compressionSpec;
     float        compression;
+    unsigned int size;
+    unsigned int sizeSpec;
     char *       ilyrrates;
     enum progression progression;
     unsigned int numrlvls;
@@ -73,10 +75,10 @@ struct cmdlineInfo {
 
 static void
 parseCommandLine(int argc, char ** argv,
-                 struct cmdlineInfo * const cmdlineP) {
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that many of the strings that this function returns in the
-   *cmdline_p structure are actually in the supplied argv array.  And
+   *cmdlineP structure are actually in the supplied argv array.  And
    sometimes, one of these strings is actually just a suffix of an entry
    in argv!
 -----------------------------------------------------------------------------*/
@@ -126,6 +128,8 @@ parseCommandLine(int argc, char ** argv,
             &modeSpec,           0);
     OPTENT3(0, "compression",  OPT_FLOAT,  &cmdlineP->compression,
             &cmdlineP->compressionSpec,    0);
+    OPTENT3(0, "size",         OPT_UINT,   &cmdlineP->size,
+            &cmdlineP->sizeSpec,           0);
     OPTENT3(0, "ilyrrates",    OPT_STRING, &cmdlineP->ilyrrates,
             &ilyrratesSpec,      0);
     OPTENT3(0, "progression",  OPT_STRING, &progressionOpt,
@@ -219,6 +223,9 @@ parseCommandLine(int argc, char ** argv,
     if (!debuglevelSpec)
         cmdlineP->debuglevel = 0;
 
+    if (cmdlineP->compressionSpec && cmdlineP->sizeSpec)
+        pm_error("You cannot specify by -compression and -size");
+
     if (argc - 1 == 0)
         cmdlineP->inputFilename = strdup("-");  /* he wants stdin */
     else if (argc - 1 == 1)
@@ -372,9 +379,11 @@ convertToJasperImage(struct pam *   const inpamP,
 
 static void
 writeJpc(jas_image_t *      const jasperP,
-         struct cmdlineInfo const cmdline,
-         FILE *             const ofP) {
-
+         struct CmdlineInfo const cmdline,
+         int                const ofd) {
+/*----------------------------------------------------------------------------
+   Write the image *jasperP to open file 'ofd'.
+-----------------------------------------------------------------------------*/
     jas_stream_t * outStreamP;
     const char * options;
     const char * ilyrratesOpt;
@@ -403,6 +412,8 @@ writeJpc(jas_image_t *      const jasperP,
 
     if (cmdline.compressionSpec)
         sprintf(rateOpt, "rate=%1.9f", 1.0/cmdline.compression);
+    else if (cmdline.sizeSpec)
+        sprintf(rateOpt, "rate=%uB", cmdline.size);
     else {
         /* No 'rate' option.  This means there is no constraint on the image
            size, so the encoder will compress losslessly.  Note that the
@@ -459,7 +470,7 @@ writeJpc(jas_image_t *      const jasperP,
     pm_strfree(ilyrratesOpt);
 
     /* Open the output image file (Standard Output) */
-    outStreamP = jas_stream_fdopen(fileno(ofP), "w+b");
+    outStreamP = jas_stream_fdopen(ofd, "w+b");
     if (outStreamP == NULL)
         pm_error("Unable to open output stream.  jas_stream_fdopen() "
                  "failed");
@@ -500,7 +511,7 @@ writeJpc(jas_image_t *      const jasperP,
 int
 main(int argc, char **argv)
 {
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     FILE * ifP;
     struct pam inpam;
     jas_image_t * jasperP;
@@ -526,7 +537,7 @@ main(int argc, char **argv)
 
     convertToJasperImage(&inpam, &jasperP);
 
-    writeJpc(jasperP, cmdline, stdout);
+    writeJpc(jasperP, cmdline, fileno(stdout));
 
 	jas_image_destroy(jasperP);
 
diff --git a/converter/other/jpegtopnm.c b/converter/other/jpegtopnm.c
index 6357e859..7d1750a7 100644
--- a/converter/other/jpegtopnm.c
+++ b/converter/other/jpegtopnm.c
@@ -4,13 +4,13 @@
   This program is part of the Netpbm package.
 
   This program converts from the JFIF format, which is based on JPEG, to
-  the fundamental ppm or pgm format (depending on whether the JFIF 
+  the fundamental ppm or pgm format (depending on whether the JFIF
   image is gray scale or color).
 
   This program is by Bryan Henderson on 2000.03.20, but is derived
   with permission from the program djpeg, which is in the Independent
   Jpeg Group's JPEG library package.  Under the terms of that permission,
-  redistribution of this software is restricted as described in the 
+  redistribution of this software is restricted as described in the
   file README.JPEG.
 
   Copyright (C) 1991-1998, Thomas G. Lane.
@@ -45,13 +45,14 @@
     (http://topo.math.u-psud.fr/~bousch/exifdump.py) and Jhead
     (http://www.sentex.net/~mwandel/jhead).
 
-    
+
 *****************************************************************************/
 
 #define _DEFAULT_SOURCE 1  /* New name for SVID & BSD source defines */
 #define _BSD_SOURCE 1      /* Make sure strdup() is in string.h */
 #define _XOPEN_SOURCE 500  /* Make sure strdup() is in string.h */
 
+#include <stdbool.h>
 #include <ctype.h>		/* to declare isprint() */
 #include <string.h>
 #include <stdlib.h>
@@ -73,76 +74,78 @@
 
 #define EXIT_WARNING 2  /* Goes with EXIT_FAILURE, EXIT_SUCCESS in stdlib.h */
 
-enum inklevel {NORMAL, ADOBE, GUESS};
+enum Inklevel {NORMAL, ADOBE, GUESS};
    /* This describes image samples that represent ink levels.  NORMAL
       means 0 is no ink; ADOBE means 0 is maximum ink.  GUESS means we
-      don't know what 0 means, so we have to guess from information in 
+      don't know what 0 means, so we have to guess from information in
       the image.
       */
 
-enum colorspace {
+enum Colorspace {
     /* These are the color spaces in which we can get pixels from the
        JPEG decompressor.  We include only those that are possible
        given our particular inputs to the decompressor.  The
        decompressor is theoretically capable of other, e.g. YCCK.
        Unlike the JPEG library, this type distinguishes between the
-       Adobe and non-Adobe style of CMYK samples.  
+       Adobe and non-Adobe style of CMYK samples.
     */
     GRAYSCALE_COLORSPACE,
-    RGB_COLORSPACE, 
-    CMYK_NORMAL_COLORSPACE, 
+    RGB_COLORSPACE,
+    CMYK_NORMAL_COLORSPACE,
     CMYK_ADOBE_COLORSPACE
     };
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
-    char *input_filespec;
-    char *exif_filespec;
-        /* Filespec in which to save EXIF information.  NULL means don't
+    char * inputFileName;
+    char * exifFileName;
+        /* Name of file in which to save EXIF information.  NULL means don't
            save.  "-" means standard output
         */
-    unsigned int verbose;
-    unsigned int nosmooth;
-    J_DCT_METHOD dct_method;
-    long int max_memory_to_use;
-    unsigned int trace_level;
-    enum inklevel inklevel;
-    unsigned int comments;
-    unsigned int dumpexif;
-    unsigned int multiple;
-    unsigned int repair;
+    unsigned int  verbose;
+    unsigned int  nosmooth;
+    J_DCT_METHOD  dctMethod;
+    long int      maxMemoryToUse;
+    unsigned int  traceLevel;
+    enum Inklevel inklevel;
+    unsigned int  comments;
+    unsigned int  dumpexif;
+    unsigned int  traceexif;
+    unsigned int  multiple;
+    unsigned int  repair;
 };
 
 
 static bool displayComments;
     /* User wants comments from the JPEG to be displayed */
 
-static void 
-interpret_maxmemory(bool         const maxmemorySpec,
-                    const char * const maxmemory, 
-                    long int *   const max_memory_to_use_p) { 
+static void
+interpretMaxmemory(bool         const maxmemorySpec,
+                   const char * const maxmemory,
+                   long int *   const maxMemoryToUseP) {
 /*----------------------------------------------------------------------------
    Interpret the "maxmemory" command line option.
 -----------------------------------------------------------------------------*/
     long int lval;
     char ch;
-    
+
     if (!maxmemorySpec) {
-        *max_memory_to_use_p = -1;  /* unspecified */
+        *maxMemoryToUseP = -1;  /* unspecified */
     } else if (sscanf(maxmemory, "%ld%c", &lval, &ch) < 1) {
         pm_error("Invalid value for --maxmemory option: '%s'.", maxmemory);
     } else {
         if (ch == 'm' || ch == 'M') lval *= 1000L;
-        *max_memory_to_use_p = lval * 1000L;
+        *maxMemoryToUseP = lval * 1000L;
     }
 }
 
 
 static void
-interpret_adobe(const int adobe, const int notadobe, 
-                enum inklevel * const inklevel_p) {
+interpretAdobe(int             const adobe,
+               int             const notadobe,
+               enum Inklevel * const inklevelP) {
 /*----------------------------------------------------------------------------
    Interpret the adobe/notadobe command line options
 -----------------------------------------------------------------------------*/
@@ -150,11 +153,11 @@ interpret_adobe(const int adobe, const int notadobe,
         pm_error("You cannot specify both -adobe and -notadobe options.");
     else {
         if (adobe)
-            *inklevel_p = ADOBE;
+            *inklevelP = ADOBE;
         else if (notadobe)
-            *inklevel_p = NORMAL;
-        else 
-            *inklevel_p = GUESS;
+            *inklevelP = NORMAL;
+        else
+            *inklevelP = GUESS;
     }
 }
 
@@ -163,7 +166,7 @@ interpret_adobe(const int adobe, const int notadobe,
 static void
 parseCommandLine(int                  const argc,
                  char **              const argv,
-                 struct cmdlineInfo * const cmdlineP) {
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that many of the strings that this function returns in the
    *cmdlineP structure are actually in the supplied argv array.  And
@@ -173,7 +176,7 @@ parseCommandLine(int                  const argc,
    On the other hand, unlike other option processing functions, we do
    not change argv at all.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def;
+    optEntry * option_def;
         /* Instructions to pm_optParseOptions3 on how to parse our options.
          */
     optStruct3 opt;
@@ -192,7 +195,7 @@ parseCommandLine(int                  const argc,
 
     MALLOCARRAY_NOFAIL(option_def, 100);
     MALLOCARRAY_NOFAIL(argv_parse, argc);
-    
+
     /* argv, except we modify it as we parse */
 
     option_def_index = 0;   /* incremented by OPTENTRY */
@@ -200,62 +203,63 @@ parseCommandLine(int                  const argc,
     OPTENT3(0, "dct",         OPT_STRING, &dctval,
             &dctvalSpec, 0);
     OPTENT3(0, "maxmemory",   OPT_STRING, &maxmemory,
-            &maxmemorySpec, 0); 
+            &maxmemorySpec, 0);
     OPTENT3(0, "nosmooth",    OPT_FLAG,   NULL, &cmdlineP->nosmooth,      0);
-    OPTENT3(0, "tracelevel",  OPT_UINT,   &cmdlineP->trace_level,   
+    OPTENT3(0, "tracelevel",  OPT_UINT,   &cmdlineP->traceLevel,
             &tracelevelSpec, 0);
     OPTENT3(0, "adobe",       OPT_FLAG,   NULL, &adobe,                   0);
     OPTENT3(0, "notadobe",    OPT_FLAG,   NULL, &notadobe,                0);
     OPTENT3(0, "comments",    OPT_FLAG,   NULL, &cmdlineP->comments,      0);
-    OPTENT3(0, "exif",        OPT_STRING, &cmdlineP->exif_filespec, 
+    OPTENT3(0, "exif",        OPT_STRING, &cmdlineP->exifFileName,
             &exifSpec, 0);
     OPTENT3(0, "dumpexif",    OPT_FLAG,   NULL, &cmdlineP->dumpexif,      0);
     OPTENT3(0, "multiple",    OPT_FLAG,   NULL, &cmdlineP->multiple,      0);
     OPTENT3(0, "repair",      OPT_FLAG,   NULL, &cmdlineP->repair,        0);
+    OPTENT3(0, "traceexif",   OPT_FLAG,   NULL, &cmdlineP->traceexif,     0);
 
     opt.opt_table = option_def;
-    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
-    opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We may have parms that are negative numbers */
 
     /* Make private copy of arguments for pm_optParseOptions to corrupt */
     argc_parse = argc;
     for (i=0; i < argc; ++i)
         argv_parse[i] = argv[i];
 
-    pm_optParseOptions3( &argc_parse, argv_parse, opt, sizeof(opt), 0);
-        /* Uses and sets argc_parse, argv_parse, 
+    pm_optParseOptions3(&argc_parse, argv_parse, opt, sizeof(opt), 0);
+        /* Uses and sets argc_parse, argv_parse,
            and some of *cmdlineP and others. */
 
     if (!tracelevelSpec)
-        cmdlineP->trace_level = 0;
+        cmdlineP->traceLevel = 0;
 
     if (!exifSpec)
-        cmdlineP->exif_filespec = NULL;
+        cmdlineP->exifFileName = NULL;
 
     if (argc_parse - 1 == 0)
-        cmdlineP->input_filespec = strdup("-");  /* he wants stdin */
+        cmdlineP->inputFileName = strdup("-");  /* he wants stdin */
     else if (argc_parse - 1 == 1)
-        cmdlineP->input_filespec = strdup(argv_parse[1]);
-    else 
+        cmdlineP->inputFileName = strdup(argv_parse[1]);
+    else
         pm_error("Too many arguments.  The only argument accepted "
                  "is the input file specification");
 
     if (!dctvalSpec)
-        cmdlineP->dct_method = JDCT_DEFAULT;
+        cmdlineP->dctMethod = JDCT_DEFAULT;
     else {
         if (streq(dctval, "int"))
-            cmdlineP->dct_method = JDCT_ISLOW;
+            cmdlineP->dctMethod = JDCT_ISLOW;
         else if (streq(dctval, "fast"))
-            cmdlineP->dct_method = JDCT_IFAST;
+            cmdlineP->dctMethod = JDCT_IFAST;
         else if (streq(dctval, "float"))
-            cmdlineP->dct_method = JDCT_FLOAT;
+            cmdlineP->dctMethod = JDCT_FLOAT;
         else pm_error("Invalid value for the --dct option: '%s'.", dctval);
     }
 
-    interpret_maxmemory(maxmemorySpec, maxmemory, 
-                        &cmdlineP->max_memory_to_use);
+    interpretMaxmemory(maxmemorySpec, maxmemory,
+                       &cmdlineP->maxMemoryToUse);
 
-    interpret_adobe(adobe, notadobe, &cmdlineP->inklevel);
+    interpretAdobe(adobe, notadobe, &cmdlineP->inklevel);
 
     free(argv_parse);
 }
@@ -270,70 +274,72 @@ parseCommandLine(int                  const argc,
 
 #if 0
 static unsigned int
-jpeg_getc (j_decompress_ptr cinfo)
+jpegGetc (j_decompress_ptr const cinfoP) {
+
 /* Read next byte */
-{
-  struct jpeg_source_mgr * datasrc = cinfo->src;
-
-  if (datasrc->bytes_in_buffer == 0) {
-      if (! (*datasrc->fill_input_buffer) (cinfo)) 
-          pm_error("Can't suspend here.");
-  }
-  datasrc->bytes_in_buffer--;
-  return GETJOCTET(*datasrc->next_input_byte++);
+    struct jpeg_source_mgr * datasrcP = cinfoP->src;
+
+    if (datasrcP->bytes_in_buffer == 0) {
+        if (! (*datasrcP->fill_input_buffer) (cinfoP))
+            pm_error("Can't suspend here.");
+    }
+    datasrcP->bytes_in_buffer--;
+    return GETJOCTET(*datasrcP->next_input_byte++);
 }
 
 
-static boolean
-print_text_marker (j_decompress_ptr cinfo) {
+static bool
+printTextMarker(j_decompress_ptr const cinfoP) {
 /*----------------------------------------------------------------------------
    This is a routine that you can register with the Jpeg decompressor
    with e.g.
 
-     jpeg_set_marker_processor(cinfoP, JPEG_APP0 + app_type, 
-                               print_text_marker);
+     jpeg_set_marker_processor(cinfoP, JPEG_APP0 + appType,
+                               printTextMarker);
 
   The decompressor then calls it when it encounters a miscellaneous marker
   of the specified type (e.g. APP1).  At that time, the jpeg input stream
   is positioned to the marker contents -- first 2 bytes of length information,
   MSB first, where the length includes those two bytes, then the data.
-  
+
   We just get and print the contents of the marker.
 
   This routine is no longer used; it is kept as an example in case we want
   to use it in the future.  Instead, we use jpeg_save_markers() and have
   the Jpeg library store all the markers in memory for our later access.
 -----------------------------------------------------------------------------*/
-    const boolean traceit = (cinfo->err->trace_level >= 1);
-    const boolean display_value = 
-        traceit || (cinfo->unread_marker == JPEG_COM && displayComments);
-    
+    const bool traceit = (cinfoP->err->trace_level >= 1);
+    const bool display_value =
+        traceit || (cinfoP->unread_marker == JPEG_COM && displayComments);
+
     INT32 length;
     unsigned int ch;
-    unsigned int lastch = 0;
-    
-    length = jpeg_getc(cinfo) << 8;
-    length += jpeg_getc(cinfo);
+    unsigned int lastch;
+
+    lastch = 0;  /* initial value */
+
+    length = jpeg_getc(cinfoP) << 8;
+    length += jpeg_getc(cinfoP);
     length -= 2;			/* discount the length word itself */
 
     if (traceit) {
-        if (cinfo->unread_marker == JPEG_COM)
+        if (cinfoP->unread_marker == JPEG_COM)
             fprintf(stderr, "Comment, length %ld:\n", (long) length);
         else			/* assume it is an APPn otherwise */
             fprintf(stderr, "APP%d, length %ld:\n",
-                    cinfo->unread_marker - JPEG_APP0, (long) length);
+                    cinfoP->unread_marker - JPEG_APP0, (long) length);
     }
-    
-    if (cinfo->unread_marker == JPEG_COM && displayComments)
+
+    if (cinfoP->unread_marker == JPEG_COM && displayComments)
         fprintf(stderr, "COMMENT: ");
-    
+
     while (--length >= 0) {
-        ch = jpeg_getc(cinfo);
+        ch = jpeg_getc(cinfoP);
         if (display_value) {
             /* Emit the character in a readable form.
              * Nonprintables are converted to \nnn form,
              * while \ is converted to \\.
-             * Newlines in CR, CR/LF, or LF form will be printed as one 
+             * Newlines in CR, CR/LF, or LF form will be printed as one
              * newline.
              */
             if (ch == '\r') {
@@ -351,18 +357,18 @@ print_text_marker (j_decompress_ptr cinfo) {
           lastch = ch;
         }
     }
-    
+
     if (display_value)
         fprintf(stderr, "\n");
-    
-    return TRUE;
+
+    return true;
 }
 #endif
 
 
 
 static void
-print_marker(struct jpeg_marker_struct const marker) {
+printMarker(struct jpeg_marker_struct const marker) {
 
     if (marker.original_length != marker.data_length) {
         /* This should be impossible, because we asked for up to 65535
@@ -376,12 +382,12 @@ print_marker(struct jpeg_marker_struct const marker) {
         int i;
         JOCTET lastch;
 
-        lastch = 0;
+        lastch = 0;  /* initial value */
         for (i = 0; i < marker.data_length; i++) {
             /* Emit the character in a readable form.
              * Nonprintables are converted to \nnn form,
              * while \ is converted to \\.
-             * Newlines in CR, CR/LF, or LF form will be printed as one 
+             * Newlines in CR, CR/LF, or LF form will be printed as one
              * newline.
              */
             if (marker.data[i] == '\r') {
@@ -407,29 +413,29 @@ typedef struct rgb {unsigned int r; unsigned int g; unsigned int b;} rgb_type;
 
 
 static rgb_type *
-read_rgb(JSAMPLE *ptr, const enum colorspace color_space, 
-         const unsigned int maxval) {
+read_rgb(JSAMPLE *       const ptr,
+         enum Colorspace const colorspace,
+         unsigned int    const maxval) {
 /*----------------------------------------------------------------------------
   Return the RGB triple corresponding to the color of the JPEG pixel at
-  'ptr', which is in color space 'color_space'.  
+  'ptr', which is in color space 'color_space'.
 
   Assume 'maxval' is the maximum sample value in the input pixel, and also
   use it for the maximum sample value in the return value.
 -----------------------------------------------------------------------------*/
     static rgb_type rgb;  /* Our return value */
 
-    switch (color_space) {
+    switch (colorspace) {
     case RGB_COLORSPACE: {
         rgb.r = GETJSAMPLE(*(ptr+0));
-        rgb.g = GETJSAMPLE(*(ptr+1)); 
-        rgb.b = GETJSAMPLE(*(ptr+2)); 
-    }
-        break;
+        rgb.g = GETJSAMPLE(*(ptr+1));
+        rgb.b = GETJSAMPLE(*(ptr+2));
+    } break;
     case CMYK_NORMAL_COLORSPACE: {
-        const int c = GETJSAMPLE(*(ptr+0));
-        const int m = GETJSAMPLE(*(ptr+1));
-        const int y = GETJSAMPLE(*(ptr+2));
-        const int k = GETJSAMPLE(*(ptr+3));
+        int const c = GETJSAMPLE(*(ptr+0));
+        int const m = GETJSAMPLE(*(ptr+1));
+        int const y = GETJSAMPLE(*(ptr+2));
+        int const k = GETJSAMPLE(*(ptr+3));
 
         /* I swapped m and y below, because they looked wrong.
            -Bryan 2000.08.20
@@ -437,74 +443,71 @@ read_rgb(JSAMPLE *ptr, const enum colorspace color_space,
         rgb.r = ((maxval-k)*(maxval-c))/maxval;
         rgb.g = ((maxval-k)*(maxval-m))/maxval;
         rgb.b = ((maxval-k)*(maxval-y))/maxval;
-    }
-        break;
+    } break;
     case CMYK_ADOBE_COLORSPACE: {
-        const int c = GETJSAMPLE(*(ptr+0));
-        const int m = GETJSAMPLE(*(ptr+1));
-        const int y = GETJSAMPLE(*(ptr+2));
-        const int k = GETJSAMPLE(*(ptr+3));
+        int const c = GETJSAMPLE(*(ptr+0));
+        int const m = GETJSAMPLE(*(ptr+1));
+        int const y = GETJSAMPLE(*(ptr+2));
+        int const k = GETJSAMPLE(*(ptr+3));
 
         rgb.r = (k*c)/maxval;
         rgb.g = (k*m)/maxval;
         rgb.b = (k*y)/maxval;
-    }
-        break;
+    } break;
     default:
         pm_error("Internal error: unknown color space %d passed to "
-                 "read_rgb().", (int) color_space);
+                 "read_rgb().", (int) colorspace);
     }
-    return(&rgb);
+    return &rgb;
 }
 
 
 
-/* pnmbuffer is declared global because it would be improper to pass a
-   pointer to it as input to copy_pixel_row(), since it isn't
-   logically a parameter of the operation, but rather is private to
-   copy_pixel_row().  But it would be impractical to allocate and free
-   the storage with every call to copy_pixel_row().
-*/
-static xel * pnmbuffer;      /* Output buffer.  Input to pnm_writepnmrow() */
-
 static void
-copyPixelRow(JSAMPROW        const jpegbuffer,
-             unsigned int    const width, 
-             unsigned int    const samplesPerPixel, 
-             enum colorspace const colorSpace,
-             FILE *          const ofP,
-             int             const format,
-             xelval          const maxval) {
+convertPixelRow(JSAMPROW        const jpegbuffer,
+                unsigned int    const width,
+                unsigned int    const samplesPerPixel,
+                enum Colorspace const colorSpace,
+                int             const format,
+                xelval          const maxval,
+                xel *           const pnmbuffer) {
+/*----------------------------------------------------------------------------
+  Convert the pixels in 'jpegbuffer' from libjpeg format to libnetpbm
+  format in 'pnmbuffer'.
 
+  The row has 'width' pixels and the data in 'jpegbuffer' is formatted with
+  'samplesPerPixel' samples per pixel with colorspace 'colorSpace'.
+
+  The output Netpbm data is in format 'format' with maxval 'maxval'.
+-----------------------------------------------------------------------------*/
     JSAMPLE * ptr;
     unsigned int outputCursor;     /* Cursor into output buffer 'pnmbuffer' */
 
     ptr = &jpegbuffer[0];  /* Start at beginning of input row */
-    
+
     for (outputCursor = 0; outputCursor < width; ++outputCursor) {
         xel currentPixel;
         if (samplesPerPixel >= 3) {
-            const rgb_type * const rgb_p = read_rgb(ptr, colorSpace, maxval);
-            PPM_ASSIGN(currentPixel, rgb_p->r, rgb_p->g, rgb_p->b);
+            const rgb_type * const rgbP = read_rgb(ptr, colorSpace, maxval);
+            PPM_ASSIGN(currentPixel, rgbP->r, rgbP->g, rgbP->b);
         } else {
             PNM_ASSIGN1(currentPixel, GETJSAMPLE(*ptr));
         }
         ptr += samplesPerPixel;  /* move to next pixel of input */
         pnmbuffer[outputCursor] = currentPixel;
     }
-    pnm_writepnmrow(ofP, pnmbuffer, width, maxval, format, FALSE);
 }
 
 
 
 static void
-set_color_spaces(const J_COLOR_SPACE jpeg_color_space,
-                 int * const output_type_p,
-                 J_COLOR_SPACE * const out_color_space_p) {
+setColorSpaces(J_COLOR_SPACE   const jpegColorSpace,
+               int *           const outputTypeP,
+               J_COLOR_SPACE * const outColorSpaceP) {
 /*----------------------------------------------------------------------------
-   Decide what type of output (PPM or PGM) we shall generate and what 
+   Decide what type of output (PPM or PGM) we shall generate and what
    color space we must request from the JPEG decompressor, based on the
-   color space of the input JPEG image, 'jpeg_color_space'.
+   color space of the input JPEG image, 'jpegColorSpace'.
 
    Write to stderr a message telling which type we picked.
 
@@ -515,72 +518,72 @@ set_color_spaces(const J_COLOR_SPACE jpeg_color_space,
        CMYK or YCCK to RGB, but can translate YCCK to CMYK.
     */
 
-    switch (jpeg_color_space) {
+    switch (jpegColorSpace) {
     case JCS_UNKNOWN:
         pm_error("Input JPEG image has 'unknown' color space "
-                 "(JCS_UNKNOWN).\n"
+                 "(JCS_UNKNOWN).  "
                  "We cannot interpret this image.");
         break;
     case JCS_GRAYSCALE:
-        *output_type_p = PGM_TYPE;
-        *out_color_space_p = JCS_GRAYSCALE;
+        *outputTypeP    = PGM_TYPE;
+        *outColorSpaceP = JCS_GRAYSCALE;
         break;
     case JCS_RGB:
-        *output_type_p = PPM_TYPE;
-        *out_color_space_p = JCS_RGB;
+        *outputTypeP    = PPM_TYPE;
+        *outColorSpaceP = JCS_RGB;
         break;
     case JCS_YCbCr:
-        *output_type_p = PPM_TYPE;
-        *out_color_space_p = JCS_RGB;
+        *outputTypeP    = PPM_TYPE;
+        *outColorSpaceP = JCS_RGB;
         /* Design note:  We found this YCbCr->RGB conversion increases
            user mode CPU time by 2.5%.  2002.10.12
         */
         break;
     case JCS_CMYK:
-        *output_type_p = PPM_TYPE;
-        *out_color_space_p = JCS_CMYK;
+        *outputTypeP    = PPM_TYPE;
+        *outColorSpaceP = JCS_CMYK;
         break;
     case JCS_YCCK:
-        *output_type_p = PPM_TYPE;
-        *out_color_space_p = JCS_CMYK;
+        *outputTypeP    = PPM_TYPE;
+        *outColorSpaceP = JCS_CMYK;
         break;
     default:
-        pm_error("Internal error: unknown color space code %d passed "
-                 "to set_color_spaces().", jpeg_color_space);
+        pm_error("INTERNAL ERROR: unknown color space code %d passed "
+                 "to setColorSpaces().", jpegColorSpace);
     }
-    pm_message("WRITING %s FILE", 
-               *output_type_p == PPM_TYPE ? "PPM" : "PGM");
+    pm_message("WRITING %s FILE",
+               *outputTypeP == PPM_TYPE ? "PPM" : "PGM");
 }
 
 
 
 static const char *
-colorspace_name(const J_COLOR_SPACE jpeg_color_space) {
-
-    const char *retval;
-
-    switch(jpeg_color_space) {
-    case JCS_UNKNOWN: retval = "JCS_UNKNOWN"; break;
-    case JCS_GRAYSCALE: retval= "JCS_GRAYSCALE"; break;
-    case JCS_RGB: retval = "JCS_RGB"; break;
-    case JCS_YCbCr: retval = "JCS_YCbCr"; break;
-    case JCS_CMYK: retval = "JCS_CMYK"; break;
-    case JCS_YCCK: retval = "JCS_YCCK"; break;
-    default: retval = "invalid"; break;
+colorspaceName(J_COLOR_SPACE const jpegColorSpace) {
+
+    const char * retval;
+
+    switch(jpegColorSpace) {
+    case JCS_UNKNOWN:   retval = "JCS_UNKNOWN";   break;
+    case JCS_GRAYSCALE: retval = "JCS_GRAYSCALE"; break;
+    case JCS_RGB:       retval = "JCS_RGB";       break;
+    case JCS_YCbCr:     retval = "JCS_YCbCr";     break;
+    case JCS_CMYK:      retval = "JCS_CMYK";      break;
+    case JCS_YCCK:      retval = "JCS_YCCK";      break;
+    default:            retval = "invalid";       break;
     };
-    return(retval);
+    return retval;
 }
 
 
 
 static void
-print_verbose_info_about_header(struct jpeg_decompress_struct const cinfo){
+printVerboseInfoAboutHeader(struct jpeg_decompress_struct const cinfo){
 
     struct jpeg_marker_struct * markerP;
 
-    pm_message("input color space is %d (%s)\n", 
-               cinfo.jpeg_color_space, 
-               colorspace_name(cinfo.jpeg_color_space));
+    pm_message("input color space is %d (%s)",
+               cinfo.jpeg_color_space,
+               colorspaceName(cinfo.jpeg_color_space));
 
     /* Note that raw information about marker, including marker type code,
        was already printed by the jpeg library, because of the jpeg library
@@ -595,15 +598,15 @@ print_verbose_info_about_header(struct jpeg_decompress_struct const cinfo){
     for (markerP = cinfo.marker_list; markerP; markerP = markerP->next) {
         if (markerP->marker == JPEG_COM)
             pm_message("Comment marker (COM):");
-        else if (markerP->marker >= JPEG_APP0 && 
+        else if (markerP->marker >= JPEG_APP0 &&
                  markerP->marker <= JPEG_APP0+15)
-            pm_message("Miscellaneous marker type APP%d:", 
+            pm_message("Miscellaneous marker type APP%d:",
                        markerP->marker - JPEG_APP0);
         else
             pm_message("Miscellaneous marker of unknown type (0x%X):",
                        markerP->marker);
-        
-        print_marker(*markerP);
+
+        printMarker(*markerP);
     }
 }
 
@@ -611,80 +614,84 @@ print_verbose_info_about_header(struct jpeg_decompress_struct const cinfo){
 
 static void
 beginJpegInput(struct jpeg_decompress_struct * const cinfoP,
-               const boolean verbose, 
-               const J_DCT_METHOD dct_method, 
-               const int max_memory_to_use, 
-               const boolean nosmooth) {
+               bool                            const verbose,
+               J_DCT_METHOD                    const dctMethod,
+               int                             const maxMemoryToUse,
+               bool                            const nosmooth) {
 /*----------------------------------------------------------------------------
    Read the JPEG header, create decompressor object (and
    allocate memory for it), set up decompressor.
 -----------------------------------------------------------------------------*/
     /* Read file header, set default decompression parameters */
-    jpeg_read_header(cinfoP, TRUE);
+    jpeg_read_header(cinfoP, true);
 
-    cinfoP->dct_method = dct_method;
-    if (max_memory_to_use != -1)
-        cinfoP->mem->max_memory_to_use = max_memory_to_use;
+    cinfoP->dct_method = dctMethod;
+    if (maxMemoryToUse != -1)
+        cinfoP->mem->max_memory_to_use = maxMemoryToUse;
     if (nosmooth)
-        cinfoP->do_fancy_upsampling = FALSE;
-    
+        cinfoP->do_fancy_upsampling = false;
+
 }
 
 
 
 static void
-print_comments(struct jpeg_decompress_struct const cinfo) {
-    
+printComments(struct jpeg_decompress_struct const cinfo) {
+
     struct jpeg_marker_struct * markerP;
 
     for (markerP = cinfo.marker_list;
-         markerP; markerP = markerP->next) 
+         markerP; markerP = markerP->next) {
         if (markerP->marker == JPEG_COM) {
             pm_message("COMMENT:");
-            print_marker(*markerP);
+            printMarker(*markerP);
         }
+    }
 }
 
 
 
 static void
-print_exif_info(struct jpeg_marker_struct const marker) {
+printExifInfo(struct jpeg_marker_struct const marker,
+              bool                      const wantTagTrace) {
 /*----------------------------------------------------------------------------
    Dump as informational messages the contents of the Jpeg miscellaneous
    marker 'marker', assuming it is an Exif header.
 -----------------------------------------------------------------------------*/
-    bool const wantTagTrace = false;
     exif_ImageInfo imageInfo;
     const char * error;
 
     assert(marker.data_length >= 6);
 
-    exif_parse(marker.data+6, marker.data_length-6, 
+    exif_parse(marker.data+6, marker.data_length-6,
                &imageInfo, wantTagTrace, &error);
 
     if (error) {
         pm_message("EXIF header is invalid.  %s", error);
         pm_strfree(error);
-    } else
+    } else {
         exif_showImageInfo(&imageInfo);
+
+        exif_terminateImageInfo(&imageInfo);
+    }
 }
 
 
 
-static boolean
-is_exif(struct jpeg_marker_struct const marker) {
+static bool
+isExif(struct jpeg_marker_struct const marker) {
 /*----------------------------------------------------------------------------
-   Return true iff the JPEG miscellaneous marker 'marker' is an Exif 
+   Return true iff the JPEG miscellaneous marker 'marker' is an Exif
    header.
 -----------------------------------------------------------------------------*/
-    boolean retval;
-    
+    bool retval;
+
     if (marker.marker == JPEG_APP0+1) {
         if (marker.data_length >=6 && memcmp(marker.data, "Exif", 4) == 0)
-            retval = TRUE;
-        else retval = FALSE;
+            retval = true;
+        else retval = false;
     }
-    else retval = FALSE;
+    else retval = false;
 
     return retval;
 }
@@ -692,69 +699,71 @@ is_exif(struct jpeg_marker_struct const marker) {
 
 
 static void
-dump_exif(struct jpeg_decompress_struct const cinfo) {
+dumpExif(struct jpeg_decompress_struct const cinfo,
+         bool                          const wantTrace) {
 /*----------------------------------------------------------------------------
    Dump as informational messages the contents of all EXIF headers in
    the image, interpreted.  An EXIF header is an APP1 marker.
 -----------------------------------------------------------------------------*/
     struct jpeg_marker_struct * markerP;
-    boolean found_one;
-
-    found_one = FALSE;  /* initial value */
+    bool foundOne;
 
-    for (markerP = cinfo.marker_list; markerP; markerP = markerP->next) 
-        if (is_exif(*markerP)) {
+    for (markerP = cinfo.marker_list, foundOne = false;
+         markerP;
+         markerP = markerP->next) {
+        if (isExif(*markerP)) {
             pm_message("EXIF INFO:");
-            print_exif_info(*markerP);
-            found_one = TRUE;
+            printExifInfo(*markerP, wantTrace);
+            foundOne = true;
         }
-    if (!found_one)
+    }
+    if (!foundOne)
         pm_message("No EXIF info in image.");
 }
 
 
 
 static void
-save_exif(struct jpeg_decompress_struct const cinfo, 
-          const char *                  const exif_filespec) {
+saveExif(struct jpeg_decompress_struct const cinfo,
+         const char *                  const exifFileName) {
 /*----------------------------------------------------------------------------
-  Write the contents of the first Exif header in the image into the
-  file with filespec 'exif_filespec'.  Start with the two byte length
-  field.  If 'exif_filespec' is "-", write to standard output.
+  Write the contents of the first Exif header in the image into the file with
+  name 'exifFileName'.  Start with the two byte length field.  If
+  'exifFileName' is "-", write to standard output.
 
-  If there is no Exif header in the image, write just zero, as a two
-  byte pure binary integer.
+  If there is no Exif header in the image, write just zero, as a two byte pure
+  binary integer.
 -----------------------------------------------------------------------------*/
-    FILE * exif_file;
+    FILE * exifFileP;
     struct jpeg_marker_struct * markerP;
 
-    exif_file = pm_openw(exif_filespec);
+    exifFileP = pm_openw(exifFileName);
 
-    for (markerP = cinfo.marker_list; 
-         markerP && !is_exif(*markerP);
+    for (markerP = cinfo.marker_list;
+         markerP && !isExif(*markerP);
          markerP = markerP->next);
 
     if (markerP) {
-        pm_writebigshort(exif_file, markerP->data_length+2);
-        if (ferror(exif_file))
-            pm_error("Write of Exif header to %s failed on first byte.",
-                     exif_filespec);
+        pm_writebigshort(exifFileP, markerP->data_length+2);
+        if (ferror(exifFileP))
+            pm_error("Write of Exif header to file '%s' failed on first byte.",
+                     exifFileName);
         else {
             int rc;
 
-            rc = fwrite(markerP->data, 1, markerP->data_length, exif_file);
+            rc = fwrite(markerP->data, 1, markerP->data_length, exifFileP);
             if (rc != markerP->data_length)
                 pm_error("Write of Exif header to '%s' failed.  Wrote "
                          "length successfully, but then failed after "
-                         "%d characters of data.", exif_filespec, rc);
+                         "%d characters of data.", exifFileName, rc);
         }
     } else {
         /* There is no Exif header in the image */
-        pm_writebigshort(exif_file, 0);
-        if (ferror(exif_file))
-            pm_error("Write of Exif header file '%s' failed.", exif_filespec);
+        pm_writebigshort(exifFileP, 0);
+        if (ferror(exifFileP))
+            pm_error("Write of Exif header file '%s' failed.", exifFileName);
     }
-    pm_close(exif_file);
+    pm_close(exifFileP);
 }
 
 
@@ -762,25 +771,25 @@ save_exif(struct jpeg_decompress_struct const cinfo,
 static void
 tellDetails(struct jpeg_decompress_struct const cinfo,
             xelval                        const maxval,
-            int                           const output_type) {
+            int                           const outputType) {
 
-    print_verbose_info_about_header(cinfo);
+    printVerboseInfoAboutHeader(cinfo);
 
-    pm_message("Input image data precision = %d bits", 
+    pm_message("Input image data precision = %d bits",
                cinfo.data_precision);
     pm_message("Output file will have format %c%c "
-               "with max sample value of %d.", 
-               (char) (output_type/256), (char) (output_type % 256),
+               "with max sample value of %d.",
+               (char) (outputType/256), (char) (outputType % 256),
                maxval);
-}  
+}
 
 
 
-static enum colorspace
+static enum Colorspace
 computeColorSpace(struct jpeg_decompress_struct * const cinfoP,
-                  enum inklevel                   const inklevel) {
-    
-    enum colorspace colorSpace;
+                  enum Inklevel                   const inklevel) {
+
+    enum Colorspace colorSpace;
 
     if (cinfoP->out_color_space == JCS_GRAYSCALE)
         colorSpace = GRAYSCALE_COLORSPACE;
@@ -806,33 +815,45 @@ computeColorSpace(struct jpeg_decompress_struct * const cinfoP,
 
 static void
 convertRaster(struct jpeg_decompress_struct * const cinfoP,
-              enum colorspace                 const color_space,
+              enum Colorspace                 const colorspace,
               FILE *                          const ofP,
               xelval                          const format,
               unsigned int                    const maxval) {
-              
+/*----------------------------------------------------------------------------
+   Read the raster from the input and write it out in Netpbm format
+   to file *ofP, in format 'format', with maxval 'maxval'.
+-----------------------------------------------------------------------------*/
     JSAMPROW jpegbuffer;  /* Input buffer.  Filled by jpeg_scanlines() */
 
+    xel * pnmbuffer;      /* Output buffer */
+
     jpegbuffer = ((*cinfoP->mem->alloc_sarray)
                   ((j_common_ptr) cinfoP, JPOOL_IMAGE,
-                   cinfoP->output_width * cinfoP->output_components, 
+                   cinfoP->output_width * cinfoP->output_components,
                    (JDIMENSION) 1)
         )[0];
 
+    pnmbuffer = pnm_allocrow(cinfoP->output_width);
+
     while (cinfoP->output_scanline < cinfoP->output_height) {
         jpeg_read_scanlines(cinfoP, &jpegbuffer, 1);
-        if (ofP)
-            copyPixelRow(jpegbuffer, cinfoP->output_width, 
-                         cinfoP->out_color_components,
-                         color_space, ofP, format, maxval);
+        if (ofP) {
+            convertPixelRow(jpegbuffer, cinfoP->output_width,
+                            cinfoP->out_color_components,
+                            colorspace, format, maxval, pnmbuffer);
+
+            pnm_writepnmrow(ofP, pnmbuffer, cinfoP->output_width,
+                            maxval, format, false);
+        }
     }
+    pnm_freerow(pnmbuffer);
 }
 
 
 
 static void
-convertImage(FILE *                          const ofP, 
-             struct cmdlineInfo              const cmdline,
+convertImage(FILE *                          const ofP,
+             struct CmdlineInfo              const cmdline,
              struct jpeg_decompress_struct * const cinfoP) {
 
     int format;
@@ -840,23 +861,23 @@ convertImage(FILE *                          const ofP,
            or PGM_TYPE, which conveniently also pass as format values
            PPM_FORMAT and PGM_FORMAT.
         */
-    xelval maxval;  
+    xelval maxval;
         /* The maximum value of a sample (color component), both in the input
            and the output.
         */
-    enum colorspace color_space;
+    enum Colorspace colorspace;
         /* The color space of the pixels coming out of the JPEG decompressor */
 
-    beginJpegInput(cinfoP, cmdline.verbose, 
-                   cmdline.dct_method, 
-                   cmdline.max_memory_to_use, cmdline.nosmooth);
-                   
-    set_color_spaces(cinfoP->jpeg_color_space, &format,
-                     &cinfoP->out_color_space);
+    beginJpegInput(cinfoP, cmdline.verbose,
+                   cmdline.dctMethod,
+                   cmdline.maxMemoryToUse, cmdline.nosmooth);
+
+    setColorSpaces(cinfoP->jpeg_color_space, &format,
+                   &cinfoP->out_color_space);
 
     maxval = pm_bitstomaxval(cinfoP->data_precision);
 
-    if (cmdline.verbose) 
+    if (cmdline.verbose)
         tellDetails(*cinfoP, maxval, format);
 
     /* Calculate output image dimensions so we can allocate space */
@@ -868,22 +889,18 @@ convertImage(FILE *                          const ofP,
     if (ofP)
         /* Write pnm output header */
         pnm_writepnminit(ofP, cinfoP->output_width, cinfoP->output_height,
-                         maxval, format, FALSE);
+                         maxval, format, false);
 
-    pnmbuffer = pnm_allocrow(cinfoP->output_width);
-    
-    color_space = computeColorSpace(cinfoP, cmdline.inklevel);
-    
-    convertRaster(cinfoP, color_space, ofP, format, maxval);
+    colorspace = computeColorSpace(cinfoP, cmdline.inklevel);
+
+    convertRaster(cinfoP, colorspace, ofP, format, maxval);
 
     if (cmdline.comments)
-        print_comments(*cinfoP);
+        printComments(*cinfoP);
     if (cmdline.dumpexif)
-        dump_exif(*cinfoP);
-    if (cmdline.exif_filespec)
-        save_exif(*cinfoP, cmdline.exif_filespec);
-
-    pnm_freerow(pnmbuffer);
+        dumpExif(*cinfoP, cmdline.traceexif);
+    if (cmdline.exifFileName)
+        saveExif(*cinfoP, cmdline.exifFileName);
 
     /* Finish decompression and release decompressor memory. */
     jpeg_finish_decompress(cinfoP);
@@ -895,18 +912,18 @@ convertImage(FILE *                          const ofP,
 static void
 saveMarkers(struct jpeg_decompress_struct * const cinfoP) {
 
-    unsigned int app_type;
+    unsigned int appType;
     /* Get all the miscellaneous markers (COM and APPn) saved for our
        later access.
     */
     jpeg_save_markers(cinfoP, JPEG_COM, 65535);
-    for (app_type = 0; app_type <= 15; ++app_type) {
-        if (app_type == 0 || app_type == 14) {
+    for (appType = 0; appType <= 15; ++appType) {
+        if (appType == 0 || appType == 14) {
             /* The jpeg library uses APP0 and APP14 internally (see
                libjpeg.doc), so we don't mess with those.
             */
         } else
-            jpeg_save_markers(cinfoP, JPEG_APP0 + app_type, 65535);
+            jpeg_save_markers(cinfoP, JPEG_APP0 + appType, 65535);
     }
 }
 
@@ -914,10 +931,10 @@ saveMarkers(struct jpeg_decompress_struct * const cinfoP) {
 
 static void
 convertImages(FILE *                          const ofP,
-              struct cmdlineInfo              const cmdline,
+              struct CmdlineInfo              const cmdline,
               struct jpeg_decompress_struct * const cinfoP,
               struct sourceManager *          const sourceManagerP) {
-              
+
     if (cmdline.multiple) {
         unsigned int imageSequence;
         for (imageSequence = 0; dsDataLeft(sourceManagerP); ++imageSequence) {
@@ -943,19 +960,19 @@ convertImages(FILE *                          const ofP,
 
 
 int
-main(int argc, char **argv) {
+main(int argc, const char **argv) {
 
     FILE * ofP;
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     struct jpeg_decompress_struct cinfo;
     struct jpeg_error_mgr jerr;
     struct sourceManager * sourceManagerP;
 
-    pnm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
-    parseCommandLine(argc, argv, &cmdline);
+    parseCommandLine(argc, (char **)argv, &cmdline);
 
-    if (cmdline.exif_filespec && streq(cmdline.exif_filespec, "-"))
+    if (cmdline.exifFileName && streq(cmdline.exifFileName, "-"))
         /* He's got exif going to stdout, so there can be no image output */
         ofP = NULL;
     else
@@ -967,14 +984,14 @@ main(int argc, char **argv) {
     cinfo.err = jpeg_std_error(&jerr);
     jpeg_create_decompress(&cinfo);
 
-    if (cmdline.trace_level == 0 && cmdline.verbose) 
+    if (cmdline.traceLevel == 0 && cmdline.verbose)
         cinfo.err->trace_level = 1;
-    else 
-        cinfo.err->trace_level = cmdline.trace_level;
-    
+    else
+        cinfo.err->trace_level = cmdline.traceLevel;
+
     saveMarkers(&cinfo);
 
-    sourceManagerP = dsCreateSource(cmdline.input_filespec);
+    sourceManagerP = dsCreateSource(cmdline.inputFileName);
 
     cinfo.src = dsJpegSourceMgr(sourceManagerP);
 
@@ -985,14 +1002,17 @@ main(int argc, char **argv) {
     if (ofP) {
         int rc;
         rc = fclose(ofP);
-        if (rc == EOF) 
+        if (rc == EOF)
             pm_error("Error writing output file.  Errno = %s (%d).",
                      strerror(errno), errno);
     }
 
     dsDestroySource(sourceManagerP);
 
-    free(cmdline.input_filespec);
-  
+    free(cmdline.inputFileName);
+
     exit(jerr.num_warnings > 0 ? EXIT_WARNING : EXIT_SUCCESS);
 }
+
+
+
diff --git a/converter/other/pamtofits.c b/converter/other/pamtofits.c
index 92e29c7e..fe81d94d 100644
--- a/converter/other/pamtofits.c
+++ b/converter/other/pamtofits.c
@@ -45,12 +45,12 @@ struct cmdlineInfo {
 
 
 
-static void 
+static void
 parseCommandLine(int argc, char ** argv,
                  struct cmdlineInfo * const cmdlineP) {
 /*--------------------------------------------------------------------------
    Parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -95,7 +95,7 @@ parseCommandLine(int argc, char ** argv,
         cmdlineP->inputFileName = "-";
     else {
         cmdlineP->inputFileName = argv[1];
-        
+
         if (argc-1 > 1)
             pm_error("Too many arguments (%u).  The only non-option argument "
                      "is the input file name.", argc-1);
@@ -127,7 +127,7 @@ padToMultipleOf36Cards(unsigned int const nCardsAlreadyWritten) {
 
     unsigned int const npadCard = 36 - (nCardsAlreadyWritten % 36);
     unsigned int i;
-    
+
     for (i = 0; i < npadCard; ++i)
         writeHeaderCard("");
 }
@@ -146,7 +146,7 @@ writeFitsHeader(int    const bitpix,
 
     char buffer[80+1];
     unsigned int cardsWritten;
-                
+
     cardsWritten = 0;  /* initial value */
 
     sprintf(buffer, "%-20.20s%10.10s", "SIMPLE  =", "T");
@@ -178,7 +178,7 @@ writeFitsHeader(int    const bitpix,
     sprintf(buffer, "%-18.18s%12.5E", "BSCALE  =", bscale);
     writeHeaderCard(buffer);
     ++cardsWritten;
-    
+
     sprintf(buffer, "%-18.18s%12.5E", "BZERO   =", fitsBzero);
     writeHeaderCard(buffer);
     ++cardsWritten;
@@ -263,7 +263,7 @@ main(int argc, char * argv[]) {
            the default case, that PNM sample value is also the FITS "physical"
            value, but user options can change that.
         */
-    
+
     pnm_init(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
@@ -287,7 +287,7 @@ main(int argc, char * argv[]) {
     assert(datamax > datamin);
 
     bscale = (datamax - datamin) / pam.maxval;
-    
+
     if (pam.maxval > 255) {
         bitpix = 16;
         /* Because 16 bit FITS samples are signed, we have to do a 2**15
@@ -315,3 +315,6 @@ main(int argc, char * argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/converter/other/pamtogif.c b/converter/other/pamtogif.c
index 022b7343..341c9c03 100644
--- a/converter/other/pamtogif.c
+++ b/converter/other/pamtogif.c
@@ -19,15 +19,14 @@
 
 #define MAXCMAPSIZE 256
 
-static unsigned int const gifMaxval = 255;
-
 static bool verbose;
 
 
 enum TransparencyType {TRANS_NONE, TRANS_COLOR, TRANS_ALPHA};
-    // The source of transparency for the GIF: nothing is transparent,
-    // All pixels of a certain color are transparent, or the alpha plane
-    // in the input tells what is transparent.
+    /* The source of transparency for the GIF: nothing is transparent,
+       All pixels of a certain color are transparent, or the alpha plane
+       in the input tells what is transparent.
+    */
 
 typedef unsigned int StringCode;
     /* A code to be place in the GIF raster.  It represents
@@ -813,7 +812,7 @@ typedef struct {
         */
     bool lzw;
         /* We're actually doing LZW compression.  False means we follow
-           the algorithm enough tht an LZW decompressor will recover the
+           the algorithm enough that an LZW decompressor will recover the
            proper data, but always using one code per pixel, and therefore
            not effecting any compression and not using the LZW patent.
         */
@@ -1676,7 +1675,7 @@ computeTransparent(enum TransparencyType const transType,
     case TRANS_NONE: {
         cmapP->haveTransparent = FALSE;
     } break;
-    }  // switch
+    }  /* switch */
     reportTransparent(transType, cmapP);
 }
 
@@ -1893,14 +1892,14 @@ computeColormapFromInput(struct pam *   const pamP,
 
 
 static void
-computeLibnetpbmColormap(struct pam *   const pamP,
-                         bool           const haveAlpha,
-                         const char *   const mapfile,
-                         tuple *        const color,
-                         tuplehash *    const tuplehashP,
-                         struct pam *   const mapPamP,
-                         unsigned int * const colorCountP,
-                         bool           const sort) {
+computeLibnetpbmColormap(struct pam *          const pamP,
+                         enum TransparencyType const transType,
+                         const char *          const mapfile,
+                         tuple *               const color,
+                         tuplehash *           const tuplehashP,
+                         struct pam *          const mapPamP,
+                         unsigned int *        const colorCountP,
+                         bool                  const sort) {
 /*----------------------------------------------------------------------------
    Compute a colormap, libnetpbm style, for the image described by
    'pamP', which is positioned to the raster.
@@ -1914,21 +1913,23 @@ computeLibnetpbmColormap(struct pam *   const pamP,
    The tuples of the color map have a meaningful depth of 1 (grayscale) or 3
    (color) and *mapPamP reflects that.
 
-   While we're at it, count the colors and validate that there aren't
-   too many.  Return the count as *colorCountP.  In determining if there are
-   too many, allow one slot for a fake transparency color if 'haveAlpha'
-   is true.  If there are too many, issue an error message and abort the
+   While we're at it, count the colors and validate that there aren't too
+   many.  Return the count as *colorCountP.  In determining if there are too
+   many, allow one slot for a fake transparency color if 'transType' is
+   'TRANS_ALPHA'.  If there are too many, issue an error message and abort the
    program.
 
    'sort' means to sort the colormap by red intensity, then by green
    intensity, then by blue intensity, as opposed to arbitrary order.
 -----------------------------------------------------------------------------*/
-    unsigned int const maxcolors = haveAlpha ? MAXCMAPSIZE - 1 : MAXCMAPSIZE;
+    unsigned int const maxcolors =
+        transType == TRANS_ALPHA ? MAXCMAPSIZE - 1 : MAXCMAPSIZE;
         /* The most colors we can tolerate in the image.  If we have
            our own made-up entry in the colormap for transparency, it
            isn't included in this count.
         */
-    unsigned int const nInputComp = haveAlpha ? pamP->depth - 1 : pamP->depth;
+    unsigned int const nInputComp =
+        pamAlphaPlane(pamP) ? pamP->depth - 1 : pamP->depth;
         /* Number of color components (not alpha) in the input image */
 
     unsigned int i;
@@ -2011,16 +2012,16 @@ main(int argc, char *argv[]) {
 
     pm_tell2(ifP, &rasterPos, sizeof(rasterPos));
 
-    computeLibnetpbmColormap(&pam, !!pamAlphaPlane(&pam), cmdline.mapfile,
+    transType = cmdline.transparent ? TRANS_COLOR :
+        pamAlphaPlane(&pam) ? TRANS_ALPHA :
+        TRANS_NONE;
+
+    computeLibnetpbmColormap(&pam, transType, cmdline.mapfile,
                              cmap.color, &cmap.tuplehash,
                              &cmap.pam, &cmap.cmapSize, cmdline.sort);
 
     assert(cmap.pam.maxval == pam.maxval);
 
-    transType = cmdline.transparent ? TRANS_COLOR :
-        pamAlphaPlane(&pam) ? TRANS_ALPHA :
-        TRANS_NONE;
-
     if (transType == TRANS_ALPHA) {
         /* Add a fake entry to the end of the colormap for transparency.
            Make its color black.
@@ -2036,7 +2037,7 @@ main(int argc, char *argv[]) {
     gifEncode(&pam, stdout, rasterPos,
               cmdline.interlace, 0, bitsPerPixel, &cmap, cmdline.comment,
               cmdline.aspect, !cmdline.nolzw, cmdline.noclear,
-              !cmdline.transparent);
+              transType==TRANS_ALPHA);
 
     destroyCmap(&cmap);
 
diff --git a/converter/other/pamtopdbimg.c b/converter/other/pamtopdbimg.c
index ce2f7659..da0f5064 100644
--- a/converter/other/pamtopdbimg.c
+++ b/converter/other/pamtopdbimg.c
@@ -32,6 +32,7 @@
 #include <stdlib.h>
 #include <assert.h>
 #include <string.h>
+#include <time.h>
 #include <sys/stat.h>
 
 #include "pm_c_util.h"
@@ -45,7 +46,7 @@
 
 enum CompMode {COMPRESSED, MAYBE, UNCOMPRESSED};
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
@@ -54,16 +55,17 @@ struct cmdlineInfo {
     const char * notefile;  /* NULL if not specified */
     enum CompMode compMode;
     unsigned int depth4;
+    unsigned int fixedtime;
 };
 
 
 
 static void
 parseCommandLine(int argc, const char ** argv,
-                 struct cmdlineInfo * const cmdlineP) {
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -96,6 +98,8 @@ parseCommandLine(int argc, const char ** argv,
             &uncompressed,            0);
     OPTENT3(0, "4depth",              OPT_FLAG,      NULL,
             &cmdlineP->depth4,        0);
+    OPTENT3(0, "fixedtime",           OPT_FLAG,      NULL,
+            &cmdlineP->fixedtime,     0);
 
     opt.opt_table = option_def;
     opt.short_allowed = false;  /* We have no short (old-fashioned) options */
@@ -110,7 +114,7 @@ parseCommandLine(int argc, const char ** argv,
 
     if (!notefileSpec)
         cmdlineP->notefile = NULL;
-    
+
     if (compressed + uncompressed + maybeCompressed > 1)
         pm_error("You may specify only one of -compressed, -uncompressed, "
                  "-maybecompressed");
@@ -144,6 +148,42 @@ parseCommandLine(int argc, const char ** argv,
 
 
 
+static uint32_t const unixepoch = (66*365+17)*24*3600;
+    /* The unix epoch in Mac time (the Mac epoch is 00:00 UTC 1904.01.01).
+       The 17 is the number of leap years.
+    */
+
+
+
+static void
+setPdbHeader(PDBHEAD *    const pdbHeadP,
+             const char * const name,
+             bool         const wantFixedTime) {
+
+    STRSCPY(pdbHeadP->name, name);
+
+    {
+        /*
+         * All of the Image Viewer pdb files that I've come across have
+         * 3510939142U (1997.08.16 14:38:22 UTC) here.  I don't know where
+         * this bizarre datetime comes from but the real date works fine so
+         * I'm using it unless user asked for a fixed time (probably just so he
+         * gets repeatable output).
+         */
+
+        uint32_t const stdTime = 3510939142U;
+
+        uint32_t const hdrDt =
+            wantFixedTime ? stdTime : (uint32_t)time(NULL) + unixepoch;
+
+        pdbHeadP->ctime = pdbHeadP->mtime = hdrDt;
+    }
+    MEMSCPY(&pdbHeadP->type, IPDB_vIMG);
+    MEMSCPY(&pdbHeadP->id,   IPDB_View);
+}
+
+
+
 static int
 pdbheadWrite(PDBHEAD * const pdbheadP,
              FILE *    const fileP) {
@@ -232,7 +272,7 @@ imageWrite(IMAGE *   const imgP,
 static int
 textWrite(TEXT * const textP,
           FILE * const fileP) {
-    
+
     if (textP)
         fwrite(textP->data, 1, strlen(textP->data), fileP);
 
@@ -249,9 +289,9 @@ compressIfRequired(IPDB *     const pdbP,
 
     if (comp == IPDB_NOCOMPRESS) {
         *compressedDataP = pdbP->i->data;
-        *compressedSizeP = ipdb_img_size(pdbP->i);
+        *compressedSizeP = ipdb_imgSize(pdbP->i);
     } else {
-        int const uncompressedSz = ipdb_img_size(pdbP->i);
+        int const uncompressedSz = ipdb_imgSize(pdbP->i);
 
         unsigned char * outbuf;
         size_t          compressedSz;
@@ -303,7 +343,7 @@ ipdbWrite(IPDB * const pdbP,
     rc = pdbheadWrite(pdbP->p, fileP);
     if (rc != 0)
         pm_error("Failed to write PDB header.  %s", ipdb_err(rc));
-            
+
     rc = rechdrWrite(irP, fileP);
     if (rc != 0)
         pm_error("Failed to write image record header.  %s", ipdb_err(rc));
@@ -475,7 +515,7 @@ imageInsertInit(IPDB * const pdbP,
                      ipdb_typeName(type), MAX_SIZE(type));
         else {
             pdbP->i =
-                ipdb_image_alloc(name, type, adjustedWidth, adjustedHeight);
+                ipdb_imageCreate(name, type, adjustedWidth, adjustedHeight);
             if (pdbP->i == NULL)
                 pm_message("Could not get memory for %u x %u image",
                            adjustedWidth, adjustedHeight);
@@ -513,7 +553,7 @@ insertG16image(IPDB *          const pdbP,
         /* Pad with white on the bottom */
         for (; row < ipdb_height(pdbP); ++row)
             memset(outP, 0, rowSize);
-    } 
+    }
 }
 
 
@@ -544,7 +584,7 @@ insertGimage(IPDB *          const pdbP,
         /* Pad with white on the bottom */
         for (; row < ipdb_height(pdbP); ++row)
             memset(outP, 0, rowSize);
-    } 
+    }
 }
 
 
@@ -575,14 +615,14 @@ insertMimage(IPDB *          const pdbP,
         /* Pad with white on the bottom */
         for (; row < ipdb_height(pdbP); ++row)
             memset(outP, 0, rowSize);
-    } 
+    }
 }
 
 
 
 static int
 insertText(IPDB *       const pdbP,
-           const char * const s) {
+           const char * const content) {
 
     int retval;
 
@@ -591,17 +631,23 @@ insertText(IPDB *       const pdbP,
     else if (pdbP->p->num_recs == 2)
         retval = E_TEXTTHERE;
     else {
-        pdbP->t = ipdb_text_alloc(s);
+        pdbP->t = ipdb_textAlloc();
         if (pdbP->t == NULL)
             retval = ENOMEM;
         else {
-            pdbP->p->num_recs = 2;
+            pdbP->t->data = strdup(content);
 
-            pdbP->i->r->offset += 8;
-            pdbP->t->r->offset =
-                pdbP->i->r->offset + IMAGESIZE + ipdb_img_size(pdbP->i);
+            if (pdbP->t->data == NULL)
+                retval = ENOMEM;
+            else {
+                pdbP->p->num_recs = 2;
 
-            retval = 0;
+                pdbP->i->r->offset += 8;
+                pdbP->t->r->offset =
+                    pdbP->i->r->offset + IMAGESIZE + ipdb_imgSize(pdbP->i);
+
+                retval = 0;
+            }
         }
     }
     return retval;
@@ -689,7 +735,7 @@ readtxt(IPDB *       const pdbP,
 int
 main(int argc, const char **argv) {
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     IPDB * pdbP;
     FILE * ifP;
     int comp;
@@ -709,11 +755,13 @@ main(int argc, const char **argv) {
     if (strlen(cmdline.title) > 31)
         pm_error("Title too long.  Max length is 31 characters.");
 
-    pdbP = ipdb_alloc(cmdline.title);
+    pdbP = ipdb_alloc();
 
     if (pdbP == NULL)
         pm_error("Failed to allocate IPDB structure");
 
+    setPdbHeader(pdbP->p, cmdline.title, cmdline.fixedtime);
+
     readimg(pdbP, ifP, cmdline.depth4);
 
     if (cmdline.notefile)
@@ -730,3 +778,6 @@ main(int argc, const char **argv) {
 
     return EXIT_SUCCESS;
 }
+
+
+
diff --git a/converter/other/pamtopng.c b/converter/other/pamtopng.c
index 3164bc29..088db3c8 100644
--- a/converter/other/pamtopng.c
+++ b/converter/other/pamtopng.c
@@ -16,7 +16,7 @@
     had become rather complex.  This program is roughly 1/3 the size of
     pnmtopng.c that it replaces.
 
-  - In 1995, bandwith was limited and therefore filesize had to be kept
+  - In 1995, bandwid was limited and therefore filesize had to be kept
     small. The original program tried to optimize for that by applying
     many "clever tricks". Today that isn't an issue anymore, so gone
     are filters, palettes, etc. Also, image conversions were removed,
@@ -251,7 +251,7 @@ colorTypeFromInputType(const struct pam * const pamP) {
 -----------------------------------------------------------------------------*/
     png_byte retval;
 
-    if (pamP->depth < 1 && pamP->depth > 4)
+    if (pamP->depth < 1 || pamP->depth > 4)
         pm_error ("Number of color planes must be between 1 and 4 inclusive");
 
     if (pamP->maxval != 1 && pamP->maxval != 3 && pamP->maxval != 15 &&
@@ -278,7 +278,7 @@ colorTypeFromInputType(const struct pam * const pamP) {
             retval = PNG_COLOR_TYPE_GRAY_ALPHA;
         else
             pm_error("Input tuple type is GRAYSCALE_ALPHA, "
-                     "but number of planes is %u instread of 2",
+                     "but number of planes is %u instead of 2",
                      pamP->depth);
     } else if (strneq(pamP->tuple_type, "GRAYSCALE", 9)) {
         if (pamP->depth == 1)
@@ -932,7 +932,7 @@ pamtopng(FILE *             const ifP,
 
     if (cmdline.interlace) {
         /* Libpng will expect us to provide pixels in interlaced sequence
-           if we write row-by-row, and that is much to difficult, so we
+           if we write row-by-row, and that is much too difficult, so we
            do whole-image-at-once and let Libpng do the work.
         */
         writeRasterWholeImg(&pam, pngxP, pnmBitDepth);
diff --git a/converter/other/pamtoqoi.c b/converter/other/pamtoqoi.c
new file mode 100644
index 00000000..638efa3a
--- /dev/null
+++ b/converter/other/pamtoqoi.c
@@ -0,0 +1,439 @@
+/*
+  pamtoqoi -  Converts PAM to a QOI - The "Quite OK Image" format file
+
+  This program is part of Netpbm.
+
+  ---------------------------------------------------------------------
+
+  QOI - The "Quite OK Image" format for fast, lossless image compression
+
+  Encoder by Dominic Szablewski - https://phoboslab.org
+
+  -- LICENSE: The MIT License(MIT)
+
+  Copyright(c) 2021 Dominic Szablewski
+
+  Permission is hereby granted, free of charge, to any person obtaining a copy
+  of this software and associated documentation files(the "Software"), to deal
+  in the Software without restriction, including without limitation the rights
+  to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
+  copies of the Software, and to permit persons to whom the Software is
+  furnished to do so, subject to the following conditions :
+
+  The above copyright notice and this permission notice shall be included in
+  all copies or substantial portions of the Software.
+
+  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
+  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+  SOFTWARE.
+
+  For more information on the format visit: https//qoiformat.org/ .
+
+  Modifications for Netpbm read routines by Akira F. Urushibata.
+
+*/
+
+#include <string.h>
+#include <assert.h>
+#include "pam.h"
+#include "nstring.h"
+#include "mallocvar.h"
+#include "shhopt.h"
+
+#include "qoi.h"
+
+
+
+struct CmdlineInfo {
+    /* All the information the user supplied in the command line,
+       in a form easy for the program to use.
+    */
+    const char * inputFileName;  /* '-' if stdin */
+};
+
+
+
+static void
+parseCommandLine(int                  argc,
+                 const char **        argv,
+                 struct CmdlineInfo * cmdlineP ) {
+/*----------------------------------------------------------------------------
+   Parse program command line described in Unix standard form by argc
+   and argv.  Return the information in the options as *cmdlineP.
+
+   If command line is internally inconsistent (invalid options, etc.),
+   issue error message to stderr and abort program.
+
+   Note that the strings we return are stored in the storage that
+   was passed to us as the argv array.  We also trash *argv.
+-----------------------------------------------------------------------------*/
+    optEntry * option_def;
+        /* Instructions to pm_optParseOptions3 on how to parse our options.
+         */
+    optStruct3 opt;
+
+    unsigned int option_def_index;
+
+    MALLOCARRAY(option_def, 100);
+
+    OPTENTINIT;
+
+    opt.opt_table = option_def;
+    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
+
+    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+        /* Uses and sets argc, argv, and some of *cmdlineP and others. */
+
+    if (argc-1 < 1)
+        cmdlineP->inputFileName = "-";
+    else if (argc-1 == 1)
+        cmdlineP->inputFileName = argv[1];
+    else
+        pm_error("Program takes at most one argument: input file name.  "
+            "you specified %d", argc-1);
+}
+
+
+
+static void
+encodeQoiHeader(qoi_Desc const qoiDesc) {
+
+    assert (QOI_MAGIC_SIZE + 4 + 4 + 1 + 1 == QOI_HEADER_SIZE);
+
+    fwrite (qoi_magic, QOI_MAGIC_SIZE, 1, stdout);
+    pm_writebiglongu(stdout, qoiDesc.width);
+    pm_writebiglongu(stdout, qoiDesc.height);
+    putchar(qoiDesc.channelCt);
+    putchar(qoiDesc.colorspace);
+
+}
+
+enum Tupletype {BW, BWAlpha, GRAY, GRAYAlpha, RGB, RGBAlpha,
+                GRAY255, GRAY255Alpha, RGB255, RGB255Alpha};
+
+
+
+static void
+createSampleMap(sample    const oldMaxval,
+                sample ** const sampleMapP) {
+
+    unsigned int i;
+    sample * sampleMap;
+    sample   const newMaxval = 255;
+
+    MALLOCARRAY_NOFAIL(sampleMap, oldMaxval+1);
+
+    for (i = 0; i <= oldMaxval; ++i)
+        sampleMap[i] = ROUNDDIV(i * newMaxval, oldMaxval);
+
+    *sampleMapP = sampleMap;
+}
+
+
+
+static enum Tupletype
+tupleTypeFmPam(const char * const pamTupleType,
+               sample       const maxval) {
+
+    enum Tupletype retval;
+
+    if (streq(pamTupleType, PAM_PBM_TUPLETYPE)) {
+        if (maxval !=1)
+            pm_error("Invalid maxval (%lu) for tuple type '%s'.",
+                     maxval, pamTupleType);
+        else
+            retval =  BW;
+    } else if (streq(pamTupleType, PAM_PBM_ALPHA_TUPLETYPE)) {
+      if (maxval !=1)
+          pm_error("Invalid maxval (%lu) for tuple type '%s'.",
+                    maxval, pamTupleType);
+      else
+          retval =  BWAlpha;
+    } else if (maxval == 255) {
+        if (streq(pamTupleType, PAM_PPM_TUPLETYPE))
+            retval =  RGB255;
+        else if(streq(pamTupleType, PAM_PPM_ALPHA_TUPLETYPE))
+            retval =  RGB255Alpha;
+        else if(streq(pamTupleType, PAM_PGM_TUPLETYPE))
+            retval =  GRAY255;
+        else if(streq(pamTupleType, PAM_PGM_ALPHA_TUPLETYPE))
+            retval =  GRAY255Alpha;
+        else
+            pm_error("Don't know how to convert tuple type '%s'.",
+                     pamTupleType);
+    } else {
+        if (streq(pamTupleType, PAM_PPM_TUPLETYPE))
+            retval =  RGB;
+        else if(streq(pamTupleType, PAM_PPM_ALPHA_TUPLETYPE))
+            retval =  RGBAlpha;
+        else if(streq(pamTupleType, PAM_PGM_TUPLETYPE))
+            retval =  GRAY;
+        else if(streq(pamTupleType, PAM_PGM_ALPHA_TUPLETYPE))
+            retval =  GRAYAlpha;
+        else
+            pm_error("Don't know how to convert tuple type '%s'.",
+                     pamTupleType);
+    }
+
+    return retval;
+}
+
+
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wreturn-type"
+
+static unsigned int
+channelCtFmTupleType(enum Tupletype const tupleType) {
+
+    switch (tupleType) {
+        case RGB:
+          return 3;
+        case RGB255:
+          return 3;
+        case RGBAlpha:
+          return 4;
+        case RGB255Alpha:
+          return 4;
+        case BW:
+        case GRAY:
+          return 3;
+        case GRAY255:
+          return 3;
+        case BWAlpha:
+        case GRAYAlpha:
+          return 4;
+        case GRAY255Alpha:
+          return 4;
+    }
+}
+#pragma GCC diagnostic pop
+
+
+
+static qoi_Rgba
+pxFmTuple(tuple          const tuple0,
+          const sample * const sampleMap,
+          enum Tupletype const tupleType) {
+/*----------------------------------------------------------------------------
+   Convert PAM tuple to qoi rgba pixel struct
+-----------------------------------------------------------------------------*/
+    qoi_Rgba px;
+
+    switch (tupleType) {
+    case RGB:
+        px.rgba.r = sampleMap[tuple0[PAM_RED_PLANE]];
+        px.rgba.g = sampleMap[tuple0[PAM_GRN_PLANE]];
+        px.rgba.b = sampleMap[tuple0[PAM_BLU_PLANE]];
+        px.rgba.a = 255;
+        break;
+    case RGB255:
+        px.rgba.r = tuple0[PAM_RED_PLANE];
+        px.rgba.g = tuple0[PAM_GRN_PLANE];
+        px.rgba.b = tuple0[PAM_BLU_PLANE];
+        px.rgba.a = 255;
+        break;
+    case RGBAlpha:
+        px.rgba.r = sampleMap[tuple0[PAM_RED_PLANE]];
+        px.rgba.g = sampleMap[tuple0[PAM_GRN_PLANE]];
+        px.rgba.b = sampleMap[tuple0[PAM_BLU_PLANE]];
+        px.rgba.a = sampleMap[tuple0[PAM_TRN_PLANE]];
+        break;
+    case RGB255Alpha:
+        px.rgba.r = tuple0[PAM_RED_PLANE];
+        px.rgba.g = tuple0[PAM_GRN_PLANE];
+        px.rgba.b = tuple0[PAM_BLU_PLANE];
+        px.rgba.a = tuple0[PAM_TRN_PLANE];
+        break;
+    case BW:
+    case GRAY : {
+        unsigned char const qoiSample = sampleMap[tuple0[0]];
+        px.rgba.r = qoiSample;
+        px.rgba.g = qoiSample;
+        px.rgba.b = qoiSample;
+        px.rgba.a = 255;
+    } break;
+    case GRAY255: {
+        unsigned char const qoiSample = tuple0[0];
+        px.rgba.r = qoiSample;
+        px.rgba.g = qoiSample;
+        px.rgba.b = qoiSample;
+        px.rgba.a = 255;
+    } break;
+    case BWAlpha:
+    case GRAYAlpha: {
+        unsigned char const qoiSample = sampleMap[tuple0[0]];
+        px.rgba.r = qoiSample;
+        px.rgba.g = qoiSample;
+        px.rgba.b = qoiSample;
+        px.rgba.a = sampleMap[tuple0[PAM_GRAY_TRN_PLANE]];
+    } break;
+    case GRAY255Alpha: {
+        unsigned char const qoiSample = tuple0[0];
+        px.rgba.r = qoiSample;
+        px.rgba.g = qoiSample;
+        px.rgba.b = qoiSample;
+        px.rgba.a = tuple0[PAM_GRAY_TRN_PLANE];
+    } break;
+    }
+
+    return px;
+}
+
+
+
+static void
+encodeNewPixel(qoi_Rgba const px,
+               qoi_Rgba const pxPrev) {
+
+    if (px.rgba.a == pxPrev.rgba.a) {
+        signed char const vr = px.rgba.r - pxPrev.rgba.r;
+        signed char const vg = px.rgba.g - pxPrev.rgba.g;
+        signed char const vb = px.rgba.b - pxPrev.rgba.b;
+
+        signed char const vgR = vr - vg;
+        signed char const vgB = vb - vg;
+
+        if (
+            vr > -3 && vr < 2 &&
+            vg > -3 && vg < 2 &&
+            vb > -3 && vb < 2
+            ) {
+            putchar(QOI_OP_DIFF |
+                    (vr + 2) << 4 | (vg + 2) << 2 | (vb + 2));
+        } else if (
+            vgR >  -9 && vgR <  8 &&
+            vg  > -33 && vg  < 32 &&
+            vgB >  -9 && vgB <  8
+            ) {
+            putchar(QOI_OP_LUMA    | (vg   + 32));
+            putchar((vgR + 8) << 4 | (vgB +  8));
+        } else {
+            putchar(QOI_OP_RGB);
+            putchar(px.rgba.r);
+            putchar(px.rgba.g);
+            putchar(px.rgba.b);
+        }
+    } else {
+        putchar(QOI_OP_RGBA);
+        putchar(px.rgba.r);
+        putchar(px.rgba.g);
+        putchar(px.rgba.b);
+        putchar(px.rgba.a);
+    }
+}
+
+
+
+static void
+qoiEncode(FILE           * const ifP,
+          struct pam     * const inpamP) {
+
+    tuple * tuplerow;
+    unsigned int row;
+
+    qoi_Rgba index[QOI_INDEX_SIZE];
+    qoi_Rgba pxPrev;
+    unsigned int run;
+    sample * sampleMap;
+    qoi_Desc qoiDesc;
+
+    enum Tupletype const tupleType =
+      tupleTypeFmPam(inpamP->tuple_type, inpamP->maxval);
+
+    if (inpamP->height > QOI_PIXELS_MAX / inpamP->width)
+        pm_error("Too many pixels for QOI: %u x %u (max is %u)",
+                 inpamP->height, inpamP->width, QOI_PIXELS_MAX);
+
+    qoiDesc.colorspace = QOI_SRGB;
+    qoiDesc.width      = inpamP->width;
+    qoiDesc.height     = inpamP->height;
+    qoiDesc.channelCt  = channelCtFmTupleType(tupleType);
+
+    encodeQoiHeader(qoiDesc);
+
+    tuplerow = pnm_allocpamrow(inpamP);
+
+    if (inpamP->maxval != 255)
+        createSampleMap(inpamP->maxval, &sampleMap);
+
+    qoi_clearQoiIndex(index);
+
+    pxPrev.rgba.r = 0;
+    pxPrev.rgba.g = 0;
+    pxPrev.rgba.b = 0;
+    pxPrev.rgba.a = 255;
+
+    /* Read and convert rows. */
+    for (row = 0, run = 0; row < inpamP->height; ++row) {
+        unsigned int col;
+
+        pnm_readpamrow(inpamP, tuplerow);
+
+        for (col = 0; col < inpamP->width; ++col) {
+            qoi_Rgba const px = pxFmTuple(tuplerow[col], sampleMap, tupleType);
+
+            if (px.v == pxPrev.v) {
+                ++run;
+                if (run == 62) {
+                    putchar(QOI_OP_RUN | (run - 1));
+                    run = 0;
+                }
+            } else {
+                unsigned int const indexPos = qoi_colorHash(px);
+
+                if (run > 0) {
+                    putchar(QOI_OP_RUN | (run - 1));
+                    run = 0;
+                }
+
+                if (index[indexPos].v == px.v) {
+                    putchar(QOI_OP_INDEX | indexPos);
+
+                } else {
+                    index[indexPos] = px;
+                    encodeNewPixel(px, pxPrev);
+                }
+            }
+            pxPrev = px;
+        }
+    }
+
+    if (run > 0)
+        putchar(QOI_OP_RUN | (run - 1));
+
+    fwrite(qoi_padding, sizeof(qoi_padding), 1, stdout);
+
+    if (inpamP->maxval != 255)
+        free(sampleMap);
+    pnm_freepamrow(tuplerow);
+}
+
+
+
+int
+main(int argc, const char **argv) {
+
+    struct CmdlineInfo cmdline;
+    struct pam inpam;
+    FILE * ifP;
+
+    pm_proginit(&argc, argv);
+
+    parseCommandLine(argc, argv, &cmdline);
+
+    ifP = pm_openr(cmdline.inputFileName);
+
+    pnm_readpaminit(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));
+
+    qoiEncode(ifP, &inpam);
+
+    return 0;
+}
+
+
diff --git a/converter/other/pamtosvg/fit.c b/converter/other/pamtosvg/fit.c
index 5ba7a2f6..179b3bdf 100644
--- a/converter/other/pamtosvg/fit.c
+++ b/converter/other/pamtosvg/fit.c
@@ -67,7 +67,7 @@ real_to_int_coord(float_coord const real_coord) {
 
     int_coord.col = ROUND(real_coord.x);
     int_coord.row = ROUND(real_coord.y);
-    
+
     return int_coord;
 }
 
@@ -152,7 +152,7 @@ find_vectors(unsigned int       const test_index,
 
     in->dx  = in->dy  = in->dz  = 0.0;
     out->dx = out->dy = out->dz = 0.0;
-    
+
     /* Add up the differences from p of the `corner_surround' points
        before p.
     */
@@ -160,7 +160,7 @@ find_vectors(unsigned int       const test_index,
          n_done < corner_surround;
          i = O_PREV(outline, i), ++n_done)
         *in = Vadd(*in, IPsubtract(O_COORDINATE(outline, i), candidate));
-    
+
     /* And the points after p. */
     for (i = O_NEXT (outline, test_index), n_done = 0;
          n_done < corner_surround;
@@ -207,19 +207,19 @@ lookAheadForBetterCorner(pixel_outline_type  const outline,
 
     bestCornerIndex = basePixelSeq;     /* initial assumption */
     bestCornerAngle = baseCornerAngle;    /* initial assumption */
-    
+
     equallyGoodList = new_index_list();
-    
+
     q = basePixelSeq;
     i = basePixelSeq + 1;  /* Start with the next pixel */
-    
+
     while (i < bestCornerIndex + cornerSurround &&
            i < O_LENGTH(outline) &&
            !at_exception_got_fatal(exceptionP)) {
 
         vector_type inVector, outVector;
         float cornerAngle;
-        
+
         /* Check the angle.  */
 
         q = i % O_LENGTH(outline);
@@ -446,7 +446,7 @@ filter(curve *             const curveP,
 
     unsigned int iteration, thisPoint;
     float_coord prevNewPoint;
-    
+
     /* We must have at least three points -- the previous one, the current
        one, and the next one.  But if we don't have at least five, we will
        probably collapse the curve down onto a single point, which means
@@ -460,26 +460,26 @@ filter(curve *             const curveP,
     prevNewPoint.x = FLT_MAX;
     prevNewPoint.y = FLT_MAX;
     prevNewPoint.z = FLT_MAX;
-    
+
     for (iteration = 0;
          iteration < fittingOptsP->filter_iterations;
          ++iteration) {
         curve * const newcurveP = copy_most_of_curve(curveP);
 
         bool collapsed;
-        
+
         collapsed = false;  /* initial value */
 
         /* Keep the first point on the curve.  */
         if (offset)
             append_point(newcurveP, CURVE_POINT(curveP, 0));
-        
+
         for (thisPoint = offset;
              thisPoint < CURVE_LENGTH(curveP) - offset;
              ++thisPoint) {
             vector_type in, out, sum;
             float_coord newPoint;
-            
+
             /* Calculate the vectors in and out, computed by looking
                at n points on either side of this_point.  Experimental
                it was found that 2 is optimal.
@@ -488,12 +488,12 @@ filter(curve *             const curveP,
             signed int prev, prevprev; /* have to be signed */
             unsigned int next, nextnext;
             float_coord candidate = CURVE_POINT(curveP, thisPoint);
-            
+
             prev = CURVE_PREV(curveP, thisPoint);
             prevprev = CURVE_PREV(curveP, prev);
             next = CURVE_NEXT(curveP, thisPoint);
             nextnext = CURVE_NEXT(curveP, next);
-            
+
             /* Add up the differences from p of the `surround' points
                before p.
             */
@@ -503,18 +503,18 @@ filter(curve *             const curveP,
             if (prevprev >= 0)
                 in = Vadd(in,
                           Psubtract(CURVE_POINT(curveP, prevprev), candidate));
-            
+
             /* And the points after p.  Don't use more points after p than we
                ended up with before it.
             */
             out.dx = out.dy = out.dz = 0.0;
-            
+
             out = Vadd(out, Psubtract(CURVE_POINT(curveP, next), candidate));
             if (nextnext < CURVE_LENGTH(curveP))
                 out = Vadd(out,
                            Psubtract(CURVE_POINT(curveP, nextnext),
                                      candidate));
-            
+
             /* Start with the old point.  */
             newPoint = candidate;
             sum = Vadd(in, out);
@@ -528,13 +528,13 @@ filter(curve *             const curveP,
                 collapsed = true;
                 break;
             }
-            
+
             /* Put the newly computed point into a separate curve, so it
                doesn't affect future computation (on this iteration).
             */
             append_point(newcurveP, prevNewPoint = newPoint);
         }
-        
+
         if (collapsed)
             free_curve(newcurveP);
         else {
@@ -543,7 +543,7 @@ filter(curve *             const curveP,
             */
             if (offset)
                 append_point(newcurveP, LAST_CURVE_POINT(curveP));
-            
+
             /* Set the original curve to the newly filtered one, and go
                again.
             */
@@ -560,7 +560,7 @@ removeAdjacent(index_list_type *   const cornerListP,
                pixel_outline_type  const outline,
                fitting_opts_type * const fittingOptsP,
                at_exception_type * const exception) {
-               
+
     /* We never want two corners next to each other, since the
        only way to fit such a ``curve'' would be with a straight
        line, which usually interrupts the continuity dreadfully.
@@ -598,7 +598,7 @@ find_corners(pixel_outline_type  const outline,
 
     establishCornerSearchLimits(outline, fittingOptsP,
                                 &firstPixelSeq, &lastPixelSeq);
-    
+
     /* Consider each pixel on the outline in turn.  */
     for (p = firstPixelSeq; p <= lastPixelSeq;) {
         vector_type inVector, outVector;
@@ -655,10 +655,10 @@ find_corners(pixel_outline_type  const outline,
                 && bestCornerIndex >= p) {
 
                 unsigned int j;
-                
+
                 appendCorner(&cornerList, bestCornerIndex,
                              outline, bestCornerAngle, '/');
-                
+
                 for (j = 0; j < INDEX_LIST_LENGTH (equallyGoodList); ++j)
                     appendCorner(&cornerList, GET_INDEX(equallyGoodList, j),
                                  outline, bestCornerAngle, '@');
@@ -675,7 +675,7 @@ find_corners(pixel_outline_type  const outline,
     }
     removeAdjacent(&cornerList, outline, fittingOptsP, exceptionP);
 
-cleanup:  
+cleanup:
     return cornerList;
 }
 
@@ -696,12 +696,12 @@ makeOutlineOneCurve(pixel_outline_type const outline,
 
     for (pixelSeq = 0; pixelSeq < O_LENGTH(outline); ++pixelSeq)
         append_pixel(curveP, O_COORDINATE(outline, pixelSeq));
-    
+
     if (outline.open)
         CURVE_CYCLIC(curveP) = false;
     else
         CURVE_CYCLIC(curveP) = true;
-    
+
     /* Make it a one-curve cycle */
     NEXT_CURVE(curveP)     = curveP;
     PREVIOUS_CURVE(curveP) = curveP;
@@ -728,23 +728,23 @@ addCurveStartingAtCorner(pixel_outline_type const outline,
    Don't include beginning and ending slope information for that curve.
 -----------------------------------------------------------------------------*/
     unsigned int const cornerPixelSeq = GET_INDEX(cornerList, cornerSeq);
-    
+
     unsigned int lastPixelSeq;
     curve * curveP;
     unsigned int pixelSeq;
-    
+
     if (cornerSeq + 1 >= cornerList.length)
         /* No more corners, so we go through the end of the outline. */
         lastPixelSeq = O_LENGTH(outline) - 1;
     else
         /* Go through the next corner */
         lastPixelSeq = GET_INDEX(cornerList, cornerSeq + 1);
-    
+
     curveP = new_curve();
 
     for (pixelSeq = cornerPixelSeq; pixelSeq <= lastPixelSeq; ++pixelSeq)
         append_pixel(curveP, O_COORDINATE(outline, pixelSeq));
-    
+
     append_curve(curveListP, curveP);
     {
         /* Add the new curve to the outline chain */
@@ -803,7 +803,7 @@ divideOutlineWithCorners(pixel_outline_type const outline,
         */
         curve * curveP;
         unsigned int pixelSeq;
-        
+
         curveP = new_curve();
 
         for (pixelSeq = 0; pixelSeq <= GET_INDEX(cornerList, 0); ++pixelSeq)
@@ -897,7 +897,7 @@ split_at_corners(pixel_outline_list_type const pixel_list,
         curve_list.open  = outline.open;
 
         LOG1("#%u:", outlineSeq);
-        
+
         /* If the outline does not have enough points, we can't do
            anything.  The endpoints of the outlines are automatically
            corners.  We need at least `corner_surround' more pixels on
@@ -926,7 +926,7 @@ split_at_corners(pixel_outline_list_type const pixel_list,
             makeOutlineOneCurve(outline, &curve_list);
         else
             divideOutlineWithCorners(outline, corner_list, &curve_list);
-        
+
         LOG1(" [%u].\n", corner_list.length);
         free_index_list(&corner_list);
 
@@ -947,7 +947,7 @@ removeKnees(curve_list_type const curveList) {
   removing a point that should be a corner.
 -----------------------------------------------------------------------------*/
     unsigned int curveSeq;
-    
+
     LOG("\nRemoving knees:\n");
     for (curveSeq = 0; curveSeq < curveList.length; ++curveSeq) {
         LOG1("#%u:", curveSeq);
@@ -955,7 +955,7 @@ removeKnees(curve_list_type const curveList) {
                            CURVE_LIST_CLOCKWISE(curveList));
     }
 }
-    
+
 
 
 static void
@@ -966,7 +966,7 @@ computePointWeights(curve_list_type     const curveList,
     unsigned int const height = distP->height;
 
     unsigned int curveSeq;
-    
+
     for (curveSeq = 0; curveSeq < curveList.length; ++curveSeq) {
         unsigned pointSeq;
         curve_type const curve = CURVE_LIST_ELT(curveList, curveSeq);
@@ -974,13 +974,13 @@ computePointWeights(curve_list_type     const curveList,
             float_coord * const coordP = &CURVE_POINT(curve, pointSeq);
             unsigned int x = coordP->x;
             unsigned int y = height - (unsigned int)coordP->y - 1;
-            
+
             float width, w;
 
             /* Each (x, y) is a point on the skeleton of the curve, which
                might be offset from the true centerline, where the width
                is maximal.  Therefore, use as the local line width the
-               maximum distance over the neighborhood of (x, y). 
+               maximum distance over the neighborhood of (x, y).
             */
             width = distP->d[y][x];  /* initial value */
             if (y - 1 >= 0) {
@@ -1017,7 +1017,7 @@ computePointWeights(curve_list_type     const curveList,
 static void
 filterCurves(curve_list_type     const curveList,
              fitting_opts_type * const fittingOptsP) {
-             
+
     unsigned int curveSeq;
 
     LOG("\nFiltering curves:\n");
@@ -1044,8 +1044,8 @@ logSplinesForCurve(unsigned int     const curveSeq,
         if (log_file)
             print_spline(log_file, SPLINE_LIST_ELT(curveSplines, splineSeq));
     }
-}     
-       
+}
+
 
 
 static void
@@ -1212,7 +1212,7 @@ fitWithLine(curve * const curveP) {
 #define B3(t) CUBE (t)
 
 static spline_type
-fitOneSpline(curve *             const curveP, 
+fitOneSpline(curve *             const curveP,
              vector_type         const begSlope,
              vector_type         const endSlope,
              at_exception_type * const exceptionP) {
@@ -1311,7 +1311,7 @@ fitOneSpline(curve *             const curveP,
     free(A);
 
     C.end.beg = C.beg.end;
-    
+
     X_Cend_det  = X.beg * C.end.end - X.end * C.beg.end;
     Cbeg_X_det  = C.beg.beg * X.end - C.beg.end * X.beg;
     C_det = C.beg.beg * C.end.end - C.end.beg * C.beg.end;
@@ -1328,7 +1328,7 @@ fitOneSpline(curve *             const curveP,
         CONTROL2(spline) = Vadd_point(END_POINT(spline),
                                       Vmult_scalar(tang.end, alpha.end));
         SPLINE_DEGREE(spline) = CUBICTYPE;
-    }        
+    }
     return spline;
 }
 
@@ -1341,7 +1341,7 @@ logSplineFit(spline_type const spline) {
         LOG("  fitted to line:\n");
     else
         LOG("  fitted to spline:\n");
-    
+
     if (log_file) {
         LOG ("    ");
         print_spline (log_file, spline);
@@ -1458,7 +1458,7 @@ findTangent(curve *       const curveP,
   means the previous curve in the outline chain for the slope at the
   start point ('toStartPoint' == true), the next curve otherwise.
   If *curveP is cyclic, then it is its own adjacent curve.
-  
+
   It is important to compute an accurate approximation, because the
   control points that we eventually decide upon to fit the curve will
   be placed on the half-lines defined by the slopes and endpoints, and
@@ -1478,7 +1478,7 @@ findTangent(curve *       const curveP,
             vector_type const slopeAdj =
                 findHalfTangent(!toStartPoint, adjacentCurveP,
                                 tangentSurround);
-               
+
             LOG3("(adjacent curve half tangent (%.3f,%.3f,%.3f)) ",
                  slopeAdj.dx, slopeAdj.dy, slopeAdj.dz);
             slope = Vmult_scalar(Vadd(slope, slopeAdj), 0.5);
@@ -1487,7 +1487,7 @@ findTangent(curve *       const curveP,
     } while (slope.dx == 0.0 && slope.dy == 0.0);
 
     *tangentP = slope;
-    
+
     LOG3("(%.3f,%.3f,%.3f).\n",
          tangentP->dx, tangentP->dy, tangentP->dz);
 }
@@ -1502,8 +1502,8 @@ findError(curve *             const curveP,
           at_exception_type * const exceptionP) {
 /*----------------------------------------------------------------------------
   Tell how good a fit 'spline' is for *curveP.
-  
-  Return the error (maximum Euclidian distance between a point on
+
+  Return the error (maximum Euclidean distance between a point on
   *curveP and the corresponding point on 'spline') as *errorP and the
   sequence number of the point on the curve where the error is
   greatest as *worstPointP.
@@ -1521,7 +1521,7 @@ findError(curve *             const curveP,
     totalError = 0.0;  /* initial value */
     worstError = FLT_MIN; /* initial value */
     worstPoint = 0;
-        
+
     for (thisPoint = 0; thisPoint < CURVE_LENGTH(curveP); ++thisPoint) {
         float_coord const curvePoint = CURVE_POINT(curveP, thisPoint);
         float const t = CURVE_T(curveP, thisPoint);
@@ -1608,7 +1608,7 @@ subdivideCurve(curve *                   const curveP,
   Split curve *curveP into two, at 'subdivisionIndex'.  (Actually,
   leave *curveP alone, but return as *leftCurvePP and *rghtCurvePP
   two new curves that are the pieces).
-  
+
   Return as *joinSlopeP what should be the slope where the subcurves
   join, i.e. the slope of the end of the left subcurve and of the start
   of the right subcurve.
@@ -1670,7 +1670,7 @@ leftRightConcat(const spline_list_type *  const leftSplineListP,
    of splines to that side of the curve.
 -----------------------------------------------------------------------------*/
     spline_list_type * retval;
-                
+
     retval = new_spline_list();
 
     if (leftSplineListP == NULL) {
@@ -1678,7 +1678,7 @@ leftRightConcat(const spline_list_type *  const leftSplineListP,
         at_exception_warning(exceptionP, "Could not fit left spline list");
     } else
         concat_spline_lists(retval, *leftSplineListP);
-    
+
     if (rghtSplineListP == NULL) {
         LOG("Could not fit spline to right curve.\n");
         at_exception_warning(exceptionP, "Could not fit right spline list");
@@ -1742,7 +1742,7 @@ divideAndFit(curve *                   const curveP,
            subcurve.
         */
     spline_list_type * leftSplineListP;
-    
+
     assert(subdivisionIndex > 1);
     assert(subdivisionIndex < CURVE_LENGTH(curveP)-1);
     subdivideCurve(curveP, subdivisionIndex, fittingOptsP,
@@ -1792,18 +1792,18 @@ fitWithLeastSquares(curve *                   const curveP,
 /*----------------------------------------------------------------------------
   The least squares method is well described in Schneider's thesis.
   Briefly, we try to fit the entire curve with one spline.  If that
-  fails, we subdivide the curve. 
+  fails, we subdivide the curve.
 -----------------------------------------------------------------------------*/
     spline_list_type * retval;
     spline_type spline;
-    
+
     LOG("\nFitting with least squares:\n");
-    
+
     /* Phoenix reduces the number of points with a "linear spline
        technique."  But for fitting letterforms, that is
        inappropriate.  We want all the points we can get.
     */
-    
+
     setInitialParameterValues(curveP);
 
     if (CURVE_CYCLIC(curveP) && CURVE_LENGTH(curveP) < 4) {
@@ -1822,7 +1822,7 @@ fitWithLeastSquares(curve *                   const curveP,
         unsigned int worstPoint;
 
         logSplineFit(spline);
-        
+
         findError(curveP, spline, &error, &worstPoint, exceptionP);
         assert(worstPoint < CURVE_LENGTH(curveP));
 
@@ -1873,7 +1873,7 @@ fitCurve(curve *                   const curveP,
 
     if (CURVE_LENGTH(curveP) < 2) {
         LOG("Tried to fit curve with fewer than two points");
-        at_exception_warning(exceptionP, 
+        at_exception_warning(exceptionP,
                              "Tried to fit curve with less than two points");
         fittedSplinesP = NULL;
     } else if (CURVE_LENGTH(curveP) < 4)
@@ -1894,12 +1894,12 @@ fitCurves(curve_list_type           const curveList,
           const fitting_opts_type * const fittingOptsP,
           spline_list_type *        const splinesP,
           at_exception_type *       const exceptionP) {
-          
+
     spline_list_type curveListSplines;
     unsigned int curveSeq;
 
     curveListSplines = empty_spline_list();
-    
+
     curveListSplines.open      = curveList.open;
     curveListSplines.clockwise = curveList.clockwise;
     curveListSplines.color     = color;
@@ -1932,13 +1932,13 @@ fitCurves(curve_list_type           const curveList,
                 at_exception_warning(exceptionP, "Could not fit curve");
             } else {
                 logSplinesForCurve(curveSeq, *curveSplinesP);
-                
+
                 /* After fitting, we may need to change some would-be lines
                    back to curves, because they are in a list with other
                    curves.
                 */
                 change_bad_lines(curveSplinesP, fittingOptsP);
-                
+
                 concat_spline_lists(&curveListSplines, *curveSplinesP);
                 free_spline_list(*curveSplinesP);
                 free(curveSplinesP);
@@ -1950,7 +1950,7 @@ fitCurves(curve_list_type           const curveList,
     else
         *splinesP = curveListSplines;
 }
-    
+
 
 
 static void
@@ -1989,7 +1989,7 @@ fitCurveList(curve_list_type     const curveList,
 
     if (dist != NULL)
         computePointWeights(curveList, fittingOptsP, dist);
-    
+
     /* We filter all the curves in 'curveList' at once; otherwise, we
        would look at an unfiltered curve when computing tangents.
     */
@@ -2030,12 +2030,12 @@ fitCurvesToSplines(curve_list_array_type    const curveArray,
                    unsigned short           const width,
                    unsigned short           const height,
                    at_exception_type *      const exception,
-                   at_progress_func               notifyProgress, 
+                   at_progress_func               notifyProgress,
                    void *                   const progressData,
                    at_testcancel_func             testCancel,
                    void *                   const testcancelData,
                    spline_list_array_type * const splineListArrayP) {
-    
+
     unsigned splineListSeq;
     bool cancelled;
     spline_list_array_type splineListArray;
@@ -2049,7 +2049,7 @@ fitCurvesToSplines(curve_list_array_type    const curveArray,
     /* Set dummy values. Real value is set in upper context. */
     splineListArray.width  = width;
     splineListArray.height = height;
-    
+
     for (splineListSeq = 0, cancelled = false;
          splineListSeq < CURVE_LIST_ARRAY_LENGTH(curveArray) &&
              !at_exception_got_fatal(exception) && !cancelled;
@@ -2057,7 +2057,7 @@ fitCurvesToSplines(curve_list_array_type    const curveArray,
 
         curve_list_type const curveList =
             CURVE_LIST_ARRAY_ELT(curveArray, splineListSeq);
-      
+
         spline_list_type curveSplineList;
 
         if (notifyProgress)
@@ -2087,7 +2087,7 @@ fit_outlines_to_splines(pixel_outline_list_type  const pixelOutlineList,
                         unsigned short           const width,
                         unsigned short           const height,
                         at_exception_type *      const exception,
-                        at_progress_func               notifyProgress, 
+                        at_progress_func               notifyProgress,
                         void *                   const progressData,
                         at_testcancel_func             testCancel,
                         void *                   const testcancelData,
@@ -2104,7 +2104,7 @@ fit_outlines_to_splines(pixel_outline_list_type  const pixelOutlineList,
                        testCancel, testcancelData, splineListArrayP);
 
     free_curve_list_array(&curveListArray, notifyProgress, progressData);
-    
+
     flush_log_output();
 }
 
diff --git a/converter/other/pamtotiff.c b/converter/other/pamtotiff.c
index 115b8b4a..1718c933 100644
--- a/converter/other/pamtotiff.c
+++ b/converter/other/pamtotiff.c
@@ -838,7 +838,7 @@ computeRasterParm(struct pam *     const pamP,
   2. Direct mode (specified with -output)
 
      We have the Tiff library write output to the specified file.  As the Tiff
-     library requires taht it be be seekable and readable, we fail the program
+     library requires that it be be seekable and readable, we fail the program
      rather than ask the Tiff library to use the file if it does not meet
      these requirements.
 
diff --git a/converter/other/pamtowinicon.c b/converter/other/pamtowinicon.c
index 3d77d731..3c2c06bf 100644
--- a/converter/other/pamtowinicon.c
+++ b/converter/other/pamtowinicon.c
@@ -71,8 +71,6 @@ parseCommandLine(int argc, const char **argv,
 
 static bool verbose;
 
-static unsigned char const pngHeader[] = PNG_HEADER;
-
 
 
 struct Palette {
@@ -285,10 +283,10 @@ writeBmpImageHeader(unsigned int const width,
 /*----------------------------------------------------------------------------
 
   Write BMP image header
-    
+
   Note: bm_height is sum of rows in XOR mask and AND mask, while
   image_size is the size of the AND mask only.
-    
+
   image_size does not include the sizes of the (optional) palette
   and the (mandatory) AND mask.
 -----------------------------------------------------------------------------*/
@@ -319,8 +317,8 @@ write32BitBmp(const struct pam *   const pamP,
   Write a 32-bit BMP encoded image to file *ofP.
 -----------------------------------------------------------------------------*/
     int row;
-    
-    writeBmpImageHeader(pamP->width, pamP->height, 32, 
+
+    writeBmpImageHeader(pamP->width, pamP->height, 32,
                         pamP->width * 4 * pamP->height, ofP);
 
     /*  write "XOR mask" */
@@ -336,7 +334,7 @@ write32BitBmp(const struct pam *   const pamP,
                 + ((uint32_t) pixel[PAM_GRN_PLANE] <<  8)
                 + ((uint32_t) pixel[PAM_BLU_PLANE] <<  0)
                 ;
-            
+
             if (haveAlpha)
                 val += (uint32_t) tuples[row][col][alphaPlane] << 24;
 
@@ -362,7 +360,7 @@ writeBmpPalette(const struct Palette * const paletteP,
                             +(paletteP->color[i][PAM_RED_PLANE] << 16)
                             +(paletteP->color[i][PAM_GRN_PLANE] <<  8)
                             +(paletteP->color[i][PAM_BLU_PLANE] <<  0));
-    
+
     for (; i < maxColors; ++i)
         pm_writelittlelongu(ofP, 0);
 }
@@ -384,7 +382,7 @@ writeXorMask(const struct pam *     const pamP,
     unsigned int const maxCol = ((pamP->width * bpp + 31) & ~31) / bpp;
 
     int row;
-                 
+
     for (row = pamP->height - 1; row >= 0; --row) {
         uint8_t  val;
         uint16_t mask;
@@ -502,7 +500,7 @@ writeAndMask(const struct pam * const pamP,
             mask <<= 1;
             val  <<= 1;
 
-            if (!andMakesOpaque(pamP, tuples, row, col, 
+            if (!andMakesOpaque(pamP, tuples, row, col,
                                 haveAlpha, alphaPlane, haveAnd, andPlane))
                 val |= 0x1;
 
@@ -539,7 +537,7 @@ makeAlphaFile(const struct pam * const imagePamP,
     struct pam alphaPam;
     tuple ** alphaTuples;
     unsigned int row;
-    
+
     pm_make_tmpfile(&alphaFileP, alphaFileNameP);
 
     alphaPam.size   = sizeof(alphaPam);
@@ -640,7 +638,7 @@ writePng(const struct pam * const pamP,
 
     acceptParm.ofP = ofP;
     acceptParm.writeCtP = &pngSize;
-    
+
     if (haveAlpha || haveAnd) {
         const char * alphaFileName;
         const char * alphaOpt;
@@ -652,15 +650,15 @@ writePng(const struct pam * const pamP,
 
         strcpy (pam.tuple_type,
                 pam.depth == 3 ? PAM_PPM_TUPLETYPE: PAM_PGM_TUPLETYPE);
-        
+
         pm_asprintf(&alphaOpt, "-alpha=%s", alphaFileName);
 
         pm_system_lp("pnmtopng", pm_feed_from_pamtuples, &pamTuples,
                      acceptToFile, &acceptParm,
                      "pnmtopng", alphaOpt, NULL);
-    
+
         pm_strfree(alphaOpt);
-    
+
         unlink(alphaFileName);
     } else {
         pm_system_lp("pnmtopng", pm_feed_from_pamtuples, &pamTuples,
@@ -908,19 +906,19 @@ writeIconAndCreateDirEntry(const struct pam *     const pamP,
             if (paletteP->colorCt <= 2) {
                 dirEntryP->color_count    = paletteP->colorCt;
                 dirEntryP->bits_per_pixel = 1;
-                    
+
                 writePaletteBmp(1, pamP, tuples, getPixel, paletteP,
                                 ofP, &bmpSize);
             } else if (paletteP->colorCt <= 16) {
                 dirEntryP->color_count    = paletteP->colorCt;
                 dirEntryP->bits_per_pixel = 4;
-                    
+
                 writePaletteBmp(4, pamP, tuples, getPixel,paletteP,
                                 ofP, &bmpSize);
             } else {
                 dirEntryP->color_count    = 0;
                 dirEntryP->bits_per_pixel = 8;
-                    
+
                 writePaletteBmp(8, pamP, tuples, getPixel, paletteP,
                                 ofP, &bmpSize);
             }
@@ -952,7 +950,7 @@ convertOneImage(unsigned int     const imageNum,
     GetPixelFn *        getPixel;
     struct Palette      palette;
     bool                doingPng;
-        
+
     /*  Output:
      *
      *  threshold^2 pixels or more:
@@ -976,6 +974,10 @@ convertOneImage(unsigned int     const imageNum,
 
     doingPng = pam.width * pam.height >= pngThreshold;
 
+    if (verbose)
+        pm_message("Image %2u: encoding as %s",
+                   imageNum, doingPng ? "PNG" : "BMP");
+
     readAndScalePam(&pam, doingPng, tuples);
 
     determineImageType(&pam, tuples, &getPixel,
@@ -1018,7 +1020,7 @@ convert(FILE *           const ifP,
 -----------------------------------------------------------------------------*/
     unsigned int imageNum;
     int eof;
-    
+
     for (imageNum = 0, eof = false; !eof; ++imageNum) {
         convertOneImage(imageNum, ifP, pngThreshold, mustBlackenXor,
                         ofP, dirP);
@@ -1032,14 +1034,14 @@ convert(FILE *           const ifP,
 static void
 writeIconDirEntry(const struct IconDirEntry * const dirEntryP,
                   FILE *                      const ofP) {
-        
+
     pm_writecharu        (ofP, dirEntryP->width);
     pm_writecharu        (ofP, dirEntryP->height);
     pm_writecharu        (ofP, dirEntryP->color_count);
     pm_writecharu        (ofP, dirEntryP->zero);
     pm_writelittleshortu (ofP, dirEntryP->color_planes);
     pm_writelittleshortu (ofP, dirEntryP->bits_per_pixel);
-    pm_writelittlelongu  (ofP, dirEntryP->size); 
+    pm_writelittlelongu  (ofP, dirEntryP->size);
     pm_writelittlelongu  (ofP, dirEntryP->offset);
 }
 
@@ -1067,7 +1069,7 @@ writeIconDirectory(const struct IconDir * const dirP,
          ++imageNum) {
 
         struct IconDirEntry * const dirEntryP = &dirP->entries[imageNum];
-        
+
         pm_message("image %2u: %3u x %3u x %2u",
                    imageNum,
                    dirEntryP->width,
@@ -1089,7 +1091,7 @@ copyFile(FILE * const ifP,
          FILE * const ofP) {
 
     bool eof;
-    
+
     for (eof = false; !eof; ) {
         unsigned char buffer[1024];
         size_t bytesRead;
diff --git a/converter/other/pamtoxvmini.c b/converter/other/pamtoxvmini.c
index b57bcc74..047de75a 100644
--- a/converter/other/pamtoxvmini.c
+++ b/converter/other/pamtoxvmini.c
@@ -23,16 +23,16 @@ typedef struct xvPalette {
 } xvPalette;
 
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     const char * inputFileName;
 };
 
 
 
 static void
-parseCommandLine(int const argc,
-                 char *    argv[],
-                 struct cmdlineInfo * const cmdlineP) {
+parseCommandLine(int const                  argc,
+                 const char *               argv[],
+                 struct CmdlineInfo * const cmdlineP) {
 
     if (argc-1 < 1)
         cmdlineP->inputFileName = "-";
@@ -75,7 +75,7 @@ static void
 writeXvHeader(FILE *       const ofP,
               unsigned int const cols,
               unsigned int const rows) {
-           
+
     fprintf(ofP, "P7 332\n");
 
     fprintf(ofP, "# Created by Pamtoxvmini\n");
@@ -94,12 +94,14 @@ writeXvHeader(FILE *       const ofP,
 
 static void
 findClosestColor(struct pam *      const pamP,
-                 tuple             const tuple, 
+                 tuple             const tuple,
                  const xvPalette * const xvPaletteP,
                  unsigned int *    const paletteIndexP) {
 /*----------------------------------------------------------------------------
    Find the color in the palette *xvPaletteP that is closest to the color
    'tuple' and return its index in the palette.
+
+   *pamP gives the format of 'tuple', which must be RGB with maxval 255.
 -----------------------------------------------------------------------------*/
     unsigned int paletteIndex;
     unsigned int bestPaletteIndex;
@@ -118,12 +120,12 @@ findClosestColor(struct pam *      const pamP,
         unsigned int const tupleRed = tuple[PAM_RED_PLANE];
         unsigned int const tupleGrn = tuple[PAM_GRN_PLANE];
         unsigned int const tupleBlu = tuple[PAM_BLU_PLANE];
-        
+
         unsigned int const paletteRed = xvPaletteP->red[paletteIndex];
         unsigned int const paletteGrn = xvPaletteP->grn[paletteIndex];
         unsigned int const paletteBlu = xvPaletteP->blu[paletteIndex];
 
-        unsigned int const distance = 
+        unsigned int const distance =
             SQR((int)tupleRed - (int)paletteRed) +
             SQR((int)tupleGrn - (int)paletteGrn) +
             SQR((int)tupleBlu - (int)paletteBlu);
@@ -155,24 +157,29 @@ getPaletteIndexThroughCache(struct pam *      const pamP,
     int found;
     int paletteIndex;
 
+    /* As required by findClosestColor(): */
+    assert(pamP->depth >= 3);
+    assert(pamP->maxval == 255);
+
     pnm_lookuptuple(pamP, paletteHash, tuple, &found, &paletteIndex);
     if (found)
         *paletteIndexP = paletteIndex;
     else {
         int fits;
+
         findClosestColor(pamP, tuple, xvPaletteP, paletteIndexP);
-        
+
         pnm_addtotuplehash(pamP, paletteHash, tuple, *paletteIndexP, &fits);
-        
+
         if (!fits)
             pm_error("Can't get memory for palette hash.");
     }
 }
 
-    
+
 
 static void
-writeXvRaster(struct pam * const pamP,
+writeXvRaster(struct pam * const inpamP,
               xvPalette *  const xvPaletteP,
               FILE *       const ofP) {
 /*----------------------------------------------------------------------------
@@ -190,33 +197,40 @@ writeXvRaster(struct pam * const pamP,
     unsigned int row;
     unsigned char * xvrow;
     struct pam scaledPam;
+    struct pam scaledRgbPam;
+
+    pnm_setminallocationdepth(inpamP, 3);
 
     paletteHash = pnm_createtuplehash();
 
-    tuplerow = pnm_allocpamrow(pamP);
-    xvrow = (unsigned char*)pm_allocrow(pamP->width, 1);
+    tuplerow = pnm_allocpamrow(inpamP);
+    xvrow = (unsigned char*)pm_allocrow(inpamP->width, 1);
 
-    scaledPam = *pamP;
+    scaledPam = *inpamP;  /* initial value */
     scaledPam.maxval = 255;
 
-    for (row = 0; row < pamP->height; ++row) {
+    scaledRgbPam = scaledPam;  /* initial value */
+    scaledRgbPam.depth = MAX(3, scaledPam.depth);
+
+    for (row = 0; row < inpamP->height; ++row) {
         unsigned int col;
 
-        pnm_readpamrow(pamP, tuplerow);
-        pnm_scaletuplerow(pamP, tuplerow, tuplerow, scaledPam.maxval);
+        pnm_readpamrow(inpamP, tuplerow);
+        pnm_scaletuplerow(inpamP, tuplerow, tuplerow, scaledPam.maxval);
         pnm_makerowrgb(&scaledPam, tuplerow);
 
-        for (col = 0; col < scaledPam.width; ++col) {
+        for (col = 0; col < scaledRgbPam.width; ++col) {
             unsigned int paletteIndex;
 
-            getPaletteIndexThroughCache(&scaledPam, tuplerow[col], xvPaletteP,
-                                        paletteHash, &paletteIndex);
+            getPaletteIndexThroughCache(&scaledRgbPam, tuplerow[col],
+                                        xvPaletteP, paletteHash,
+                                        &paletteIndex);
 
             assert(paletteIndex < 256);
 
             xvrow[col] = paletteIndex;
         }
-        fwrite(xvrow, 1, scaledPam.width, ofP);
+        fwrite(xvrow, 1, scaledRgbPam.width, ofP);
     }
 
     pm_freerow((char*)xvrow);
@@ -227,16 +241,16 @@ writeXvRaster(struct pam * const pamP,
 
 
 
-int 
-main(int    argc,
-     char * argv[]) {
+int
+main(int          argc,
+     const char * argv[]) {
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     FILE * ifP;
     struct pam pam;
     xvPalette xvPalette;
- 
-    pnm_init(&argc, argv);
+
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
@@ -246,13 +260,14 @@ main(int    argc,
 
     pnm_readpaminit(ifP, &pam, PAM_STRUCT_SIZE(allocation_depth));
 
-    pnm_setminallocationdepth(&pam, 3);
-
     writeXvHeader(stdout, pam.width, pam.height);
-    
+
     writeXvRaster(&pam, &xvPalette, stdout);
 
     pm_close(ifP);
 
     return 0;
 }
+
+
+
diff --git a/converter/other/pbmtopgm.c b/converter/other/pbmtopgm.c
index c35e1cbe..817fb5b3 100644
--- a/converter/other/pbmtopgm.c
+++ b/converter/other/pbmtopgm.c
@@ -6,6 +6,7 @@
 #include <limits.h>
 
 #include "pm_c_util.h"
+#include "nstring.h"
 #include "pgm.h"
 
 int
@@ -17,26 +18,23 @@ main(int argc, char *argv[]) {
     int rows, cols;
     FILE *ifd;
     int row;
-    int width, height;
+    unsigned int width, height;
     const char * const usage = "<w> <h> [pbmfile]";
-   
+    const char * error; /* error message of pm_string_to_uint */
 
     pgm_init( &argc, argv );
 
     if (argc > 4 || argc < 3)
         pm_usage(usage);
 
-    width = atoi(argv[1]);
-    height = atoi(argv[2]);
+    pm_string_to_uint(argv[1], &width, &error);
+    if (error)
+        pm_error("Invalid width argument: %s", error);
+    pm_string_to_uint(argv[2], &height, &error);
+    if (error)
+        pm_error("Invalid height argument: %s", error);
     if (width < 1 || height < 1)
         pm_error("width and height must be > 0");
-    if (width > INT_MAX / height)
-        /* prevent overflow of "value" below */
-        pm_error("sample area (%u columns %u rows) too large",
-                 width, height);
-
-    left=width/2; right=width-left;
-    up=height/2; down=height-up;
 
     if (argc == 4)
         ifd = pm_openr(argv[3]);
@@ -44,13 +42,22 @@ main(int argc, char *argv[]) {
         ifd = stdin ;
 
     inbits = pbm_readpbm(ifd, &cols, &rows) ;
-    
+
     if (width > cols)
         pm_error("You specified a sample width (%u columns) which is greater "
                  "than the image width (%u columns)", height, rows);
     if (height > rows)
         pm_error("You specified a sample height (%u rows) which is greater "
                  "than the image height (%u rows)", height, rows);
+    if (width > INT_MAX / height)
+        /* prevent overflow of "value" below */
+        pm_error("sample area (%u columns %u rows) too large",
+                 width, height);
+
+    left = width  / 2;  right = width  - left;
+    up   = height / 2;  down  = height - up;
+
+
 
     outrow = pgm_allocrow(cols) ;
     maxval = MIN(PGM_OVERALLMAXVAL, width*height);
@@ -65,7 +72,7 @@ main(int argc, char *argv[]) {
             int const l = (col > left) ? (col-left) : 0;
             int const r = (col+right < cols) ? (col+right) : cols;
             int const onh = width - (l-col+left) - (col+right-r);
-            int value;
+            int value;  /* See above */
             int x;
 
             value = 0;  /* initial value */
@@ -73,10 +80,10 @@ main(int argc, char *argv[]) {
             for (x = l; x < r; ++x) {
                 int y;
                 for (y = t; y < b; ++y)
-                    if (inbits[y][x] == PBM_WHITE) 
+                    if (inbits[y][x] == PBM_WHITE)
                         ++value;
             }
-            outrow[col] = maxval*value/(onh*onv);
+            outrow[col] = (gray) ((double) maxval*value/(onh*onv));
         }
         pgm_writepgmrow(stdout, outrow, cols, maxval, 0) ;
     }
diff --git a/converter/other/pdbimgtopam.c b/converter/other/pdbimgtopam.c
index 67044109..b191644f 100644
--- a/converter/other/pdbimgtopam.c
+++ b/converter/other/pdbimgtopam.c
@@ -56,7 +56,7 @@ parseCommandLine(int argc, const char ** argv,
                  struct cmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -90,7 +90,7 @@ parseCommandLine(int argc, const char ** argv,
 
     if (!notefileSpec)
         cmdlineP->notefile = NULL;
-    
+
     if (argc-1 < 1)
         cmdlineP->inputFileName = "-";
     else if (argc-1 == 1)
@@ -152,7 +152,7 @@ decompress(const uint8_t * const compressed,
         const uint8_t * inP;
         uint8_t *       outP;
         size_t          bytesLeft;
-        
+
         for (bytesLeft = imageSize,
                  inP  = &compressed[0], outP = &uncompressed[0];
              bytesLeft > 0;
@@ -224,7 +224,7 @@ readCompressed(IMAGE *    const imgP,
          * this extra byte and ignore it by paying attention to
          * the image dimensions.
          */
-       size_t const maxCompressedSizeWithBloat = ipdb_img_size(imgP) * 2;
+       size_t const maxCompressedSizeWithBloat = ipdb_imgSize(imgP) * 2;
          /*
           * Provide a buffer large enough for the worst case.
           * See note in lib/util/runlength.c .
@@ -251,7 +251,7 @@ readCompressed(IMAGE *    const imgP,
          * Read to the indicated offset.
          */
         dataSize = end_offset - ftell(fP) + 1;
-        
+
         MALLOCARRAY(buffer, dataSize);
 
         if (buffer == NULL)
@@ -306,9 +306,9 @@ imageReadHeader(FILE *  const fileP,
         pm_message("  Y_anchor: %u", imgP->y_anchor);
         pm_message("  Width: %u", imgP->width);
         pm_message("  Height: %u", imgP->height);
-        pm_message("Pixels per byte: %u", ipdb_img_ppb(imgP));
+        pm_message("Pixels per byte: %u", ipdb_imgPpb(imgP));
         pm_message("Image size: %lu bytes",
-                   (unsigned long)ipdb_img_size(imgP));
+                   (unsigned long)ipdb_imgSize(imgP));
     }
 }
 
@@ -318,7 +318,7 @@ imageReadData(FILE *   const fileP,
               IMAGE *  const imgP,
               uint32_t const end_offset) {
 
-    size_t const imageSize = ipdb_img_size(imgP);  
+    size_t const imageSize = ipdb_imgSize(imgP);
 
     int retval;
     size_t dataSize;
@@ -390,7 +390,7 @@ textRead(TEXT * const textP,
         return 0;
 
     textP->r->offset = (uint32_t)ftell(fileP);
-    
+
     /*
      * What a pain in the ass!  Why the hell isn't there a length
      * attached to the text record?  I suppose the designer wasn't
@@ -453,7 +453,7 @@ pdbheadRead(PDBHEAD * const pdbHeadP,
     pm_readbiglongu2(fileP, &pdbHeadP->next_rec);
     pm_readbigshortu(fileP, &pdbHeadP->num_recs);
 
-    if (!memeq(pdbHeadP->type, IPDB_vIMG, 4) 
+    if (!memeq(pdbHeadP->type, IPDB_vIMG, 4)
         || !memeq(pdbHeadP->id, IPDB_View, 4))
         retval = E_NOTIMAGE;
     else
@@ -531,62 +531,54 @@ ipdbRead(IPDB * const pdbP,
 
     int retval;
 
-    ipdb_clear(pdbP);
+    int status;
 
-    pdbP->p = ipdb_pdbhead_alloc(NULL);
+    status = pdbheadRead(pdbP->p, fileP);
 
-    if (pdbP->p == NULL)
-        retval = ENOMEM;
+    if (status != 0)
+        retval = status;
     else {
-        int status;
-
-        status = pdbheadRead(pdbP->p, fileP);
-
-        if (status != 0)
-            retval = status;
+        pdbP->i = ipdb_imageCreate(pdbP->p->name, IMG_GRAY, 0, 0);
+        if (pdbP->i == NULL)
+            retval = ENOMEM;
         else {
-            pdbP->i = ipdb_image_alloc(pdbP->p->name, IMG_GRAY, 0, 0);
-            if (pdbP->i == NULL)
-                retval = ENOMEM;
+            int status;
+            status = rechdrRead(pdbP->i->r, fileP);
+            if (status != 0)
+                retval = status;
             else {
-                int status;
-                status = rechdrRead(pdbP->i->r, fileP);
-                if (status != 0)
-                    retval = status;
-                else {
-                    if (pdbP->p->num_recs > 1) {
-                        pdbP->t = ipdb_text_alloc(NULL);
-                        if (pdbP->t == NULL)
-                            retval = ENOMEM;
-                        else {
-                            int status;
-                            status = rechdrRead(pdbP->t->r, fileP);
-                            if (status != 0)
-                                retval = status;
-                            else
-                                retval = 0;
-                        }
-                    } else
-                        retval = 0;
-                    
-                    if (retval == 0) {
-                        uint32_t const offset =
-                            pdbP->t == NULL ?
-                            UNKNOWN_OFFSET : pdbP->t->r->offset - 1;
-
+                if (pdbP->p->num_recs > 1) {
+                    pdbP->t = ipdb_textAlloc();
+                    if (pdbP->t == NULL)
+                        retval = ENOMEM;
+                    else {
                         int status;
-
-                        status = imageRead(pdbP->i, offset, fileP, verbose);
+                        status = rechdrRead(pdbP->t->r, fileP);
                         if (status != 0)
                             retval = status;
-                        else {
-                            if (pdbP->t != NULL) {
-                                int status;
-                                
-                                status = textRead(pdbP->t, fileP);
-                                if (status != 0)
-                                    retval = status;
-                            }
+                        else
+                            retval = 0;
+                    }
+                } else
+                    retval = 0;
+
+                if (retval == 0) {
+                    uint32_t const offset =
+                        pdbP->t == NULL ?
+                        UNKNOWN_OFFSET : pdbP->t->r->offset - 1;
+
+                    int status;
+
+                    status = imageRead(pdbP->i, offset, fileP, verbose);
+                    if (status != 0)
+                        retval = status;
+                    else {
+                        if (pdbP->t != NULL) {
+                            int status;
+
+                            status = textRead(pdbP->t, fileP);
+                            if (status != 0)
+                                retval = status;
                         }
                     }
                 }
@@ -663,8 +655,8 @@ static void
 g16row(IPDB *       const pdbP,
        unsigned int const row,
        uint8_t *    const buffer) {
-    
-    g16unpack(ipdb_img_row(pdbP->i, row), buffer, ipdb_width(pdbP));
+
+    g16unpack(ipdb_imgRow(pdbP->i, row), buffer, ipdb_width(pdbP));
 }
 
 
@@ -674,7 +666,7 @@ grow(IPDB *       const pdbP,
      unsigned int const row,
      uint8_t *    const buffer) {
 
-    gunpack(ipdb_img_row(pdbP->i, row), buffer, ipdb_width(pdbP));
+    gunpack(ipdb_imgRow(pdbP->i, row), buffer, ipdb_width(pdbP));
 }
 
 
@@ -684,7 +676,7 @@ mrow(IPDB *       const pdbP,
      unsigned int const row,
      uint8_t *    const buffer) {
 
-    munpack(ipdb_img_row(pdbP->i, row), buffer, ipdb_width(pdbP));
+    munpack(ipdb_imgRow(pdbP->i, row), buffer, ipdb_width(pdbP));
 }
 
 
@@ -715,7 +707,7 @@ writeImgPam(IPDB * const pdbP,
            PAM_PBM_TUPLETYPE : PAM_PGM_TUPLETYPE);
 
     pnm_writepaminit(&pam);
-    
+
     tupleRow = pnm_allocpamrow(&pam);
 
     for (row = 0; row < pam.height; ++row) {
@@ -731,7 +723,7 @@ writeImgPam(IPDB * const pdbP,
 
         for (col = 0; col < pam.width; ++col)
             tupleRow[col][0] = imgRow[col];
-        
+
         pnm_writepamrow(&pam, tupleRow);
     }
     pnm_freepamrow(tupleRow);
@@ -754,7 +746,7 @@ writeText(IPDB *       const pdbP,
         fP = pm_openw(name);
         if (fP == NULL)
             pm_error("Could not open note file '%s' for output", name);
-        
+
         fprintf(fP, "%s\n", note);
 
         pm_close(fP);
@@ -777,7 +769,7 @@ main(int argc, const char ** argv) {
 
     ifP = pm_openr(cmdline.inputFileName);
 
-    pdbP = ipdb_alloc(NULL);
+    pdbP = ipdb_alloc();
     if (pdbP == NULL)
         pm_error("Could not allocate IPDB structure.");
 
@@ -795,3 +787,6 @@ main(int argc, const char ** argv) {
 
     return EXIT_SUCCESS;
 }
+
+
+
diff --git a/converter/other/pgmtopbm.c b/converter/other/pgmtopbm.c
index 67cac468..d5f67a06 100644
--- a/converter/other/pgmtopbm.c
+++ b/converter/other/pgmtopbm.c
@@ -17,19 +17,23 @@
 #include "pgm.h"
 #include "dithers.h"
 #include "mallocvar.h"
+#include "rand.h"
 
 enum halftone {QT_FS, QT_THRESH, QT_DITHER8, QT_CLUSTER, QT_HILBERT};
 
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
     const char *  inputFilespec;
     enum halftone halftone;
     unsigned int  clumpSize;
-    unsigned int  clusterRadius;  
+    unsigned int  clusterRadius;
         /* Defined only for halftone == QT_CLUSTER */
+    unsigned int  randomSeed;
+    unsigned int  randomSeedSpec;
+        /* Defined only for halftone == QT_FS */
     float         threshval;
 };
 
@@ -37,8 +41,8 @@ struct cmdlineInfo {
 
 
 static void
-parseCommandLine(int argc, char ** argv,
-                 struct cmdlineInfo *cmdlineP) {
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo *cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that the file spec array we return is stored in the storage that
    was passed to us as the argv array.
@@ -68,22 +72,24 @@ parseCommandLine(int argc, char ** argv,
     OPTENT3(0, "c4",        OPT_FLAG,  NULL, &cluster4Opt,  0);
     OPTENT3(0, "cluster8",  OPT_FLAG,  NULL, &cluster8Opt,  0);
     OPTENT3(0, "c8",        OPT_FLAG,  NULL, &cluster8Opt,  0);
-    OPTENT3(0, "value",     OPT_FLOAT, &cmdlineP->threshval, 
+    OPTENT3(0, "value",     OPT_FLOAT, &cmdlineP->threshval,
             &valueSpec, 0);
-    OPTENT3(0, "clump",     OPT_UINT,  &cmdlineP->clumpSize, 
+    OPTENT3(0, "clump",     OPT_UINT,  &cmdlineP->clumpSize,
             &clumpSpec, 0);
+    OPTENT3(0, "randomseed", OPT_UINT,  &cmdlineP->randomSeed,
+            &cmdlineP->randomSeedSpec, 0);
 
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
+    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
-    if (floydOpt + thresholdOpt + hilbertOpt + dither8Opt + 
+    if (floydOpt + thresholdOpt + hilbertOpt + dither8Opt +
         cluster3Opt + cluster4Opt + cluster8Opt == 0)
         cmdlineP->halftone = QT_FS;
-    else if (floydOpt + thresholdOpt + dither8Opt + 
+    else if (floydOpt + thresholdOpt + dither8Opt +
         cluster3Opt + cluster4Opt + cluster8Opt > 1)
         pm_error("No cannot specify more than one halftoning type");
     else {
@@ -104,7 +110,7 @@ parseCommandLine(int argc, char ** argv,
         } else if (cluster8Opt) {
             cmdlineP->halftone = QT_CLUSTER;
             cmdlineP->clusterRadius = 8;
-        } else 
+        } else
             pm_error("INTERNAL ERROR.  No halftone option");
     }
 
@@ -118,7 +124,7 @@ parseCommandLine(int argc, char ** argv,
             pm_error("-value cannot be greater than one.  You specified %f",
                      cmdlineP->threshval);
     }
-            
+
     if (!clumpSpec)
         cmdlineP->clumpSize = 5;
     else {
@@ -127,6 +133,10 @@ parseCommandLine(int argc, char ** argv,
                      cmdlineP->clumpSize);
     }
 
+    if (cmdlineP->halftone != QT_FS && cmdlineP->randomSeedSpec)
+        pm_message ("Ignoring -randomseed value "
+                    "(meaningful only with Floyd-Steinberg)");
+
     if (argc-1 > 1)
         pm_error("Too many arguments (%d).  There is at most one "
                  "non-option argument:  the file name",
@@ -150,11 +160,11 @@ static int hil_x,hil_y;
 static int hil_stage[MAXORD];
 static int hil_width,hil_height;
 
-static void 
-init_hilbert(int const w, 
+static void
+init_hilbert(int const w,
              int const h) {
 /*----------------------------------------------------------------------------
-  Initialize the Hilbert curve tracer 
+  Initialize the Hilbert curve tracer
 -----------------------------------------------------------------------------*/
     int big,ber;
     hil_width = w;
@@ -169,7 +179,7 @@ init_hilbert(int const w,
 
 
 
-static int 
+static int
 hilbert(int * const px, int * const py) {
 /*----------------------------------------------------------------------------
   Return non-zero if got another point
@@ -215,7 +225,7 @@ hilbert(int * const px, int * const py) {
             temp = hil_dy;
             hil_dy = -hil_turn * hil_dx;
             hil_dx = hil_turn * temp;
-            if (hil_ord > 0) { 
+            if (hil_ord > 0) {
                 /* recurse */
 
                 hil_stage[hil_ord] = 3;
@@ -338,7 +348,7 @@ static void doHilbert(FILE *       const ifP,
 struct converter {
     void (*convertRow)(struct converter * const converterP,
                        unsigned int       const row,
-                       gray                     grayrow[], 
+                       gray                     grayrow[],
                        bit                      bitrow[]);
     void (*destroy)(struct converter * const converterP);
     unsigned int cols;
@@ -379,7 +389,7 @@ fsConvertRow(struct converter * const converterP,
 
     unsigned int limitcol;
     unsigned int col;
-    
+
     for (col = 0; col < converterP->cols + 2; ++col)
         nexterr[col] = 0;
     if (stateP->fs_forward) {
@@ -395,20 +405,20 @@ fsConvertRow(struct converter * const converterP,
     }
     do {
         long sum;
-        sum = ((long) *gP * fs_scale) / converterP->maxval + 
+        sum = ((long) *gP * fs_scale) / converterP->maxval +
             thiserr[col + 1];
         if (sum >= stateP->threshval) {
             *bP = PBM_WHITE;
             sum = sum - stateP->threshval - half_fs_scale;
         } else
             *bP = PBM_BLACK;
-        
+
         if (stateP->fs_forward) {
             thiserr[col + 2] += (sum * 7) / 16;
             nexterr[col    ] += (sum * 3) / 16;
             nexterr[col + 1] += (sum * 5) / 16;
             nexterr[col + 2] += (sum    ) / 16;
-            
+
             ++col;
             ++gP;
             ++bP;
@@ -417,13 +427,13 @@ fsConvertRow(struct converter * const converterP,
             nexterr[col + 2] += (sum * 3) / 16;
             nexterr[col + 1] += (sum * 5) / 16;
             nexterr[col    ] += (sum    ) / 16;
-            
+
             --col;
             --gP;
             --bP;
         }
     } while (col != limitcol);
-    
+
     stateP->thiserr = nexterr;
     stateP->nexterr = thiserr;
     stateP->fs_forward = ! stateP->fs_forward;
@@ -439,9 +449,11 @@ fsDestroy(struct converter * const converterP) {
 
 
 static struct converter
-createFsConverter(unsigned int const cols, 
+createFsConverter(unsigned int const cols,
                   gray         const maxval,
-                  float        const threshFraction) {
+                  float        const threshFraction,
+                  unsigned int const randomSeedSpec,
+                  unsigned int const randomSeed) {
 
     struct fsState * stateP;
     struct converter converter;
@@ -451,14 +463,19 @@ createFsConverter(unsigned int const cols,
     /* Initialize Floyd-Steinberg error vectors. */
     MALLOCARRAY_NOFAIL(stateP->thiserr, cols + 2);
     MALLOCARRAY_NOFAIL(stateP->nexterr, cols + 2);
-    srand(pm_randseed());
 
     {
         /* (random errors in [-fs_scale/8 .. fs_scale/8]) */
         unsigned int col;
+        struct pm_randSt randSt;
+        pm_randinit(&randSt);
+        pm_srand2(&randSt, randomSeedSpec, randomSeed);
+
         for (col = 0; col < cols + 2; ++col)
-            stateP->thiserr[col] = 
-                (long)(rand() % fs_scale - half_fs_scale) / 4;
+            stateP->thiserr[col] =
+                (long)(pm_rand(&randSt) % fs_scale - half_fs_scale) / 4;
+
+        pm_randterm(&randSt);
     }
 
     stateP->fs_forward = TRUE;
@@ -488,7 +505,7 @@ threshConvertRow(struct converter * const converterP,
                  unsigned int       const row,
                  gray                     grayrow[],
                  bit                      bitrow[]) {
-    
+
     struct threshState * const stateP = converterP->stateP;
 
     unsigned int col;
@@ -509,7 +526,7 @@ threshDestroy(struct converter * const converterP) {
 
 
 static struct converter
-createThreshConverter(unsigned int const cols, 
+createThreshConverter(unsigned int const cols,
                       gray         const maxval,
                       float        const threshFraction) {
 
@@ -571,7 +588,7 @@ dither8Destroy(struct converter * const converterP) {
 
 
 static struct converter
-createDither8Converter(unsigned int const cols, 
+createDither8Converter(unsigned int const cols,
                        gray         const maxval) {
 
     struct converter converter;
@@ -642,7 +659,7 @@ clusterDestroy(struct converter * const converterP) {
         free(stateP->clusterMatrix[row]);
 
     free(stateP->clusterMatrix);
-    
+
     free(stateP);
 }
 
@@ -650,9 +667,9 @@ clusterDestroy(struct converter * const converterP) {
 
 static struct converter
 createClusterConverter(unsigned int const radius,
-                       unsigned int const cols, 
+                       unsigned int const cols,
                        gray         const maxval) {
-    
+
     int const clusterNormalizer = radius * radius * 2;
     unsigned int const diameter = 2 * radius;
 
@@ -674,7 +691,7 @@ createClusterConverter(unsigned int const radius,
         unsigned int col;
 
         MALLOCARRAY_NOFAIL(stateP->clusterMatrix[row], diameter);
-        
+
         for (col = 0; col < diameter; ++col) {
             int val;
             switch (radius) {
@@ -686,7 +703,7 @@ createClusterConverter(unsigned int const radius,
             }
             stateP->clusterMatrix[row][col] = val * maxval / clusterNormalizer;
         }
-    }            
+    }
 
     converter.stateP = stateP;
 
@@ -696,14 +713,14 @@ createClusterConverter(unsigned int const radius,
 
 
 int
-main(int argc, char *argv[]) {
+main(int argc, const char *argv[]) {
 
-    struct cmdlineInfo cmdline;
-    FILE* ifP;
-    gray* grayrow;
-    bit* bitrow;
+    struct CmdlineInfo cmdline;
+    FILE * ifP;
+    gray * grayrow;
+    bit *  bitrow;
 
-    pgm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
@@ -719,24 +736,26 @@ main(int argc, char *argv[]) {
         int row;
 
         pgm_readpgminit(ifP, &cols, &rows, &maxval, &format);
-        
+
         pbm_writepbminit(stdout, cols, rows, 0);
 
         switch (cmdline.halftone) {
         case QT_FS:
-            converter = createFsConverter(cols, maxval, cmdline.threshval);
+            converter = createFsConverter(cols, maxval, cmdline.threshval,
+                                          cmdline.randomSeedSpec,
+                                          cmdline.randomSeed);
             break;
         case QT_THRESH:
             converter = createThreshConverter(cols, maxval, cmdline.threshval);
             break;
-        case QT_DITHER8: 
-            converter = createDither8Converter(cols, maxval); 
+        case QT_DITHER8:
+            converter = createDither8Converter(cols, maxval);
             break;
-        case QT_CLUSTER: 
-            converter = 
+        case QT_CLUSTER:
+            converter =
                 createClusterConverter(cmdline.clusterRadius, cols, maxval);
             break;
-        case QT_HILBERT: 
+        case QT_HILBERT:
                 pm_error("INTERNAL ERROR: halftone is QT_HILBERT where it "
                          "shouldn't be.");
                 break;
@@ -749,7 +768,7 @@ main(int argc, char *argv[]) {
             pgm_readpgmrow(ifP, grayrow, cols, maxval, format);
 
             converter.convertRow(&converter, row, grayrow, bitrow);
-            
+
             pbm_writepbmrow(stdout, bitrow, cols, 0);
         }
         pbm_freerow(bitrow);
@@ -763,3 +782,6 @@ main(int argc, char *argv[]) {
 
     return 0;
 }
+
+
+
diff --git a/converter/other/pgmtoppm.c b/converter/other/pgmtoppm.c
index c3a26594..dea6c4ca 100644
--- a/converter/other/pgmtoppm.c
+++ b/converter/other/pgmtoppm.c
@@ -17,27 +17,30 @@
 
 #include "pm_c_util.h"
 #include "mallocvar.h"
+#include "nstring.h"
 #include "shhopt.h"
 #include "ppm.h"
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
     const char * inputFilename;  /* '-' if stdin */
     const char * map;
-    const char * colorBlack;
-    const char * colorWhite;
+    const char * colorBlack;  /* malloc'ed */
+        /* The color to which the user says to map black */
+    const char * colorWhite;  /* malloc'ed */
+        /* The color to which the user says to map white */
 };
 
 
 
 static void
-parseCommandLine(int argc, char ** argv,
-                 struct cmdlineInfo * const cmdlineP) {
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -52,11 +55,18 @@ parseCommandLine(int argc, char ** argv,
 
     unsigned int option_def_index;
 
-    unsigned int mapSpec;
+    unsigned int blackSpec, whiteSpec, mapSpec;
+
+    const char * blackOpt;
+    const char * whiteOpt;
 
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENT3 */
+    OPTENT3(0, "black",          OPT_STRING,    &blackOpt,
+            &blackSpec,          0);
+    OPTENT3(0, "white",          OPT_STRING,    &whiteOpt,
+            &whiteSpec,          0);
     OPTENT3(0, "map",            OPT_STRING,    &cmdlineP->map,
             &mapSpec,            0);
 
@@ -64,13 +74,20 @@ parseCommandLine(int argc, char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
+    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (!mapSpec)
         cmdlineP->map = NULL;
 
     if (mapSpec) {
+        if (blackSpec || whiteSpec)
+            pm_error("You may not specify -black or -white "
+                     "together with -map");
+
+        cmdlineP->colorBlack = NULL;
+        cmdlineP->colorWhite = NULL;
+
         /* No color argument; only argument is file name */
         if (argc-1 < 1)
             cmdlineP->inputFilename = "-";
@@ -81,37 +98,77 @@ parseCommandLine(int argc, char ** argv,
                          "the file name.  You specified %u", argc-1);
         }
     } else {
-        /* Arguments are color or color range and file name */
-        if (argc-1 < 1) {
-            cmdlineP->colorBlack = "black";
-            cmdlineP->colorWhite = "white";
+        /* For default colors, we use "rgbi:..." instead of the simpler
+           "black" and "white" so that we don't have an unnecessary dependency
+           on a color dictionary being available.
+        */
+        if (blackSpec || whiteSpec) {
+            cmdlineP->colorBlack =
+                pm_strdup(blackSpec ? blackOpt : "rgbi:0/0/0");
+            cmdlineP->colorWhite =
+                pm_strdup(whiteSpec ? whiteOpt : "rgbi:1/1/1");
+
+            /* The only possibly argument is input file name */
+            if (argc-1 < 1)
+                cmdlineP->inputFilename = "-";
+            else {
+                cmdlineP->inputFilename = argv[1];
+                if (argc-1 > 1)
+                    pm_error("Whten you specify -black or -white, "
+                             "there can be at most one non-option arguments:  "
+                             "the file name.  "
+                             "You specified %u", argc-1);
+            }
         } else {
-            char * buffer = strdup(argv[1]);
-            char * hyphenPos = strchr(buffer, '-');
-            if (hyphenPos) {
-                *hyphenPos = '\0';
-                cmdlineP->colorBlack = buffer;
-                cmdlineP->colorWhite = hyphenPos+1;
+            /* Arguments are color or color range and optional file name */
+
+            if (argc-1 < 1) {
+                cmdlineP->colorBlack = pm_strdup("rgbi:0/0/0");
+                cmdlineP->colorWhite = pm_strdup("rgbi:1/1/1");
             } else {
-                cmdlineP->colorBlack = "black";
-                cmdlineP->colorWhite = buffer;
+                char * buffer = strdup(argv[1]);
+                if (!buffer)
+                    pm_error("Out of memory allocating tiny buffer");
+                char * hyphenPos = strchr(buffer, '-');
+                if (hyphenPos) {
+                    *hyphenPos = '\0';
+                    cmdlineP->colorBlack = pm_strdup(buffer);
+                    cmdlineP->colorWhite = pm_strdup(hyphenPos+1);
+                } else {
+                    cmdlineP->colorBlack = pm_strdup("rgbi:0/0/0");
+                    cmdlineP->colorWhite = pm_strdup(buffer);
+                }
+                free(buffer);
+            }
+
+            if (argc-1 < 2)
+                cmdlineP->inputFilename = "-";
+            else {
+                cmdlineP->inputFilename = argv[2];
+
+                if (argc-1 > 2)
+                    pm_error("Program takes at most 2 arguments:  "
+                             "color name/range and input file name.  "
+                             "You specified %u", argc-1);
             }
         }
-        if (argc-1 < 2)
-            cmdlineP->inputFilename = "-";
-        else
-            cmdlineP->inputFilename = argv[2];
-        
-        if (argc-1 > 2)
-            pm_error("Program takes at most 2 arguments:  "
-                     "color name/range and input file name.  "
-                     "You specified %u", argc-1);
     }
 }
 
 
 
 static void
+freeCommandLine(struct CmdlineInfo const cmdline) {
+
+    if (cmdline.colorBlack)
+        pm_strfree(cmdline.colorBlack);
+    if (cmdline.colorWhite)
+        pm_strfree(cmdline.colorWhite);
+}
+
+
+
+static void
 convertWithMap(FILE * const ifP,
                unsigned int const cols,
                unsigned int const rows,
@@ -128,7 +185,7 @@ convertWithMap(FILE * const ifP,
     pixval mapmaxval;
     pixel ** mappixels;
     unsigned int mapmaxcolor;
-    
+
     mapFileP = pm_openr(mapFileName);
     mappixels = ppm_readppm(mapFileP, &mapcols, &maprows, &mapmaxval);
     pm_close(mapFileP);
@@ -138,7 +195,7 @@ convertWithMap(FILE * const ifP,
 
     for (row = 0; row < rows; ++row) {
         unsigned int col;
-            
+
         pgm_readpgmrow(ifP, grayrow, cols, maxval, format);
 
         for (col = 0; col < cols; ++col) {
@@ -168,22 +225,20 @@ convertLinear(FILE * const ifP,
               gray *       const grayrow,
               pixel *      const pixelrow) {
 
-    pixel colorBlack, colorWhite;
-    pixval red0, grn0, blu0, red1, grn1, blu1;
+    pixel const colorBlack = ppm_parsecolor(colorNameBlack, maxval);
+    pixel const colorWhite = ppm_parsecolor(colorNameWhite, maxval);
+
+    pixval const red0 = PPM_GETR(colorBlack);
+    pixval const grn0 = PPM_GETG(colorBlack);
+    pixval const blu0 = PPM_GETB(colorBlack);
+    pixval const red1 = PPM_GETR(colorWhite);
+    pixval const grn1 = PPM_GETG(colorWhite);
+    pixval const blu1 = PPM_GETB(colorWhite);
+
     unsigned int row;
 
     ppm_writeppminit(ofP, cols, rows, maxval, 0);
 
-    colorBlack = ppm_parsecolor(colorNameBlack, maxval);
-    colorWhite = ppm_parsecolor(colorNameWhite, maxval);
- 
-    red0 = PPM_GETR(colorBlack);
-    grn0 = PPM_GETG(colorBlack);
-    blu0 = PPM_GETB(colorBlack);
-    red1 = PPM_GETR(colorWhite);
-    grn1 = PPM_GETG(colorWhite);
-    blu1 = PPM_GETB(colorWhite);
-
     for (row = 0; row < rows; ++row) {
         unsigned int col;
 
@@ -204,17 +259,17 @@ convertLinear(FILE * const ifP,
 
 
 int
-main(int    argc,
-     char * argv[]) {
+main(int          argc,
+     const char * argv[]) {
 
     FILE * ifP;
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     gray * grayrow;
     pixel * pixelrow;
     int rows, cols, format;
     gray maxval;
 
-    ppm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
@@ -228,7 +283,7 @@ main(int    argc,
         convertWithMap(ifP, cols, rows, maxval, format, cmdline.map,
                        stdout, grayrow, pixelrow);
     else
-        convertLinear(ifP, cols, rows, maxval, format, 
+        convertLinear(ifP, cols, rows, maxval, format,
                       cmdline.colorBlack, cmdline.colorWhite, stdout,
                       grayrow, pixelrow);
 
@@ -236,8 +291,13 @@ main(int    argc,
     pgm_freerow(grayrow);
     pm_close(ifP);
 
+    freeCommandLine(cmdline);
+
     /* If the program failed, it previously aborted with nonzero completion
        code, via various function calls.
     */
     return 0;
 }
+
+
+
diff --git a/converter/other/pngtopam.c b/converter/other/pngtopam.c
index 1023c6c6..3c0f81a5 100644
--- a/converter/other/pngtopam.c
+++ b/converter/other/pngtopam.c
@@ -22,7 +22,7 @@
 #include <math.h>
 #include <float.h>
 #include <png.h>
-/* Becaues of a design error in png.h, you must not #include <setjmp.h> before
+/* Because of a design error in png.h, you must not #include <setjmp.h> before
    <png.h>.  If you do, png.h won't compile.
 */
 #include <setjmp.h>
@@ -668,10 +668,16 @@ dumpPngInfo(struct pngx * const pngxP) {
                    background.blue);
     }
 
-    if (pngx_chunkIsPresent(pngxP, PNG_INFO_tRNS))
-        pm_message("tRNS chunk (transparency): %u entries",
-                   pngx_trns(pngxP).numTrans);
-    else
+    if (pngx_chunkIsPresent(pngxP, PNG_INFO_tRNS)) {
+        struct pngx_trns const trns = pngx_trns(pngxP);
+
+        pm_message("tRNS chunk (transparency):");
+        pm_message("  %u palette entries", trns.numTrans);
+        pm_message("  transparent color = (%u,%u,%u)",
+                   trns.transColor.red,
+                   trns.transColor.green,
+                   trns.transColor.blue);
+    } else
         pm_message("tRNS chunk (transparency): not present");
 
     if (pngx_chunkIsPresent(pngxP, PNG_INFO_gAMA))
@@ -868,17 +874,17 @@ paletteHasPartialTransparency(struct pngx * const pngxP) {
         if (pngx_chunkIsPresent(pngxP, PNG_INFO_tRNS)) {
             struct pngx_trns const trans = pngx_trns(pngxP);
 
-            bool foundGray;
+            bool foundPartial;
             unsigned int i;
 
-            for (i = 0, foundGray = FALSE;
-                 i < trans.numTrans && !foundGray;
+            for (i = 0, foundPartial = FALSE;
+                 i < trans.numTrans && !foundPartial;
                  ++i) {
                 if (trans.trans[i] != 0 && trans.trans[i] != pngxP->maxval) {
-                    foundGray = TRUE;
+                    foundPartial = TRUE;
                 }
             }
-            retval = foundGray;
+            retval = foundPartial;
         } else
             retval = FALSE;
     } else
diff --git a/converter/other/pngx.c b/converter/other/pngx.c
index 4bb09421..7840b2da 100644
--- a/converter/other/pngx.c
+++ b/converter/other/pngx.c
@@ -24,7 +24,7 @@ errorHandler(png_structp     const png_ptr,
 
     jmp_buf * jmpbufP;
 
-    /* this function, aside from the extra step of retrieving the "error
+    /* This function, aside from the extra step of retrieving the "error
        pointer" (below) and the fact that it exists within the application
        rather than within libpng, is essentially identical to libpng's
        default error handler.  The second point is critical:  since both
@@ -416,6 +416,26 @@ void
 pngx_setFilter(struct pngx * const pngxP,
                int           const filterSet) {
 
+    /* This sets the allowed filters in the compressor.  The filters, and thus
+       the interpretation of 'filterSet', is specific to a filter method (aka
+       filter type), which you set with pngx_setIhdr.  There is only one
+       filter method defined today, though (PNG_FILTER_TYPE_BASE).
+
+       For filter method Base, 'filterSet' is the OR of the following masks,
+       each one allowing the compressor to use one filter.  Not that  the
+       compressor decides on a row-by-row basis what filter to use.
+
+         PNG_FILTER_NONE
+         PNG_FILTER_SUB
+         PNG_FILTER_UP
+         PNG_FILTER_AVG
+         PNG_FILTER_PAETH
+
+       There are also
+
+         PNG_NO_FILTERS
+         PNG_ALL_FILTERS
+    */
     png_set_filter(pngxP->png_ptr, 0, filterSet);
 }
 
diff --git a/converter/other/pnmtoddif.c b/converter/other/pnmtoddif.c
index ac02e425..b7b942b3 100644
--- a/converter/other/pnmtoddif.c
+++ b/converter/other/pnmtoddif.c
@@ -53,7 +53,7 @@ typedef struct {
 #define CONS 1
 
 /* "tag": Emit an ASN tag of the specified class and tag number.    */
-/* This is used in conjuntion with the                  */
+/* This is used in conjunction with the                  */
 /* wr_xxx routines that follow to construct the various ASN.1 entities. */
 /* Writing each entity is a two-step process, where first the tag is    */
 /* written and then the length and value.               */
@@ -263,7 +263,7 @@ write_header(FILE *file, imageparams *ip)
     tag(&p,CONTEXT,CONS, 0); ind(&p);        /* Document Descriptor */
     tag(&p,CONTEXT,PRIM, 0); wr_int(&p,1);  /* Major Version */
     tag(&p,CONTEXT,PRIM, 1); wr_int(&p,3);  /* Minor Version */
-    tag(&p,CONTEXT,PRIM, 2); wr_string(&p,"PBM+"); /* Product Indentifier */
+    tag(&p,CONTEXT,PRIM, 2); wr_string(&p,"PBM+"); /* Product Identifier */
     tag(&p,CONTEXT,CONS, 3); ind(&p);       /* Product Name */
     tag(&p,PRIVATE,PRIM, 9); emit_isolatin1(&p,"PBMPLUS Writer V1.0");
     eoc(&p);
diff --git a/converter/other/pnmtojpeg.c b/converter/other/pnmtojpeg.c
index 44826245..e3458319 100644
--- a/converter/other/pnmtojpeg.c
+++ b/converter/other/pnmtojpeg.c
@@ -9,7 +9,7 @@
   This program is by Bryan Henderson on 2000.03.06, but is derived
   with permission from the program cjpeg, which is in the Independent
   Jpeg Group's JPEG library package.  Under the terms of that permission,
-  redistribution of this software is restricted as described in the 
+  redistribution of this software is restricted as described in the
   file README.JPEG.
 
   Copyright (C) 1991-1998, Thomas G. Lane.
@@ -84,12 +84,12 @@ struct cmdlineInfo {
     struct density density;
 };
 
-static void 
-interpret_maxmemory (const char * const maxmemory, 
-                     long int * const max_memory_to_use_p) { 
+static void
+interpret_maxmemory (const char * const maxmemory,
+                     long int * const max_memory_to_use_p) {
     long int lval;
     char ch;
-    
+
     if (maxmemory == NULL) {
         *max_memory_to_use_p = -1;  /* unspecified */
     } else if (sscanf(maxmemory, "%ld%c", &lval, &ch) < 1) {
@@ -119,9 +119,9 @@ interpret_restart(const char * const restart,
         long lval;
         char ch;
         unsigned int matches;
-        
+
         matches= sscanf(restart, "%ld%c", &lval, &ch);
-        if (matches == 0) 
+        if (matches == 0)
             pm_error("Invalid value for the --restart option : '%s'.",
                      restart);
         else {
@@ -160,7 +160,7 @@ interpret_density(const char *        const densityString,
         int horiz, vert;
 
         unitName = malloc(strlen(densityString)+1);
-    
+
         matched = sscanf(densityString, "%dx%d%s", &horiz, &vert, unitName);
 
         if (matched < 2)
@@ -178,7 +178,7 @@ interpret_density(const char *        const densityString,
                 densityP->horiz = horiz;
                 densityP->vert  = vert;
 
-                if (matched < 3) 
+                if (matched < 3)
                     densityP->unit = DEN_UNSPECIFIED;
                 else {
                     if (streq(unitName, "dpi") || streq(unitName, "DPI"))
@@ -235,7 +235,7 @@ parseCommandLine(const int argc, char ** argv,
 
     option_def_index = 0;   /* incremented by OPTENTRY */
     OPTENT3(0, "verbose",     OPT_FLAG,   NULL, &cmdlineP->verbose,        0);
-    OPTENT3(0, "quality",     OPT_UINT,   &cmdlineP->quality, 
+    OPTENT3(0, "quality",     OPT_UINT,   &cmdlineP->quality,
             &qualitySpec,        0);
     OPTENT3(0, "baseline",    OPT_FLAG,   NULL, &cmdlineP->force_baseline, 0);
     OPTENT3(0, "progressive", OPT_FLAG,   NULL, &cmdlineP->progressive,    0);
@@ -250,14 +250,14 @@ parseCommandLine(const int argc, char ** argv,
     OPTENT3(0, "qtables",     OPT_STRING, &cmdlineP->qtablefile,  NULL,    0);
     OPTENT3(0, "sample",      OPT_STRING, &cmdlineP->sample,      NULL,    0);
     OPTENT3(0, "scans",       OPT_STRING, &cmdlineP->scans,       NULL,    0);
-    OPTENT3(0, "smooth",      OPT_UINT,   &cmdlineP->smoothing_factor, 
+    OPTENT3(0, "smooth",      OPT_UINT,   &cmdlineP->smoothing_factor,
             &smoothSpec,  0);
     OPTENT3(0, "optimize",    OPT_FLAG,   NULL, &cmdlineP->optimize,       0);
     OPTENT3(0, "optimise",    OPT_FLAG,   NULL, &cmdlineP->optimize,       0);
     OPTENT3(0, "restart",     OPT_STRING, &restart, NULL,                   0);
     OPTENT3(0, "comment",     OPT_STRING, &cmdlineP->comment, NULL,        0);
     OPTENT3(0, "exif",        OPT_STRING, &cmdlineP->exif_filespec, NULL,  0);
-    OPTENT3(0, "density",     OPT_STRING, &density, 
+    OPTENT3(0, "density",     OPT_STRING, &density,
             &cmdlineP->density_spec, 0);
 
     /* Set the defaults */
@@ -295,7 +295,7 @@ parseCommandLine(const int argc, char ** argv,
         cmdlineP->input_filespec = strdup("-");  /* he wants stdin */
     else if (argc_parse - 1 == 1)
         cmdlineP->input_filespec = strdup(argv_parse[1]);
-    else 
+    else
         pm_error("Too many arguments.  The only argument accepted "
                  "is the input file specification.");
     if (dctval == NULL)
@@ -314,15 +314,15 @@ parseCommandLine(const int argc, char ** argv,
     interpret_maxmemory(maxmemory, &cmdlineP->max_memory_to_use);
     interpret_restart(restart, &cmdlineP->restart_value,
                       &cmdlineP->restart_unit);
-    if (cmdlineP->density_spec) 
+    if (cmdlineP->density_spec)
         interpret_density(density, &cmdlineP->density);
-    
+
     if (cmdlineP->smoothing_factor > 100)
         pm_error("Smoothing factor %d is greater than 100 (%%).",
                  cmdlineP->smoothing_factor);
 
     if (streq(cmdlineP->input_filespec, "=") &&
-        cmdlineP->exif_filespec && 
+        cmdlineP->exif_filespec &&
         streq(cmdlineP->exif_filespec, "-"))
 
         pm_error("Cannot have both input image and exif header be from "
@@ -336,7 +336,7 @@ parseCommandLine(const int argc, char ** argv,
 
 static void
 report_compressor(const struct jpeg_compress_struct cinfo) {
-    
+
     if (cinfo.scan_info == NULL)
         pm_message("No scan script is being used");
     else {
@@ -346,7 +346,7 @@ report_compressor(const struct jpeg_compress_struct cinfo) {
         for (i = 0; i < cinfo.num_scans; i++) {
             int j;
             pm_message("    Scan %2d: Ss=%2d Se=%2d Ah=%2d Al=%2d  "
-                       "%d components", 
+                       "%d components",
                        i,
                        cinfo.scan_info[i].Ss,
                        cinfo.scan_info[i].Se,
@@ -364,11 +364,11 @@ report_compressor(const struct jpeg_compress_struct cinfo) {
 
 
 static void
-setup_jpeg_source_parameters(struct jpeg_compress_struct * const cinfoP, 
-                             int const width, int const height, 
+setup_jpeg_source_parameters(struct jpeg_compress_struct * const cinfoP,
+                             int const width, int const height,
                              int const format) {
 /*----------------------------------------------------------------------------
-   Set up in the compressor descriptor *cinfoP the description of the 
+   Set up in the compressor descriptor *cinfoP the description of the
    source image as required by the compressor.
 -----------------------------------------------------------------------------*/
 
@@ -379,7 +379,7 @@ setup_jpeg_source_parameters(struct jpeg_compress_struct * const cinfoP,
         cinfoP->input_components = 1;
         break;
     case PPM_TYPE:
-        cinfoP->in_color_space = JCS_RGB; 
+        cinfoP->in_color_space = JCS_RGB;
         cinfoP->input_components = 3;
         break;
     default:
@@ -391,7 +391,7 @@ setup_jpeg_source_parameters(struct jpeg_compress_struct * const cinfoP,
 
 
 static void
-setup_jpeg_density(struct jpeg_compress_struct * const cinfoP, 
+setup_jpeg_density(struct jpeg_compress_struct * const cinfoP,
                    struct density                const density) {
 /*----------------------------------------------------------------------------
    Set up in the compressor descriptor *cinfoP the density information
@@ -402,7 +402,7 @@ setup_jpeg_density(struct jpeg_compress_struct * const cinfoP,
     case DEN_DOTS_PER_INCH: cinfoP->density_unit = 1; break;
     case DEN_DOTS_PER_CM:   cinfoP->density_unit = 2; break;
     }
-    
+
     cinfoP->X_density = density.horiz;
     cinfoP->Y_density = density.vert;
 }
@@ -411,7 +411,7 @@ setup_jpeg_density(struct jpeg_compress_struct * const cinfoP,
 
 /*----------------------------------------------------------------------------
    The functions below here are essentially the file rdswitch.c from
-   the JPEG library.  They perform the functions specifed by the following
+   the JPEG library.  They perform the functions specified by the following
    pnmtojpeg options:
 
    -qtables file          Read quantization tables from text file
@@ -426,7 +426,7 @@ text_getc (FILE * file)
 /* A comment/newline sequence is returned as a newline */
 {
     register int ch;
-  
+
     ch = getc(file);
     if (ch == '#') {
         do {
@@ -454,12 +454,12 @@ readTextInteger(FILE * const fileP,
 -----------------------------------------------------------------------------*/
     int ch;
     boolean retval;
-  
+
     /* Skip any leading whitespace, detect EOF */
     do {
         ch = text_getc(fileP);
     } while (isspace(ch));
-  
+
     if (!isdigit(ch))
         retval = FALSE;
     else {
@@ -554,7 +554,7 @@ read_scan_script(j_compress_ptr const cinfo,
         ncomps = 1;
         while (termchar == ' ') {
             if (ncomps >= MAX_COMPS_IN_SCAN) {
-                pm_message("Too many components in one scan in file %s", 
+                pm_message("Too many components in one scan in file %s",
                            filename);
                 fclose(fp);
                 return FALSE;
@@ -603,10 +603,10 @@ read_scan_script(j_compress_ptr const cinfo,
         /* Stash completed scan list in cinfo structure.  NOTE: in
            this program, JPOOL_IMAGE is the right lifetime for this
            data, but if you want to compress multiple images you'd
-           want JPOOL_PERMANENT.  
+           want JPOOL_PERMANENT.
         */
         const unsigned int scan_info_size = nscans * sizeof(jpeg_scan_info);
-        jpeg_scan_info * const scan_info = 
+        jpeg_scan_info * const scan_info =
             (jpeg_scan_info *)
             (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
                                         scan_info_size);
@@ -656,7 +656,7 @@ read_quant_tables (j_compress_ptr cinfo, char * filename,
                 if (tblno >= NUM_QUANT_TBLS) {
                     pm_message("Too many tables in file %s", filename);
                     error = TRUE;
-                } else { 
+                } else {
                     unsigned int table[DCTSIZE2];
                     unsigned int i;
 
@@ -686,7 +686,7 @@ read_quant_tables (j_compress_ptr cinfo, char * filename,
         fclose(fp);
         retval = !error;
     }
-        
+
     return retval;
 }
 
@@ -717,7 +717,7 @@ set_quant_slots (j_compress_ptr cinfo, char *arg)
                 return FALSE;
             }
             cinfo->comp_info[ci].quant_tbl_no = val;
-            while (*arg && *arg++ != ',') 
+            while (*arg && *arg++ != ',')
                 /* advance to next segment of arg string */
                 ;
         } else {
@@ -747,7 +747,7 @@ set_sample_factors (j_compress_ptr cinfo, char *arg)
             if ((ch1 != 'x' && ch1 != 'X') || ch2 != ',') /* syntax check */
                 return FALSE;
             if (val1 <= 0 || val1 > 4) {
-                pm_message("Invalid sampling factor: %d.  " 
+                pm_message("Invalid sampling factor: %d.  "
                            "JPEG sampling factors must be 1..4", val1);
                 return FALSE;
             }
@@ -758,11 +758,11 @@ set_sample_factors (j_compress_ptr cinfo, char *arg)
             }
             cinfo->comp_info[ci].h_samp_factor = val1;
             cinfo->comp_info[ci].v_samp_factor = val2;
-            while (*arg && *arg++ != ',') 
+            while (*arg && *arg++ != ',')
                 /* advance to next segment of arg string */
                 ;
         } else {
-            /* reached end of parameter, set remaining components 
+            /* reached end of parameter, set remaining components
                to 1x1 sampling */
             cinfo->comp_info[ci].h_samp_factor = 1;
             cinfo->comp_info[ci].v_samp_factor = 1;
@@ -776,13 +776,13 @@ set_sample_factors (j_compress_ptr cinfo, char *arg)
 static void
 setup_jpeg(struct jpeg_compress_struct * const cinfoP,
            struct jpeg_error_mgr       * const jerrP,
-           struct cmdlineInfo            const cmdline, 
+           struct cmdlineInfo            const cmdline,
            int                           const width,
            int                           const height,
            pixval                        const maxval,
            int                           const input_fmt,
            FILE *                        const output_file) {
-  
+
     int quality;
     int q_scale_factor;
 
@@ -794,14 +794,14 @@ setup_jpeg(struct jpeg_compress_struct * const cinfoP,
 
     jpeg_set_defaults(cinfoP);
 
-    cinfoP->data_precision = BITS_IN_JSAMPLE; 
+    cinfoP->data_precision = BITS_IN_JSAMPLE;
         /* we always rescale data to this */
     cinfoP->image_width = (unsigned int) width;
     cinfoP->image_height = (unsigned int) height;
 
     cinfoP->arith_code = cmdline.arith_code;
     cinfoP->dct_method = cmdline.dct_method;
-    if (cmdline.trace_level == 0 && cmdline.verbose) 
+    if (cmdline.trace_level == 0 && cmdline.verbose)
         cinfoP->err->trace_level = 1;
     else cinfoP->err->trace_level = cmdline.trace_level;
     if (cmdline.grayscale)
@@ -822,26 +822,26 @@ setup_jpeg(struct jpeg_compress_struct * const cinfoP,
         quality = cmdline.quality;
         q_scale_factor = jpeg_quality_scaling(cmdline.quality);
     }
-    if (cmdline.smoothing_factor != -1) 
+    if (cmdline.smoothing_factor != -1)
         cinfoP->smoothing_factor = cmdline.smoothing_factor;
 
     /* Set quantization tables for selected quality. */
     /* Some or all may be overridden if user specified --qtables. */
     jpeg_set_quality(cinfoP, quality, cmdline.force_baseline);
-                   
+
     if (cmdline.qtablefile != NULL) {
         if (! read_quant_tables(cinfoP, cmdline.qtablefile,
-                                q_scale_factor, cmdline.force_baseline)) 
+                                q_scale_factor, cmdline.force_baseline))
             pm_error("Can't use quantization table file '%s'.",
                      cmdline.qtablefile);
     }
-   
+
     if (cmdline.qslots != NULL) {
         if (! set_quant_slots(cinfoP, cmdline.qslots))
-            pm_error("Bad quantization-table-selectors parameter string '%s'.", 
+            pm_error("Bad quantization-table-selectors parameter string '%s'.",
                      cmdline.qslots);
     }
-          
+
     if (cmdline.sample != NULL) {
         if (! set_sample_factors(cinfoP, cmdline.sample))
             pm_error("Bad sample-factors parameters string '%s'.",
@@ -878,7 +878,7 @@ write_exif_header(struct jpeg_compress_struct * const cinfoP,
 /*----------------------------------------------------------------------------
    Generate an APP1 marker in the JFIF output that is an Exif header.
 
-   The contents of the Exif header are in the file with filespec 
+   The contents of the Exif header are in the file with filespec
    'exif_filespec' (file spec and contents are not validated).
 
    exif_filespec = "-" means Standard Input.
@@ -888,7 +888,7 @@ write_exif_header(struct jpeg_compress_struct * const cinfoP,
 -----------------------------------------------------------------------------*/
     FILE * exif_file;
     unsigned short length;
-    
+
     exif_file = pm_openr(exif_filespec);
 
     pm_readbigshort(exif_file, (short*)&length);
@@ -900,7 +900,7 @@ write_exif_header(struct jpeg_compress_struct * const cinfoP,
     else {
         unsigned char * exif_data;
         size_t rc;
-        size_t const data_length = length - 2;  
+        size_t const data_length = length - 2;
             /* Subtract 2 byte length field*/
 
         assert(data_length > 0);
@@ -917,16 +917,16 @@ write_exif_header(struct jpeg_compress_struct * const cinfoP,
                      "%u bytes of data, read only %u",
                      (unsigned)data_length, (unsigned)rc);
 
-        jpeg_write_marker(cinfoP, JPEG_APP0+1, 
+        jpeg_write_marker(cinfoP, JPEG_APP0+1,
                           (const JOCTET *) exif_data, data_length);
 
         free(exif_data);
     }
-    
+
     pm_close(exif_file);
 }
 
-                  
+
 
 static void
 compute_rescaling_array(JSAMPLE ** const rescale_p, const pixval maxval,
@@ -940,7 +940,7 @@ compute_rescaling_array(JSAMPLE ** const rescale_p, const pixval maxval,
 
   *rescale_p = (JSAMPLE *)
     (cinfo.mem->alloc_small) ((j_common_ptr) &cinfo, JPOOL_IMAGE,
-                              (size_t) (((long) maxval + 1L) * 
+                              (size_t) (((long) maxval + 1L) *
                                         sizeof(JSAMPLE)));
   for (val = 0; val <= maxval; val++) {
     /* The multiplication here must be done in 32 bits to avoid overflow */
@@ -951,9 +951,9 @@ compute_rescaling_array(JSAMPLE ** const rescale_p, const pixval maxval,
 
 
 static void
-translate_row(const pixel pnm_buffer[], 
-              JSAMPLE jpeg_buffer[], 
-              int const width, 
+translate_row(const pixel pnm_buffer[],
+              JSAMPLE jpeg_buffer[],
+              int const width,
               int const input_components,
               const JSAMPLE translate[]) {
 /*----------------------------------------------------------------------------
@@ -971,16 +971,16 @@ translate_row(const pixel pnm_buffer[],
 
   switch (input_components) {
   case 1:
-      for (column = 0; column < width; column++) 
+      for (column = 0; column < width; column++)
           jpeg_buffer[column] = translate[(int)PNM_GET1(pnm_buffer[column])];
       break;
   case 3:
       for (column = 0; column < width; column++) {
-          jpeg_buffer[column*3+0] = 
+          jpeg_buffer[column*3+0] =
               translate[(int)PPM_GETR(pnm_buffer[column])];
-          jpeg_buffer[column*3+1] = 
+          jpeg_buffer[column*3+1] =
               translate[(int)PPM_GETG(pnm_buffer[column])];
-          jpeg_buffer[column*3+2] = 
+          jpeg_buffer[column*3+2] =
               translate[(int)PPM_GETB(pnm_buffer[column])];
       }
       break;
@@ -1000,17 +1000,17 @@ convert_scanlines(struct jpeg_compress_struct * const cinfo_p,
                   int                           const input_fmt,
                   JSAMPLE                             xlate_table[]){
 /*----------------------------------------------------------------------------
-   Read scan lines from the input file, which is already opened in the 
-   netpbm library sense and ready for reading, and write them to the 
+   Read scan lines from the input file, which is already opened in the
+   netpbm library sense and ready for reading, and write them to the
    output JPEG object.  Translate the pnm sample values to JPEG sample
    values through the thable xlate_table[].
 -----------------------------------------------------------------------------*/
-  xel * pnm_buffer;  
+  xel * pnm_buffer;
     /* contains the row of the input image currently being processed,
        in pnm_readpnmrow format
     */
   JSAMPARRAY buffer;
-    /* Row 0 of this array contains the row of the output image currently 
+    /* Row 0 of this array contains the row of the output image currently
        being processed, in JPEG compressor input format.  The array only
        has that one row.
     */
@@ -1018,26 +1018,26 @@ convert_scanlines(struct jpeg_compress_struct * const cinfo_p,
   /* Allocate the libpnm output and compressor input buffers */
   buffer = (*cinfo_p->mem->alloc_sarray)
     ((j_common_ptr) cinfo_p, JPOOL_IMAGE,
-     (unsigned int) cinfo_p->image_width * cinfo_p->input_components, 
+     (unsigned int) cinfo_p->image_width * cinfo_p->input_components,
      (unsigned int) 1);
-  
+
   pnm_buffer = pnm_allocrow(cinfo_p->image_width);
 
   while (cinfo_p->next_scanline < cinfo_p->image_height) {
-    if (cinfo_p->err->trace_level > 1) 
+    if (cinfo_p->err->trace_level > 1)
         pm_message("Converting Row %d...", cinfo_p->next_scanline);
-    pnm_readpnmrow(input_file, pnm_buffer, cinfo_p->image_width, 
+    pnm_readpnmrow(input_file, pnm_buffer, cinfo_p->image_width,
                    maxval, input_fmt);
-    translate_row(pnm_buffer, buffer[0], 
+    translate_row(pnm_buffer, buffer[0],
                   cinfo_p->image_width, cinfo_p->input_components,
                   xlate_table);
     jpeg_write_scanlines(cinfo_p, buffer, 1);
-    if (cinfo_p->err->trace_level > 1) 
+    if (cinfo_p->err->trace_level > 1)
         pm_message("Done.");
   }
 
   pnm_freerow(pnm_buffer);
-  /* Don't worry about the compressor input buffer; it gets freed 
+  /* Don't worry about the compressor input buffer; it gets freed
      automatically
   */
 }
@@ -1053,11 +1053,11 @@ main(int     argc,
     struct jpeg_error_mgr jerr;
     FILE * input_file;
     FILE * output_file;
-    int height;  
+    int height;
         /* height of the input image in rows, as specified by its header */
-    int width;   
+    int width;
         /* width of the input image in columns, as specified by its header */
-    pixval maxval;  
+    pixval maxval;
         /* maximum value of an input pixel component, as specified by header */
     int input_fmt;
         /* The input format, as determined by its header.  */
@@ -1081,7 +1081,7 @@ main(int     argc,
     if (cmdline.verbose) {
         pm_message("Input file has format %c%c.\n"
                    "It has %d rows of %d columns of pixels "
-                   "with max sample value of %d.", 
+                   "with max sample value of %d.",
                    (char) (input_fmt/256), (char) (input_fmt % 256),
                    height, width, maxval);
     }
@@ -1091,13 +1091,13 @@ main(int     argc,
 
     compute_rescaling_array(&rescale, maxval, cinfo);
 
-    if (cmdline.comment) 
-        jpeg_write_marker(&cinfo, JPEG_COM, (const JOCTET *) cmdline.comment, 
+    if (cmdline.comment)
+        jpeg_write_marker(&cinfo, JPEG_COM, (const JOCTET *) cmdline.comment,
                           strlen(cmdline.comment));
 
     if (cmdline.exif_filespec)
         write_exif_header(&cinfo, cmdline.exif_filespec);
-    
+
     /* Translate and copy over the actual scanlines */
     convert_scanlines(&cinfo, input_file, maxval, input_fmt, rescale);
 
@@ -1110,7 +1110,10 @@ main(int     argc,
         pm_close(input_file);
 
     /* Program may have exited with non-zero completion code via
-       various function calls above. 
+       various function calls above.
     */
     return jerr.num_warnings > 0 ? EXIT_WARNING : EXIT_SUCCESS;
 }
+
+
+
diff --git a/converter/other/pnmtopalm/README b/converter/other/pnmtopalm/README
index ebae9492..3a2cf18d 100644
--- a/converter/other/pnmtopalm/README
+++ b/converter/other/pnmtopalm/README
@@ -40,7 +40,7 @@ Usage: ppmtoTbmp [-2bit] [file.ppm]
 If the ppm file is not specified, one is read from stdin.  The -2bit option
 produces a 2-bit bitmap instead of the normal 1-bit bitmap.  The ppm must
 have at most 4 colors in it (for 2-bit) or at most 2 colors (for 1-bit).
-Common invokations might be:
+Common invocations might be:
 
 xbmtopbm icon.xbm | ppmquant -fs -map q2.map | ppmtoTbmp > tAIB03e8.bin
 giftopnm image.gif | ppmquant -fs -map q4.map | ppmtoTbmp -2bit > Tbmp0bb8.bin
diff --git a/converter/other/pnmtopalm/palmtopnm.c b/converter/other/pnmtopalm/palmtopnm.c
index 0666141d..a64ab01c 100644
--- a/converter/other/pnmtopalm/palmtopnm.c
+++ b/converter/other/pnmtopalm/palmtopnm.c
@@ -798,10 +798,12 @@ readRleRow(FILE *          const ifP,
         if (incount == 0)
             pm_error("Invalid (zero) count in RLE compression.");
         if (j + incount > bytesPerRow)
-            pm_error("Bytes in RLE compressed row exceed bytes per row.  "
-                     "Bytes per row is %u.  A run length of %u bytes "
-                     "pushes the bytes in this row up to %u bytes (and then "
-                     "we gave up).", bytesPerRow, incount, j + incount);
+            pm_error("Invalid Palm image input.  Header says %u bytes "
+                     "per row after uncompressing from RLE, "
+                     "but we encountered a row with a run length of %u bytes "
+                     "that pushes the bytes in the row up to %u bytes "
+                     "(and we didn't look at the rest of the row)",
+                     bytesPerRow, incount, j + incount);
         pm_readcharu(ifP, &inval);
         memset(palmrow + j, inval, incount);
         j += incount;
@@ -867,10 +869,11 @@ readPackBitsRow16(FILE *          const ifP,
             j += nonrunlength;
         }
         if (j > bytesPerRow)
-            pm_error("Bytes in PackBits compressed row exceed bytes per row.  "
-                     "Bytes per row is %u.  "
-                     "The bytes in this row were pushed up to %u bytes "
-                     "(and then we gave up).", bytesPerRow, j);
+            pm_error("Invalid Palm image input.  Header says %u bytes "
+                     "per row after uncompressing from 16-bit Packbits at, "
+                     "but we counted %u bytes in a row, "
+                     "before we stopped processing the row",
+                     bytesPerRow, j);
     }
 }
 
@@ -915,10 +918,11 @@ readPackBitsRow(FILE *          const ifP,
             j += nonrunlength;
         }
         if (j > bytesPerRow)
-            pm_error("Bytes in PackBits compressed row exceed bytes per row.  "
-                     "Bytes per row is %u.  "
-                     "The bytes in this row were pushed up to %u bytes "
-                     "(and then we gave up).", bytesPerRow, j);
+            pm_error("Invalid Palm image input.  Header says %u bytes "
+                     "per row after uncompressing from 8-bit Packbits, "
+                     "but we counted %u bytes in a row, "
+                     "before we stopped processing the row",
+                     bytesPerRow, j);
     }
 }
 
diff --git a/converter/other/pnmtopalm/pnmtopalm.c b/converter/other/pnmtopalm/pnmtopalm.c
index 25c8af2e..9fc92790 100644
--- a/converter/other/pnmtopalm/pnmtopalm.c
+++ b/converter/other/pnmtopalm/pnmtopalm.c
@@ -74,27 +74,27 @@ parseCommandLine(int argc, const char ** argv, struct CmdlineInfo *cmdlineP) {
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENTRY */
-    OPTENT3(0, "transparent",      OPT_STRING, 
+    OPTENT3(0, "transparent",      OPT_STRING,
             &cmdlineP->transparent, &transSpec, 0);
-    OPTENT3(0, "depth",            OPT_UINT, 
+    OPTENT3(0, "depth",            OPT_UINT,
             &cmdlineP->depth,       &cmdlineP->depthSpec, 0);
-    OPTENT3(0, "maxdepth",         OPT_UINT, 
+    OPTENT3(0, "maxdepth",         OPT_UINT,
             &cmdlineP->maxdepth,    &cmdlineP->maxdepthSpec, 0);
-    OPTENT3(0, "scanline_compression", OPT_FLAG, 
+    OPTENT3(0, "scanline_compression", OPT_FLAG,
             NULL,                   &scanline_compression, 0);
-    OPTENT3(0, "rle_compression",  OPT_FLAG, 
+    OPTENT3(0, "rle_compression",  OPT_FLAG,
             NULL,                   &rle_compression, 0);
-    OPTENT3(0, "packbits_compression", OPT_FLAG, 
+    OPTENT3(0, "packbits_compression", OPT_FLAG,
             NULL,                   &packbits_compression, 0);
-    OPTENT3(0, "verbose",          OPT_FLAG, 
+    OPTENT3(0, "verbose",          OPT_FLAG,
             NULL,                   &cmdlineP->verbose, 0);
-    OPTENT3(0, "colormap",         OPT_FLAG, 
+    OPTENT3(0, "colormap",         OPT_FLAG,
             NULL,                   &cmdlineP->colormap, 0);
-    OPTENT3(0, "offset",           OPT_FLAG, 
+    OPTENT3(0, "offset",           OPT_FLAG,
             NULL,                   &cmdlineP->offset, 0);
-    OPTENT3(0, "density",          OPT_UINT, 
+    OPTENT3(0, "density",          OPT_UINT,
             &cmdlineP->density,     &densitySpec, 0);
-    OPTENT3(0, "withdummy",        OPT_FLAG, 
+    OPTENT3(0, "withdummy",        OPT_FLAG,
             NULL,                   &cmdlineP->withdummy, 0);
 
     opt.opt_table = option_def;
@@ -105,7 +105,7 @@ parseCommandLine(int argc, const char ** argv, struct CmdlineInfo *cmdlineP) {
         /* Uses and sets argc, argv, and some of *cmdline_p and others. */
 
     if (cmdlineP->depthSpec) {
-        if (cmdlineP->depth != 1 && cmdlineP->depth != 2 
+        if (cmdlineP->depth != 1 && cmdlineP->depth != 2
             && cmdlineP->depth != 4 && cmdlineP->depth != 8
             && cmdlineP->depth != 16)
             pm_error("invalid value for -depth: %u.  Valid values are "
@@ -113,14 +113,14 @@ parseCommandLine(int argc, const char ** argv, struct CmdlineInfo *cmdlineP) {
     }
 
     if (cmdlineP->maxdepthSpec) {
-        if (cmdlineP->maxdepth != 1 && cmdlineP->maxdepth != 2 
+        if (cmdlineP->maxdepth != 1 && cmdlineP->maxdepth != 2
             && cmdlineP->maxdepth != 4 && cmdlineP->maxdepth != 8
             && cmdlineP->maxdepth != 16)
             pm_error("invalid value for -maxdepth: %u.  Valid values are "
                      "1, 2, 4, 8, and 16", cmdlineP->maxdepth);
     }
 
-    if (cmdlineP->depthSpec && cmdlineP->maxdepthSpec && 
+    if (cmdlineP->depthSpec && cmdlineP->maxdepthSpec &&
         cmdlineP->depth > cmdlineP->maxdepth)
         pm_error("-depth value (%u) is greater than -maxdepth (%u) value.",
                  cmdlineP->depth, cmdlineP->maxdepth);
@@ -135,7 +135,7 @@ parseCommandLine(int argc, const char ** argv, struct CmdlineInfo *cmdlineP) {
             cmdlineP->density != PALM_DENSITY_TRIPLE &&
             cmdlineP->density != PALM_DENSITY_QUADRUPLE)
             pm_error("Invalid value for -density: %u.  Valid values are "
-                     "%u, %u, %u, %u and %u.", cmdlineP->density, 
+                     "%u, %u, %u, %u and %u.", cmdlineP->density,
                      PALM_DENSITY_LOW, PALM_DENSITY_ONEANDAHALF,
                      PALM_DENSITY_DOUBLE, PALM_DENSITY_TRIPLE,
                      PALM_DENSITY_QUADRUPLE);
@@ -163,11 +163,11 @@ parseCommandLine(int argc, const char ** argv, struct CmdlineInfo *cmdlineP) {
         else
             cmdlineP->compression = COMP_NONE;
     }
-        
+
     if (argc-1 > 1)
         pm_error("This program takes at most 1 argument: the file name.  "
                  "You specified %u", argc-1);
-    else if (argc-1 > 0) 
+    else if (argc-1 > 0)
         cmdlineP->inputFilespec = argv[1];
     else
         cmdlineP->inputFilespec = "-";
@@ -186,16 +186,16 @@ scaleSample(pixval const arg,
 
 
 static void
-determinePalmFormatPgm(xelval               const maxval, 
+determinePalmFormatPgm(xelval               const maxval,
                        bool                 const bppSpecified,
                        unsigned int         const bpp,
                        bool                 const maxBppSpecified,
-                       unsigned int         const maxBpp, 
+                       unsigned int         const maxBpp,
                        bool                 const wantCustomColormap,
                        enum CompressionType const compression,
                        bool                 const verbose,
                        unsigned int *       const bppP) {
-        
+
     /* We can usually handle this one, but may not have enough pixels.  So
        check.
     */
@@ -241,10 +241,10 @@ validateImageAgainstStandardColormap(const Colormap * const colormapP,
         unsigned int col;
 
         for (col = 0; col < cols; ++col) {
-            ColormapEntry const searchTarget = 
+            ColormapEntry const searchTarget =
                 palmcolor_mapEntryColorFmPixel(xels[row][col], maxval, 255);
 
-            ColormapEntry * const foundEntryP = 
+            ColormapEntry * const foundEntryP =
                 (bsearch(&searchTarget,
                          colormapP->color_entries, colormapP->ncolors,
                          sizeof(ColormapEntry), palmcolor_compare_colors));
@@ -261,21 +261,21 @@ validateImageAgainstStandardColormap(const Colormap * const colormapP,
 
 
 static void
-determinePalmFormatPpm(unsigned int         const cols, 
-                       unsigned int         const rows, 
-                       xelval               const maxval, 
+determinePalmFormatPpm(unsigned int         const cols,
+                       unsigned int         const rows,
+                       xelval               const maxval,
                        xel **               const xels,
                        bool                 const bppSpecified,
                        unsigned int         const bpp,
                        bool                 const maxBppSpecified,
-                       unsigned int         const maxBpp, 
+                       unsigned int         const maxBpp,
                        bool                 const wantCustomColormap,
                        enum CompressionType const compression,
                        bool                 const verbose,
-                       unsigned int *       const bppP, 
-                       bool *               const directColorP, 
+                       unsigned int *       const bppP,
+                       bool *               const directColorP,
                        Colormap **          const colormapPP) {
-            
+
     /* We don't attempt to identify PPM files that are actually
        monochrome.  So there are two options here: either 8-bit with a
        colormap, either the standard one or a custom one, or 16-bit direct
@@ -287,7 +287,7 @@ determinePalmFormatPpm(unsigned int         const cols,
        palmcolor8.map file that comes with Netpbm to avoid this).  We try
        for colormapped first, since it works on more PalmOS devices.
     */
-    if ((bppSpecified && bpp == 16) || 
+    if ((bppSpecified && bpp == 16) ||
         (!bppSpecified && maxBppSpecified && maxBpp == 16)) {
         /* we do the 16-bit direct color */
         *directColorP = TRUE;
@@ -296,7 +296,7 @@ determinePalmFormatPpm(unsigned int         const cols,
     } else if (!wantCustomColormap) {
         /* colormapped with the standard colormap */
         Colormap * colormapP;
-            
+
         if ((bppSpecified && bpp != 8) || (maxBppSpecified && maxBpp < 8))
             pm_error("Must use depth of 8 for color Palm Bitmap without "
                      "custom color table.");
@@ -311,7 +311,7 @@ determinePalmFormatPpm(unsigned int         const cols,
             pm_message("Output is color with default colormap at 8 bpp");
     } else {
         /* colormapped with a custom colormap */
-        *colormapPP = 
+        *colormapPP =
             palmcolor_build_custom_8bit_colormap(xels, rows, cols, maxval);
         for (*bppP = 1; (1 << *bppP) < (*colormapPP)->ncolors; *bppP *= 2);
         if (bppSpecified) {
@@ -337,7 +337,7 @@ determinePalmFormatPpm(unsigned int         const cols,
         *directColorP = FALSE;
         if (verbose)
             pm_message("Output is color with custom colormap "
-                       "with %u colors at %u bpp", 
+                       "with %u colors at %u bpp",
                        (*colormapPP)->ncolors, *bppP);
     }
 }
@@ -345,20 +345,20 @@ determinePalmFormatPpm(unsigned int         const cols,
 
 
 static void
-determinePalmFormat(unsigned int         const cols, 
-                    unsigned int         const rows, 
-                    xelval               const maxval, 
-                    int                  const format, 
+determinePalmFormat(unsigned int         const cols,
+                    unsigned int         const rows,
+                    xelval               const maxval,
+                    int                  const format,
                     xel **               const xels,
                     bool                 const bppSpecified,
                     unsigned int         const bpp,
                     bool                 const maxBppSpecified,
-                    unsigned int         const maxBpp, 
+                    unsigned int         const maxBpp,
                     bool                 const wantCustomColormap,
                     enum CompressionType const compression,
                     bool                 const verbose,
-                    unsigned int *       const bppP, 
-                    bool *               const directColorP, 
+                    unsigned int *       const bppP,
+                    bool *               const directColorP,
                     Colormap **          const colormapPP) {
 /*----------------------------------------------------------------------------
    Determine what kind of Palm output file to make.
@@ -414,9 +414,9 @@ determinePalmFormat(unsigned int         const cols,
 
 
 
-static const char * 
+static const char *
 formatName(int const format) {
-    
+
     const char * retval;
 
     switch(PNM_FORMAT_TYPE(format)) {
@@ -428,22 +428,22 @@ formatName(int const format) {
     return retval;
 }
 
-        
+
 
 static void
-findTransparentColor(const char *   const colorSpec, 
+findTransparentColor(const char *   const colorSpec,
                      pixval         const newMaxval,
-                     bool           const directColor, 
-                     pixval         const maxval, 
+                     bool           const directColor,
+                     pixval         const maxval,
                      Colormap *     const colormapP,
-                     xel *          const transcolorP, 
+                     xel *          const transcolorP,
                      unsigned int * const transindexP) {
 
     *transcolorP = ppm_parsecolor(colorSpec, maxval);
     if (!directColor) {
-        ColormapEntry const searchTarget = 
+        ColormapEntry const searchTarget =
             palmcolor_mapEntryColorFmPixel(*transcolorP, maxval, newMaxval);
-        ColormapEntry * const foundEntryP = 
+        ColormapEntry * const foundEntryP =
             (bsearch(&searchTarget,
                      colormapP->color_entries, colormapP->ncolors,
                      sizeof(ColormapEntry), palmcolor_compare_colors));
@@ -530,7 +530,7 @@ writeCommonHeader(unsigned int         const cols,
 
 
 
-static unsigned char 
+static unsigned char
 compressionFieldValue(enum CompressionType const compression) {
 
     unsigned char retval;
@@ -560,7 +560,7 @@ writeRemainingHeaderLow(unsigned int         const nextDepthOffset,
                         enum CompressionType const compression,
                         unsigned int         const bpp) {
 /*----------------------------------------------------------------------------
-   Write last 6 bytes of a low density Palm Bitmap header. 
+   Write last 6 bytes of a low density Palm Bitmap header.
 -----------------------------------------------------------------------------*/
     if (nextDepthOffset > USHRT_MAX)
         pm_error("Image too large for Palm Bitmap");
@@ -572,7 +572,7 @@ writeRemainingHeaderLow(unsigned int         const nextDepthOffset,
         fputc(transindex, stdout);    /* transparent index */
     } else
         fputc(0, stdout);    /* the DirectInfoType will hold this info */
-    
+
     fputc(compressionFieldValue(compression), stdout);
 
     pm_writebigshort(stdout, 0);  /* reserved by Palm */
@@ -590,7 +590,7 @@ writeRemainingHeaderHigh(unsigned int         const bpp,
                          unsigned int         const transindex,
                          unsigned int         const nextBitmapOffset) {
 /*----------------------------------------------------------------------------
-   Write last 16 bytes of a high density Palm Bitmap header. 
+   Write last 16 bytes of a high density Palm Bitmap header.
 -----------------------------------------------------------------------------*/
     if ((nextBitmapOffset >> 31) > 1)
         pm_error("Image too large for Palm Bitmap.  nextBitmapOffset "
@@ -648,7 +648,7 @@ writeDummy() {
     pm_writebiglong(stdout, 0x00);
     fputc(0xFF, stdout);               /* pixelSize */
     fputc(0x01, stdout);               /* version */
-    pm_writebigshort(stdout, 0x00); 
+    pm_writebigshort(stdout, 0x00);
     pm_writebiglong(stdout, 0x00);
 }
 
@@ -663,7 +663,7 @@ writeColormap(bool         const explicitColormap,
               xel          const transcolor,
               xelval       const maxval,
               unsigned int const version) {
-              
+
     /* if there's a colormap, write it out */
     if (explicitColormap) {
         unsigned int row;
@@ -681,11 +681,11 @@ writeColormap(bool         const explicitColormap,
         /* write the DirectInfoType (8 bytes) */
         if (bpp == 16) {
             fputc(5, stdout);   /* # of bits of red */
-            fputc(6, stdout);   /* # of bits of green */    
+            fputc(6, stdout);   /* # of bits of green */
             fputc(5, stdout);   /* # of bits of blue */
             fputc(0, stdout);   /* reserved by Palm */
         } else
-            pm_error("Don't know how to create %u bit DirectColor bitmaps.", 
+            pm_error("Don't know how to create %u bit DirectColor bitmaps.",
                      bpp);
         if (transparent) {
             fputc(0, stdout);
@@ -714,13 +714,13 @@ computeRawRowDirectColor(const xel *     const xelrow,
   'xelrow' is the image contents of row.  It is 'cols' columns wide and
   samples are based on maxval 'maxval'.
 
-  Put the output data at 'rowdata'. 
+  Put the output data at 'rowdata'.
 -----------------------------------------------------------------------------*/
     unsigned int col;
     unsigned char * outCursor;
-    
+
     for (col = 0, outCursor = &rowdata[0]; col < cols; ++col) {
-        unsigned int const color = 
+        unsigned int const color =
             (scaleSample(PPM_GETR(xelrow[col]), maxval, 31) << 11) |
             (scaleSample(PPM_GETG(xelrow[col]), maxval, 63) <<  5) |
             (scaleSample(PPM_GETB(xelrow[col]), maxval, 31) <<  0);
@@ -782,16 +782,16 @@ computeRawRowNonDirect(const xel *     const xelrow,
                 palmcolor_mapEntryColorFmPixel(xelrow[col], maxval, 255);
             ColormapEntry * const foundEntryP =
                 bsearch(&searchTarget,
-                        colormapP->color_entries, 
+                        colormapP->color_entries,
                         colormapP->ncolors,
-                        sizeof(ColormapEntry), 
+                        sizeof(ColormapEntry),
                         palmcolor_compare_colors);
             if (!foundEntryP) {
-                pm_error("INERNAL ERROR: "
+                pm_error("INTERNAL ERROR: "
                          "Color (%u,%u,%u) not found in colormap, "
                          "though it was supposedly there before",
-                         PPM_GETR(xelrow[col]), 
-                         PPM_GETG(xelrow[col]), 
+                         PPM_GETR(xelrow[col]),
+                         PPM_GETG(xelrow[col]),
                          PPM_GETB(xelrow[col]));
             }
             color = (*foundEntryP >> 24) & 0xFF;
@@ -816,27 +816,27 @@ computeRawRowNonDirect(const xel *     const xelrow,
 }
 
 
-struct seqBuffer {
+typedef struct {
 /*----------------------------------------------------------------------------
    A buffer to which one can write bytes sequentially.
 -----------------------------------------------------------------------------*/
     char * buffer;
     unsigned int allocatedSize;
     unsigned int occupiedSize;
-};
+} SeqBuffer;
 
 
 static void
-createBuffer(struct seqBuffer ** const bufferPP) {
+seqBuffer_create(SeqBuffer ** const bufferPP) {
 
-    struct seqBuffer * bufferP;
+    SeqBuffer * bufferP;
 
     MALLOCVAR_NOFAIL(bufferP);
 
     bufferP->allocatedSize = 4096;
     MALLOCARRAY(bufferP->buffer, bufferP->allocatedSize);
     if (bufferP == NULL)
-        pm_error("Unable to allocate %u bytes of buffer", 
+        pm_error("Unable to allocate %u bytes of buffer",
                  bufferP->allocatedSize);
     bufferP->occupiedSize = 0;
 
@@ -846,7 +846,7 @@ createBuffer(struct seqBuffer ** const bufferPP) {
 
 
 static void
-destroyBuffer(struct seqBuffer * const bufferP) {
+seqBuffer_destroy(SeqBuffer * const bufferP) {
 
     free(bufferP->buffer);
     free(bufferP);
@@ -855,8 +855,8 @@ destroyBuffer(struct seqBuffer * const bufferP) {
 
 
 static void
-addByteToBuffer(struct seqBuffer * const bufferP,
-                unsigned char      const newByte) {
+seqBuffer_addByte(SeqBuffer *   const bufferP,
+                  unsigned char const newByte) {
 /*-----------------------------------------------------------------------------
   Append one byte to buffer, expanding with realloc() whenever necessary.
 
@@ -866,7 +866,6 @@ addByteToBuffer(struct seqBuffer * const bufferP,
   compression can lead to an arithmetic overflow.
   Abort with error if an arithmetic overflow is detected during doubling.
 -----------------------------------------------------------------------------*/
-
     assert(bufferP->allocatedSize >= bufferP->occupiedSize);
 
     if (bufferP->allocatedSize == bufferP->occupiedSize) {
@@ -890,19 +889,19 @@ addByteToBuffer(struct seqBuffer * const bufferP,
 
 
 static unsigned int
-bufferLength(struct seqBuffer * const bufferP) {
+seqBuffer_length(SeqBuffer * const bufferP) {
     return bufferP->occupiedSize;
 }
 
 
 
 static void
-writeOutBuffer(struct seqBuffer * const bufferP,
-               FILE *             const fileP) {
+seqBuffer_writeOut(SeqBuffer * const bufferP,
+                   FILE *      const fileP) {
 
     size_t bytesWritten;
 
-    bytesWritten = fwrite(bufferP->buffer, sizeof(char), 
+    bytesWritten = fwrite(bufferP->buffer, sizeof(char),
                           bufferP->occupiedSize, fileP);
 
     if (bytesWritten != bufferP->occupiedSize)
@@ -914,19 +913,19 @@ writeOutBuffer(struct seqBuffer * const bufferP,
 static void
 copyRowToBuffer(const unsigned char * const rowdata,
                 unsigned int          const rowbytes,
-                struct seqBuffer *    const rasterBufferP) {
+                SeqBuffer *           const rasterBufferP) {
 
     unsigned int pos;
     for (pos = 0; pos < rowbytes; ++pos)
-        addByteToBuffer(rasterBufferP, rowdata[pos]);
-} 
+        seqBuffer_addByte(rasterBufferP, rowdata[pos]);
+}
 
 
 
 static void
 scanlineCompressAndBufferRow(const unsigned char * const rowdata,
                              unsigned int          const rowbytes,
-                             struct seqBuffer *    const rasterBufferP,
+                             SeqBuffer *           const rasterBufferP,
                              const unsigned char * const lastrow) {
 /*----------------------------------------------------------------------------
    Take the raw Palm Bitmap row 'rowdata', which is 'rowbytes'
@@ -945,27 +944,27 @@ scanlineCompressAndBufferRow(const unsigned char * const rowdata,
         unsigned char map;
             /* mask indicating which of the next 8 pixels are
                different from the previous row, and therefore present
-               in the file immediately following the map byte.  
+               in the file immediately following the map byte.
             */
         unsigned char differentPixels[8];
         unsigned char *outptr;
         unsigned char outbit;
-            
+
         for (outbit = 0, map = 0x00, outptr = differentPixels;
-             outbit < limit;  
+             outbit < limit;
              ++outbit) {
-            if (!lastrow 
+            if (!lastrow
                 || (lastrow[pos + outbit] != rowdata[pos + outbit])) {
                 map |= (1 << (7 - outbit));
                 *outptr++ = rowdata[pos + outbit];
             }
         }
 
-        addByteToBuffer(rasterBufferP, map);
+        seqBuffer_addByte(rasterBufferP, map);
         {
             unsigned int j;
             for (j = 0; j < (outptr - differentPixels); ++j)
-                addByteToBuffer(rasterBufferP, differentPixels[j]);
+                seqBuffer_addByte(rasterBufferP, differentPixels[j]);
         }
     }
 }
@@ -975,7 +974,7 @@ scanlineCompressAndBufferRow(const unsigned char * const rowdata,
 static void
 rleCompressAndBufferRow(const unsigned char * const rowdata,
                         unsigned int          const rowbytes,
-                        struct seqBuffer *    const rasterBufferP) {
+                        SeqBuffer *           const rasterBufferP) {
 /*----------------------------------------------------------------------------
    Take the raw Palm Bitmap row 'rowdata', which is 'rowbytes' bytes,
    and add the rle-compressed representation of it to the buffer with
@@ -984,19 +983,19 @@ rleCompressAndBufferRow(const unsigned char * const rowdata,
     unsigned int pos;
 
     /* we output a count of the number of bytes a value is
-       repeated, followed by that byte value 
+       repeated, followed by that byte value
     */
     pos = 0;
     while (pos < rowbytes) {
         unsigned int repeatcount;
-        for (repeatcount = 1;  
-             repeatcount < (rowbytes - pos) && repeatcount  < 255;  
-             ++repeatcount) 
+        for (repeatcount = 1;
+             repeatcount < (rowbytes - pos) && repeatcount  < 255;
+             ++repeatcount)
             if (rowdata[pos + repeatcount] != rowdata[pos])
                 break;
 
-        addByteToBuffer(rasterBufferP, repeatcount);
-        addByteToBuffer(rasterBufferP, rowdata[pos]);
+        seqBuffer_addByte(rasterBufferP, repeatcount);
+        seqBuffer_addByte(rasterBufferP, rowdata[pos]);
         pos += repeatcount;
     }
 }
@@ -1006,10 +1005,10 @@ rleCompressAndBufferRow(const unsigned char * const rowdata,
 static void
 packbitsCompressAndBufferRow(const unsigned char * const rowdata,
                              unsigned int          const rowbytes,
-                             struct seqBuffer *    const rasterBufferP) {
+                             SeqBuffer *           const rasterBufferP) {
 /*----------------------------------------------------------------------------
    Take the raw Palm Bitmap row 'rowdata', which is 'rowbytes' bytes, and
-   add the packbits-compressed representation of it to the buffer 
+   add the packbits-compressed representation of it to the buffer
    with handle 'rasterBufferP'.
 -----------------------------------------------------------------------------*/
     unsigned char * compressedData;
@@ -1021,7 +1020,7 @@ packbitsCompressAndBufferRow(const unsigned char * const rowdata,
                           rowbytes, &compressedDataCt);
 
     for (byteCt = 0; byteCt < compressedDataCt; ++byteCt)
-        addByteToBuffer(rasterBufferP, compressedData[byteCt]);
+        seqBuffer_addByte(rasterBufferP, compressedData[byteCt]);
 
     free(compressedData);
 }
@@ -1033,7 +1032,7 @@ bufferRowFromRawRowdata(const unsigned char *  const rowdata,
                         unsigned int           const rowbytes,
                         enum CompressionType   const compression,
                         const unsigned char *  const lastrow,
-                        struct seqBuffer *     const rasterBufferP) {
+                        SeqBuffer *            const rasterBufferP) {
 /*----------------------------------------------------------------------------
    Starting with a raw (uncompressed) Palm raster line, do the
    compression identified by 'compression' and add the compressed row
@@ -1049,7 +1048,7 @@ bufferRowFromRawRowdata(const unsigned char *  const rowdata,
         copyRowToBuffer(rowdata, rowbytes, rasterBufferP);
         break;
     case COMP_SCANLINE:
-        scanlineCompressAndBufferRow(rowdata, rowbytes, rasterBufferP, 
+        scanlineCompressAndBufferRow(rowdata, rowbytes, rasterBufferP,
                                      lastrow);
         break;
     case COMP_RLE:
@@ -1075,10 +1074,10 @@ bufferRow(const xel *          const xelrow,
           Colormap *           const colormapP,
           unsigned char *      const rowdata,
           unsigned char *      const lastrow,
-          struct seqBuffer *   const rasterBufferP) {
+          SeqBuffer *          const rasterBufferP) {
 /*----------------------------------------------------------------------------
    Add a row of the Palm Bitmap raster to buffer 'rasterBufferP'.
-   
+
    'xelrow' is the image contents of row.  It is 'cols' columns wide and
    samples are based on maxval 'maxval'.
 
@@ -1091,7 +1090,7 @@ bufferRow(const xel *          const xelrow,
 -----------------------------------------------------------------------------*/
     if (directColor)
         computeRawRowDirectColor(xelrow, cols, maxval, rowdata);
-    else 
+    else
         computeRawRowNonDirect(xelrow, cols, maxval, bpp, colormapP, newMaxval,
                                rowdata);
 
@@ -1101,7 +1100,7 @@ bufferRow(const xel *          const xelrow,
 
 
 
-static void 
+static void
 bufferRaster(xel **               const xels,
              unsigned int         const cols,
              unsigned int         const rows,
@@ -1112,14 +1111,14 @@ bufferRaster(xel **               const xels,
              enum CompressionType const compression,
              bool                 const directColor,
              Colormap *           const colormapP,
-             struct seqBuffer **  const rasterBufferPP) {
-    
+             SeqBuffer **         const rasterBufferPP) {
+
     unsigned char * rowdata;
     unsigned char * lastrow;
     unsigned int row;
 
-    createBuffer(rasterBufferPP);
-    
+    seqBuffer_create(rasterBufferPP);
+
     MALLOCARRAY_NOFAIL(rowdata, rowbytes);
     if (compression == COMP_SCANLINE)
         MALLOCARRAY_NOFAIL(lastrow, rowbytes);
@@ -1157,25 +1156,25 @@ computeOffsetStuff(bool                 const offsetWanted,
                    unsigned int *       const nextDepthOffsetP,
                    unsigned int *       const nextBitmapOffsetP,
                    unsigned int *       const padBytesRequiredP) {
-    
+
     if (offsetWanted) {
         /* Offset is measured in 4-byte words (double words in
            Intel/Microsoft terminology).  Account for header,
-           colormap, and raster size and round up 
+           colormap, and raster size and round up
         */
         unsigned int const headerSize = ((version < 3) ? 16 : 24);
         unsigned int const colormapSize =
             (colormapped ? (2 + colormapColorCount * 4) : 0);
         if (version < 3) {
-            unsigned int const directSize = 
-                (directColor && version < 3) ? 8 : 0; 
+            unsigned int const directSize =
+                (directColor && version < 3) ? 8 : 0;
             if (compression != COMP_NONE && sizePlusRasterSize > USHRT_MAX)
                 pm_error("Oversized compressed bitmap: %u bytes",
                          sizePlusRasterSize);
-            *padBytesRequiredP = 4 - (sizePlusRasterSize + headerSize + 
+            *padBytesRequiredP = 4 - (sizePlusRasterSize + headerSize +
                                       directSize + colormapSize) % 4;
-            *nextDepthOffsetP = 
-                (sizePlusRasterSize + headerSize + 
+            *nextDepthOffsetP =
+                (sizePlusRasterSize + headerSize +
                  directSize + colormapSize + *padBytesRequiredP) / 4;
         } else {
             if (compression != COMP_NONE && (sizePlusRasterSize >> 31) > 1)
@@ -1184,7 +1183,7 @@ computeOffsetStuff(bool                 const offsetWanted,
             /* Does version 3 need padding? Probably won't hurt */
             *padBytesRequiredP = 4 - (sizePlusRasterSize + headerSize +
                                       colormapSize) % 4;
-            *nextBitmapOffsetP = sizePlusRasterSize + headerSize + 
+            *nextBitmapOffsetP = sizePlusRasterSize + headerSize +
                 colormapSize + *padBytesRequiredP;
         }
     } else {
@@ -1204,7 +1203,7 @@ writeRasterSize(unsigned int const sizePlusRasterSize,
    Write to file 'fileP' a raster size field for a Palm Bitmap version
    'version' header, indicating 'sizePlusRasterSize' bytes.
 -----------------------------------------------------------------------------*/
-    if (version < 3) 
+    if (version < 3)
         pm_writebigshort(fileP, sizePlusRasterSize);
     else
         pm_writebiglong(fileP, sizePlusRasterSize);
@@ -1231,37 +1230,37 @@ writeBitmap(xel **               const xels,
             unsigned int         const version,
             unsigned int         const density,
             bool                 const withdummy) {
-    
+
     unsigned int sizePlusRasterSize;
     unsigned int nextDepthOffset;
     unsigned int nextBitmapOffset;
         /* Offset from the beginning of the image we write to the beginning
            of the next one, assuming user writes another one following this
            one.
-           nextDepthOffset is used in encodings 1, 2 and is in 4 byte words 
-           nextBitmapOffset is used in encoding 3, is in 4 bytes 
+           nextDepthOffset is used in encodings 1, 2 and is in 4 byte words
+           nextBitmapOffset is used in encoding 3, is in 4 bytes
         */
     unsigned int padBytesRequired;
         /* Number of bytes of padding we need to put after the image in
            order to align properly for User to add the next image to the
            stream.
         */
-    struct seqBuffer * rasterBufferP;
+    SeqBuffer * rasterBufferP;
 
-    writeCommonHeader(cols, rows, rowbytes, compression, colormapped, 
+    writeCommonHeader(cols, rows, rowbytes, compression, colormapped,
                       transparent, directColor, bpp, version);
-    
+
     bufferRaster(xels, cols, rows, maxval, rowbytes, bpp, newMaxval,
                  compression, directColor, colormapP, &rasterBufferP);
 
     /* rasterSize itself takes 2 or 4 bytes */
     if (version < 3)
-        sizePlusRasterSize = 2 + bufferLength(rasterBufferP);
+        sizePlusRasterSize = 2 + seqBuffer_length(rasterBufferP);
     else
-        sizePlusRasterSize = 4 + bufferLength(rasterBufferP);
-    
+        sizePlusRasterSize = 4 + seqBuffer_length(rasterBufferP);
+
     computeOffsetStuff(offsetWanted, version, directColor, compression,
-                       colormapped, colormapped ? colormapP->ncolors : 0, 
+                       colormapped, colormapped ? colormapP->ncolors : 0,
                        sizePlusRasterSize,
                        &nextDepthOffset, &nextBitmapOffset,
                        &padBytesRequired);
@@ -1273,15 +1272,15 @@ writeBitmap(xel **               const xels,
                                  maxval, transparent, transcolor,
                                  transindex, nextBitmapOffset);
 
-    writeColormap(colormapped, colormapP, directColor, bpp, 
+    writeColormap(colormapped, colormapP, directColor, bpp,
                   transparent, transcolor, maxval, version);
 
     if (compression != COMP_NONE)
         writeRasterSize(sizePlusRasterSize, version, stdout);
 
-    writeOutBuffer(rasterBufferP, stdout);
+    seqBuffer_writeOut(rasterBufferP, stdout);
 
-    destroyBuffer(rasterBufferP);
+    seqBuffer_destroy(rasterBufferP);
 
     {
         unsigned int i;
@@ -1291,11 +1290,11 @@ writeBitmap(xel **               const xels,
 
     if (withdummy)
         writeDummy();
-}        
+}
 
 
 
-int 
+int
 main( int argc, const char **argv ) {
     struct CmdlineInfo cmdline;
     unsigned int version;
@@ -1311,7 +1310,7 @@ main( int argc, const char **argv ) {
     bool directColor;
     unsigned int newMaxval;
     Colormap * colormapP;
-    
+
     pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
@@ -1322,9 +1321,9 @@ main( int argc, const char **argv ) {
     pm_close(ifP);
 
     if (cmdline.verbose)
-        pm_message("Input is %ux%u %s, maxval %u", 
+        pm_message("Input is %ux%u %s, maxval %u",
                    cols, rows, formatName(format), maxval);
-    
+
     determinePalmFormat(cols, rows, maxval, format, xels,
                         cmdline.depthSpec, cmdline.depth,
                         cmdline.maxdepthSpec, cmdline.maxdepth,
@@ -1333,23 +1332,23 @@ main( int argc, const char **argv ) {
 
     newMaxval = (1 << bpp) - 1;
 
-    if (cmdline.transparent) 
+    if (cmdline.transparent)
         findTransparentColor(cmdline.transparent, newMaxval, directColor,
                              maxval, colormapP, &transcolor, &transindex);
-    else 
+    else
         transindex = 0;
 
-    rowbytes = ((cols + (16 / bpp -1)) / (16 / bpp)) * 2;    
+    rowbytes = ((cols + (16 / bpp -1)) / (16 / bpp)) * 2;
         /* bytes per row - always a word boundary */
 
-    version = bitmapVersion(bpp, cmdline.colormap, !!cmdline.transparent, 
+    version = bitmapVersion(bpp, cmdline.colormap, !!cmdline.transparent,
                             cmdline.compression, cmdline.density);
 
     writeBitmap(xels, cols, rows, maxval,
                 rowbytes, bpp, newMaxval, cmdline.compression,
-                !!cmdline.transparent, directColor, cmdline.offset, 
+                !!cmdline.transparent, directColor, cmdline.offset,
                 cmdline.colormap, colormapP, transindex, transcolor,
                 version, cmdline.density, cmdline.withdummy);
-    
+
     return 0;
 }
diff --git a/converter/other/pnmtopng.c b/converter/other/pnmtopng.c
index cbbbc47d..2230d226 100644
--- a/converter/other/pnmtopng.c
+++ b/converter/other/pnmtopng.c
@@ -56,6 +56,7 @@
 #endif                               /*  2 for warnings (1 == error) */
 
 #include <assert.h>
+#include <stdbool.h>
 #include <string.h> /* strcat() */
 #include <limits.h>
 #include <png.h>
@@ -140,12 +141,6 @@ typedef struct _jmpbuf_wrapper {
   jmp_buf jmpbuf;
 } jmpbuf_wrapper;
 
-#ifndef TRUE
-#  define TRUE 1
-#endif
-#ifndef FALSE
-#  define FALSE 0
-#endif
 #ifndef NONE
 #  define NONE 0
 #endif
@@ -394,8 +389,8 @@ parseCommandLine(int argc, const char ** argv,
 
 
     opt.opt_table = option_def;
-    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
-    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We have no parms that are negative numbers */
 
     pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
@@ -424,7 +419,7 @@ parseCommandLine(int argc, const char ** argv,
         cmdlineP->palette = NULL;
 
     if (filterSpec && (nofilter + sub + up + avg + paeth > 0))
-        pm_error("You may mot specify -filter with "
+        pm_error("You may not specify -filter with "
                  "-nofilter, -sub, -up, -avg, or -paeth");
 
     if (filterSpec) {
@@ -511,6 +506,8 @@ parseCommandLine(int argc, const char ** argv,
         cmdlineP->inputFileName = argv[1];
     else
         pm_error("Program takes at most one argument:  input file name");
+
+    free(option_def);
 }
 
 
@@ -671,7 +668,7 @@ lookupColorAlpha(coloralphahash_table const caht,
 
 
 /* The following variables belong to getChv() and freeChv() */
-static bool getChv_computed = FALSE;
+static bool getChv_computed = false;
 static colorhist_vector getChv_chv;
 
 
@@ -722,7 +719,7 @@ getChv(FILE *             const ifP,
             else
                 pm_message("Too many colors (more than %u) found", maxColors);
         }
-        getChv_computed = TRUE;
+        getChv_computed = true;
     }
     *chvP = getChv_chv;
     *colorsP = getChv_colors;
@@ -736,7 +733,7 @@ static void freeChv(void) {
         if (getChv_chv)
             ppm_freecolorhist(getChv_chv);
 
-    getChv_computed = FALSE;
+    getChv_computed = false;
 }
 
 
@@ -750,7 +747,7 @@ pgmBitsAreRepeated(unsigned int const repeatedSize,
                    xelval       const maxval,
                    int          const format) {
 /*----------------------------------------------------------------------------
-   Return TRUE iff all the samples in the image in file 'ifP',
+   Return true iff all the samples in the image in file 'ifP',
    described by 'cols', 'rows', 'maxval', and 'format', consist in the
    rightmost 'repeatedSize' * 2 bits of two identical sets of
    'repeatedSize' bits.
@@ -774,7 +771,7 @@ pgmBitsAreRepeated(unsigned int const repeatedSize,
 
     pm_seek2(ifP, &rasterPos, sizeof(rasterPos));
 
-    mayscale = TRUE;  /* initial assumption */
+    mayscale = true;  /* initial assumption */
 
     for (row = 0; row < rows && mayscale; ++row) {
         unsigned int col;
@@ -785,7 +782,7 @@ pgmBitsAreRepeated(unsigned int const repeatedSize,
             xelval const testbits1 = testbits2 & mask1;
                 /* The lower half of the bits of interest in the sample */
             if (((testbits1 << repeatedSize) | testbits1) != testbits2)
-                mayscale = FALSE;
+                mayscale = false;
         }
     }
     pnm_freerow(xelrow);
@@ -878,7 +875,7 @@ meaningful_bits_ppm(FILE *         const ifp,
     maxMeaningfulBits = pm_maxvaltobits(maxval);
 
     if (maxval == 65535) {
-        mayscale = TRUE;   /* initial assumption */
+        mayscale = true;   /* initial assumption */
         pm_seek2(ifp, &rasterPos, sizeof(rasterPos));
         for (row = 0; row < rows && mayscale; ++row) {
             unsigned int col;
@@ -888,7 +885,7 @@ meaningful_bits_ppm(FILE *         const ifp,
                 if ((PPM_GETR(p) & 0xff) * 0x101 != PPM_GETR(p) ||
                     (PPM_GETG(p) & 0xff) * 0x101 != PPM_GETG(p) ||
                     (PPM_GETB(p) & 0xff) * 0x101 != PPM_GETB(p))
-                    mayscale = FALSE;
+                    mayscale = false;
             }
         }
         if (mayscale)
@@ -902,7 +899,7 @@ meaningful_bits_ppm(FILE *         const ifp,
 
 
 static void
-tryTransparentColor(FILE *     const ifp,
+tryTransparentColor(FILE *     const ifP,
                     pm_filepos const rasterPos,
                     int        const cols,
                     int        const rows,
@@ -912,7 +909,14 @@ tryTransparentColor(FILE *     const ifp,
                     gray       const alphaMaxval,
                     pixel      const transcolor,
                     bool *     const singleColorIsTransP) {
+/*----------------------------------------------------------------------------
+   Find out if the transparent pixels identified by alpha mask 'alphaMask'
+   (whose maxval is 'alphaMaxval') are exactly the pixels of color
+   'transcolor'.  Return answer as *singleColorIsTransP.
 
+   The image we analyze is that on input stream *ifP, starting at position
+   'rasterPos', and we leave that stream positioned arbitrarily.
+-----------------------------------------------------------------------------*/
     int const pnmType = PNM_FORMAT_TYPE(format);
 
     xel * xelrow;
@@ -922,13 +926,13 @@ tryTransparentColor(FILE *     const ifp,
 
     xelrow = pnm_allocrow(cols);
 
-    pm_seek2(ifp, &rasterPos, sizeof(rasterPos));
+    pm_seek2(ifP, &rasterPos, sizeof(rasterPos));
 
-    singleColorIsTrans = TRUE;  /* initial assumption */
+    singleColorIsTrans = true;  /* initial assumption */
 
     for (row = 0; row < rows && singleColorIsTrans; ++row) {
         int col;
-        pnm_readpnmrow(ifp, xelrow, cols, maxval, format);
+        pnm_readpnmrow(ifP, xelrow, cols, maxval, format);
         for (col = 0 ; col < cols && singleColorIsTrans; ++col) {
             if (alphaMask[row][col] == 0) { /* transparent */
                 /* If we have a second transparent color, we're
@@ -936,16 +940,16 @@ tryTransparentColor(FILE *     const ifp,
                 */
                 if (pnmType == PPM_TYPE) {
                     if (!PPM_EQUAL(xelrow[col], transcolor))
-                        singleColorIsTrans = FALSE;
+                        singleColorIsTrans = false;
                 } else {
                     if (PNM_GET1(xelrow[col]) != PNM_GET1(transcolor))
-                        singleColorIsTrans = FALSE;
+                        singleColorIsTrans = false;
                 }
             } else if (alphaMask[row][col] != alphaMaxval) {
                 /* Here's an area of the mask that is translucent.  That
                    disqualified us.
                 */
-                singleColorIsTrans = FALSE;
+                singleColorIsTrans = false;
             } else {
                 /* Here's an area of the mask that is opaque.  If it's
                    the same color as our candidate transparent color,
@@ -953,10 +957,10 @@ tryTransparentColor(FILE *     const ifp,
                 */
                 if (pnmType == PPM_TYPE) {
                     if (PPM_EQUAL(xelrow[col], transcolor))
-                        singleColorIsTrans = FALSE;
+                        singleColorIsTrans = false;
                 } else {
                     if (PNM_GET1(xelrow[col]) == PNM_GET1(transcolor))
-                        singleColorIsTrans = FALSE;
+                        singleColorIsTrans = false;
                 }
             }
         }
@@ -990,8 +994,8 @@ analyzeAlpha(FILE *       const ifP,
   of a certain color fully transparent and every other pixel opaque,
   we can simply identify that color in the PNG.
 
-  We have to do this before any scaling occurs, since alpha is only
-  possible with 8 and 16-bit.
+  We have to do this before any scaling occurs, since alpha is possible
+  only with 8 and 16-bit.
 -----------------------------------------------------------------------------*/
     xel * xelrow;
     bool foundTransparentPixel;
@@ -1034,7 +1038,7 @@ analyzeAlpha(FILE *       const ifP,
             pnm_readpnmrow(ifP, xelrow, cols, maxval, format);
             for (col = 0; col < cols && !foundTransparentPixel; ++col) {
                 if (alphaMask[row][col] == 0) {
-                    foundTransparentPixel = TRUE;
+                    foundTransparentPixel = true;
                     transcolor = pnm_xeltopixel(xelrow[col], format);
                 }
             }
@@ -1115,16 +1119,16 @@ determineTransparency(struct cmdlineInfo const cmdline,
         if (alphaCanBeTransparencyIndex && !cmdline.force) {
             if (verbose)
                 pm_message("converting alpha mask to transparency index");
-            *alphaP       = FALSE;
+            *alphaP       = false;
             *transparentP = 2;
             *transColorP  = alphaTranscolor;
         } else if (allOpaque) {
             if (verbose)
                 pm_message("Skipping alpha because mask is all opaque");
-            *alphaP       = FALSE;
+            *alphaP       = false;
             *transparentP = -1;
         } else {
-            *alphaP       = TRUE;
+            *alphaP       = true;
             *transparentP = -1;
         }
         *alphaMaxvalP = alphaMaxval;
@@ -1134,17 +1138,17 @@ determineTransparency(struct cmdlineInfo const cmdline,
            use with trans[], which can have stuff in it if the user specified
            a transparent color.
         */
-        *alphaP       = FALSE;
+        *alphaP       = false;
         *alphaMaxvalP = 255;
 
         if (cmdline.transparent) {
             const char * transstring2;
             /* The -transparent value, but with possible leading '=' removed */
             if (cmdline.transparent[0] == '=') {
-                *transExactP = TRUE;
+                *transExactP = true;
                 transstring2 = &cmdline.transparent[1];
             } else {
-                *transExactP = FALSE;
+                *transExactP = false;
                 transstring2 = cmdline.transparent;
             }
             /* We do this funny PPM_DEPTH thing instead of just passing 'maxval'
@@ -1206,7 +1210,7 @@ hasColor(FILE *       const ifP,
             for (col = 0; col < cols && isGray; ++col) {
                     xel const p = xelrow[col];
                 if (PPM_GETR(p) != PPM_GETG(p) || PPM_GETG(p) != PPM_GETB(p))
-                    isGray = FALSE;
+                    isGray = false;
             }
         }
 
@@ -1335,10 +1339,10 @@ compute_nonalpha_palette(colorhist_vector const chv,
             int j;
             bool found;
 
-            found = FALSE;
+            found = false;
             for (j = 0; j < ordered_palette_size && !found; ++j) {
                 if (PNM_EQUAL(ordered_palette[j], chv[colorIndex].color))
-                    found = TRUE;
+                    found = true;
             }
             if (!found)
                 pm_error("failed to find color (%d, %d, %d), which is in the "
@@ -1636,7 +1640,7 @@ compute_alpha_palette(FILE *         const ifP,
    MAXPALETTEENTRIES elements.
 
    If there are more than MAXPALETTEENTRIES color/alpha pairs in the image,
-   don't return any palette information -- just return *tooBigP == TRUE.
+   don't return any palette information -- just return *tooBigP == true.
 -----------------------------------------------------------------------------*/
     colorhist_vector chv;
     unsigned int colors;
@@ -1714,9 +1718,9 @@ makeOneColorTransparentInPalette(xel            const transColor,
    can do a better job when the opaque entries are all last in the
    color/alpha palette).
 
-   If the specified color is not there and exact == TRUE, return
+   If the specified color is not there and exact == true, return
    without changing anything, but issue a warning message.  If it's
-   not there and exact == FALSE, just find the closest color.
+   not there and exact == false, just find the closest color.
 
    We assume every entry in the palette is opaque upon entry.
 
@@ -2369,7 +2373,8 @@ writeRaster(struct pngx *        const pngxP,
     /* max: 3 color channels, one alpha channel, 16-bit */
     MALLOCARRAY(line, cols * 8);
     if (line == NULL)
-        pm_error("out of memory allocating PNG row buffer");
+        pm_error("out of memory allocating PNG row buffer for %u columns",
+                 cols);
 
     for (pass = 0; pass < pngxP->numPassesRequired; ++pass) {
         unsigned int row;
@@ -2386,6 +2391,7 @@ writeRaster(struct pngx *        const pngxP,
             pngx_writeRow(pngxP, line);
         }
     }
+    free(line);
     pnm_freerow(xelrow);
 }
 
@@ -2837,9 +2843,9 @@ convertpnm(struct cmdlineInfo const cmdline,
         if (verbose)
             pm_message("Not using color map.  %s", noColormapReason);
         pm_strfree(noColormapReason);
-        colorMapped = FALSE;
+        colorMapped = false;
     } else
-        colorMapped = TRUE;
+        colorMapped = true;
 
     computeColorMapLookupTable(colorMapped, palettePnm, paletteSize,
                                transPnm, transSize, alpha, alphaMaxval,
diff --git a/converter/other/pnmtops.c b/converter/other/pnmtops.c
index a286bc1e..3ca158b5 100644
--- a/converter/other/pnmtops.c
+++ b/converter/other/pnmtops.c
@@ -9,7 +9,7 @@
 
          We use methods we learned from Dirk Krause's program Bmeps.
          Previous versions used raster encoding code based on Bmeps
-         code.  This program does not used any code from Bmeps.
+         code.  This program does not use any code from Bmeps.
 
       2) Use our own filters and redefine /readstring .  This is aboriginal
          Netpbm code, from when Postscript was young.  The filters are
@@ -125,8 +125,8 @@ static bool verbose;
 
 
 static void
-parseDpi(const char *   const dpiOpt, 
-         unsigned int * const dpiXP, 
+parseDpi(const char *   const dpiOpt,
+         unsigned int * const dpiXP,
          unsigned int * const dpiYP) {
 
     char *dpistr2;
@@ -253,9 +253,9 @@ parseCommandLine(int argc, const char ** argv,
     OPTENT3(0, "showpage",    OPT_FLAG,  NULL, &showpage,                0);
     OPTENT3(0, "verbose",     OPT_FLAG,  NULL, &cmdlineP->verbose,       0);
     OPTENT3(0, "debug",       OPT_FLAG,  NULL, &cmdlineP->debug,         0);
-    OPTENT3(0, "level",       OPT_UINT, &cmdlineP->level, 
+    OPTENT3(0, "level",       OPT_UINT, &cmdlineP->level,
             &cmdlineP->levelSpec,              0);
-    
+
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;
     opt.allowNegNum = FALSE;
@@ -293,7 +293,7 @@ parseCommandLine(int argc, const char ** argv,
 
     validateCompDimension(width, 72, "-width value");
     validateCompDimension(height, 72, "-height value");
-    
+
     cmdlineP->width  = width * 72;
     cmdlineP->height = height * 72;
 
@@ -318,7 +318,7 @@ parseCommandLine(int argc, const char ** argv,
     if (cmdlineP->bitspersampleSpec)
         validateBps_1_2_4_8_12(cmdlineP->bitspersample);
 
-    if (argc-1 == 0) 
+    if (argc-1 == 0)
         cmdlineP->inputFileName = "-";
     else if (argc-1 != 1)
         pm_error("Program takes zero or one argument (filename).  You "
@@ -326,7 +326,7 @@ parseCommandLine(int argc, const char ** argv,
     else
         cmdlineP->inputFileName = argv[1];
 
-    free(option_def); 
+    free(option_def);
 }
 
 
@@ -432,7 +432,7 @@ addToPidList(pid_t * const pidList,
 /*===========================================================================
   The output encoder
   ===========================================================================*/
-    
+
 enum OutputType {AsciiHex, Ascii85};
 
 typedef struct {
@@ -453,7 +453,7 @@ bytesPerRow (unsigned int const cols,
 -----------------------------------------------------------------------------*/
     unsigned int retval;
 
-    assert(bitsPerSample==1 || bitsPerSample==2 || bitsPerSample==4 || 
+    assert(bitsPerSample==1 || bitsPerSample==2 || bitsPerSample==4 ||
            bitsPerSample==8 || bitsPerSample==12);
 
     switch (bitsPerSample) {
@@ -519,7 +519,7 @@ typedef void FilterFn(FILE *          const ifP,
     /* This is a function that can be run in a separate process to do
        arbitrary modifications of the raster data stream.
     */
-       
+
 
 
 #ifndef NOFLATE
@@ -545,7 +545,7 @@ initZlib(z_stream * const strmP) {
 
 static FilterFn flateFilter;
 
-static void 
+static void
 flateFilter(FILE *          const ifP,
             FILE *          const ofP,
             OutputEncoder * const oeP) {
@@ -600,12 +600,12 @@ flateFilter(FILE *          const ifP,
     } while (flush != Z_FINISH);
 
     free(in);
-    free(out); 
+    free(out);
     deflateEnd(&strm);
     fclose(ifP);
     fclose(ofP);
 #else
-    assert(false);    /* filter is never used */ 
+    assert(false);    /* filter is never used */
 #endif
 }
 
@@ -687,7 +687,7 @@ asciiHexFilter(FILE *          const ifP,
             unsigned int i;
 
             for (i = 0; i < readCt; ++i) {
-                int const item = inbuff[i]; 
+                int const item = inbuff[i];
                 outbuff[i*2]   = hexits[item >> 4];
                 outbuff[i*2+1] = hexits[item & 15];
             }
@@ -736,7 +736,7 @@ ascii85Filter(FILE *          const ifP,
                 ++outcount;
                 count = 0;
             } else if (count == 4) {
-                outbuff[4] = value % 85 + 33;  value/=85; 
+                outbuff[4] = value % 85 + 33;  value/=85;
                 outbuff[3] = value % 85 + 33;  value/=85;
                 outbuff[2] = value % 85 + 33;  value/=85;
                 outbuff[1] = value % 85 + 33;
@@ -745,7 +745,7 @@ ascii85Filter(FILE *          const ifP,
                 writeFileChar(outbuff, count + 1, "ASCII 85 filter", ofP);
 
                 count = value = 0;
-                outcount += 5; 
+                outcount += 5;
             }
 
             if (outcount > 75) {
@@ -794,9 +794,9 @@ closeAllBut(int const saveFd0,
    'saveFd1', and 'saveFd2'.
 
    This is helpful because even if this process doesn't touch other file
-   desriptors, its very existence will keep the files open.
+   descriptors, its very existence will keep the files open.
 -----------------------------------------------------------------------------*/
-    
+
     /* Unix provides no good way to do this; we just assume file descriptors
        above 9 are not used in this program; Caller must ensure that is true.
     */
@@ -829,15 +829,15 @@ spawnFilter(FILE *          const ofP,
     pid_t rc;
 
     makePipe(pipeFd);
-    
+
     rc = fork();
 
     if (rc == (pid_t)-1)
-        pm_error("fork() of filter process failed.  errno=%d (%s)", 
+        pm_error("fork() of filter process failed.  errno=%d (%s)",
                  errno, strerror(errno));
     else if (rc == 0) {
         /* This is the child process */
- 
+
         FILE * ifP;
 
         ifP = fdopen(pipeFd[0], "r");
@@ -892,11 +892,11 @@ addFilter(const char *    const description,
     pid_t pid;
 
     spawnFilter(oldFeedFileP, filter, oeP, &newFeedFileP, &pid);
-            
+
     if (verbose)
         pm_message("%s filter spawned: pid %u",
                    description, (unsigned)pid);
-    
+
     if (debug) {
         int const outFd    = fileno(oldFeedFileP);
         int const supplyFd = fileno(newFeedFileP);
@@ -971,7 +971,7 @@ waitForChildren(const pid_t * const pidList) {
        signal is the default), the process' children do not become
        zombies.  Consequently, waitpid() always fails with ECHILD - but
        nonetheless waits for the child to exit.
-    
+
        We expect the process not to have the action for SIGCHLD set that
        way.
     */
@@ -1004,9 +1004,9 @@ waitForChildren(const pid_t * const pidList) {
 
 
 static void
-validateComputableBoundingBox(float const scols, 
+validateComputableBoundingBox(float const scols,
                               float const srows,
-                              float const llx, 
+                              float const llx,
                               float const lly) {
 
     float const bbWidth  = llx + scols + 0.5;
@@ -1036,22 +1036,22 @@ warnUserRescaling(float const scale) {
 
 
 static void
-computeImagePosition(int     const dpiX, 
-                     int     const dpiY, 
-                     int     const icols, 
+computeImagePosition(int     const dpiX,
+                     int     const dpiY,
+                     int     const icols,
                      int     const irows,
                      bool    const mustturn,
                      bool    const canturn,
                      bool    const center,
-                     int     const pagewid, 
-                     int     const pagehgt, 
+                     int     const pagewid,
+                     int     const pagehgt,
                      float   const requestedScale,
                      float   const imagewidth,
                      float   const imageheight,
                      bool    const equalpixels,
                      float * const scolsP,
                      float * const srowsP,
-                     float * const llxP, 
+                     float * const llxP,
                      float * const llyP,
                      bool *  const turnedP ) {
 /*----------------------------------------------------------------------------
@@ -1091,7 +1091,7 @@ computeImagePosition(int     const dpiX,
        rotated if applicable
     */
     bool shouldturn;  /* The image fits the page better if we turn it */
-    
+
     if (icols > irows && pagehgt > pagewid)
         shouldturn = TRUE;
     else if (irows > icols && pagewid > pagehgt)
@@ -1120,27 +1120,27 @@ computeImagePosition(int     const dpiX,
             scale = (float) imagewidth/cols;
         else
             scale = MIN((float)imagewidth/cols, (float)imageheight/rows);
-    
+
         *scolsP = cols*scale;
         *srowsP = rows*scale;
     } else {
         /* He didn't give us a bounding box for the image so figure
            out output image size from other inputs.
         */
-        const int devpixX = dpiX / 72.0 + 0.5;        
-        const int devpixY = dpiY / 72.0 + 0.5;        
+        const int devpixX = dpiX / 72.0 + 0.5;
+        const int devpixY = dpiY / 72.0 + 0.5;
         /* How many device pixels make up 1/72 inch, rounded to
            nearest integer */
         const float pixfacX = 72.0 / dpiX * devpixX;  /* 1, approx. */
         const float pixfacY = 72.0 / dpiY * devpixY;  /* 1, approx. */
         float scale;
 
-        scale = MIN(requestedScale, 
+        scale = MIN(requestedScale,
                     MIN((float)pagewid/cols, (float)pagehgt/rows));
 
         *scolsP = scale * cols * pixfacX;
         *srowsP = scale * rows * pixfacY;
-    
+
         if (scale != requestedScale)
             warnUserRescaling(scale);
 
@@ -1236,7 +1236,7 @@ defineReadstring(bool const rle) {
 static void
 setupReadstringNative(bool         const rle,
                       bool         const color,
-                      unsigned int const icols, 
+                      unsigned int const icols,
                       unsigned int const bitsPerSample) {
 /*----------------------------------------------------------------------------
   Write to Standard Output statements to define /readstring and also
@@ -1247,7 +1247,7 @@ setupReadstringNative(bool         const rle,
         /* Size of row buffer, padded up to byte boundary. */
 
     defineReadstring(rle);
-    
+
     if (color) {
         printf("/rpicstr %d string def\n", bytesPerRow);
         printf("/gpicstr %d string def\n", bytesPerRow);
@@ -1266,18 +1266,18 @@ putFilters(unsigned int const postscriptLevel,
            bool         const color) {
 
     assert(postscriptLevel > 1);
-    
+
     /* We say to decode flate, then rle, so Caller must ensure it encodes
-       rel, then flate.
+       rle, then flate.
     */
 
     if (ascii85)
         printf("/ASCII85Decode filter ");
-    else 
+    else
         printf("/ASCIIHexDecode filter ");
     if (flate)
         printf("/FlateDecode filter ");
-    if (rle) 
+    if (rle)
         printf("/RunLengthDecode filter ");
 }
 
@@ -1311,7 +1311,7 @@ putSetup(unsigned int const dictSize,
     if (dictSize > 0)
         /* inputf {r,g,b,}pictsr readstring readrlestring rlestring */
         printf("%u dict begin\n", dictSize);
-    
+
     if (!psFilter)
         setupReadstringNative(rle, color, icols, bitsPerSample);
 
@@ -1353,7 +1353,7 @@ putInitPsFilter(unsigned int const postscriptLevel,
     putFilters(postscriptLevel, rle, flate, ascii85, color);
 
     putImage(filterTrue, color);
-    
+
     printf(" } exec");
 }
 
@@ -1365,7 +1365,7 @@ putInitReadstringNative(bool const color) {
     bool const filterFalse = FALSE;
 
     putReadstringNative(color);
-    
+
     putImage(filterFalse, color);
 }
 
@@ -1373,18 +1373,18 @@ putInitReadstringNative(bool const color) {
 
 static void
 putInit(unsigned int const postscriptLevel,
-        char         const name[], 
-        int          const icols, 
-        int          const irows, 
-        float        const scols, 
+        char         const name[],
+        int          const icols,
+        int          const irows,
+        float        const scols,
         float        const srows,
-        float        const llx, 
+        float        const llx,
         float        const lly,
         int          const bitsPerSample,
-        int          const pagewid, 
+        int          const pagewid,
         int          const pagehgt,
-        bool         const color, 
-        bool         const turned, 
+        bool         const color,
+        bool         const turned,
         bool         const rle,
         bool         const flate,
         bool         const ascii85,
@@ -1438,7 +1438,7 @@ putInit(unsigned int const postscriptLevel,
 
 
 static void
-putEnd(bool         const showpage, 
+putEnd(bool         const showpage,
        bool         const psFilter,
        bool         const ascii85,
        unsigned int const dictSize,
@@ -1486,7 +1486,7 @@ validateBpsRequest(unsigned int const bitsPerSampleReq,
                  "-psfilter, the maximum is 8", bitsPerSampleReq);
 }
 
-    
+
 
 static unsigned int
 bpsFromInput(unsigned int const bitsRequiredByMaxval,
@@ -1553,7 +1553,7 @@ warnUserAboutReducedDepth(unsigned int const bitsGot,
 
 static void
 computeDepth(xelval         const inputMaxval,
-             unsigned int   const postscriptLevel, 
+             unsigned int   const postscriptLevel,
              bool           const psFilter,
              unsigned int   const bitsPerSampleReq,
              unsigned int * const bitsPerSampleP) {
@@ -1584,7 +1584,7 @@ computeDepth(xelval         const inputMaxval,
                    "%u bits per sample, so maxval = %u",
                    inputMaxval, *bitsPerSampleP, psMaxval);
     }
-}    
+}
 
 
 
@@ -1643,7 +1643,7 @@ ba_add(BitAccumulator * const baP,
 /*----------------------------------------------------------------------------
   Combine bit sequences that do not fit into a byte.
 
-  Used when bitsPerSample =1, 2, 4.  
+  Used when bitsPerSample =1, 2, 4.
   Logic also works for bitsPerSample = 8, 16.
 
   The accumulator, baP->value is unsigned int (usually 32 bits), but
@@ -1725,7 +1725,7 @@ flushOutput(BitAccumulator * const baP,
 
   convertRowNative and convertRowPsFilter are the general converters.
   They are quite similar, the differences being:
-  (1) Native output separates the color planes: 
+  (1) Native output separates the color planes:
   (RRR...RRR GGG...GGG BBB...BBB),
   whereas psFilter does not:
   (RGB RGB RGB RGB ......... RGB).
@@ -1765,10 +1765,10 @@ convertRowPbm(struct pam *     const pamP,
 
 
 static void
-convertRowNative(struct pam *     const pamP, 
-                 tuple *                tuplerow, 
+convertRowNative(struct pam *     const pamP,
+                 tuple *                tuplerow,
                  unsigned int     const bitsPerSample,
-                 FILE           * const fP) { 
+                 FILE           * const fP) {
 
     unsigned int const psMaxval = pm_bitstomaxval(bitsPerSample);
 
@@ -1795,7 +1795,7 @@ static void
 convertRowPsFilter(struct pam *     const pamP,
                    tuple *                tuplerow,
                    unsigned int     const bitsPerSample,
-                   FILE           * const fP) { 
+                   FILE           * const fP) {
 
     unsigned int const psMaxval = pm_bitstomaxval(bitsPerSample);
 
@@ -1828,7 +1828,7 @@ selectPostscriptLevel(bool           const levelIsGiven,
                       bool           const psFilter,
                       unsigned int * const postscriptLevelP) {
 
-    unsigned int const maxPermittedLevel = 
+    unsigned int const maxPermittedLevel =
         levelIsGiven ? levelGiven : UINT_MAX;
     unsigned int minPossibleLevel;
 
@@ -1877,7 +1877,7 @@ convertRaster(struct pam * const inpamP,
    Read the raster described by *inpamP, and write a bit stream of samples
    to *fP.  This stream has to be compressed and converted to text before it
    can be part of a Postscript program.
-   
+
    'psFilter' means to do the conversion using built in Postscript filters, as
    opposed to our own filters via /readstring.
 
@@ -1897,7 +1897,7 @@ convertRaster(struct pam * const inpamP,
     } else  {
         tuple *tuplerow;
         unsigned int row;
-        
+
         tuplerow = pnm_allocpamrow(inpamP);
 
         for (row = 0; row < inpamP->height; ++row) {
@@ -1920,31 +1920,31 @@ convertRaster(struct pam * const inpamP,
    pipe but this program's output, then we don't want it closed when the
    filter terminates because we'll need it to be open for the next image
    the program converts (with a whole new chain of filters).
-   
-   To prevent the progam output file from getting closed, we pass a
+
+   To prevent the program output file from getting closed, we pass a
    duplicate of it to spawnFilters() and keep the original open.
 */
 
 
 
 static void
-convertPage(FILE *       const ifP, 
-            int          const turnflag, 
-            int          const turnokflag, 
+convertPage(FILE *       const ifP,
+            int          const turnflag,
+            int          const turnokflag,
             bool         const psFilter,
-            bool         const rle, 
+            bool         const rle,
             bool         const flate,
             bool         const ascii85,
             bool         const setpage,
             bool         const showpage,
-            bool         const center, 
+            bool         const center,
             float        const scale,
-            int          const dpiX, 
-            int          const dpiY, 
-            int          const pagewid, 
+            int          const dpiX,
+            int          const dpiY,
+            int          const pagewid,
             int          const pagehgt,
-            int          const imagewidth, 
-            int          const imageheight, 
+            int          const imagewidth,
+            int          const imageheight,
             bool         const equalpixels,
             unsigned int const bitsPerSampleReq,
             char         const name[],
@@ -1952,7 +1952,7 @@ convertPage(FILE *       const ifP,
             bool         const vmreclaim,
             bool         const levelIsGiven,
             unsigned int const levelGiven) {
-    
+
     struct pam inpam;
     float scols, srows;
     float llx, lly;
@@ -1960,7 +1960,7 @@ convertPage(FILE *       const ifP,
     bool color;
     unsigned int postscriptLevel;
     unsigned int bitsPerSample;
-    unsigned int dictSize;  
+    unsigned int dictSize;
         /* Size of Postscript dictionary we should define */
     OutputEncoder oe;
     pid_t filterPidList[MAX_FILTER_CT + 1];
@@ -1974,19 +1974,19 @@ convertPage(FILE *       const ifP,
     pnm_readpaminit(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));
 
     validateCompDimension(inpam.width, 16, "Input image width");
-    
+
     if (!STRSEQ(inpam.tuple_type, PAM_PBM_TUPLETYPE) &&
         !STRSEQ(inpam.tuple_type, PAM_PGM_TUPLETYPE) &&
         !STRSEQ(inpam.tuple_type, PAM_PPM_TUPLETYPE))
         pm_error("Unrecognized tuple type %s.  This program accepts only "
-                 "PBM, PGM, PPM, and equivalent PAM input images", 
+                 "PBM, PGM, PPM, and equivalent PAM input images",
                  inpam.tuple_type);
 
     color = STRSEQ(inpam.tuple_type, PAM_PPM_TUPLETYPE);
-    
-    selectPostscriptLevel(levelIsGiven, levelGiven, color, 
+
+    selectPostscriptLevel(levelIsGiven, levelGiven, color,
                           dict, flate, ascii85, psFilter, &postscriptLevel);
-    
+
     if (color)
         pm_message("generating color Postscript program.");
 
@@ -1996,16 +1996,16 @@ convertPage(FILE *       const ifP,
     /* In positioning/scaling the image, we treat the input image as if
        it has a density of 72 pixels per inch.
     */
-    computeImagePosition(dpiX, dpiY, inpam.width, inpam.height, 
+    computeImagePosition(dpiX, dpiY, inpam.width, inpam.height,
                          turnflag, turnokflag, center,
                          pagewid, pagehgt, scale, imagewidth, imageheight,
                          equalpixels,
                          &scols, &srows, &llx, &lly, &turned);
 
     determineDictionaryRequirement(dict, psFilter, &dictSize);
-    
-    putInit(postscriptLevel, name, inpam.width, inpam.height, 
-            scols, srows, llx, lly, bitsPerSample, 
+
+    putInit(postscriptLevel, name, inpam.width, inpam.height,
+            scols, srows, llx, lly, bitsPerSample,
             pagewid, pagehgt, color,
             turned, rle, flate, ascii85, setpage, psFilter, dictSize);
 
@@ -2017,7 +2017,7 @@ convertPage(FILE *       const ifP,
         /* spawnFilters() closes this.  See FILE MANAGEMENT above */
 
     spawnFilters(filterChainOfP, &oe, &feedFileP, filterPidList);
- 
+
     convertRaster(&inpam, bitsPerSample, psFilter, feedFileP);
 
     fflush(feedFileP);
@@ -2081,17 +2081,17 @@ main(int argc, const char * argv[]) {
 
         eof = FALSE;  /* There is always at least one image */
         for (imageSeq = 0; !eof; ++imageSeq) {
-            convertPage(ifP, cmdline.mustturn, cmdline.canturn, 
+            convertPage(ifP, cmdline.mustturn, cmdline.canturn,
                         cmdline.psfilter,
-                        cmdline.rle, cmdline.flate, cmdline.ascii85, 
+                        cmdline.rle, cmdline.flate, cmdline.ascii85,
                         cmdline.setpage, cmdline.showpage,
                         cmdline.center, cmdline.scale,
                         cmdline.dpiX, cmdline.dpiY,
-                        cmdline.width, cmdline.height, 
-                        cmdline.imagewidth, cmdline.imageheight, 
+                        cmdline.width, cmdline.height,
+                        cmdline.imagewidth, cmdline.imageheight,
                         cmdline.equalpixels,
                         cmdline.bitspersampleSpec ? cmdline.bitspersample : 0,
-                        name, 
+                        name,
                         cmdline.dict, cmdline.vmreclaim,
                         cmdline.levelSpec, cmdline.level);
             pnm_nextimage(ifP, &eof);
@@ -2121,7 +2121,7 @@ main(int argc, const char * argv[]) {
 **  wrzl@gup.uni-linz.ac.at.
 **
 ** July 2011 afu
-** row convertors rewritten, fast PBM-only row convertor added,
+** row converters rewritten, fast PBM-only row converter added,
 ** rle compression slightly modified, flate compression added
 ** ascii85 output end added.
 **
diff --git a/converter/other/pnmtorle.c b/converter/other/pnmtorle.c
index 7c378246..17c9cfbc 100644
--- a/converter/other/pnmtorle.c
+++ b/converter/other/pnmtorle.c
@@ -1,7 +1,7 @@
 /*
  * This is derived from the file of the same name dated June 5, 1995,
  * copied from the Army High Performance Computing Research Center's
- * media-tools.tar.gz package, received from 
+ * media-tools.tar.gz package, received from
  * http://www.arc.umn.edu/gvl-software/media-tools.tar.gz on 2000.04.13.
  *
  * This software is copyrighted as noted below.  It may be freely copied,
@@ -29,75 +29,161 @@
  *              Minnesota Supercomputer Center, Inc.
  * Date:        March 30, 1994
  * Copyright (c) Minnesota Supercomputer Center, Inc.
- * 
- * 2000.04.13 adapted for Netpbm by Bryan Henderson.  Quieted compiler 
+ *
+ * 2000.04.13 adapted for Netpbm by Bryan Henderson.  Quieted compiler
  *            warnings.
  *
+ * 2022.03.06 revision by Akira F Urushibata
+ *            use shhopt instead of scanargs
+ *            proper handling of multiple image files with -h
+ *
  */
 /*-----------------------------------------------------
  * System includes.
  */
 #include <string.h>
 #include <stdio.h>
+#include <assert.h>
 #include "pnm.h"
 #include "mallocvar.h"
 #include "rle.h"
+#include "shhopt.h"
+#include "pm_c_util.h"
 
-#define VPRINTF if (verbose || header) fprintf
 
-typedef unsigned char U_CHAR;
-/*
- * Global variables.
- */
-static FILE    *fp;
-static rle_hdr hdr;
-static int  format;
-static int width, height;
-static int verbose = 0, header = 0, do_alpha = 0;
-static gray    maxval;
+struct CmdlineInfo {
+    /* All the information the user supplied in the command line,
+       in a form easy for the program to use.
+    */
+    const char * inFileName;
+    const char * outfile;
+    unsigned int verbose;
+    unsigned int header;
+    unsigned int alpha;
+};
+
+
+
+static void
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
+/*----------------------------------------------------------------------------
+   Note that the file spec array we return is stored in the storage that
+   was passed to us as the argv array.
+-----------------------------------------------------------------------------*/
+    optEntry * option_def;
+    /* Instructions to pm_optParseOptions3 on how to parse our options. */
+
+    optStruct3 opt;
+
+    unsigned int option_def_index;
+    unsigned int outfileSpec;
+
+    MALLOCARRAY_NOFAIL(option_def, 100);
+
+    option_def_index = 0;   /* incremented by OPTENTRY */
+    OPTENT3(0, "alpha",    OPT_FLAG,   NULL,  &cmdlineP->alpha,     0);
+    OPTENT3(0, "header",   OPT_FLAG,   NULL,  &cmdlineP->header,    0);
+    OPTENT3(0, "verbose",  OPT_FLAG,   NULL,  &cmdlineP->verbose,   0);
+    OPTENT3(0, "outfile",  OPT_STRING, &cmdlineP->outfile,
+                                              &outfileSpec,         0);
+
+    opt.opt_table = option_def;
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We have no parms that are negative numbers */
+
+    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+        /* Uses and sets argc, argv, and some of *cmdlineP and others. */
+
+    free(option_def);
+
+    if (argc-1 == 0)
+        cmdlineP->inFileName = "-";
+    else if (argc-1 != 1) {
+        pm_error("Program takes zero or one argument (filename).  You "
+                 "specified %d", argc-1);
+    }
+    else
+        cmdlineP->inFileName = argv[1];
+
+    if (!outfileSpec)
+        cmdlineP->outfile = "-";
+}
+
+
+
+static void
+readPnmHeader(bool      const verbose,
+              bool      const wantAlpha,
+              FILE    * const ifP,
+              int     * const widthP,
+              int     * const heightP,
+              gray    * const maxvalP,
+              int     * const formatP) {
 /*-----------------------------------------------------------------------------
- *                                        Read the pnm image file header.
- */
-static void 
-read_pnm_header(void) {
+  Read the pnm image file header.
+---------------------------------------------------------------------------- */
+    int   width;
+    int   height;
+    gray  maxval;
+    int   format;
+    const char * type;
+
+    pnm_readpnminit(ifP, &width, &height, &maxval, &format);
 
-    pnm_readpnminit(fp, &width, &height, &maxval, &format);
     switch (format) {
     case PBM_FORMAT:
-        VPRINTF(stderr, "Image type: plain pbm format\n");
+        type="plain pbm";
         break;
     case RPBM_FORMAT:
-        VPRINTF(stderr, "Image type: raw pbm format\n");
+        type="raw pbm";
         break;
     case PGM_FORMAT:
-        VPRINTF(stderr, "Image type: plain pgm format\n");
+        type="plain pgm";
         break;
     case RPGM_FORMAT:
-        VPRINTF(stderr, "Image type: raw pgm format\n");
+        type="raw pgm";
         break;
     case PPM_FORMAT:
-        VPRINTF(stderr, "Image type: plain ppm format\n");
+        type="plain ppm";
         break;
     case RPPM_FORMAT:
-        VPRINTF(stderr, "Image type: raw ppm format\n");
+        type="raw ppm";
         break;
     }
-    VPRINTF(stderr, "Full image: %dx%d\n", width, height);
-    VPRINTF(stderr, "Maxval:     %d\n", maxval);
-    if (do_alpha)
-        VPRINTF(stderr, "Computing alpha channel...\n");
+    if (verbose) {
+        pm_message("Image type: %s format", type);
+        pm_message("Full image: %dx%d", width, height);
+        pm_message("Maxval:     %d", maxval);
+
+        if (wantAlpha)
+            pm_message("Computing alpha channel...");
+    }
+    *widthP  = width;
+    *heightP = height;
+    *maxvalP = maxval;
+    *formatP = format;
 }
 
 
 
-static void 
-write_rle_header(void) {
+static void
+writeRleHeader(bool         const wantAlpha,
+               int          const format,
+               unsigned int const width,
+               unsigned int const height,
+               rle_hdr *    const hdrP) {
+
+    rle_hdr hdr;
+
+    hdr = *hdrP;  /* initial value */
 
     hdr.xmin    = 0;
     hdr.xmax    = width-1;
     hdr.ymin    = 0;
     hdr.ymax    = height-1;
     hdr.background = 0;
+
     switch (format) {
     case PBM_FORMAT:
     case RPBM_FORMAT:
@@ -114,31 +200,44 @@ write_rle_header(void) {
         RLE_SET_BIT(hdr, RLE_BLUE);
         break;
     }
-    if (do_alpha) {
+    if (wantAlpha) {
         hdr.alpha = 1;
         RLE_SET_BIT(hdr, RLE_ALPHA);
     }
     rle_put_setup(&hdr);
+
+    *hdrP = hdr;
 }
 
 
 
-static void 
-write_rle_data(void) {
+static void
+writeRleData(bool         const verbose,
+             bool         const wantAlpha,
+             FILE      *  const ifP,
+             rle_hdr   *  const hdrP,
+             unsigned int const width,
+             unsigned int const height,
+             gray         const maxval,
+             int          const format) {
 
     unsigned int scan;
     xel * xelrow;
     rle_pixel *** scanlines;
 
     MALLOCARRAY(xelrow, width);
-    MALLOCARRAY(scanlines, height);
+    if (xelrow == NULL)
+        pm_error("Failed to allocate memory for row of %u pixels", width);
 
-    RLE_CHECK_ALLOC(hdr.cmd, scanlines, "scanline pointers");
+    MALLOCARRAY(scanlines, height);
+    if (scanlines == NULL)
+        pm_error("Failed to allocate memory for %u scanline pointers", height);
 
     for (scan = 0; scan < height; ++scan) {
         int rc;
-        rc = rle_row_alloc(&hdr, &scanlines[scan]);
-        RLE_CHECK_ALLOC(hdr.cmd, rc >= 0, "pixel memory");
+        rc = rle_row_alloc(hdrP, &scanlines[scan]);
+        if (rc < 0)
+            pm_error("Failed to allocate memory for a scanline");
     }
     /* Loop through the pnm files image window, read data and flip vertically.
      */
@@ -149,10 +248,10 @@ write_rle_data(void) {
         for (scan = 0; scan < height; ++scan) {
             rle_pixel ** const scanline = scanlines[height - scan - 1];
             unsigned int col;
-            pnm_readpnmrow(fp, xelrow, width, maxval, format);
+            pnm_readpnmrow(ifP, xelrow, width, maxval, format);
             for (col = 0; col < width; ++col) {
                 scanline[RLE_RED][col] = PNM_GET1(xelrow[col]) ? 255 : 0;
-                if (do_alpha)
+                if (wantAlpha)
                     scanline[RLE_ALPHA][col] = scanline[RLE_RED][col];
             }
         }
@@ -163,10 +262,10 @@ write_rle_data(void) {
         for (scan = 0; scan < height; ++scan) {
             rle_pixel ** const scanline = scanlines[height - scan - 1];
             unsigned int col;
-            pnm_readpnmrow(fp, xelrow, width, maxval, format);
+            pnm_readpnmrow(ifP, xelrow, width, maxval, format);
             for (col = 0; col < width; ++col) {
                 scanline[RLE_RED][col] = PNM_GET1(xelrow[col]);
-                if (do_alpha)
+                if (wantAlpha)
                     scanline[RLE_ALPHA][col] =
                         scanline[RLE_RED][col] ? 255 : 0;
             }
@@ -177,13 +276,16 @@ write_rle_data(void) {
         unsigned int scan;
         for (scan = 0; scan < height; scan++) {
             rle_pixel ** const scanline = scanlines[height - scan - 1];
+
             unsigned int col;
-            pnm_readpnmrow(fp, xelrow, width, maxval, format);
+
+            pnm_readpnmrow(ifP, xelrow, width, maxval, format);
+
             for (col = 0; col < width; ++col) {
                 scanline[RLE_RED][col]   = PPM_GETR(xelrow[col]);
                 scanline[RLE_GREEN][col] = PPM_GETG(xelrow[col]);
                 scanline[RLE_BLUE][col]  = PPM_GETB(xelrow[col]);
-                if (do_alpha)
+                if (wantAlpha)
                     scanline[RLE_ALPHA][col] =
                         (scanline[RLE_RED][col] ||
                          scanline[RLE_GREEN][col] ||
@@ -194,25 +296,27 @@ write_rle_data(void) {
     }
     /* Write out data in URT order (bottom to top). */
     for (scan = 0; scan < height; ++scan)
-        rle_putrow(scanlines[scan], width, &hdr);
+        rle_putrow(scanlines[scan], width, hdrP);
 
     for (scan = 0; scan < height; ++scan)
-        rle_row_free(&hdr, scanlines[scan]);
+        rle_row_free(hdrP, scanlines[scan]);
     free(scanlines);
     free(xelrow);
 
-    VPRINTF(stderr, "Done -- write eof to RLE data.\n");
-    rle_puteof(&hdr);
+    if (verbose)
+        pm_message("Done -- write eof to RLE data.");
+
+    rle_puteof(hdrP);
 }
 
 
 
 static void
-skip_data(FILE      * const fp,
-          int         const width,
-          int         const height,
-          gray        const maxval,
-          int         const format) {
+skipData(FILE      *  const ifP,
+         unsigned int const width,
+         unsigned int const height,
+         gray         const maxval,
+         int          const format) {
 
     xel * xelrow;
     unsigned int scan;
@@ -221,8 +325,8 @@ skip_data(FILE      * const fp,
     if (xelrow == NULL)
         pm_error("Failed to allocate memory for row of %u pixels", width);
 
-    for(scan=0; scan < height; ++scan)
-        pnm_readpnmrow(fp, xelrow, width, maxval, format);
+    for (scan=0; scan < height; ++scan)
+        pnm_readpnmrow(ifP, xelrow, width, maxval, format);
 
     free(xelrow);
 }
@@ -230,57 +334,57 @@ skip_data(FILE      * const fp,
 
 
 int
-main(int argc, char **  argv) {
-
-    const char * pnmname;
-    const char * outname;
-    int oflag;
+main(int argc, char ** argv) {
+
+    struct CmdlineInfo cmdline;
+
+    FILE   * ifP;
+    rle_hdr hdr;
+    int  format;
+    int  width, height;
+    gray maxval;
+    bool verbose;
+    const char ** argvWork;
+    unsigned int i;
     int eof;
 
-    pnm_init(&argc, argv);
-
-    pnmname = NULL;  /* initial value */
-    outname = NULL;  /* initial value */
-
-    /* Get those options. */
-    if (!scanargs(argc,argv,
-                  "% v%- h%- a%- o%-outfile!s pnmfile%s\n(\
-\tConvert a PNM file to URT RLE format.\n\
-\t-a\tFake an alpha channel.  Alpha=0 when input=0, 255 otherwise.\n\
-\t-h\tPrint header of PNM file and exit.\n\
-\t-v\tVerbose mode.)",
-                  &verbose,
-                  &header,
-                  &do_alpha,
-                  &oflag, &outname,
-                  &pnmname))
-        exit(-1);
+    MALLOCARRAY_NOFAIL(argvWork, argc + 1);
+
+    for (i = 0; i < argc; ++i)  /* Make a copy of argv */
+        argvWork[i] = argv[i];
+
+    pm_proginit(&argc, argvWork);
+
+    parseCommandLine(argc, argvWork, &cmdline);
+
+    verbose = cmdline.verbose || cmdline.header;
 
     hdr = *rle_hdr_init(NULL);
-    rle_names(&hdr, cmd_name(argv), outname, 0);
+
+    rle_names(&hdr, "pnmtorle", cmdline.outfile, 0);
 
     /* Open the file. */
-    if (pnmname == NULL) {
-        fp = pm_openr("-");
-    } else {
-        fp = pm_openr(pnmname);
-    }
+    assert(cmdline.inFileName != NULL);
+    ifP = pm_openr(cmdline.inFileName);
 
-    hdr.rle_file = rle_open_f( hdr.cmd, outname, "wb" );
+    hdr.rle_file = rle_open_f(hdr.cmd, cmdline.outfile, "wb");
 
     for (eof = 0; !eof; ) {
-        read_pnm_header();
+        readPnmHeader(verbose, cmdline.alpha, ifP,
+                      &width, &height, &maxval, &format);
 
-        if (header)
-            skip_data(fp, width, height, maxval, format);
-        else {
+        if (cmdline.header) {
+            skipData(ifP, width, height, maxval, format);
+        } else {
             rle_addhist(argv, NULL, &hdr);
-            write_rle_header();
-            write_rle_data();
+            writeRleHeader(cmdline.alpha, format, width, height, &hdr);
+            writeRleData(verbose, cmdline.alpha, ifP, &hdr,
+                         width, height, maxval, format);
         }
-        pnm_nextimage(fp, &eof);
+        pnm_nextimage(ifP, &eof);
     }
-    pm_close(fp);
+
+    pm_close(ifP);
 
     return 0;
 }
diff --git a/converter/other/pnmtosir.c b/converter/other/pnmtosir.c
index 20bb6178..7b7650fe 100644
--- a/converter/other/pnmtosir.c
+++ b/converter/other/pnmtosir.c
@@ -20,16 +20,16 @@
 
 int
 main(int argc, const char * argv[]) {
-    
+
     FILE * ifP;
     xel ** xels;
     int rows, cols, format;
     unsigned int n;
     bool isGrayscale;
     xelval maxval;
-    unsigned short Header[16];
-    unsigned short LutHeader[16];
-    unsigned short Lut[2048];
+    unsigned short Header[10];
+    unsigned short LutHeader[5];
+    unsigned short Lut[1024];
 
     pm_proginit(&argc, argv);
 
@@ -43,9 +43,9 @@ main(int argc, const char * argv[]) {
     }  else {
         ifP = stdin;
     }
-    
+
     xels = pnm_readpnm(ifP, &cols, &rows, &maxval, &format);
-    
+
     /* Figure out the colormap. */
     switch (PNM_FORMAT_TYPE(format) ) {
     case PPM_TYPE:
@@ -93,15 +93,19 @@ main(int argc, const char * argv[]) {
         pm_writelittleshort(stdout,LutHeader[n]);
     for (n = 5; n < 256; ++n)
         pm_writelittleshort(stdout,0);
- 
-    for (n = 0; n < 3; ++n) {
+
+    for (n = 0; n < 256; ++n) {
         unsigned int m;
-        for (m = 0; m < 256; ++m)
-            Lut[m * 4 + n] = m << 8;
+        for (m = 0; m < 3; ++m)
+            Lut[n * 4 + m] = n << 8;
+
+        Lut[n * 4 + 3] = 0;
+            /* Clear to ensure repeatable output, suppress Valgrind error */
     }
+
     for (n = 0; n < 1024; ++n)
         pm_writelittleshort(stdout,Lut[n]);
- 
+
     /* Finally, write out the data. */
     switch (PNM_FORMAT_TYPE(format)) {
     case PPM_TYPE: {
@@ -110,13 +114,13 @@ main(int argc, const char * argv[]) {
             unsigned int col;
             for (col = 0; col < cols; ++col) {
                 unsigned char const ub =
-                    (char) (PPM_GETR(xels[row][col]) * (255 / maxval)); 
+                    (char) (PPM_GETR(xels[row][col]) * (255 / maxval));
                 fputc(ub, stdout);
             }
         }
         for (row = 0; row < rows; ++row) {
             unsigned int col;
-            for (col = 0; col < cols; ++col) {  
+            for (col = 0; col < cols; ++col) {
                 unsigned const char ub =
                     (char) (PPM_GETG(xels[row][col]) * (255 / maxval));
                 fputc(ub, stdout);
@@ -124,7 +128,7 @@ main(int argc, const char * argv[]) {
         }
         for (row = 0; row < rows; ++row) {
             unsigned int col;
-            for (col = 0; col < cols; ++col) {  
+            for (col = 0; col < cols; ++col) {
                 unsigned const char ub =
                     (char) (PPM_GETB(xels[row][col]) * (255 / maxval));
                 fputc(ub, stdout);
@@ -144,10 +148,11 @@ main(int argc, const char * argv[]) {
         }
     } break;
     }
-    
+
     pm_close(ifP);
 
     return 0;
 }
 
 
+
diff --git a/converter/other/pstopnm.c b/converter/other/pstopnm.c
index f5342655..25f2c429 100644
--- a/converter/other/pstopnm.c
+++ b/converter/other/pstopnm.c
@@ -442,7 +442,7 @@ languageDeclaration(char const inputFileName[]) {
 /*----------------------------------------------------------------------------
   Return the Postscript language in which the file declares it is written.
   (Except that if the file is on Standard Input or doesn't validly declare
-  a languages, just say it is Common Postscript).
+  a language, just say it is Common Postscript).
 -----------------------------------------------------------------------------*/
     enum PostscriptLanguage language;
 
@@ -909,6 +909,27 @@ execGhostscript(int               const inputPipeFd,
 
 
 static void
+copyFileStream(FILE * const ifP,
+               FILE * const ofP) {
+
+    bool eof;
+
+    for (eof = false; !eof; ) {
+        char buffer[4096];
+        size_t readCt;
+
+        readCt = fread(buffer, 1, sizeof(buffer), ifP);
+
+        if (readCt == 0)
+            eof = true;
+        else
+            fwrite(buffer, 1, readCt, ofP);
+    }
+}
+
+
+
+static void
 feedPsToGhostScript(const char *            const inputFileName,
                     struct Box              const borderedBox,
                     struct Dimensions       const imageDim,
@@ -927,7 +948,6 @@ feedPsToGhostScript(const char *            const inputFileName,
 -----------------------------------------------------------------------------*/
     FILE * pipeToGsP;  /* Pipe to Ghostscript's standard input */
     FILE * ifP;
-    bool eof;  /* End of file on input */
 
     pipeToGsP = fdopen(pipeToGhostscriptFd, "w");
     if (pipeToGsP == NULL)
@@ -947,8 +967,14 @@ feedPsToGhostScript(const char *            const inputFileName,
       The example given is a much fancier solution than we need
       here, I think, so I boiled it down a bit.  JM
     */
-    if (language == ENCAPSULATED_POSTSCRIPT)
-        fprintf(pipeToGsP, "\n/b4_Inc_state save def /showpage { } def\n");
+    if (language == ENCAPSULATED_POSTSCRIPT) {
+        const char * const defShowpageCmd =
+            "/b4_Inc_state save def /showpage { } def";
+        if (verbose)
+            pm_message("Defining showpage with '%s'", defShowpageCmd);
+
+        fprintf(pipeToGsP, "\n%s\n", defShowpageCmd);
+    }
 
     writePstrans(borderedBox, imageDim, orientation, pipeToGsP);
 
@@ -958,22 +984,19 @@ feedPsToGhostScript(const char *            const inputFileName,
     */
     signal(SIGPIPE, SIG_IGN);
 
-    eof = FALSE;
-    while (!eof) {
-        char buffer[4096];
-        size_t readCt;
+    copyFileStream(ifP, pipeToGsP);
 
-        readCt = fread(buffer, 1, sizeof(buffer), ifP);
-        if (readCt == 0)
-            eof = TRUE;
-        else
-            fwrite(buffer, 1, readCt, pipeToGsP);
-    }
     pm_close(ifP);
 
-    if (language == ENCAPSULATED_POSTSCRIPT)
-        fprintf(pipeToGsP, "\nb4_Inc_state restore showpage\n");
+    if (language == ENCAPSULATED_POSTSCRIPT) {
+        const char * const restoreShowpageCmd =
+            "b4_Inc_state restore showpage";
+
+        if (verbose)
+            pm_message("Restoring showpage with '%s'", restoreShowpageCmd);
 
+        fprintf(pipeToGsP, "\n%s\n", restoreShowpageCmd);
+    }
     fclose(pipeToGsP);
 }
 
diff --git a/converter/other/pstopnm.csh b/converter/other/pstopnm.csh
index adde3e6f..22e3306d 100755
--- a/converter/other/pstopnm.csh
+++ b/converter/other/pstopnm.csh
@@ -5,7 +5,7 @@
 #	pstopnm will create as many files as the number of pages in 
 #	the Postscript document.  The name of the files will be 
 #	psfile001.ppm, psfile002.ppm, etc.
-#	The ouput files will contain the area inside the BoundingBox.
+#	The output files will contain the area inside the BoundingBox.
 #	If BoundingBox parameters are not found in the PostScript
 #	document, default values are used.
 #
diff --git a/converter/other/qoi.h b/converter/other/qoi.h
new file mode 100644
index 00000000..52ee95e2
--- /dev/null
+++ b/converter/other/qoi.h
@@ -0,0 +1,101 @@
+#ifndef QOI_H_INCLUDED
+#define QOI_H_INCLUDED
+/*
+
+QOI - The "Quite OK Image" format for fast, lossless image compression
+
+Dominic Szablewski - https://phoboslab.org
+
+
+-- LICENSE: The MIT License(MIT)
+
+Copyright(c) 2021 Dominic Szablewski
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files(the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions :
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+*/
+
+
+typedef enum {
+    QOI_SRGB = 0,
+    QOI_LINEAR = 1
+} qoi_Colorspace;
+
+
+typedef struct {
+    unsigned int   width;
+    unsigned int   height;
+    unsigned int   channelCt;
+    qoi_Colorspace colorspace;
+} qoi_Desc;
+
+
+
+#define QOI_OP_INDEX  0x00 /* 00xxxxxx */
+#define QOI_OP_DIFF   0x40 /* 01xxxxxx */
+#define QOI_OP_LUMA   0x80 /* 10xxxxxx */
+#define QOI_OP_RUN    0xc0 /* 11xxxxxx */
+#define QOI_OP_RGB    0xfe /* 11111110 */
+#define QOI_OP_RGBA   0xff /* 11111111 */
+
+#define QOI_MASK_2    0xc0 /* 11000000 */
+
+#define QOI_HEADER_SIZE 14
+
+/* 2GB is the max file size that this implementation can safely handle. We
+   guard against anything larger than that, assuming the worst case with 5
+   bytes per pixel, rounded down to a nice clean value. 400 million pixels
+   ought to be enough for anybody.
+ */
+#define QOI_PIXELS_MAX 400000000
+
+static unsigned int const qoi_pixels_max = (unsigned int) QOI_PIXELS_MAX;
+
+#define QOI_MAXVAL 255
+
+#define QOI_INDEX_SIZE 64
+
+
+typedef union {
+    struct { unsigned char r, g, b, a; } rgba;
+    unsigned int v;
+} qoi_Rgba;
+
+static __inline__ unsigned int
+qoi_colorHash(qoi_Rgba const x) {
+
+    return
+        (x.rgba.r*3 + x.rgba.g*5 + x.rgba.b*7 + x.rgba.a*11) % QOI_INDEX_SIZE;
+}
+
+static __inline__ void
+qoi_clearQoiIndex(qoi_Rgba * index) {
+
+    memset(index, 0, QOI_INDEX_SIZE * sizeof(qoi_Rgba));
+
+}
+
+#define QOI_MAGIC_SIZE 4
+
+static char const qoi_magic[QOI_MAGIC_SIZE + 1] = {'q','o','i','f','\0'};
+
+#define QOI_PADDING_SIZE 8
+
+static unsigned char const qoi_padding[QOI_PADDING_SIZE] = {0,0,0,0,0,0,0,1};
+
+
+#endif
diff --git a/converter/other/qoitopam.c b/converter/other/qoitopam.c
new file mode 100644
index 00000000..af6817b7
--- /dev/null
+++ b/converter/other/qoitopam.c
@@ -0,0 +1,323 @@
+/*
+  qoitopam -  Converts from a QOI - The "Quite OK Image" format file to PAM
+
+  This program is part of Netpbm.
+
+  ---------------------------------------------------------------------
+
+
+  QOI - The "Quite OK Image" format for fast, lossless image compression
+
+  Decoder by Dominic Szablewski - https://phoboslab.org
+
+  -- LICENSE: The MIT License(MIT)
+
+  Copyright(c) 2021 Dominic Szablewski
+
+  Permission is hereby granted, free of charge, to any person obtaining a copy
+  of this software and associated documentation files(the "Software"), to deal
+  in the Software without restriction, including without limitation the rights
+  to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
+  copies of the Software, and to permit persons to whom the Software is
+  furnished to do so, subject to the following conditions :
+
+  The above copyright notice and this permission notice shall be included in
+  all copies or substantial portions of the Software.
+
+  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
+  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+  SOFTWARE.
+
+  For more information on the format visit: https//qoiformat.org/ .
+
+  Modifications for Netpbm & PAM write routines by Akira F. Urushibata.
+*/
+
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+
+#include "pm.h"
+#include "pam.h"
+#include "mallocvar.h"
+#include "nstring.h"
+#include "shhopt.h"
+
+#include "qoi.h"
+
+
+
+struct CmdlineInfo {
+    /* All the information the user supplied in the command line,
+       in a form easy for the program to use.
+    */
+    const char * inputFileName;  /* '-' if stdin */
+};
+
+
+
+static void
+parseCommandLine(int                  argc,
+                 const char **        argv,
+                 struct CmdlineInfo * cmdlineP ) {
+/*----------------------------------------------------------------------------
+   Parse program command line described in Unix standard form by argc
+   and argv.  Return the information in the options as *cmdlineP.
+
+   If command line is internally inconsistent (invalid options, etc.),
+   issue error message to stderr and abort program.
+
+   Note that the strings we return are stored in the storage that
+   was passed to us as the argv array.  We also trash *argv.
+-----------------------------------------------------------------------------*/
+    optEntry * option_def;
+        /* Instructions to pm_optParseOptions3 on how to parse our options.
+         */
+    optStruct3 opt;
+
+    unsigned int option_def_index;
+
+    MALLOCARRAY(option_def, 100);
+
+    OPTENTINIT;
+
+    opt.opt_table = option_def;
+    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
+
+    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+        /* Uses and sets argc, argv, and some of *cmdlineP and others. */
+
+    if (argc-1 < 1)
+        cmdlineP->inputFileName = "-";
+    else if (argc-1 == 1)
+        cmdlineP->inputFileName = argv[1];
+    else
+        pm_error("Program takes at most one argument: input file name.  "
+            "you specified %d", argc-1);
+}
+
+
+
+static void
+readAndValidateMagic(FILE * const ifP){
+
+    char magicBuff[QOI_MAGIC_SIZE];
+    size_t charsReadCt;
+
+    charsReadCt = fread(magicBuff, 1, QOI_MAGIC_SIZE, ifP);
+
+    if (charsReadCt == 0)
+        pm_error("Input file is empty.");
+    else if (charsReadCt < QOI_MAGIC_SIZE || !MEMSEQ(&magicBuff, &qoi_magic)) {
+        assert(QOI_MAGIC_SIZE == 4);
+        pm_error("Invalid QOI image: does not start with magic number "
+                 "'%c%c%c%c'",
+                 qoi_magic[0], qoi_magic[1], qoi_magic[2], qoi_magic[3]);
+    }
+}
+
+
+/* The following two functions are from lib/pmfileio.c */
+
+static void
+abortWithReadError(FILE * const ifP) {
+
+    if (feof(ifP))
+        pm_error("Unexpected end of input file");
+    else
+        pm_error("Error (not EOF) reading file.");
+}
+
+
+
+static unsigned char
+getcNofail(FILE * const ifP) {
+
+    int c;
+
+    c = getc(ifP);
+
+    if (c == EOF)
+        abortWithReadError(ifP);
+
+    return (unsigned char) c;
+}
+
+
+
+static void
+decodeQoiHeader(FILE *     const ifP,
+                qoi_Desc * const qoiDescP) {
+
+    unsigned long int width, height;
+
+    readAndValidateMagic(ifP);
+
+    pm_readbiglongu(ifP, &width);
+    if (width == 0)
+        pm_error("Invalid QOI image: width is zero");
+    else
+        qoiDescP->width = width;
+
+    pm_readbiglongu(ifP, &height);
+    if (height == 0)
+        pm_error("Invalid QOI image: height is zero");
+    else if (height > QOI_PIXELS_MAX / width)
+        pm_error ("Invalid QOI image: %u x %u is more than %u pixels",
+                  (unsigned int) width, (unsigned int) height, QOI_PIXELS_MAX);
+    else
+        qoiDescP->height = height;
+
+    qoiDescP->channelCt = getcNofail(ifP);
+    if (qoiDescP->channelCt != 3 && qoiDescP->channelCt != 4)
+        pm_error("Invalid QOI image: channel count is %u.  "
+                 "Only 3 and 4 are valid", qoiDescP->channelCt);
+
+    qoiDescP->colorspace = getcNofail(ifP);
+    if (qoiDescP->colorspace != QOI_SRGB && qoiDescP->colorspace != QOI_LINEAR)
+        pm_error("Invalid QOI image: colorspace code is %u.  "
+                 "Only %u (SRGB) and %u (LINEAR) are valid",
+                 qoiDescP->colorspace, QOI_SRGB, QOI_LINEAR);
+}
+
+
+
+static void
+qoiDecode(FILE *       const ifP,
+          qoi_Desc *   const qoiDescP,
+          struct pam * const outpamP) {
+
+    qoi_Rgba index[QOI_INDEX_SIZE];
+    unsigned int row;
+    qoi_Rgba px;
+    unsigned int run;
+    tuple * tuplerow;
+
+    assert(qoiDescP);
+    tuplerow = pnm_allocpamrow(outpamP);
+
+    qoi_clearQoiIndex(index);
+    px.rgba.r = px.rgba.g = px.rgba.b = 0;
+    px.rgba.a = 255;
+
+    for (row = 0, run = 0; row < outpamP->height; ++row) {
+        unsigned int col;
+
+        for (col = 0; col < outpamP->width; ++col) {
+            if (run > 0) {
+                 --run;
+            } else {
+                unsigned char const b1 = getcNofail(ifP);
+
+                if (b1 == QOI_OP_RGB) {
+                    px.rgba.r = getcNofail(ifP);
+                    px.rgba.g = getcNofail(ifP);
+                    px.rgba.b = getcNofail(ifP);
+                } else if (b1 == QOI_OP_RGBA) {
+                    px.rgba.r = getcNofail(ifP);
+                    px.rgba.g = getcNofail(ifP);
+                    px.rgba.b = getcNofail(ifP);
+                    px.rgba.a = getcNofail(ifP);
+                } else if ((b1 & QOI_MASK_2) == QOI_OP_INDEX) {
+                  /* Official spec says 2 or more consecutive instances of
+                     QOI_OP_INDEX are not allowed, but we don't check */
+                    px = index[b1];
+                } else if ((b1 & QOI_MASK_2) == QOI_OP_DIFF) {
+                    px.rgba.r += ((b1 >> 4) & 0x03) - 2;
+                    px.rgba.g += ((b1 >> 2) & 0x03) - 2;
+                    px.rgba.b += ( b1       & 0x03) - 2;
+                } else if ((b1 & QOI_MASK_2) == QOI_OP_LUMA) {
+                    unsigned char const b2 = getcNofail(ifP);
+                    unsigned char const vg = (b1 & 0x3f) - 32;
+                    px.rgba.r += vg - 8 + ((b2 >> 4) & 0x0f);
+                    px.rgba.g += vg;
+                    px.rgba.b += vg - 8 +  (b2       & 0x0f);
+                } else if ((b1 & QOI_MASK_2) == QOI_OP_RUN) {
+                    run = (b1 & 0x3f);
+                }
+                /* register pixel in hash lookup array */
+                index[qoi_colorHash(px)] = px;
+            }
+            tuplerow[col][PAM_RED_PLANE] = px.rgba.r;
+            tuplerow[col][PAM_GRN_PLANE] = px.rgba.g;
+            tuplerow[col][PAM_BLU_PLANE] = px.rgba.b;
+            if (qoiDescP->channelCt == 4)
+                tuplerow[col][PAM_TRN_PLANE] = px.rgba.a;
+        }
+        pnm_writepamrow(outpamP, tuplerow);
+    }
+    if (run > 0)
+        pm_error("Invalid QOI image: %u (or more) extra pixels "
+                 "beyond end of image.", run);
+
+    pnm_freepamrow(tuplerow);
+}
+
+
+
+static void
+readAndValidatePadding(FILE * const ifP){
+
+    unsigned char padBuff[QOI_PADDING_SIZE];
+    size_t charsReadCt;
+
+    charsReadCt = fread(padBuff, 1, QOI_PADDING_SIZE, ifP);
+
+    if(charsReadCt < QOI_PADDING_SIZE) {
+        pm_error("Invalid QOI image.  Error reading final 8-byte padding.  "
+                 "Premature end of file.");
+    } else if (!MEMSEQ(&padBuff, &qoi_padding))
+        pm_error("Invalid QOI image.  Final 8-byte padding incorrect.");
+    else if (fgetc(ifP) != EOF)
+        pm_error("Invalid QOI image.  "
+                 "Extraneous bytes after final 8-byte padding.");
+}
+
+
+
+int
+main(int argc, const char **argv) {
+
+    struct CmdlineInfo cmdline;
+    qoi_Desc qoiDesc;
+    struct pam outpam;
+    FILE * ifP;
+
+    pm_proginit(&argc, argv);
+
+    parseCommandLine(argc, argv, &cmdline);
+
+    ifP = pm_openr(cmdline.inputFileName);
+
+    outpam.size        = sizeof(struct pam);
+    outpam.len         = PAM_STRUCT_SIZE(tuple_type);
+    outpam.maxval      = QOI_MAXVAL;
+    outpam.plainformat = 0;
+
+    decodeQoiHeader(ifP, &qoiDesc);
+
+    outpam.depth  = qoiDesc.channelCt == 3 ? 3 : 4;
+    outpam.width  = qoiDesc.width;
+    outpam.height = qoiDesc.height;
+    outpam.format = PAM_FORMAT;
+    outpam.file   = stdout;
+
+    if (qoiDesc.channelCt == 3)
+        strcpy(outpam.tuple_type, PAM_PPM_TUPLETYPE);
+    else
+        strcpy(outpam.tuple_type, PAM_PPM_ALPHA_TUPLETYPE);
+
+    pnm_writepaminit(&outpam);
+    qoiDecode(ifP, &qoiDesc, &outpam);
+
+    readAndValidatePadding(ifP);
+
+    return 0;
+}
+
+
diff --git a/converter/other/rlatopam.c b/converter/other/rlatopam.c
index 703c4820..2c694bd4 100644
--- a/converter/other/rlatopam.c
+++ b/converter/other/rlatopam.c
@@ -85,9 +85,9 @@ read_header(FILE *   const ifP,
 
     rlahdr hdr;
     size_t bytesRead;
-    
+
     fseek (ifP, 0, SEEK_SET);
-    
+
     /* Here we have a hack.  The bytes in the file are almost in the
        same format as the compiler stores 'hdr' in memory.  The only
        difference is that the compiler may store the integer values
@@ -185,7 +185,7 @@ decode(unsigned char * const input,
     x = xFile;
     bytes = 0;
     useX = 0;
-    
+
     while (x > 0) {
         int count;
 
@@ -246,7 +246,7 @@ decode_row(FILE *          const ifP,
     for (chan = 0; chan < outpam.depth; ++chan) {
         unsigned short length;
         size_t bytesRead;
-        
+
         pm_readbigshortu(ifP, &length);
         if (length > width * 4)
             pm_error("Line too long - row %u, channel %u", row, chan);
@@ -266,7 +266,7 @@ decode_row(FILE *          const ifP,
             decode(newpos, rb + chan * 2 + 1, width, width,
                    outpam.depth * 2);
         } else
-            decode(read_buffer, rb + chan, width, width, outpam.depth); 
+            decode(read_buffer, rb + chan, width, width, outpam.depth);
     }
 }
 
@@ -280,7 +280,7 @@ getHeaderInfo(FILE *         const ifP,
               bool *         const hasMatteP,
               unsigned int * const chanBitsP,
               short *        const storageType) {
-    
+
     rlahdr hdr;
     int width, height;
 
@@ -350,7 +350,7 @@ readAndWriteRaster(FILE *             const ifP,
     /* Hold one row of all image planes */
     rowBuffer = calloc(1, width * outpamP->depth * 4);
     if (rowBuffer == NULL)
-        pm_error("Unable to allocate memor for row buffer.");
+        pm_error("Unable to allocate memory for row buffer.");
 
     tuplerow = pnm_allocpamrow(outpamP);
 
@@ -403,7 +403,7 @@ main(int    argc,
     outpam.height = height;
     outpam.width  = width;
     outpam.depth  = numChan + (has_matte ? 1 : 0);
-    outpam.maxval = (1 << (chanBits > 16 ? 
+    outpam.maxval = (1 << (chanBits > 16 ?
                            (9 + (chanBits - 1) % 8)
                                 /* Take top 2 of 3 or 4 bytes */
                            : chanBits)) - 1;
@@ -427,8 +427,11 @@ main(int    argc,
     readAndWriteRaster(ifP, &outpam);
 
     destroyOffsetArray(offsets);
-    
+
     pm_close(ifP);
 
-    return 0; 
+    return 0;
 }
+
+
+
diff --git a/converter/other/rletopnm.c b/converter/other/rletopnm.c
index 018456c8..97f271dc 100644
--- a/converter/other/rletopnm.c
+++ b/converter/other/rletopnm.c
@@ -1,7 +1,7 @@
 /*
  * This is derived from the file of the same name dated June 5, 1995,
  * copied from the Army High Performance Computing Research Center's
- * media-tools.tar.gz package, received from 
+ * media-tools.tar.gz package, received from
  * http://www.arc.umn.edu/gvl-software/media-tools.tar.gz on 2000.04.13.
  *
  * This software is copyrighted as noted below.  It may be freely copied,
@@ -29,8 +29,8 @@
  *              Minnesota Supercomputer Center, Inc.
  * Date:        March 30, 1994
  * Copyright (c) Minnesota Supercomputer Center 1994
- * 
- * 2000.04.13 adapted for Netpbm by Bryan Henderson.  Quieted compiler 
+ *
+ * 2000.04.13 adapted for Netpbm by Bryan Henderson.  Quieted compiler
  *            warnings.  Added --alpha option.  Accept input on stdin
  *
  */
@@ -105,11 +105,11 @@ parseCommandLine(int argc, char ** argv,
     MALLOCARRAY(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3('h', "headerdump", OPT_FLAG,   
+    OPTENT3('h', "headerdump", OPT_FLAG,
             NULL,                      &cmdlineP->headerdump,     0);
-    OPTENT3('v', "verbose",    OPT_FLAG,   
+    OPTENT3('v', "verbose",    OPT_FLAG,
             NULL,                      &cmdlineP->verbose,        0);
-    OPTENT3(0,   "alphaout",   OPT_STRING, 
+    OPTENT3(0,   "alphaout",   OPT_STRING,
             &cmdlineP->alphaout, &alphaoutSpec,                   0);
 
     opt.opt_table = option_def;
@@ -127,16 +127,16 @@ parseCommandLine(int argc, char ** argv,
     else if (argc - 1 == 1) {
         if (streq(argv[1], "-"))
             cmdlineP->inputFilename = NULL;  /* he wants stdin */
-        else 
+        else
             cmdlineP->inputFilename = strdup(argv[1]);
-    } else 
+    } else
         pm_error("Too many arguments.  The only argument accepted "
                  "is the input file specification");
 
-    if (cmdlineP->alphaout && 
+    if (cmdlineP->alphaout &&
         streq(cmdlineP->alphaout, "-"))
         cmdlineP->alphaStdout = TRUE;
-    else 
+    else
         cmdlineP->alphaStdout = FALSE;
 }
 
@@ -144,7 +144,7 @@ parseCommandLine(int argc, char ** argv,
 
 static void
 reportRleGetSetupError(int const rleGetSetupRc) {
-    
+
     switch (rleGetSetupRc) {
     case -1:
         pm_error("According to the URT library, the input is not "
@@ -168,7 +168,7 @@ reportRleGetSetupError(int const rleGetSetupRc) {
 
 
 
-static void 
+static void
 readRleHeader(FILE * const ifP,
               bool   const headerDump) {
 
@@ -256,7 +256,7 @@ readRleHeader(FILE * const ifP,
 
 
 
-static void 
+static void
 writePpmRaster(FILE * const imageoutFileP,
                FILE * const alphaFileP) {
 
@@ -264,7 +264,7 @@ writePpmRaster(FILE * const imageoutFileP,
     pixval r, g, b;
     pixel *pixelrow;
     gray *alpharow;
-   
+
     int scan;
     int x;
     /*
@@ -274,11 +274,15 @@ writePpmRaster(FILE * const imageoutFileP,
     alpharow = pgm_allocrow(width);
 
     MALLOCARRAY(scanlines, height);
-    RLE_CHECK_ALLOC( hdr.cmd, scanlines, "scanline pointers" );
+    if (!scanlines)
+        pm_error("Failed to allocate memory for %u scanline pointers", height);
 
-    for ( scan = 0; scan < height; scan++ )
-        RLE_CHECK_ALLOC( hdr.cmd, (rle_row_alloc(&hdr, &scanlines[scan]) >= 0),
-                         "pixel memory" );
+    for (scan = 0; scan < height; ++scan) {
+        int rc;
+        rc = rle_row_alloc(&hdr, &scanlines[scan]);
+        if (rc < 0)
+            pm_error("Failed to allocate memory for a scanline");
+    }
     /*
      * Loop through those scan lines.
      */
@@ -295,7 +299,7 @@ writePpmRaster(FILE * const imageoutFileP,
                 PPM_ASSIGN(pixelrow[x], r, g, b);
                 if (hdr.alpha)
                     alpharow[x] = scanline[-1][x];
-                else 
+                else
                     alpharow[x] = 0;
             }
             break;
@@ -305,7 +309,7 @@ writePpmRaster(FILE * const imageoutFileP,
                 g = colormap[scanline[1][x]+256]>>8;
                 b = colormap[scanline[2][x]+512]>>8;
                 PPM_ASSIGN(pixelrow[x], r, g, b);
-                if (hdr.alpha) 
+                if (hdr.alpha)
                     alpharow[x] = colormap[scanline[-1][x]];
                 else
                     alpharow[x] = 0;
@@ -329,7 +333,7 @@ writePpmRaster(FILE * const imageoutFileP,
                 g = colormap[scanline[0][x]+256]>>8;
                 b = colormap[scanline[0][x]+512]>>8;
                 PPM_ASSIGN(pixelrow[x], r, g, b);
-                if (hdr.alpha) 
+                if (hdr.alpha)
                     alpharow[x] = colormap[scanline[-1][x]];
                 else
                     alpharow[x] = 0;
@@ -341,7 +345,7 @@ writePpmRaster(FILE * const imageoutFileP,
         /*
          * Write the scan line.
          */
-        if (imageoutFileP) 
+        if (imageoutFileP)
             ppm_writeppmrow(imageoutFileP, pixelrow, width, RLE_MAXVAL, 0);
         if (alphaFileP)
             pgm_writepgmrow(alphaFileP, alpharow, width, RLE_MAXVAL, 0);
@@ -358,7 +362,7 @@ writePpmRaster(FILE * const imageoutFileP,
 
 
 
-static void 
+static void
 writePgmRaster(FILE * const imageoutFileP,
                FILE * const alphaFileP) {
 /*----------------------------------------------------------------------------
@@ -375,11 +379,15 @@ writePgmRaster(FILE * const imageoutFileP,
     alpharow = pgm_allocrow(width);
 
     MALLOCARRAY(scanlines, height);
-    RLE_CHECK_ALLOC( hdr.cmd, scanlines, "scanline pointers" );
+    if (!scanlines)
+        pm_error("Failed to allocate memory for %u scanline pointers", height);
 
-    for (scan = 0; scan < height; ++scan)
-        RLE_CHECK_ALLOC(hdr.cmd, (rle_row_alloc(&hdr, &scanlines[scan]) >= 0),
-                        "pixel memory" );
+    for (scan = 0; scan < height; ++scan) {
+        int rc;
+        rc = rle_row_alloc(&hdr, &scanlines[scan]);
+        if (rc < 0)
+            pm_error("Failed to allocate memory for a scanline");
+    }
     /*
      * Loop through those scan lines.
      */
@@ -391,12 +399,12 @@ writePgmRaster(FILE * const imageoutFileP,
         scanline = scanlines[scan];
         for (x = 0; x < width; ++x) {
             pixelrow[x] = scanline[0][x];
-            if (hdr.alpha) 
+            if (hdr.alpha)
                 alpharow[x] = scanline[1][x];
             else
                 alpharow[x] = 0;
         }
-        if (imageoutFileP) 
+        if (imageoutFileP)
             pgm_writepgmrow(imageoutFileP, pixelrow, width, RLE_MAXVAL, 0);
         if (alphaFileP)
             pgm_writepgmrow(alphaFileP, alpharow, width, RLE_MAXVAL, 0);
@@ -428,20 +436,20 @@ main(int argc, char ** argv) {
 
     fname = NULL;  /* initial value */
 
-    if (cmdline.inputFilename != NULL ) 
+    if (cmdline.inputFilename != NULL )
         ifP = pm_openr(cmdline.inputFilename);
     else
         ifP = stdin;
 
     if (cmdline.alphaStdout)
         alphaFileP = stdout;
-    else if (cmdline.alphaout == NULL) 
+    else if (cmdline.alphaout == NULL)
         alphaFileP = NULL;
     else {
         alphaFileP = pm_openw(cmdline.alphaout);
     }
 
-    if (cmdline.alphaStdout) 
+    if (cmdline.alphaStdout)
         imageoutFileP = NULL;
     else
         imageoutFileP = stdout;
@@ -461,7 +469,7 @@ main(int argc, char ** argv) {
     if (cmdline.headerdump)
         exit(0);
 
-    /* 
+    /*
      * Write the alpha file header
      */
     if (alphaFileP)
@@ -486,9 +494,9 @@ main(int argc, char ** argv) {
         writePpmRaster(imageoutFileP, alphaFileP);
         break;
     }
-   
+
     pm_close(ifP);
-    if (imageoutFileP) 
+    if (imageoutFileP)
         pm_close(imageoutFileP);
     if (alphaFileP)
         pm_close(alphaFileP);
diff --git a/converter/other/sunicontopnm.c b/converter/other/sunicontopnm.c
index db26663e..93ddc0ab 100644
--- a/converter/other/sunicontopnm.c
+++ b/converter/other/sunicontopnm.c
@@ -30,9 +30,9 @@
 
 
 static void
-ReadIconFileHeader(FILE * const file, 
-                   int *  const widthP, 
-                   int *  const heightP, 
+ReadIconFileHeader(FILE * const file,
+                   int *  const widthP,
+                   int *  const heightP,
                    int *  const depthP,
                    int *  const bitsPerItemP) {
 
@@ -51,7 +51,7 @@ ReadIconFileHeader(FILE * const file,
                 ch == ' ')
             ;
         for (i = 0;
-             ch != '=' && ch != ',' && ch != '\n' && ch != '\t' && 
+             ch != '=' && ch != ',' && ch != '\n' && ch != '\t' &&
                  ch != ' ' && (i < (sizeof(variable) - 1));
              ++i) {
             variable[i] = ch;
@@ -84,7 +84,7 @@ ReadIconFileHeader(FILE * const file,
         } else if (streq(variable, "Valid_bits_per_item")) {
             if (value != 16 && value !=32)
                 pm_error("invalid Valid_bits_per_item");
-            *bitsPerItemP = value; 
+            *bitsPerItemP = value;
             ++fieldCt;
         }
     }
@@ -165,7 +165,7 @@ main(int argc, const char ** argv) {
                 else
                     grayrow[colChar] = data;
             } else
-                pm_error("error scanning bits item %u" , colChar);
+                pm_error("error scanning bits item %u", colChar);
         }
 
         /* output row */
diff --git a/converter/other/tifftopnm.c b/converter/other/tifftopnm.c
index c1e7af85..0c301a4a 100644
--- a/converter/other/tifftopnm.c
+++ b/converter/other/tifftopnm.c
@@ -24,16 +24,16 @@
 /* Design note:
 
    We have two different ways of converting from Tiff, as provided by the
-   Tiff library:  
+   Tiff library:
 
    1) decode the entire image into memory at once, using
       TIFFRGBAImageGet(), then convert to PNM and output row by row.
-   
+
    2) read, convert, and output one row at a time using TIFFReadScanline().
 
    (1) is preferable because the Tiff library does more of the work, which
-   means it understands more of the Tiff format possibilities now and in 
-   the future.  Also, some compressed TIFF formats don't allow you to 
+   means it understands more of the Tiff format possibilities now and in
+   the future.  Also, some compressed TIFF formats don't allow you to
    extract an individual row.
 
    (2) uses far less memory, and because our code does more of the work,
@@ -117,17 +117,17 @@ parseCommandLine(int argc, const char ** const argv,
     opt.allowNegNum = FALSE;
 
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0, "verbose", 
+    OPTENT3(0, "verbose",
             OPT_FLAG,   NULL, &cmdlineP->verbose,              0);
-    OPTENT3(0, "respectfillorder", 
+    OPTENT3(0, "respectfillorder",
             OPT_FLAG,   NULL, &cmdlineP->respectfillorder,     0);
-    OPTENT3(0,   "byrow",   
+    OPTENT3(0,   "byrow",
             OPT_FLAG,   NULL, &cmdlineP->byrow,                0);
-    OPTENT3(0,   "orientraw",   
+    OPTENT3(0,   "orientraw",
             OPT_FLAG,   NULL, &cmdlineP->orientraw,            0);
-    OPTENT3('h', "headerdump", 
+    OPTENT3('h', "headerdump",
             OPT_FLAG,   NULL, &cmdlineP->headerdump,           0);
-    OPTENT3(0,   "alphaout",   
+    OPTENT3(0,   "alphaout",
             OPT_STRING, &cmdlineP->alphaFilename, &alphaSpec,  0);
 
     pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
@@ -136,7 +136,7 @@ parseCommandLine(int argc, const char ** const argv,
         cmdlineP->inputFilename = strdup("-");  /* he wants stdin */
     else if (argc - 1 == 1)
         cmdlineP->inputFilename = strdup(argv[1]);
-    else 
+    else
         pm_error("Too many arguments.  The only argument accepted "
                  "is the input file name");
 
@@ -309,11 +309,11 @@ validatePlanarConfig(unsigned short const planarconfig,
     case PLANARCONFIG_CONTIG:
         break;
     case PLANARCONFIG_SEPARATE:
-        if (photomet != PHOTOMETRIC_RGB && 
+        if (photomet != PHOTOMETRIC_RGB &&
             photomet != PHOTOMETRIC_SEPARATED)
             pm_error("This program can handle separate planes only "
                      "with RGB (PHOTOMETRIC tag = %u) or SEPARATED "
-                     "(PHOTOMETRIC tag = %u) data.  The input Tiff file " 
+                     "(PHOTOMETRIC tag = %u) data.  The input Tiff file "
                      "has PHOTOMETRIC tag = %hu.",
                      PHOTOMETRIC_RGB, PHOTOMETRIC_SEPARATED,
                      photomet);
@@ -351,7 +351,7 @@ dumpHeader(const struct tiffDirInfo * const headerP) {
 
 
 
-static void 
+static void
 readDirectory(TIFF *               const tiffP,
               bool                 const headerdump,
               struct tiffDirInfo * const headerP) {
@@ -409,11 +409,11 @@ readDirectory(TIFF *               const tiffP,
 
 
 static void
-readscanline(TIFF *          const tif, 
+readscanline(TIFF *          const tif,
              unsigned char * const scanbuf,
-             int             const row, 
+             int             const row,
              int             const plane,
-             unsigned int    const cols, 
+             unsigned int    const cols,
              unsigned short  const bps,
              unsigned short  const spp,
              unsigned short  const fillorder,
@@ -433,7 +433,7 @@ readscanline(TIFF *          const tif,
 
     /* The TIFFReadScanline man page doesn't tell the format of its
        'buf' return value, but it is exactly the same format as the 'buf'
-       input to TIFFWriteScanline.  The man page for that doesn't say 
+       input to TIFFWriteScanline.  The man page for that doesn't say
        anything either, but the source code for Pamtotiff contains a
        specification.
     */
@@ -446,7 +446,7 @@ readscanline(TIFF *          const tif,
                   row, plane);
     else if (bps == 8) {
         unsigned int sample;
-        for (sample = 0; sample < cols * spp; ++sample) 
+        for (sample = 0; sample < cols * spp; ++sample)
             samplebuf[sample] = scanbuf[sample];
     } else if (bps < 8) {
         /* Note that in this format, samples do not span bytes.  Rather,
@@ -458,26 +458,26 @@ readscanline(TIFF *          const tif,
         unsigned int bitsleft;
         unsigned char * inP;
 
-        for (sample = 0, bitsleft = 8, inP = scanbuf; 
-             sample < cols * spp; 
+        for (sample = 0, bitsleft = 8, inP = scanbuf;
+             sample < cols * spp;
              ++sample) {
             if (bitsleft == 0) {
-                ++inP; 
+                ++inP;
                 bitsleft = 8;
-            } 
+            }
             switch (fillorder) {
             case FILLORDER_MSB2LSB:
-                samplebuf[sample] = (*inP >> (bitsleft-bps)) & bpsmask; 
+                samplebuf[sample] = (*inP >> (bitsleft-bps)) & bpsmask;
                 break;
             case FILLORDER_LSB2MSB:
                 samplebuf[sample] = (*inP >> (8-bitsleft)) & bpsmask;
                 break;
             default:
-                pm_error("Internal error: invalid value for fillorder: %u", 
+                pm_error("Internal error: invalid value for fillorder: %u",
                          fillorder);
             }
             assert(bitsleft >= bps);
-            bitsleft -= bps; 
+            bitsleft -= bps;
             if (bitsleft < bps)
                 /* Don't count dregs at end of byte */
                 bitsleft = 0;
@@ -490,7 +490,7 @@ readscanline(TIFF *          const tif,
            none of our concern).  The pre-9.17 code also presumed that
            the TIFF "FILLORDER" tag determined the order in which the
            bytes of each sample appear in a TIFF file, which is
-           contrary to the TIFF spec.  
+           contrary to the TIFF spec.
         */
         const uint16 * const scanbuf16 = (const uint16 *) scanbuf;
         unsigned int sample;
@@ -500,10 +500,10 @@ readscanline(TIFF *          const tif,
     } else if (bps == 32) {
         const uint32 * const scanbuf32 = (const uint32 *) scanbuf;
         unsigned int sample;
-        
+
         for (sample = 0; sample < cols * spp; ++sample)
             samplebuf[sample] = scanbuf32[sample];
-    } else 
+    } else
         pm_error("Internal error: invalid bits per sample passed to "
                  "readscanline()");
 }
@@ -528,7 +528,7 @@ pick_cmyk_pixel(unsigned int const samplebuf[],
     unsigned int const y = samplebuf[sampleCursor + 2];
     unsigned int const k = samplebuf[sampleCursor + 3];
 
-    /* The CMYK->RGB formula used by TIFFRGBAImageGet() in the TIFF 
+    /* The CMYK->RGB formula used by TIFFRGBAImageGet() in the TIFF
        library is the following, (with some apparent confusion with
        the names of the yellow and magenta pigments being reversed).
 
@@ -539,9 +539,9 @@ pick_cmyk_pixel(unsigned int const samplebuf[],
        We used that too before Netpbm 10.21 (March 2004).
 
        Now we use the inverse of what Pnmtotiffcmyk has always used, which
-       makes sense as follows:  A microliter of black ink is simply a 
+       makes sense as follows:  A microliter of black ink is simply a
        substitute for a microliter each of cyan, magenta, and yellow ink.
-       Yellow ink removes blue light from what the white paper reflects.  
+       Yellow ink removes blue light from what the white paper reflects.
     */
 
     *redP = 255 - MIN(255, c + k);
@@ -552,16 +552,16 @@ pick_cmyk_pixel(unsigned int const samplebuf[],
 
 
 static void
-computeFillorder(unsigned short   const fillorderTag, 
-                 unsigned short * const fillorderP, 
+computeFillorder(unsigned short   const fillorderTag,
+                 unsigned short * const fillorderP,
                  bool             const respectfillorder) {
 
     if (respectfillorder) {
-        if (fillorderTag != FILLORDER_MSB2LSB && 
+        if (fillorderTag != FILLORDER_MSB2LSB &&
             fillorderTag != FILLORDER_LSB2MSB)
             pm_error("Invalid value in Tiff input for the FILLORDER tag: %u.  "
                      "Valid values are %u and %u.  Try omitting the "
-                     "-respectfillorder option.", 
+                     "-respectfillorder option.",
                      fillorderTag, FILLORDER_MSB2LSB, FILLORDER_LSB2MSB);
         else
             *fillorderP = fillorderTag;
@@ -577,12 +577,12 @@ computeFillorder(unsigned short   const fillorderTag,
 
 
 static void
-analyzeImageType(TIFF *             const tiffP, 
-                 unsigned short     const bps, 
-                 unsigned short     const spp, 
+analyzeImageType(TIFF *             const tiffP,
+                 unsigned short     const bps,
+                 unsigned short     const spp,
                  unsigned short     const photomet,
-                 xelval *           const maxvalP, 
-                 int *              const formatP, 
+                 xelval *           const maxvalP,
+                 int *              const formatP,
                  xel *              const colormap,
                  bool               const headerdump,
                  struct CmdlineInfo const cmdline) {
@@ -604,13 +604,13 @@ analyzeImageType(TIFF *             const tiffP,
         *maxvalP = pm_bitstomaxval(MIN(bps, 16));
 
         if (headerdump)
-            pm_message("grayscale image, (min=%s) output maxval %u ", 
-                       photomet == PHOTOMETRIC_MINISBLACK ? 
+            pm_message("grayscale image, (min=%s) output maxval %u ",
+                       photomet == PHOTOMETRIC_MINISBLACK ?
                        "black" : "white",
                        *maxvalP
                 );
         break;
-            
+
     case PHOTOMETRIC_PALETTE: {
         int fldPresent;
         int i;
@@ -627,7 +627,7 @@ analyzeImageType(TIFF *             const tiffP,
                      "We understand only 1.", spp);
 
         fldPresent = TIFFGetField(
-            tiffP, TIFFTAG_COLORMAP, 
+            tiffP, TIFFTAG_COLORMAP,
             &redcolormap, &greencolormap, &bluecolormap);
 
         if (!fldPresent)
@@ -662,7 +662,7 @@ analyzeImageType(TIFF *             const tiffP,
         if (fldPresent && inkset != INKSET_CMYK)
             pm_error("This color separation file uses an inkset (%d) "
                      "we can't handle.  We handle only CMYK.", inkset);
-        if (spp != 4) 
+        if (spp != 4)
             pm_error("This CMYK color separation file is %d samples per "
                      "pixel.  "
                      "We need 4 samples, though: C, M, Y, and K.  ",
@@ -673,7 +673,7 @@ analyzeImageType(TIFF *             const tiffP,
         *maxvalP = (1 << bps) - 1;
     }
         break;
-            
+
     case PHOTOMETRIC_RGB:
         if (headerdump)
             pm_message("RGB truecolor");
@@ -704,7 +704,7 @@ analyzeImageType(TIFF *             const tiffP,
 
     case PHOTOMETRIC_LOGLUV:
         pm_error("don't know how to handle PHOTOMETRIC_LOGLUV");
-            
+
     default:
         pm_error("unknown photometric: %d", photomet);
     }
@@ -778,7 +778,7 @@ static const char *
 xformNeeded(unsigned short const tiffOrientation) {
 /*----------------------------------------------------------------------------
    Return the value of the Pamflip -xform option that causes Pamflip
-   to change a raster from orienation 'tiffOrientation' to Row 0 top,
+   to change a raster from orientation 'tiffOrientation' to Row 0 top,
    Column 0 left.
 -----------------------------------------------------------------------------*/
     switch (tiffOrientation) {
@@ -829,7 +829,7 @@ spawnWithInputPipe(const char *  const shellCmd,
 
                 *pidP   = childPid;
                 *pipePP = fdopen(fd[PIPE_WRITE], "w");
-                
+
                 if (*pipePP == NULL)
                     pm_asprintf(errorP,"Unable to create stream from pipe.  "
                                 "fdopen() fails with errno=%d (%s)",
@@ -858,7 +858,7 @@ spawnWithInputPipe(const char *  const shellCmd,
     }
 }
 
-                  
+
 
 static void
 createFlipProcess(FILE *         const outFileP,
@@ -964,7 +964,7 @@ setupFlipper(pnmOut *       const pnmOutP,
             pnmOutP->flipping = FALSE;
             *flipOkP   = FALSE;
             *noflipOkP = TRUE;
-        } else {            
+        } else {
             if (flipIfNeeded) {
                 if (verbose)
                     pm_message("Transforming raster with Pamflip");
@@ -979,7 +979,7 @@ setupFlipper(pnmOut *       const pnmOutP,
                                       verbose,
                                       &pnmOutP->imagePipeP,
                                       &pnmOutP->imageFlipPid);
-                
+
                 /* The stream will flip it, so Caller must not: */
                 pnmOutP->flipping = TRUE;
                 *flipOkP   = FALSE;
@@ -1081,22 +1081,22 @@ pnmOut_init(FILE *         const imageoutFileP,
     } else {
         pnmOutP->inCols = pnmOutP->outCols;  /* Caller will flip */
         pnmOutP->inRows = pnmOutP->outRows;
-    }    
+    }
     if (pnmOutP->flipping) {
-        if (pnmOutP->imagePipeP != NULL) 
+        if (pnmOutP->imagePipeP != NULL)
             pnm_writepnminit(pnmOutP->imagePipeP,
                              pnmOutP->inCols, pnmOutP->inRows,
                              pnmOutP->maxval, pnmOutP->format, 0);
-        if (pnmOutP->alphaPipeP != NULL) 
+        if (pnmOutP->alphaPipeP != NULL)
             pgm_writepgminit(pnmOutP->alphaPipeP,
                              pnmOutP->inCols, pnmOutP->inRows,
                              pnmOutP->alphaMaxval, 0);
     } else {
-        if (imageoutFileP != NULL) 
+        if (imageoutFileP != NULL)
             pnm_writepnminit(pnmOutP->imageoutFileP,
                              pnmOutP->outCols, pnmOutP->outRows,
                              pnmOutP->maxval, pnmOutP->format, 0);
-        if (alphaFileP != NULL) 
+        if (alphaFileP != NULL)
             pgm_writepgminit(pnmOutP->alphaFileP,
                              pnmOutP->outCols, pnmOutP->outRows,
                              pnmOutP->alphaMaxval, 0);
@@ -1149,19 +1149,19 @@ pnmOut_writeRow(pnmOut *     const pnmOutP,
     assert(cols == pnmOutP->inCols);
 
     if (pnmOutP->flipping) {
-        if (pnmOutP->imagePipeP != NULL) 
+        if (pnmOutP->imagePipeP != NULL)
             pnm_writepnmrow(pnmOutP->imagePipeP, (xel *)imageRow,
                             pnmOutP->inCols, pnmOutP->maxval,
                             pnmOutP->format, 0);
-        if (pnmOutP->alphaPipeP != NULL) 
+        if (pnmOutP->alphaPipeP != NULL)
             pgm_writepgmrow(pnmOutP->alphaPipeP, alphaRow,
                             pnmOutP->inCols, pnmOutP->alphaMaxval, 0);
     } else {
-        if (pnmOutP->imageoutFileP != NULL) 
+        if (pnmOutP->imageoutFileP != NULL)
             pnm_writepnmrow(pnmOutP->imageoutFileP, (xel *)imageRow,
                             pnmOutP->outCols, pnmOutP->maxval,
                             pnmOutP->format, 0);
-        if (pnmOutP->alphaFileP != NULL) 
+        if (pnmOutP->alphaFileP != NULL)
             pgm_writepgmrow(pnmOutP->alphaFileP, alphaRow,
                             pnmOutP->outCols, pnmOutP->alphaMaxval, 0);
     }
@@ -1170,12 +1170,12 @@ pnmOut_writeRow(pnmOut *     const pnmOutP,
 
 
 static void
-convertRow(unsigned int   const samplebuf[], 
-           xel *          const xelrow, 
+convertRow(unsigned int   const samplebuf[],
+           xel *          const xelrow,
            gray *         const alpharow,
-           int            const cols, 
-           xelval         const maxval, 
-           unsigned short const photomet, 
+           int            const cols,
+           xelval         const maxval,
+           unsigned short const photomet,
            unsigned short const spp,
            xel            const colormap[]) {
 /*----------------------------------------------------------------------------
@@ -1191,7 +1191,7 @@ convertRow(unsigned int   const samplebuf[],
         }
     }
     break;
-    
+
     case PHOTOMETRIC_MINISWHITE: {
         int col;
         for (col = 0; col < cols; ++col) {
@@ -1220,7 +1220,7 @@ convertRow(unsigned int   const samplebuf[],
         for (col = 0, sample = 0; col < cols; ++col, sample+=spp) {
             xelval r, g, b;
             pick_cmyk_pixel(samplebuf, sample, &r, &b, &g);
-            
+
             PPM_ASSIGN(xelrow[col], r, g, b);
             alpharow[col] = 0;
         }
@@ -1238,7 +1238,7 @@ convertRow(unsigned int   const samplebuf[],
                 alpharow[col] = 0;
         }
         break;
-    }       
+    }
     default:
         pm_error("internal error:  unknown photometric in the picking "
                  "routine: %d", photomet);
@@ -1257,7 +1257,7 @@ scale32to16(unsigned int * const samplebuf,
 -----------------------------------------------------------------------------*/
     unsigned int i;
     for (i = 0; i < cols * spp; ++i)
-        samplebuf[i] >>= 16; 
+        samplebuf[i] >>= 16;
 }
 
 
@@ -1288,39 +1288,39 @@ convertMultiPlaneRow(TIFF *          const tif,
         unsigned int col;
 
         /* First, clear the buffer so we can add red, green,
-           and blue one at a time.  
+           and blue one at a time.
         */
-        for (col = 0; col < cols; ++col) 
+        for (col = 0; col < cols; ++col)
             PPM_ASSIGN(xelrow[col], 0, 0, 0);
 
         /* Read the reds */
-        readscanline(tif, scanbuf, row, 0, cols, bps, spp, fillorder, 
+        readscanline(tif, scanbuf, row, 0, cols, bps, spp, fillorder,
                      samplebuf);
         if (bps == 32)
             scale32to16(samplebuf, cols, spp);
-        for (col = 0; col < cols; ++col) 
+        for (col = 0; col < cols; ++col)
             PPM_PUTR(xelrow[col], samplebuf[col]);
-                
+
         /* Next the greens */
         readscanline(tif, scanbuf, row, 1, cols, bps, spp, fillorder,
                      samplebuf);
         if (bps == 32)
             scale32to16(samplebuf, cols, spp);
-        for (col = 0; col < cols; ++col) 
+        for (col = 0; col < cols; ++col)
             PPM_PUTG( xelrow[col], samplebuf[col] );
-            
+
         /* And finally the blues */
         readscanline(tif, scanbuf, row, 2, cols, bps, spp, fillorder,
                      samplebuf);
         if (bps == 32)
             scale32to16(samplebuf, cols, spp);
-        for (col = 0; col < cols; ++col) 
+        for (col = 0; col < cols; ++col)
             PPM_PUTB(xelrow[col], samplebuf[col]);
 
         /* Could there be an alpha plane?  (We assume no.  But if so,
-           here is where to read it) 
+           here is where to read it)
         */
-        for (col = 0; col < cols; ++col) 
+        for (col = 0; col < cols; ++col)
             alpharow[col] = 0;
     }
 }
@@ -1329,11 +1329,11 @@ convertMultiPlaneRow(TIFF *          const tif,
 
 static void
 convertRasterByRows(pnmOut *       const pnmOutP,
-                    unsigned int   const cols, 
+                    unsigned int   const cols,
                     unsigned int   const rows,
                     xelval         const maxval,
                     TIFF *         const tif,
-                    unsigned short const photomet, 
+                    unsigned short const photomet,
                     unsigned short const planarconfig,
                     unsigned short const bps,
                     unsigned short const spp,
@@ -1341,7 +1341,7 @@ convertRasterByRows(pnmOut *       const pnmOutP,
                     xel            const colormap[],
                     bool           const verbose) {
 /*----------------------------------------------------------------------------
-   With the TIFF header all processed (and relevant information from it in 
+   With the TIFF header all processed (and relevant information from it in
    our arguments), write out the TIFF raster to the Netpbm output files
    as described by *pnmOutP.
 
@@ -1357,10 +1357,10 @@ convertRasterByRows(pnmOut *       const pnmOutP,
            represented as single array element, so it's easy to work with.
         */
     xel * xelrow;
-        /* The ppm-format row of the image row we are presently converting */
+        /* The ppm-format row of the image row we are currently converting */
     gray * alpharow;
-        /* The pgm-format row representing the alpha values for the image 
-           row we are presently converting.
+        /* The pgm-format row representing the alpha values for the image
+           row we are currently converting.
         */
 
     unsigned int row;
@@ -1383,13 +1383,13 @@ convertRasterByRows(pnmOut *       const pnmOutP,
         /* Read one row of samples into samplebuf[] */
 
         if (planarconfig == PLANARCONFIG_CONTIG) {
-            readscanline(tif, scanbuf, row, 0, cols, bps, spp, fillorder, 
+            readscanline(tif, scanbuf, row, 0, cols, bps, spp, fillorder,
                          samplebuf);
             if (bps == 32)
                 scale32to16(samplebuf, cols, spp);
-            convertRow(samplebuf, xelrow, alpharow, cols, maxval, 
+            convertRow(samplebuf, xelrow, alpharow, cols, maxval,
                        photomet, spp, colormap);
-        } else 
+        } else
             convertMultiPlaneRow(tif, xelrow, alpharow, cols, maxval, row,
                                  photomet, bps, spp, fillorder,
                                  scanbuf, samplebuf);
@@ -1401,7 +1401,7 @@ convertRasterByRows(pnmOut *       const pnmOutP,
 
     free(samplebuf);
     free(scanbuf);
-}    
+}
 
 
 
@@ -1416,7 +1416,7 @@ warnBrokenTiffLibrary(TIFF * const tiffP) {
    the transposition part, so e.g. it treats ORIENTATION_LEFTBOT as
    ORIENTATION_BOTLEFT.  And because we provide a raster buffer dimensioned
    for the properly transposed image, the result is somewhat of a mess.
-   
+
    We have found no documentation of the TIFF library that suggests
    this behavior is as designed, so it's probably not a good idea to
    work around it; it might be fixed somewhere.
@@ -1452,8 +1452,8 @@ warnBrokenTiffLibrary(TIFF * const tiffP) {
 
 
 
-static void 
-convertTiffRaster(uint32 *        const raster, 
+static void
+convertTiffRaster(uint32 *        const raster,
                   unsigned int    const cols,
                   unsigned int    const rows,
                   xelval          const maxval,
@@ -1465,11 +1465,11 @@ convertTiffRaster(uint32 *        const raster,
 -----------------------------------------------------------------------------*/
     xel * xelrow;
         /* The ppm-format row of the image row we are
-           presently converting 
+           currently converting
         */
     gray * alpharow;
         /* The pgm-format row representing the alpha values
-           for the image row we are presently converting.  
+           for the image row we are currently converting.
         */
     unsigned int row;
 
@@ -1477,35 +1477,35 @@ convertTiffRaster(uint32 *        const raster,
     alpharow = pgm_allocrow(cols);
 
     for (row = 0; row < rows; ++row) {
-        uint32 * rp;  
-            /* Address of pixel in 'raster' we are presently converting */
+        uint32 * rp;
+            /* Address of pixel in 'raster' we are currently converting */
         unsigned int col;
 
         /* Start at beginning of row: */
         rp = raster + (rows - row - 1) * cols;
-    
+
         for (col = 0; col < cols; ++col) {
             uint32 const tiffPixel = *rp++;
-                    
-            PPM_ASSIGN(xelrow[col], 
-                       TIFFGetR(tiffPixel) * maxval / 255, 
-                       TIFFGetG(tiffPixel) * maxval / 255, 
+
+            PPM_ASSIGN(xelrow[col],
+                       TIFFGetR(tiffPixel) * maxval / 255,
+                       TIFFGetG(tiffPixel) * maxval / 255,
                        TIFFGetB(tiffPixel) * maxval / 255);
             alpharow[col] = TIFFGetA(tiffPixel) * maxval / 255 ;
         }
         pnmOut_writeRow(pnmOutP, cols, xelrow, alpharow);
     }
-    
+
     pgm_freerow(alpharow);
     pnm_freerow(xelrow);
-}    
+}
 
 
 
 enum convertDisp {CONV_DONE,
                   CONV_OOM,
                   CONV_UNABLE,
-                  CONV_FAILED, 
+                  CONV_FAILED,
                   CONV_NOTATTEMPTED};
 
 
@@ -1524,7 +1524,7 @@ convertRasterIntoProvidedMemory(pnmOut *           const pnmOutP,
     TIFFRGBAImage img;
     char emsg[1024];
     int ok;
-                
+
     ok = TIFFRGBAImageBegin(&img, tif, stopOnErrorFalse, emsg);
     if (!ok) {
         pm_message("%s", emsg);
@@ -1540,7 +1540,7 @@ convertRasterIntoProvidedMemory(pnmOut *           const pnmOutP,
             *statusP = CONV_DONE;
             convertTiffRaster(raster, cols, rows, maxval, pnmOutP);
         }
-    } 
+    }
 }
 
 
@@ -1584,7 +1584,7 @@ convertRasterInMemory(pnmOut *           const pnmOutP,
         unsigned int cols, rows;  /* Dimensions of output image */
         getTiffDimensions(tif, &cols, &rows);
 
-        if (rows == 0 || cols == 0) 
+        if (rows == 0 || cols == 0)
             *statusP = CONV_DONE;
         else {
             if (cols > UINT_MAX/rows) {
@@ -1608,7 +1608,7 @@ convertRasterInMemory(pnmOut *           const pnmOutP,
                     convertRasterIntoProvidedMemory(
                         pnmOutP, cols, rows, maxval, tif, verbose,
                         raster, statusP);
-                    
+
                     free(raster);
                 }
             }
@@ -1653,7 +1653,7 @@ convertRaster(pnmOut *           const pnmOutP,
                          "and we already committed to in-memory "
                          "conversion.  To avoid this failure, "
                          "use -byrow .");
-        }            
+        }
         convertRasterByRows(
             pnmOutP, tiffDir.width, tiffDir.height, maxval,
             tifP, tiffDir.photomet, tiffDir.planarconfig,
@@ -1681,7 +1681,7 @@ convertImage(TIFF *             const tifP,
 
     computeFillorder(tiffDir.fillorder, &fillorder, cmdline.respectfillorder);
 
-    analyzeImageType(tifP, tiffDir.bps, tiffDir.spp, tiffDir.photomet, 
+    analyzeImageType(tifP, tiffDir.bps, tiffDir.spp, tiffDir.photomet,
                      &maxval, &format, colormap, cmdline.headerdump, cmdline);
 
     reportOutputFormat(format);
@@ -1704,7 +1704,7 @@ convertImage(TIFF *             const tifP,
 
 static void
 convertIt(TIFF *             const tifP,
-          FILE *             const alphaFile, 
+          FILE *             const alphaFile,
           FILE *             const imageoutFile,
           struct CmdlineInfo const cmdline) {
 
@@ -1744,19 +1744,19 @@ main(int argc, const char * argv[]) {
 
     if (cmdline.alphaStdout)
         alphaFile = stdout;
-    else if (cmdline.alphaFilename == NULL) 
+    else if (cmdline.alphaFilename == NULL)
         alphaFile = NULL;
     else
         alphaFile = pm_openw(cmdline.alphaFilename);
 
-    if (cmdline.alphaStdout) 
+    if (cmdline.alphaStdout)
         imageoutFile = NULL;
     else
         imageoutFile = stdout;
 
     convertIt(tiffP, alphaFile, imageoutFile, cmdline);
 
-    if (imageoutFile != NULL) 
+    if (imageoutFile != NULL)
         pm_close( imageoutFile );
     if (alphaFile != NULL)
         pm_close( alphaFile );
@@ -1770,3 +1770,6 @@ main(int argc, const char * argv[]) {
     */
     return 0;
 }
+
+
+
diff --git a/converter/other/winicon.h b/converter/other/winicon.h
index 9ede01f5..e5c4aa89 100644
--- a/converter/other/winicon.h
+++ b/converter/other/winicon.h
@@ -65,8 +65,7 @@ typedef enum {
 
 } BiCompression;
 
-/*  PNG image structures  */
-#define PNG_HEADER { 0x89, 'P', 'N', 'G', '\r', '\n', 0x1A /* ^Z */, '\n' }
+#define PNG_SIGNATURE { 0x89, 'P', 'N', 'G', '\r', '\n', 0x1A /* ^Z */, '\n' }
 
 struct PngIhdr {
     uint32_t length;              /* 13 */
diff --git a/converter/other/winicontopam.c b/converter/other/winicontopam.c
index 69ce7f05..bb39bf60 100644
--- a/converter/other/winicontopam.c
+++ b/converter/other/winicontopam.c
@@ -1,3 +1,25 @@
+/*=============================================================================
+                             winicontopam
+===============================================================================
+  Convert from Windows icon format to PAM
+=============================================================================*/
+
+/*
+  Here are some references for the Windows icon format:
+
+  ICO (file format) - Wikipedia
+  https://en.wikipedia.org/wiki/ICO_(file_format)
+
+  ICO - Just Solve the File Format Problem
+  http://fileformats.archiveteam.org/wiki/ICO
+  (Has links to example icon file collections)
+
+  GFF Format Summary: Microsoft Windows Cursor and Icon
+  https://web.archive.org/web/20050421161512/http:/www.oreilly.com/www/centers/gff/formats/miccur/index.htm
+
+
+*/
+
 #include <assert.h>
 #include <stdio.h>
 #include <string.h>
@@ -25,7 +47,7 @@ static bool verbose;
 
 
 struct CmdlineInfo {
-    
+
     const char * inputFileName;
     unsigned int allimages;
     unsigned int imageSpec;
@@ -78,13 +100,13 @@ parseCommandLine(int argc, const char **argv,
             pm_error("Too many arguments.  The only possible "
                      "non-option argument is the input file name");
     }
-        
+
     free(option_def);
 }
 
 
 
-static unsigned char const pngHeader[] = PNG_HEADER;
+static unsigned char const pngSignature[] = PNG_SIGNATURE;
 
 
 
@@ -93,7 +115,7 @@ struct File {
     FILE *       fileP;
     const char * name;
     pm_filepos   pos;
-    
+
 };
 
 
@@ -122,7 +144,7 @@ static uint32_t
 u32_le(const unsigned char * const buf,
        size_t                const offset) {
 
-    return 
+    return
         ((uint32_t)buf[offset + 0] <<  0) +
         ((uint32_t)buf[offset + 1] <<  8) +
         ((uint32_t)buf[offset + 2] << 16) +
@@ -135,7 +157,7 @@ static uint32_t
 s32_le(const unsigned char * const buf,
        size_t                const offset) {
 
-    return 
+    return
         ((uint32_t)buf[offset + 0] <<  0) +
         ((uint32_t)buf[offset + 1] <<  8) +
         ((uint32_t)buf[offset + 2] << 16) +
@@ -156,8 +178,8 @@ u8_be(const unsigned char * const buf,
 static uint32_t
 u32_be(const unsigned char * const buf,
        size_t                const offset) {
-    
-    return 
+
+    return
         ((uint32_t)buf[offset + 0] << 24) +
         ((uint32_t)buf[offset + 1] << 16) +
         ((uint32_t)buf[offset + 2] <<  8) +
@@ -225,7 +247,7 @@ dumpIconDir(const struct IconDir * const dirP) {
     }
 }
 
-            
+
 
 static struct IconDir *
 readIconDir(struct File * const fP,
@@ -246,7 +268,7 @@ readIconDir(struct File * const fP,
     MALLOCVAR(dirP);
 
     if (dirP == NULL)
-        pm_error("Could't allocate memory for Icon directory");
+        pm_error("Couldn't allocate memory for Icon directory");
 
     MALLOCARRAY(dirP->entries, head.count);
 
@@ -271,7 +293,7 @@ readIconDir(struct File * const fP,
 
         pm_readcharu(fP->fileP, &heightField);
         dirEntryP->height = (heightField == 0 ? 256 : heightField);
-        
+
         pm_readcharu(fP->fileP, &dirEntryP->color_count);
 
         pm_readcharu(fP->fileP, &dirEntryP->zero);
@@ -290,7 +312,7 @@ readIconDir(struct File * const fP,
     }
 
     /* The following is paranoia code only:
-     
+
        I've never seen a windows icon file in the wild with having the entries
        in the directory stored in a different order than the images
        themselves.  However, the file format allows for it ...
@@ -301,7 +323,7 @@ readIconDir(struct File * const fP,
         pm_message("%s icon directory (%u image%s):",
                    fP->name,
                    dirP->count, dirP->count == 1 ? "" : "s");
-        
+
         for (imageIndex = 0; imageIndex < dirP->count; ++imageIndex) {
             const struct IconDirEntry * const dirEntryP =
                 &dirP->entries[imageIndex];
@@ -355,7 +377,7 @@ readImage(struct File *         const fP,
 
     /*  Don't try to read an image that is smaller than the
         BITMAPINFOHEADER of BMP images (40 bytes).
-     
+
         PNG compressed images can't be smaller than that either, as the
         PNG header plus the mandantory IHDR and IEND chunks already take
         8 + 25 + 12 = 35 bytes, and there is to be a IDAT chunk too.
@@ -369,7 +391,7 @@ readImage(struct File *         const fP,
                  dirEntryP->index);
 
     /* The following is paranoia code only:
-     
+
        I've never seen a windows icon file in the wild with gaps between
        the images, but the file format allows for it, and Microsoft
        expects the user to fseek() to the start of each image.
@@ -472,11 +494,11 @@ readXorPalette(struct BitmapInfoHeader * const hdrP,
     uint32_t    bytesPerRow;
     const unsigned char * bitmapCursor;
     uint32_t sizeRemaining;
-  
+
     uint8_t (*getIdx) (const unsigned char * bitmap,
                        uint32_t rowOffset,
                        int16_t col);
-  
+
     if (hdrP->compression_method != BI_RGB)
         pm_error("image %2u: invalid compression method %u.",
                  index, hdrP->compression_method);
@@ -518,7 +540,7 @@ readXorPalette(struct BitmapInfoHeader * const hdrP,
     if (sizeRemaining < paletteSize)
         pm_error("image %2u: "
                  "reading palette: image truncated.", index);
-    
+
     palette = (const PaletteEntry *) bitmapCursor;
 
     if (needHeaderDump)
@@ -562,7 +584,7 @@ readXorPalette(struct BitmapInfoHeader * const hdrP,
 
                 /*  The palette is an array of little-endian 32-bit values,
                     where the RGB value is encoded as follows:
-                 
+
                     red:   bits 2^16..2^23
                     green: bits 2^8 ..2^15
                     blue:  bits 2^0 ..2^7
@@ -591,7 +613,10 @@ readXorBitfields(struct BitmapInfoHeader * const hdrP,
                  uint16_t                  const index,
                  bool *                    const haveAlphaP,
                  uint32_t *                const bytesConsumedP) {
-
+/*----------------------------------------------------------------------------
+   Return as *haveAlphaP whether the Xor mask indicates the pixels are
+   anything but fully opaque.
+-----------------------------------------------------------------------------*/
     uint32_t   bitfields[4];
     uint8_t    shift    [4];
     sample     maxval   [4];
@@ -758,12 +783,21 @@ readXorBitfields(struct BitmapInfoHeader * const hdrP,
     bytesConsumed += truncatedXorSize;
 
     /*  A fully transparent alpha channel (all zero) in XOR mask is
-        defined to be void by Microsoft, and a fully opaque alpha
-        channel (all maxval) is trivial and will be dropped.
+        defined to be void by Microsoft.
     */
+    if (verbose) {
+        if (allTransparent)
+            pm_message("image %2u: All pixels are nominally coded in the "
+                       "transparency map as fully transparent, "
+                       "which is defined by the format to mean they "
+                       "are all opaque", index);
+        if (allOpaque)
+            pm_message("image %2u: All pixels are fully opaque "
+                       "in the transparency map", index);
+    }
     *haveAlphaP = !allTransparent && !allOpaque;
 
-    if (!allTransparent && verbose) {
+    if (!allTransparent && ! allOpaque && verbose) {
         unsigned int i;
         unsigned int c;
 
@@ -787,7 +821,16 @@ readAnd(struct BitmapInfoHeader * const hdrP,
         uint16_t                  const index,
         unsigned int              const plane,
         sample                    const maxval) {
+/*----------------------------------------------------------------------------
+  Fill in plane 'plane' of the tuple array 'tuples' according to the and
+  mask of a Windows icon.  Where the and mask for a pixel is 1, set the
+  plane to 'maxval'; where it is zero, set it to zero.
+
+  'bitmap' is the and mask, in a format describe dby *hdrP.
 
+  'index' is the position of the icon in question in the Windows icon file --
+  the first image in the file is 0, second is 1, etc.
+-----------------------------------------------------------------------------*/
     int16_t  row;
     uint32_t bytesConsumed;
     uint32_t bytesPerRow;
@@ -823,7 +866,7 @@ readAnd(struct BitmapInfoHeader * const hdrP,
 
         if (offset + bytesPerRow <= sizeRemaining) {
             unsigned int col;
-            
+
             for (col = 0; col < hdrP->bm_width; ++col) {
                 tuples[row][col][plane] =
                     ((u8_le(bitmap, offset + col/8)
@@ -916,7 +959,13 @@ readXorMask(struct BitmapInfoHeader * const hdrP,
             uint32_t *                const bytesConsumedP) {
 /*----------------------------------------------------------------------------
    Read the so-called XOR mask (for non-monochrome images, this is the
-   color pixmap)
+   color pixmap, which may include transparency).
+
+   Return the pixels as 'tuples', an array whose width and height are
+   given by *hdrP and depth is 4.
+
+   Return as *haveAlphaP whether the Xor mask indicates the pixels are
+   anything but fully opaque.
 -----------------------------------------------------------------------------*/
     /*  preset the PAM with fully opaque black (just in case the image
         is truncated and not all pixels are filled in below).
@@ -952,7 +1001,7 @@ reportImage(unsigned int            const imageIndex,
             struct BitmapInfoHeader const hdr,
             bool                    const haveAlpha) {
 
-    const char * const style = 
+    const char * const style =
         haveAlpha ? "RGB +alpha" :
         hdr.bits_per_pixel < 16 ? "RGB/palette" :
         "RGB"
@@ -973,7 +1022,7 @@ convertBmp(const unsigned char * const image,
            struct IconDirEntry * const dirEntryP,
            bool                  const needHeaderDump,
            bool                  const wantAndMaskPlane) {
-    
+
     struct BitmapInfoHeader hdr;
     uint32_t                offset;
     bool                    haveAlpha;
@@ -1024,7 +1073,7 @@ convertBmp(const unsigned char * const image,
 
     tuples = pnm_allocpamarray(&outpam);
 
-    readXorMask(&hdr, &image[offset], 
+    readXorMask(&hdr, &image[offset],
                 dirEntryP->size - offset,
                 tuples, dirEntryP->index, needHeaderDump,
                 &haveAlpha, &xorByteCt);
@@ -1032,9 +1081,9 @@ convertBmp(const unsigned char * const image,
     offset += xorByteCt;
 
     {
-        /* If there is no alpha channel in XOR mask, store the AND mask to
-           the transparency plane.  Else, here are two transparency
-           maps. If requested, store the AND mask to a fifth PAM plane
+        /* If there is no alpha channel in the XOR mask, use the AND mask as
+           the transparency plane.  Else, there are two transparency
+           maps. If requested, return the AND mask as a fifth PAM plane.
         */
         bool haveAnd;
         unsigned int andPlane;
@@ -1070,18 +1119,18 @@ convertBmp(const unsigned char * const image,
 static void
 reportPngInfo(const unsigned char * const image,
               struct IconDirEntry * const dirEntryP) {
-    
+
     struct PngIhdr ihdr;
 
-    ihdr.length      = u32_be (image, sizeof(pngHeader)  +0);
-    ihdr.signature   = u32_xx (image, sizeof(pngHeader)  +4);
-    ihdr.width       = u32_be (image, sizeof(pngHeader)  +8);
-    ihdr.height      = u32_be (image, sizeof(pngHeader) +12);
-    ihdr.bit_depth   = u8_be  (image, sizeof(pngHeader) +16);
-    ihdr.color_type  = u8_be  (image, sizeof(pngHeader) +17);
-    ihdr.compression = u8_be  (image, sizeof(pngHeader) +18);
-    ihdr.filter      = u8_be  (image, sizeof(pngHeader) +19);
-    ihdr.interlace   = u8_be  (image, sizeof(pngHeader) +20);
+    ihdr.length      = u32_be (image, sizeof(pngSignature)  +0);
+    ihdr.signature   = u32_xx (image, sizeof(pngSignature)  +4);
+    ihdr.width       = u32_be (image, sizeof(pngSignature)  +8);
+    ihdr.height      = u32_be (image, sizeof(pngSignature) +12);
+    ihdr.bit_depth   = u8_be  (image, sizeof(pngSignature) +16);
+    ihdr.color_type  = u8_be  (image, sizeof(pngSignature) +17);
+    ihdr.compression = u8_be  (image, sizeof(pngSignature) +18);
+    ihdr.filter      = u8_be  (image, sizeof(pngSignature) +19);
+    ihdr.interlace   = u8_be  (image, sizeof(pngSignature) +20);
 
     if ((ihdr.length != 13)
         || ihdr.signature != *(uint32_t*)"IHDR") {
@@ -1148,14 +1197,16 @@ convertPng(const unsigned char * const image,
            FILE *                const ofP,
            struct IconDirEntry * const dirEntryP) {
 
-    struct bufferDesc imageBuffer;
+    pm_bufferDesc imageBuffer;
 
     reportPngInfo(image, dirEntryP);
 
-    imageBuffer.size = dirEntryP->size;
-    imageBuffer.buffer = (unsigned char *)image;
+    imageBuffer.size              = dirEntryP->size;
+    imageBuffer.buffer            = (unsigned char *)image;
+    imageBuffer.bytesTransferredP = NULL;
+
+    fflush(stdout);
 
-    fflush (stdout);
     pm_system_lp("pngtopam", pm_feed_from_memory, &imageBuffer,
                  NULL /* stdout accepter */, NULL,
                  "pngtopam", "-alphapam", NULL);
@@ -1174,7 +1225,7 @@ bestImage(struct IconDir * const dirP) {
     bestPixelCt = 0;  /* initial value */
     bestColorCt = 0;  /* initial value */
     best        = 0;  /* initial value */
-    
+
     for (imageIndex = 0; dirP->count > imageIndex; ++imageIndex) {
         struct IconDirEntry * const dirEntryP = &dirP->entries[imageIndex];
 
@@ -1183,7 +1234,7 @@ bestImage(struct IconDir * const dirP) {
         uint32_t colorCt;
 
         /*  32-bit icons have 24 bit color information only.
-         
+
             Since NT 5.1 (aka WinXP), it is allowed to place 8-bit
             transparency information in the remaining bits (to check,
             you have to read all these bits in the image!), so I prefer
@@ -1222,7 +1273,7 @@ convertImage(struct File *         const icoP,
 
     image = readImage(icoP, dirEntryP);
 
-    if (MEMEQ(image, pngHeader, sizeof (pngHeader)))
+    if (memeq(image, pngSignature, sizeof (pngSignature)))
         convertPng(image, ofP, dirEntryP);
     else
         convertBmp(image, ofP, dirEntryP, needHeaderDump, wantAndMaskPlane);
@@ -1273,7 +1324,7 @@ main (int argc, const char *argv []) {
         convertImage(&ico, &dirP->entries[bestImage(dirP)], stdout,
                      cmdline.headerdump, cmdline.andmasks);
     }
-    
+
     freeIconDir(dirP);
 
     if (ico.fileP != stdin)
diff --git a/converter/other/xwdtopnm.c b/converter/other/xwdtopnm.c
index df3c7375..4eb16def 100644
--- a/converter/other/xwdtopnm.c
+++ b/converter/other/xwdtopnm.c
@@ -70,14 +70,14 @@ static unsigned int pixel_count = 0;
 static int
 zero_bits(const unsigned long mask) {
 /*----------------------------------------------------------------------------
-   Return the number of consective zero bits at the least significant end
+   Return the number of consecutive zero bits at the least significant end
    of the binary representation of 'mask'.  E.g. if mask == 0x00fff800,
    we would return 11.
 -----------------------------------------------------------------------------*/
     int i;
     unsigned long shifted_mask;
 
-    for (i=0, shifted_mask = mask; 
+    for (i=0, shifted_mask = mask;
          i < sizeof(mask)*8 && (shifted_mask & 0x00000001) == 0;
          i++, shifted_mask >>= 1 );
     return(i);
@@ -122,9 +122,9 @@ parseCommandLine(int argc, char ** argv,
     else if (argc - 1 == 1) {
         if (streq(argv[1], "-"))
             cmdlineP->inputFilename = NULL;  /* he wants stdin */
-        else 
+        else
             cmdlineP->inputFilename = strdup(argv[1]);
-    } else 
+    } else
         pm_error("Too many arguments.  The only argument accepted\n"
                  "is the input file specification");
 }
@@ -132,17 +132,17 @@ parseCommandLine(int argc, char ** argv,
 
 
 static void
-processX10Header(X10WDFileHeader *  const h10P, 
+processX10Header(X10WDFileHeader *  const h10P,
                  FILE *             const file,
-                 int *              const colsP, 
-                 int *              const rowsP, 
-                 unsigned int *     const padrightP, 
-                 xelval *           const maxvalP, 
-                 enum visualclass * const visualclassP, 
-                 int *              const formatP, 
-                 xel **             const colorsP, 
-                 int *              const bits_per_pixelP, 
-                 int *              const bits_per_itemP, 
+                 int *              const colsP,
+                 int *              const rowsP,
+                 unsigned int *     const padrightP,
+                 xelval *           const maxvalP,
+                 enum visualclass * const visualclassP,
+                 int *              const formatP,
+                 xel **             const colorsP,
+                 int *              const bits_per_pixelP,
+                 int *              const bits_per_itemP,
                  struct compMask *  const compMaskP,
                  enum byteorder *   const byte_orderP,
                  enum byteorder *   const bit_orderP) {
@@ -214,7 +214,7 @@ processX10Header(X10WDFileHeader *  const h10P,
             (((h10P->pixmap_width + 15) / 16) * 16 - h10P->pixmap_width) * 8;
         *bits_per_itemP = 16;
         *bits_per_pixelP = 1;
-    } else if (h10P->window_ncolors == 0) { 
+    } else if (h10P->window_ncolors == 0) {
         /* Must be grayscale. */
         unsigned int i;
         *formatP = PGM_TYPE;
@@ -314,8 +314,8 @@ dumpX11Cmap(unsigned int       const nColors,
 
     unsigned int i;
     for (i = 0; i < nColors; ++i)
-        pm_message("Color %u r/g/b = %u/%u/%u", i, 
-                   x11colors[i].red, x11colors[i].green, 
+        pm_message("Color %u r/g/b = %u/%u/%u", i,
+                   x11colors[i].red, x11colors[i].green,
                    x11colors[i].blue);
 }
 
@@ -323,11 +323,11 @@ dumpX11Cmap(unsigned int       const nColors,
 
 static void
 readX11Colormap(FILE *       const file,
-                unsigned int const nColors, 
+                unsigned int const nColors,
                 bool         const byteSwap,
                 bool         const cmapDump,
                 X11XColor**  const x11colorsP) {
-                
+
     X11XColor * x11colors;
     int rc;
 
@@ -362,7 +362,7 @@ colormapAllGray(const X11XColor* const x11colors,
     bool grayscale;
 
     grayscale = TRUE;  /* initial assumption */
-    for (i = 0; i < ncolors; ++i) 
+    for (i = 0; i < ncolors; ++i)
         if (x11colors[i].red != x11colors[i].green ||
             x11colors[i].green != x11colors[i].blue )
             grayscale = FALSE;
@@ -383,7 +383,7 @@ dumpX11Header(X11WDFileHeader * const h11P) {
     X11WDFileHeader * h11FixedP;
 
     fixH11ByteOrder(h11P, &h11FixedP);
- 
+
     switch(h11FixedP->pixmap_format) {
     case XYBitmap: formatDesc = "XY bit map"; break;
     case XYPixmap: formatDesc = "XY pix map"; break;
@@ -421,12 +421,12 @@ dumpX11Header(X11WDFileHeader * const h11P) {
     pm_message("X offset: %u", h11FixedP->xoffset);
     pm_message("byte order: %s (%u)", byteOrderDesc, h11FixedP->byte_order);
     pm_message("bitmap unit: %u", h11FixedP->bitmap_unit);
-    pm_message("bit order: %s (%u)", 
+    pm_message("bit order: %s (%u)",
                bitOrderDesc, h11FixedP->bitmap_bit_order);
     pm_message("bitmap pad: %u", h11FixedP->bitmap_pad);
     pm_message("bits per pixel: %u", h11FixedP->bits_per_pixel);
     pm_message("bytes per line: %u", h11FixedP->bytes_per_line);
-    pm_message("visual class: %s (%u)", 
+    pm_message("visual class: %s (%u)",
                visualClassDesc, h11FixedP->visual_class);
     pm_message("red mask:   %08x", h11FixedP->red_mask);
     pm_message("green mask: %08x", h11FixedP->green_mask);
@@ -517,18 +517,18 @@ computeComponentMasks(X11WDFileHeader * const h11P,
 
 
 static void
-processX11Header(X11WDFileHeader *  const h11P, 
+processX11Header(X11WDFileHeader *  const h11P,
                  FILE *             const fileP,
                  bool               const cmapDump,
-                 int *              const colsP, 
-                 int *              const rowsP, 
-                 unsigned int *     const padrightP, 
-                 xelval *           const maxvalP, 
-                 enum visualclass * const visualclassP, 
-                 int *              const formatP, 
-                 xel **             const colorsP, 
-                 int *              const bits_per_pixelP, 
-                 int *              const bits_per_itemP, 
+                 int *              const colsP,
+                 int *              const rowsP,
+                 unsigned int *     const padrightP,
+                 xelval *           const maxvalP,
+                 enum visualclass * const visualclassP,
+                 int *              const formatP,
+                 xel **             const colorsP,
+                 int *              const bits_per_pixelP,
+                 int *              const bits_per_itemP,
                  struct compMask *  const compMaskP,
                  enum byteorder *   const byte_orderP,
                  enum byteorder *   const bit_orderP) {
@@ -538,21 +538,21 @@ processX11Header(X11WDFileHeader *  const h11P,
     bool grayscale;
     bool const byte_swap = (h11P->file_version != X11WD_FILE_VERSION);
     X11WDFileHeader * h11FixedP;
- 
+
     fixH11ByteOrder(h11P, &h11FixedP);
 
     if (byte_swap && verbose)
         pm_message("Header is different endianness from this machine.");
-    
+
     for (i = 0; i < h11FixedP->header_size - sizeof(*h11FixedP); ++i)
         if (getc(fileP) == EOF)
             pm_error("couldn't read rest of X11 XWD file header");
 
     /* Check whether we can handle this dump. */
-    if (h11FixedP->pixmap_depth > 24)
-        pm_error( "can't handle X11 pixmap_depth > 24");
-    if (h11FixedP->bits_per_rgb > 24)
-        pm_error("can't handle X11 bits_per_rgb > 24");
+    if (h11FixedP->pixmap_depth > 32)
+        pm_error( "can't handle X11 pixmap_depth > 32");
+    if (h11FixedP->bits_per_rgb > 32)
+        pm_error("can't handle X11 bits_per_rgb > 32");
     if (h11FixedP->pixmap_format != ZPixmap && h11FixedP->pixmap_depth != 1)
         pm_error("can't handle X11 pixmap_format %d with depth != 1",
                  h11FixedP->pixmap_format);
@@ -593,6 +593,9 @@ processX11Header(X11WDFileHeader *  const h11P,
         *formatP = PPM_TYPE;
 
         /* See discussion above about this maxval */
+        if (h11FixedP->bits_per_rgb > 16)
+            pm_error("Invalid bits_per_rgb for TrueColor image: %u. "
+                     "Maximum possible is 16", h11FixedP->bits_per_rgb);
         *maxvalP = pm_bitstomaxval(h11FixedP->bits_per_rgb);
     } else if (*visualclassP == StaticGray && h11FixedP->bits_per_pixel == 1) {
         *formatP = PBM_TYPE;
@@ -649,7 +652,7 @@ processX11Header(X11WDFileHeader *  const h11P,
        from a truecolor 32 bit window on a Hummingbird Exceed X server
        on Win32, and it had bitmap_unit = 8 and bitmap_pad = 32.
 
-       But Björn Eriksson in October 2003 had an xwd file from a 24
+       But Bjorn Eriksson in October 2003 had an xwd file from a 24
        bit-per-pixel direct color window that had bitmap_unit = 32 and
        bitmap_pad = 8.  This was made by Xwd in Red Hat Xfree86 4.3.0-2.
 
@@ -687,21 +690,21 @@ processX11Header(X11WDFileHeader *  const h11P,
     computeComponentMasks(h11FixedP, compMaskP);
 
     free(h11FixedP);
-} 
+}
 
 
 
 static void
-getinit(FILE *             const ifP, 
-        int *              const colsP, 
-        int *              const rowsP, 
-        unsigned int *     const padrightP, 
-        xelval *           const maxvalP, 
-        enum visualclass * const visualclassP, 
-        int *              const formatP, 
+getinit(FILE *             const ifP,
+        int *              const colsP,
+        int *              const rowsP,
+        unsigned int *     const padrightP,
+        xelval *           const maxvalP,
+        enum visualclass * const visualclassP,
+        int *              const formatP,
         xel **             const colorsP,
-        int *              const bits_per_pixelP, 
-        int *              const bits_per_itemP, 
+        int *              const bits_per_pixelP,
+        int *              const bits_per_itemP,
         struct compMask *  const compMaskP,
         enum byteorder *   const byte_orderP,
         enum byteorder *   const bit_orderP,
@@ -729,13 +732,13 @@ getinit(FILE *             const ifP,
     if ( sizeof(*h10P) > sizeof(*h11P) )
         pm_error("ARGH!  On this machine, X10 headers are larger than "
                  "X11 headers!\n    You will have to re-write xwdtopnm." );
-    
+
     /* We read an X10 header's worth of data from the file, then look
        at it to see if it looks like an X10 header.  If so we process
        the X10 header.  If not, but it looks like the beginning of an
        X11 header, we read more bytes so we have an X11 header's worth
        of data, then process the X11 header.  Otherwise, we raise an
-       error.  
+       error.
     */
 
     rc = fread(&header[0], sizeof(*h10P), 1, ifP);
@@ -744,23 +747,23 @@ getinit(FILE *             const ifP,
 
     if (h10P->file_version == X10WD_FILE_VERSION ||
         pm_bs_long(h10P->file_version) == X10WD_FILE_VERSION) {
-        
+
         if (verbose)
             pm_message("Input is X10");
-        processX10Header(h10P, ifP, colsP, rowsP, padrightP, maxvalP, 
-                         visualclassP, formatP, 
-                         colorsP, bits_per_pixelP, bits_per_itemP, 
+        processX10Header(h10P, ifP, colsP, rowsP, padrightP, maxvalP,
+                         visualclassP, formatP,
+                         colorsP, bits_per_pixelP, bits_per_itemP,
                          compMaskP, byte_orderP, bit_orderP);
     } else if (h11P->file_version == X11WD_FILE_VERSION ||
                pm_bs_long(h11P->file_version) == X11WD_FILE_VERSION) {
-        
+
         int rc;
 
         if (verbose)
             pm_message("Input is X11");
 
         /* Read the balance of the X11 header */
-        rc = fread(&header[sizeof(*h10P)], 
+        rc = fread(&header[sizeof(*h10P)],
                    sizeof(*h11P) - sizeof(*h10P), 1, ifP);
         if (rc != 1)
             pm_error("couldn't read end of X11 XWD file header");
@@ -769,9 +772,9 @@ getinit(FILE *             const ifP,
             dumpX11Header(h11P);
 
         processX11Header(h11P, ifP, cmapDump,
-                         colsP, rowsP, padrightP, maxvalP, 
-                         visualclassP, formatP, 
-                         colorsP, bits_per_pixelP, bits_per_itemP, 
+                         colsP, rowsP, padrightP, maxvalP,
+                         visualclassP, formatP,
+                         colorsP, bits_per_pixelP, bits_per_itemP,
                          compMaskP, byte_orderP, bit_orderP);
     } else
         pm_error("unknown XWD file version: %u", h11P->file_version);
@@ -786,7 +789,7 @@ getinit(FILE *             const ifP,
 
 #define DEBUG_PIXEL_2 \
     if (pixel_count < 4) \
-        pm_message("item: %.8lx", row_controlP->item.l); 
+        pm_message("item: %.8lx", row_controlP->item.l);
 
 
 #define DEBUG_PIXEL_3 \
@@ -876,10 +879,10 @@ static void
 pixelReader_init(pixelReader *  const pixelReaderP,
                  FILE *         const fileP,
                  int            const bitsPerPixel,
-                 int            const bitsPerItem, 
+                 int            const bitsPerItem,
                  enum byteorder const byteOrder,
                  enum byteorder const bitOrder) {
-    
+
     pixelReaderP->fileP           = fileP;
     pixelReaderP->bitsPerPixel    = bitsPerPixel;
     pixelReaderP->bitsPerItem     = bitsPerItem;
@@ -887,7 +890,7 @@ pixelReader_init(pixelReader *  const pixelReaderP,
     pixelReaderP->bitOrder        = bitOrder;
 
     pixelReaderP->nBitsLeft       = 0;
-}    
+}
 
 
 
@@ -950,10 +953,10 @@ readItem(pixelReader * const rdrP) {
         rdrP->nBitsLeft = 16;
     }
         break;
-        
+
     case 32: {
         long item32;
-        
+
         switch (rdrP->byteOrder) {
         case MSBFirst:
             pm_readbiglong(rdrP->fileP, &item32);
@@ -979,7 +982,7 @@ static unsigned long const lsbmask[] = {
    of a bit string.
 -----------------------------------------------------------------------------*/
     0x00000000,
-    0x00000001, 0x00000003, 0x00000007, 0x0000000f, 
+    0x00000001, 0x00000003, 0x00000007, 0x0000000f,
     0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
     0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff,
     0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff,
@@ -999,10 +1002,10 @@ pixelReader_getbits(pixelReader * const rdrP,
 -----------------------------------------------------------------------------*/
     unsigned long pixel;
         /* Accumulator for the value we ultimately return.  We shift in
-           bits from the right end.  The number of bits presently in the
+           bits from the right end.  The number of bits currently in the
            accumulator is rdrP->bitsPerPixel - nBitsStillNeeded .
         */
-    
+
     unsigned int nBitsStillNeeded;
         /* How many bits we still need to add to 'pixel',
            as we build it up to the
@@ -1030,7 +1033,7 @@ pixelReader_getbits(pixelReader * const rdrP,
                 /* The actual bits we take, in the 'nBitsToTake' low bits */
 
             assert(nBitsToTake <= 32);
-            
+
             if (rdrP->bitOrder == MSBFirst) {
                 unsigned int const nBitsToLeave =
                     rdrP->nBitsLeft - nBitsToTake;
@@ -1039,7 +1042,7 @@ pixelReader_getbits(pixelReader * const rdrP,
             } else {
                 bitsToTake = rdrP->itemBuffer & bitsToTakeMask;
                 rdrP->itemBuffer >>= nBitsToTake;
-            }                
+            }
             /* Shift the bits into the right end of the accumulator */
             pixel <<= nBitsToTake;
             pixel |= bitsToTake;
@@ -1064,7 +1067,7 @@ pixelReader_getpix(pixelReader * const rdrP) {
 
    We return an integer.  It's the integer that the pixel represents as
    pure binary cipher, with the first bit the most significant bit.
-   
+
    The basic unit of storage in the input file is an "item."  An item
    can be 1, 2, or 4 bytes, and 'bits_per_item' tells us which.  Each
    item can have its bytes stored in forward or reverse order, and
@@ -1103,18 +1106,18 @@ pixelReader_getpix(pixelReader * const rdrP) {
 
 
 static void
-reportInfo(int              const cols, 
-           int              const rows, 
-           unsigned int     const padright, 
-           xelval           const maxval, 
+reportInfo(int              const cols,
+           int              const rows,
+           unsigned int     const padright,
+           xelval           const maxval,
            enum visualclass const visualclass,
-           int              const format, 
+           int              const format,
            int              const bits_per_pixel,
-           int              const bits_per_item, 
+           int              const bits_per_item,
            struct compMask  const compMask,
-           enum byteorder   const byte_order, 
+           enum byteorder   const byte_order,
            enum byteorder   const bit_order) {
-    
+
     const char *visualclass_name;
     const char *byte_order_name;
     const char *bit_order_name;
@@ -1140,7 +1143,7 @@ reportInfo(int              const cols,
     pm_message("%d rows of %d columns with maxval %d",
                rows, cols, maxval);
     pm_message("padright=%u bits.  visualclass = %s.  format=%d (%c%c)",
-               padright, visualclass_name, 
+               padright, visualclass_name,
                format, format/256, format%256);
     pm_message("bits_per_pixel=%d; bits_per_item=%d",
                bits_per_pixel, bits_per_item);
@@ -1174,12 +1177,12 @@ warn16Bit(xelval const maxval) {
 
 
 
-static void 
+static void
 convertRowSimpleIndex(pixelReader *  const pixelReaderP,
                       int            const cols,
                       const xel *    const colors,
                       xel *          const xelrow) {
-    
+
     unsigned int col;
     for (col = 0; col < cols; ++col)
         xelrow[col] = colors[pixelReader_getpix(pixelReaderP)];
@@ -1193,7 +1196,7 @@ convertRowDirect(pixelReader *   const pixelReaderP,
                  const xel *     const colors,
                  struct compMask const compMask,
                  xel *           const xelrow) {
-        
+
     unsigned int col;
 
     for (col = 0; col < cols; ++col) {
@@ -1204,11 +1207,11 @@ convertRowDirect(pixelReader *   const pixelReaderP,
         unsigned int red_index, grn_index, blu_index;
             /* These are indices into the color map, unpacked from 'pixel'.
              */
-            
+
         pixel = pixelReader_getpix(pixelReaderP);
 
         red_index = (pixel & compMask.red) >> zero_bits(compMask.red);
-        grn_index = (pixel & compMask.grn) >> zero_bits(compMask.grn); 
+        grn_index = (pixel & compMask.grn) >> zero_bits(compMask.grn);
         blu_index = (pixel & compMask.blu) >> zero_bits(compMask.blu);
 
         PPM_ASSIGN(xelrow[col],
@@ -1263,12 +1266,12 @@ convertRowTrueColor(pixelReader *   const pixelReaderP,
 static void
 convertRow(pixelReader *    const pixelReaderP,
            FILE *           const ofP,
-           unsigned int     const padright, 
-           int              const cols, 
+           unsigned int     const padright,
+           int              const cols,
            xelval           const maxval,
-           int              const format, 
+           int              const format,
            struct compMask  const compMask,
-           const xel*       const colors, 
+           const xel*       const colors,
            enum visualclass const visualclass) {
 /*----------------------------------------------------------------------------
    Read a row from the XWD pixel input stream 'pixelReaderP' and write
@@ -1290,20 +1293,20 @@ convertRow(pixelReader *    const pixelReaderP,
     case PseudoColor:
         convertRowSimpleIndex(pixelReaderP, cols, colors, xelrow);
         break;
-    case DirectColor: 
+    case DirectColor:
         convertRowDirect(pixelReaderP, cols, colors, compMask, xelrow);
-        
+
         break;
-    case TrueColor: 
+    case TrueColor:
         convertRowTrueColor(pixelReaderP, cols, maxval, colors,
                             compMask, xelrow);
         break;
-            
+
     default:
         pm_error("unknown visual class");
     }
     pixelReader_getbits(pixelReaderP, padright);
-    
+
     pnm_writepnmrow(ofP, xelrow, cols, maxval, format, 0);
     pnm_freerow(xelrow);
 }
@@ -1321,11 +1324,11 @@ reportOutputType(int const format) {
     case PGM_TYPE:
         pm_message("writing PGM file");
     break;
-    
+
     case PPM_TYPE:
         pm_message("writing PPM file");
     break;
-    
+
     default:
         pm_error("shouldn't happen");
     }
@@ -1358,19 +1361,19 @@ main(int argc, char *argv[]) {
     debug = cmdline.debug;
     verbose = cmdline.verbose;
 
-    if (cmdline.inputFilename != NULL) 
+    if (cmdline.inputFilename != NULL)
         ifP = pm_openr(cmdline.inputFilename);
     else
         ifP = stdin;
 
-    getinit(ifP, &cols, &rows, &padright, &maxval, &visualclass, &format, 
-            &colors, &bitsPerPixel, &bitsPerItem, 
+    getinit(ifP, &cols, &rows, &padright, &maxval, &visualclass, &format,
+            &colors, &bitsPerPixel, &bitsPerItem,
             &compMask, &byteOrder, &bitOrder,
             cmdline.headerdump, cmdline.cmapdump);
 
     warn16Bit(maxval);
-    
-    if (verbose) 
+
+    if (verbose)
         reportInfo(cols, rows, padright, maxval, visualclass,
                    format, bitsPerPixel, bitsPerItem, compMask,
                    byteOrder, bitOrder);
@@ -1389,17 +1392,17 @@ main(int argc, char *argv[]) {
     }
 
     pixelReader_term(&pixelReader);
-    
+
     pm_close(ifP);
     pm_close(stdout);
-    
+
     return 0;
 }
 
 
 
 /*
-   This used to be the way we parsed a direct/true color pixel.  I'm 
+   This used to be the way we parsed a direct/true color pixel.  I'm
    keeping it here in case we find out some application needs it this way.
 
    There doesn't seem to be any reason to do this hard-coded stuff when
@@ -1411,7 +1414,7 @@ main(int argc, char *argv[]) {
    this whole switch thing.  -Bryan 00.03.01
 
    switch (bits_per_pixel) {
-                
+
    case 16:
        PPM_ASSIGN( *xP,
                    ( ( ul & red_mask )   >> 0    ),
diff --git a/converter/other/yuy2topam.c b/converter/other/yuy2topam.c
index 40ab98b3..49f284ac 100644
--- a/converter/other/yuy2topam.c
+++ b/converter/other/yuy2topam.c
@@ -31,12 +31,12 @@ struct CmdlineInfo {
 
 
 
-static void 
-parseCommandLine(int argc, const char ** argv, 
+static void
+parseCommandLine(int argc, const char ** argv,
                  struct CmdlineInfo * const cmdlineP) {
 /* --------------------------------------------------------------------------
    Parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -84,7 +84,7 @@ parseCommandLine(int argc, const char ** argv,
         cmdlineP->inputFileName = "-";
     else {
         cmdlineP->inputFileName = argv[1];
-        
+
         if (argc-1 > 1)
             pm_error("Too many arguments (%u).  The only non-option argument "
                      "is the input file name.", argc-1);
diff --git a/converter/pbm/atktopbm.c b/converter/pbm/atktopbm.c
index 807e4f4a..57782d91 100644
--- a/converter/pbm/atktopbm.c
+++ b/converter/pbm/atktopbm.c
@@ -44,7 +44,7 @@
 #define dataobject_OBJECTCREATIONFAILED 4
 #define dataobject_BADFORMAT 5
 
-/* ReadRow(file, row, length) 
+/* ReadRow(file, row, length)
 ** Reads from 'file' the encoding of bytes to fill in 'row'.  Row will be
 ** truncated or padded (with WHITE) to exactly 'length' bytes.
 **
@@ -52,7 +52,7 @@
 **      '|'     correct end of line
 **      '\0'    if the length was satisfied (before a terminator)
 **      EOF     if the file ended
-**      '\'  '{'    other recognized ends. 
+**      '\'  '{'    other recognized ends.
 ** The '|' is the expected end and pads the row with WHITE.
 ** The '\' and '{' are error conditions and may indicate the
 ** beginning of some other portion of the data stream.
@@ -76,11 +76,11 @@ ReadRow(FILE *          const file,
   'file' is where to get them from.
   'row' is where to put bytes.
   'length' is how many bytes in row must be filled.
-  
+
   Return the delimiter that marks the end of the row, or EOF if EOF marks
   the end of the row, or NUL in some cases.
 -----------------------------------------------------------------------------*/
-    /* Each input character is processed by the central loop.  There are 
+    /* Each input character is processed by the central loop.  There are
     ** some input codes which require two or three characters for
     ** completion; these are handled by advancing the state machine.
     ** Errors are not processed; instead the state machine is reset
@@ -98,7 +98,7 @@ ReadRow(FILE *          const file,
         RepeatAndDigit
             /* have seen repeat code and its first following digit */
     };
-    
+
     enum StateCode InputState;  /* current state */
     int c;     /* the current input character */
     long repeatcount;  /* current repeat value */
@@ -106,8 +106,8 @@ ReadRow(FILE *          const file,
     long pendinghex;    /* the first of a pair of hex characters */
     int lengthRemaining;
     unsigned char * cursor;
-    
-    /* We cannot exit when length becomes zero because we need to check 
+
+    /* We cannot exit when length becomes zero because we need to check
     ** to see if a row ending character follows.  Thus length is checked
     ** only when we get a data generating byte.  If length then is
     ** zero, we ungetc the byte.
@@ -148,7 +148,7 @@ ReadRow(FILE *          const file,
             while (lengthRemaining-- > 0)
                 *cursor++ = WHITEBYTE;
             return c;
-    
+
         CASE1(0x21):
         CASE6(0x22):
         CASE8(0x28):
@@ -227,9 +227,9 @@ ReadRow(FILE *          const file,
             break;
 
         store:
-            /* generate byte(s) into the output row 
+            /* generate byte(s) into the output row
                Use repeatcount, depending on state.  */
-            if (lengthRemaining < repeatcount) 
+            if (lengthRemaining < repeatcount)
                 /* reduce repeat count if it would exceed
                    available space */
                 repeatcount = lengthRemaining;
@@ -269,7 +269,7 @@ ReadATKRaster(FILE * const ifP) {
         pm_error ("input file not Andrew raster object");
 
     fscanf(ifP, " %d ", &version);
-    if (version < 2) 
+    if (version < 2)
         pm_error ("version too old to parse");
 
     {
@@ -277,8 +277,8 @@ ReadATKRaster(FILE * const ifP) {
         long xscale, yscale;
         long xoffset, yoffset, subwidth, subheight;
         /* ignore all these features: */
-        fscanf(ifP, " %u %ld %ld %ld %ld %ld %ld",  
-               &options, &xscale, &yscale, &xoffset, 
+        fscanf(ifP, " %u %ld %ld %ld %ld %ld %ld",
+               &options, &xscale, &yscale, &xoffset,
                &yoffset, &subwidth, &subheight);
     }
     /* scan to end of line in case this is actually something beyond V2 */
@@ -291,8 +291,12 @@ ReadATKRaster(FILE * const ifP) {
 
     fscanf(ifP, " %d %d %d ", &objectid, &width, &height);
 
-    if (width < 1 || height < 1 || width > 1000000 || height > 1000000) 
+    if (width < 1 || height < 1 || width > 1000000 || height > 1000000)
         pm_error("bad width or height");
+        /* Note: Whether these values are upper limits set by the author of
+           the original version of this program, or come from the official
+           file format specification is unknown.
+        */
 
     pbm_writepbminit(stdout, width, height, 0);
     bitrow = pbm_allocrow_packed(width);
@@ -302,7 +306,7 @@ ReadATKRaster(FILE * const ifP) {
         long const nextChar = ReadRow(ifP, bitrow, rowlen);
 
         switch (nextChar) {
-        case '|': 
+        case '|':
             pbm_writepbmrow_packed(stdout, bitrow, width, 0);
             break;
         case EOF:
diff --git a/converter/pbm/escp2topbm.c b/converter/pbm/escp2topbm.c
index 8acd13d6..de3ea931 100644
--- a/converter/pbm/escp2topbm.c
+++ b/converter/pbm/escp2topbm.c
@@ -104,7 +104,7 @@ readChar(FILE * const ifP) {
 
 
 
-static void       
+static void
 readStripeHeader(unsigned int * const widthThisStripeP,
                  unsigned int * const rowsThisStripeP,
                  unsigned int * const compressionP,
@@ -120,7 +120,7 @@ readStripeHeader(unsigned int * const widthThisStripeP,
     compression     = stripeHeader[0];
     /* verticalResolution   = stripeHeader[1]; */
     /* horizontalResolution = stripeHeader[2]; */
-    rowsThisStripe  = stripeHeader[3];  
+    rowsThisStripe  = stripeHeader[3];
     widthThisStripe = stripeHeader[5] * 256 + stripeHeader[4];
 
     if (widthThisStripe == 0 || rowsThisStripe == 0)
@@ -143,7 +143,7 @@ readStripeHeader(unsigned int * const widthThisStripeP,
 
 /* RLE decoder */
 static void
-decEpsonRLE(unsigned int    const blockSize, 
+decEpsonRLE(unsigned int    const blockSize,
             unsigned char * const outBuffer,
             FILE *          const ifP) {
 
@@ -174,7 +174,7 @@ decEpsonRLE(unsigned int    const blockSize,
             unsigned int i;
 
             for (i = 0; i < runLength; ++i)
-                outBuffer[dpos + i] = repeatChar;  
+                outBuffer[dpos + i] = repeatChar;
             dpos += runLength;
         }
     }
@@ -191,7 +191,7 @@ processStripeRaster(unsigned char ** const bitarray,
                     unsigned int     const compression,
                     FILE *           const ifP,
                     unsigned int *   const rowIdxP) {
-         
+
     unsigned int const initialRowIdx = *rowIdxP;
     unsigned int const widthInBytes = pbm_packed_bytes(width);
     unsigned int const blockSize = rowsThisStripe * widthInBytes;
@@ -237,7 +237,7 @@ expandBitarray(unsigned char *** const bitarrayP,
     if (*bitarraySizeP > heightMax)
         pm_error("Error: Image too tall");
     else
-        REALLOCARRAY_NOFAIL(*bitarrayP, *bitarraySizeP); 
+        REALLOCARRAY_NOFAIL(*bitarrayP, *bitarraySizeP);
 }
 
 
@@ -253,7 +253,7 @@ writePbmImage(unsigned char ** const bitarray,
         pm_error("No image");
 
     pbm_writepbminit(stdout, width, height, 0);
- 
+
     for (row = 0; row < height; ++row) {
         pbm_cleanrowend_packed(bitarray[row], width);
         pbm_writepbmrow_packed(stdout, bitarray[row], width, 0);
@@ -309,7 +309,7 @@ main(int          argc,
                 unsigned int compression;
                 unsigned int rowsThisStripe;
                 unsigned int widthThisStripe;
-            
+
                 readStripeHeader(&widthThisStripe, &rowsThisStripe,
                                  &compression, ifP);
 
@@ -320,7 +320,7 @@ main(int          argc,
                     /* The official Epson manual says valid values are 1, 8,
                        24 but we just print a warning message and continue if
                        other values are detected.
-                    */ 
+                    */
                     pm_message("Abnormal data block height value: %u "
                                "(ignoring)",
                                rowsThisStripe);
diff --git a/converter/pbm/g3topbm.c b/converter/pbm/g3topbm.c
index 5d98fcb2..5db507a3 100644
--- a/converter/pbm/g3topbm.c
+++ b/converter/pbm/g3topbm.c
@@ -552,12 +552,11 @@ readFaxRow(struct BitStream * const bitStreamP,
                 curcode = (curcode << 1) | bit;
                 ++curlen;
 
-		if (curlen > 11 && curcode == 0x00) {
-		    if (++fillbits > MAXFILLBITS)
-                pm_error("Encountered %u consecutive fill bits.  "
-                       "Aborting", fillbits);
-		}
-		else if (curlen - fillbits > 13) {
+                if (curlen > 11 && curcode == 0x00) {
+                    if (++fillbits > MAXFILLBITS)
+                        pm_error("Encountered %u consecutive fill bits.  "
+                                 "Aborting", fillbits);
+                } else if (curlen - fillbits > 13) {
                     formatBadCodeException(exceptionP, col, curlen, curcode);
                     done = TRUE;
                 } else if (curcode != 0) {
diff --git a/converter/pbm/mdatopbm.c b/converter/pbm/mdatopbm.c
index d8e06572..461b3f80 100644
--- a/converter/pbm/mdatopbm.c
+++ b/converter/pbm/mdatopbm.c
@@ -36,7 +36,7 @@ static bit **data;          /* PBM image */
 static mdbyte *mdrow;           /* MDA row after decompression (MD3 only) */
 static int bInvert = 0;     /* Invert image? */
 static int bScale  = 0;     /* Scale image? */
-static int bAscii  = 0;     /* Ouput ASCII PBM? */
+static int bAscii  = 0;     /* Output ASCII PBM? */
 static int nInRows, nInCols;        /* Height, width of input (rows x bytes) */
 static int nOutCols, nOutRows;      /* Height, width of output (rows x bytes) */
 
diff --git a/converter/pbm/mgrtopbm.c b/converter/pbm/mgrtopbm.c
index 712e3be9..e0a88883 100644
--- a/converter/pbm/mgrtopbm.c
+++ b/converter/pbm/mgrtopbm.c
@@ -58,12 +58,12 @@ interpHdrHeight(struct b_header const head,
 
 
 static void
-readMgrHeader(FILE *          const ifP, 
-              unsigned int *  const colsP, 
-              unsigned int *  const rowsP, 
-              unsigned int *  const depthP, 
+readMgrHeader(FILE *          const ifP,
+              unsigned int *  const colsP,
+              unsigned int *  const rowsP,
+              unsigned int *  const depthP,
               unsigned int *  const padrightP ) {
-    
+
     struct b_header head;
     unsigned int pad;
     size_t bytesRead;
@@ -73,10 +73,10 @@ readMgrHeader(FILE *          const ifP,
         pm_error("Unable to read 1st byte of file.  "
                  "fread() returns errno %d (%s)",
                  errno, strerror(errno));
-    if (head.magic[0] == 'y' && head.magic[1] == 'z') { 
+    if (head.magic[0] == 'y' && head.magic[1] == 'z') {
         /* new style bitmap */
         size_t bytesRead;
-        bytesRead = fread(&head.depth, 
+        bytesRead = fread(&head.depth,
                           sizeof(head) - sizeof(struct old_b_header), 1, ifP);
         if (bytesRead != 1 )
             pm_error("Unable to read header after 1st byte.  "
@@ -84,11 +84,11 @@ readMgrHeader(FILE *          const ifP,
                      errno, strerror(errno));
         *depthP = (int) head.depth - ' ';
         pad = 8;
-    } else if (head.magic[0] == 'x' && head.magic[1] == 'z') { 
+    } else if (head.magic[0] == 'x' && head.magic[1] == 'z') {
         /* old style bitmap with 32-bit padding */
         *depthP = 1;
         pad = 32;
-    } else if (head.magic[0] == 'z' && head.magic[1] == 'z') { 
+    } else if (head.magic[0] == 'z' && head.magic[1] == 'z') {
         /* old style bitmap with 16-bit padding */
         *depthP = 1;
         pad = 16;
@@ -104,8 +104,8 @@ readMgrHeader(FILE *          const ifP,
 
     interpHdrWidth (head, colsP);
     interpHdrHeight(head, rowsP);
-    
-    *padrightP = ( ( *colsP + pad - 1 ) / pad ) * pad - *colsP;
+
+    *padrightP = ((*colsP + pad - 1) / pad) * pad - *colsP;
 }
 
 
@@ -131,7 +131,7 @@ main(int    argc,
         inputFileName = argv[1];
     else
         inputFileName = "-";
-    
+
     ifP = pm_openr(inputFileName);
 
     readMgrHeader(ifP, &cols, &rows, &depth, &padright);
@@ -141,7 +141,7 @@ main(int    argc,
     pbm_writepbminit(stdout, cols, rows, 0);
 
     bitrow = pbm_allocrow_packed(cols + padright);
-    
+
     itemCount = (cols + padright ) / 8;
 
     for (row = 0; row < rows; ++row) {
@@ -166,9 +166,9 @@ main(int    argc,
    Changed bitrow from plain to raw, read function from getc() to fread(),
    write function from pbm_writepbmrow() to pbm_writepbmrow_packed().
    Retired bitwise transformation functions.
-   
+
    NOT tested for old-style format files.  Only one zz file in mgrsrc-0.69 .
-  
+
 */
 
 
diff --git a/converter/pbm/pbmtoatk.c b/converter/pbm/pbmtoatk.c
index ea5b7abe..5f2b625c 100644
--- a/converter/pbm/pbmtoatk.c
+++ b/converter/pbm/pbmtoatk.c
@@ -22,8 +22,8 @@
 
 
 static void
-write_atk_bytes(FILE *        const file, 
-                unsigned char const curbyte, 
+write_atk_bytes(FILE *        const file,
+                unsigned char const curbyte,
                 unsigned int  const startcount) {
 
     /* codes for data stream */
@@ -37,7 +37,7 @@ write_atk_bytes(FILE *        const file,
     #define BLACKBYTE 0xFF
 
     /* WriteRow table for conversion of a byte value to two character
-       hex representation 
+       hex representation
     */
 
     static unsigned char hex[16] = {
@@ -82,10 +82,10 @@ write_atk_bytes(FILE *        const file,
 
 
 static void
-process_atk_byte(int *           const pcurcount, 
-                 unsigned char * const pcurbyte, 
-                 FILE *          const file, 
-                 unsigned char   const newbyte, 
+process_atk_byte(int *           const pcurcount,
+                 unsigned char * const pcurbyte,
+                 FILE *          const file,
+                 unsigned char   const newbyte,
                  int             const eolflag) {
 
     int curcount;
@@ -93,7 +93,7 @@ process_atk_byte(int *           const pcurcount,
 
     curcount = *pcurcount;  /* initial value */
     curbyte  = *pcurbyte;  /* initial value */
-    
+
     if (curcount < 1) {
         *pcurbyte = curbyte = newbyte;
         *pcurcount = curcount = 1;
@@ -139,6 +139,17 @@ main(int argc, const char ** argv) {
     }
 
     pbm_readpbminit(ifP, &cols, &rows, &format);
+    /* Note: atktopbm imposes limits: cols <= 1000000 rows <= 1000000
+       Whether these values are defined in the official file format
+       specification is unknown.  We issue warning messages when large
+       values are encountered.
+     */
+
+    if (cols > 1000000)
+        pm_message("Proceeding with extremely large width value: %u", cols);
+    if (rows > 1000000)
+        pm_message("Proceeding with extremely large height value: %u", rows);
+
     bitrow = pbm_allocrow_packed(cols);
 
     printf("\\begindata{raster,%d}\n", 1);
@@ -152,7 +163,7 @@ main(int argc, const char ** argv) {
 
         pbm_readpbmrow_packed(ifP, bitrow, cols, format);
         pbm_cleanrowend_packed(bitrow, cols);
-        
+
         for (i = 0, curbyte = 0, curcount = 0; i < byteCt; ++i) {
             process_atk_byte(&curcount, &curbyte, stdout,
                              bitrow[i],
@@ -162,7 +173,7 @@ main(int argc, const char ** argv) {
 
     pbm_freerow_packed(bitrow);
     pm_close(ifP);
-    
+
     printf("\\enddata{raster, %d}\n", 1);
 
     return 0;
diff --git a/converter/pbm/pbmtoescp2.c b/converter/pbm/pbmtoescp2.c
index 6f284f3c..942ecec9 100644
--- a/converter/pbm/pbmtoescp2.c
+++ b/converter/pbm/pbmtoescp2.c
@@ -18,6 +18,7 @@
 *
 *  ESC/P Reference Manual (1997)
 *  ftp://download.epson-europe.com/pub/download/182/epson18162eu.zip
+*  See Part 1 "ESC ." Print Raster Graphics
 */
 
 #include <string.h>
@@ -28,7 +29,7 @@
 #include "runlength.h"
 #include "pbm.h"
 
-
+#define MAXCOLS (127 * 256 + 255)  /* Limit in official Epson manual */
 
 static char const esc = 033;
 
@@ -57,19 +58,19 @@ parseCommandLine(int argc, const char ** argv,
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;
     opt.allowNegNum = FALSE;
-    OPTENT3(0, "compress",     OPT_UINT,    &cmdlineP->compress,    
+    OPTENT3(0, "compress",     OPT_UINT,    &cmdlineP->compress,
             &compressSpec,    0);
-    OPTENT3(0, "resolution",   OPT_UINT,    &cmdlineP->resolution,  
+    OPTENT3(0, "resolution",   OPT_UINT,    &cmdlineP->resolution,
             &resolutionSpec,  0);
-    OPTENT3(0, "stripeheight", OPT_UINT,    &cmdlineP->stripeHeight,  
+    OPTENT3(0, "stripeheight", OPT_UINT,    &cmdlineP->stripeHeight,
             &stripeHeightSpec, 0);
-    OPTENT3(0, "raw",          OPT_FLAG,    NULL,  
+    OPTENT3(0, "raw",          OPT_FLAG,    NULL,
             &rawSpec,    0);
-    OPTENT3(0, "formfeed",     OPT_FLAG,    NULL,  
+    OPTENT3(0, "formfeed",     OPT_FLAG,    NULL,
             &formfeedSpec,    0);
-    
+
     pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
-    
+
     if (argc-1 > 1)
         pm_error("Too many arguments: %d.  "
                  "Only argument is the filename", argc-1);
@@ -155,7 +156,7 @@ main(int argc, const char * argv[]) {
     unsigned char * bitrow[256];
     unsigned char * compressedData;
     struct CmdlineInfo cmdline;
-    
+
     pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
@@ -164,7 +165,7 @@ main(int argc, const char * argv[]) {
 
     pbm_readpbminit(ifP, &cols, &rows, &format);
 
-    if (cols / 256 > 127)  /* Limit in official Epson manual */
+    if (cols > MAXCOLS)
         pm_error("Image width is too large");
 
     outColByteCt = pbm_packed_bytes(cols);
@@ -229,7 +230,7 @@ main(int argc, const char * argv[]) {
         }
     }
 
-    free(inBuff); 
+    free(inBuff);
     free(compressedData);
     pm_close(ifP);
 
diff --git a/converter/pbm/pbmtogem.c b/converter/pbm/pbmtogem.c
index 9eab0416..4fd30e92 100644
--- a/converter/pbm/pbmtogem.c
+++ b/converter/pbm/pbmtogem.c
@@ -26,7 +26,7 @@
 *  changed header length to count words to conform with Atari ST documentation
 *  removed rounding of the imagewidth to the next word boundary
 *  removed arbitrary limit to imagewidth
-*  changed pattern length to 1 to simplify locating of compressable parts
+*  changed pattern length to 1 to simplify locating of compressible parts
 *       in real world images
 *  add solid run and pattern run compression
 *
diff --git a/converter/pbm/pbmtogo.c b/converter/pbm/pbmtogo.c
index 23b2ee9a..4f84f391 100644
--- a/converter/pbm/pbmtogo.c
+++ b/converter/pbm/pbmtogo.c
@@ -1,29 +1,29 @@
 /* pbmtogo.c - read a PBM image and produce a GraphOn terminal raster file
-**      
+**
 **      Rev 1.1 was based on pbmtolj.c
 **
 **      Bo Thide', Swedish Institute of Space Physics, bt@irfu.se
-**                                 
+**
 **
 ** $Log:        pbmtogo.c,v $
  * Revision 1.5  89/11/25  00:24:12  00:24:12  root (Bo Thide)
  * Bug found: The byte after 64 repeated bytes sometimes lost. Fixed.
- * 
+ *
  * Revision 1.4  89/11/24  14:56:04  14:56:04  root (Bo Thide)
  * Fixed the command line parsing since pbmtogo now always uses 2D
  * compression.  Added a few comments to the source.
- * 
+ *
  * Revision 1.3  89/11/24  13:43:43  13:43:43  root (Bo Thide)
  * Added capability for > 63 repeated bytes and > 62 repeated lines in
  * the 2D compression scheme.
- * 
+ *
  * Revision 1.2  89/11/15  01:04:47  01:04:47  root (Bo Thide)
  * First version that works reasonably well with GraphOn 2D runlength
  * encoding/compression.
- * 
+ *
  * Revision 1.1  89/11/02  23:25:25  23:25:25  root (Bo Thide)
  * Initial revision
- * 
+ *
 **
 ** Copyright (C) 1988, 1989 by Jef Poskanzer, Michael Haberler, and Bo Thide'.
 **
@@ -44,10 +44,10 @@
 
 #define GRAPHON_WIDTH 1056 /* GraphOn has 1056 bit wide raster lines */
 #define GRAPHON_WIDTH_BYTES (GRAPHON_WIDTH / 8)
-#define REPEAT_CURRENT_LINE_MASK        0x00 
-#define SKIP_AND_PLOT_MASK              0x40 
-#define REPEAT_PLOT_MASK                0x80 
-#define PLOT_ARBITRARY_DATA_MASK        0xc0 
+#define REPEAT_CURRENT_LINE_MASK        0x00
+#define SKIP_AND_PLOT_MASK              0x40
+#define REPEAT_PLOT_MASK                0x80
+#define PLOT_ARBITRARY_DATA_MASK        0xc0
 #define MAX_REPEAT 64
 
 static unsigned char * scanlineptr;
@@ -167,7 +167,7 @@ main(int           argc,
       buffer[i] = oldscanline[i] = 0;
     putinit();
 
-    /* Start donwloading screen raster */
+    /* Start downloading screen raster */
     printf("\033P0;1;0;4;1;%d;%d;1!R1/", rows, rucols);
 
     linerepeat = 63; /*  63 means "Start new picture" */
@@ -183,32 +183,32 @@ main(int           argc,
           putbit(0);
 
         assert(bytesperrow <= GRAPHON_WIDTH_BYTES);
-        
+
         /* XOR data from the new scan line with data from old scan line */
         for (i = 0; i < bytesperrow; i++)
           diff[i] = oldscanline[i]^newscanline[i];
-        
+
         /*
          ** If the difference map is different from current internal buffer,
-         ** encode the difference and put it in the output buffer. 
+         ** encode the difference and put it in the output buffer.
          ** Else, increase the counter for the current buffer by one.
          */
-        
+
         if ((memcmp(buffer, diff, bytesperrow) != 0) || (row == 0)) {
-            /*    
+            /*
              **Since the data in the buffer has changed, send the
              **scan line repeat count to cause the old line(s) to
              **be plotted on the screen, copy the new data into
-             **the internal buffer, and reset the counters.  
+             **the internal buffer, and reset the counters.
              */
-              
+
             putchar(linerepeat);
             for (i = 0; i < bytesperrow; ++i)
               buffer[i] = diff[i];
             nbyte = 0;          /* Internal buffer byte counter */
             nout = 0;           /* Output buffer byte counter */
-              
-            /* Run length encode the new internal buffr (= difference map) */
+
+            /* Run length encode the new internal buffer (= difference map) */
             while (TRUE) {
                 ucount = 0;     /* Unique items counter */
                 do              /* Find unique patterns */
@@ -217,16 +217,16 @@ main(int           argc,
                       ucount++;
                   } while (nbyte < bytesperrow && (olditem != buffer[nbyte])
                            && (ucount < MIN(bytesperrow, MAX_REPEAT)));
-                  
+
                 if ((ucount != MAX_REPEAT) && (nbyte != bytesperrow)) {
                     /* Back up to the last truly unique pattern */
                     ucount--;
                     nbyte--;
                 }
 
-                if (ucount > 0) { 
+                if (ucount > 0) {
                     /* Output the unique patterns */
-                    outbuffer[nout++] = 
+                    outbuffer[nout++] =
                       (ucount-1) | PLOT_ARBITRARY_DATA_MASK;
                     for (i = nbyte-ucount; i < nbyte; i++)
                       outbuffer[nout++] = buffer[i];
@@ -235,12 +235,12 @@ main(int           argc,
                 /*
                  ** If we already are at the end of the current scan
                  ** line, skip the rest of the encoding and start
-                 ** with a new scan line.  
+                 ** with a new scan line.
                  */
 
                 if (nbyte >= bytesperrow)
                   goto nextrow;
-                  
+
                 ecount = 0;     /* Equal items counter */
                 do              /* Find equal patterns */
                   {
@@ -248,25 +248,25 @@ main(int           argc,
                       ecount++;
                   } while (nbyte < bytesperrow && (olditem == buffer[nbyte])
                            && (ecount < MIN(bytesperrow, MAX_REPEAT)));
-                  
+
                 if (ecount > 1) {
                     /* More than 1 equal pattern */
                     if (olditem == '\0') {
                         /* White patterns */
                         if (nbyte >= bytesperrow-1) {
                             /* No more valid data ahead */
-                            outbuffer[nout++] = 
+                            outbuffer[nout++] =
                               (ecount-2) | SKIP_AND_PLOT_MASK;
                             outbuffer[nout++] = buffer[nbyte-1];
-                        } 
-                        else { 
+                        }
+                        else {
                             /* More valid data ahead */
-                            outbuffer[nout++] = 
+                            outbuffer[nout++] =
                               (ecount-1) | SKIP_AND_PLOT_MASK;
                             outbuffer[nout++] = buffer[nbyte++];
-                        } 
+                        }
                     }
-                    else { 
+                    else {
                         /* Non-white patterns */
                         outbuffer[nout++] = (ecount-1) | REPEAT_PLOT_MASK;
                         outbuffer[nout++] = olditem;
@@ -274,11 +274,11 @@ main(int           argc,
                 } /* if (ecount > 1) */
                 else
                   nbyte--;      /* No equal items found */
-                  
+
                 if (nbyte >= bytesperrow)
                   goto nextrow;
             } /* while (TRUE) */
-              
+
           nextrow: printf("%d/", nout+1); /* Total bytes to xfer = nout+1 */
             fflush(stdout);
 
@@ -298,7 +298,7 @@ main(int           argc,
                   linerepeat = 0;
               }
         }
-        
+
         /* Now we are ready for a new scan line */
         for (i = 0; i < bytesperrow; ++i)
           oldscanline[i] = newscanline[i];
diff --git a/converter/pbm/pbmtoibm23xx.c b/converter/pbm/pbmtoibm23xx.c
index 183d5419..3f1f9679 100644
--- a/converter/pbm/pbmtoibm23xx.c
+++ b/converter/pbm/pbmtoibm23xx.c
@@ -18,7 +18,7 @@
  */
 
 /*
- * This prgram is primarily based on the description of Brothers PPDS
+ * This program is primarily based on the description of Brothers PPDS
  * emulation (see
  * http://www.brother.de/download/send_file.cfm?file_name=guide_ibmpro.pdf).
  * However, there are some differences.  Their document states that
@@ -39,7 +39,7 @@
  * normally achieve in y.  But the printer is able to do line feeds in
  * terms of 1/240", so the trick to print in higher resolutions is to
  * print in several interleaved passes, and do a line feed of 1/240"
- * or 1/120" inbetween.
+ * or 1/120" in between.
  */
 
 #include <stdio.h>
@@ -131,7 +131,7 @@ process_handle(FILE *        const fh,
         int cols, rows, format;
         /* iteration variables */
         unsigned int x, y;
-        unsigned int bitline; /* pixel line within a sigle printing line */
+        unsigned int bitline; /* pixel line within a single printing line */
         unsigned int pass;
         /* here we build the to-be-printed data */
         unsigned char *output;  /* for reading one row from the file */
diff --git a/converter/pbm/pbmtolps.c b/converter/pbm/pbmtolps.c
index 5adef4c8..d974fcb2 100644
--- a/converter/pbm/pbmtolps.c
+++ b/converter/pbm/pbmtolps.c
@@ -1,181 +1,253 @@
-/*
- * pbmtolps -- convert a Portable BitMap into Postscript.  The
- * output Postscript uses lines instead of the image operator to
- * generate a (device dependent) picture which will be imaged
- * much faster.
- *
- * The Postscript path length is constrained to be less that 1000
- * points so that no limits are overrun on the Apple Laserwriter
- * and (presumably) no other printers.
- *
- * To do:
- *      make sure encapsulated format is correct
- *      repitition of black-white strips
- *      make it more device independent (is this possible?)
- *
- * Author:
- *      George Phillips <phillips@cs.ubc.ca>
- *      Department of Computer Science
- *      University of British Columbia
- */
-
-#include <string.h>
-#include <stdio.h>
-
+/*=============================================================================
+                             pbmtolps
+===============================================================================
+
+  Convert a PBM image to Postscript.  The output Postscript uses lines instead
+  of the image operator to generate a (device dependent) picture which will be
+  imaged much faster.
+
+  The Postscript path length is constrained to be at most 1000 vertices so that
+  no limits are overrun on the Apple Laserwriter and (presumably) no other
+  printers.  The typical limit is 1500.  See "4.4 Path Construction" and
+  "Appendix B: Implementation Limits" in: PostScript Language Reference Manual
+  https://www.adobe.com/content/dam/acom/en/devnet/actionscript/
+  articles/psrefman.pdf
+
+  To do:
+       make sure encapsulated format is correct
+       repetition of black-white strips
+       make it more device independent (is this possible?)
+
+  Author:
+       George Phillips <phillips@cs.ubc.ca>
+       Department of Computer Science
+       University of British Columbia
+=============================================================================*/
+#include <stdbool.h>
+
+#include "pm_c_util.h"
+#include "mallocvar.h"
 #include "nstring.h"
+#include "shhopt.h"
 #include "pbm.h"
 
 
-static int prev_white = -1;
-static int prev_black = -1;
-static char cmd = '\0';
-static int pointcount = 2;
+static float        const MAX_DPI           = 5000;
+static float        const MIN_DPI           = 10;
+static unsigned int const MAX_PATH_VERTICES = 1000;
 
-#ifdef RUN
-static int run = 1;
-#endif
 
-static char 
-morepoints(char cmd, int howmany_pbmtolps) {
-    pointcount += 2;
-    if (pointcount > 1000) {
-        pointcount = 2;
-        cmd += 'm' - 'a';
-    }
-    return(cmd);
+struct CmdlineInfo {
+    /* All the information the user supplied in the command line, in a form
+       easy for the program to use.
+    */
+    const char * inputFileName;  /* File name of input file */
+    unsigned int inputFileSpec;  /* Input file name specified */
+    float        lineWidth;      /* Line width, if specified */
+    unsigned int lineWidthSpec;  /* Line width specified */
+    float        dpi;            /* Resolution in DPI, if specified */
+    unsigned int dpiSpec;        /* Resolution specified */
+};
+
+
+
+static void
+validateDpi(float const dpi) {
+
+    if (dpi > MAX_DPI || dpi < MIN_DPI)
+        pm_error("Specified DPI value out of range (%f)", dpi);
 }
 
 
 
-static void 
-addstrip(int const white, 
-         int const black) {
-
-    if (cmd) {
-#ifdef RUN
-        if (white == prev_white && black == prev_black)
-            run++;
-        else {
-            if (run == 1)
-#endif
-                printf("%d %d %c ", 
-                       prev_black, prev_white, morepoints(cmd, 2));
-#ifdef RUN
-            else
-                                /* of course, we need to give a new command */
-                printf("%d %d %d %c ",
-                       prev_white, prev_black, run,
-                       morepoints(cmd + 'f' - 'a', 2 * run));
-            run = 1;
-        }
-#endif
+static void
+parseCommandLine(int                        argc,
+                 const char **        const argv,
+                 struct CmdlineInfo * const cmdlineP) {
+/*----------------------------------------------------------------------------
+   Parse program command line described in Unix standard form by argc
+   and argv.  Return the information in the options as *cmdlineP.
+-----------------------------------------------------------------------------*/
+    optEntry * option_def;  /* malloc'ed */
+        /* Instructions to OptParseOptions3 on how to parse our options.  */
+    optStruct3 opt;
+
+    unsigned int option_def_index;
+
+    MALLOCARRAY_NOFAIL(option_def, 100);
+
+    option_def_index = 0;   /* incremented by OPTENTRY */
+    OPTENT3(0, "linewidth", OPT_FLOAT, &cmdlineP->lineWidth,
+                            &cmdlineP->lineWidthSpec,    0);
+    OPTENT3(0, "dpi",       OPT_FLOAT,  &cmdlineP->dpi,
+                            &cmdlineP->dpiSpec,          0);
+
+    opt.opt_table = option_def;
+    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
+
+    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+        /* Uses and sets argc, argv, and some of *cmdlineP and others. */
+
+    if (cmdlineP->dpiSpec)
+        validateDpi(cmdlineP->dpi);
+    else
+        cmdlineP->dpi = 300;
+
+    if (argc-1 < 1)
+        cmdlineP->inputFileName = "-";
+    else {
+        if (argc-1 > 1)
+            pm_error("Program takes zero or one argument (filename).  You "
+                     "specified %u", argc-1);
+        else
+            cmdlineP->inputFileName = argv[1];
     }
 
-    prev_white = white;
-    prev_black = black;
-    cmd = 'a';
+    if (cmdlineP->inputFileName[0] == '-' &&
+        cmdlineP->inputFileName[1] == '\0')
+        cmdlineP->inputFileSpec = false;
+    else
+        cmdlineP->inputFileSpec = true;
+
+    free(option_def);
 }
 
 
 
-static void 
-nextline(void) {
-    /* need to check run, should have an outcommand */
-    if (cmd)
-        printf("%d %d %c\n", prev_black, prev_white, morepoints('c', 3));
-    else
-        printf("%c\n", morepoints('b', 1));
-    cmd = '\0';
+static void
+validateLineWidth(float const scCols,
+                  float const scRows,
+                  float const lineWidth) {
+
+    if (lineWidth >= scCols || lineWidth >= scRows)
+        pm_error("Absurdly large -linewidth value (%f)", lineWidth);
 }
 
 
 
-int
-main(int argc, char ** argv) {
-    FILE*   fp;
-    bit*    bits;
-    int             row;
-    int             col;
-    int         rows;
-    int             cols;
-    int             format;
-    int             white;
-    int             black;
-    const char*   name;
-    float   dpi = 300.0;
-    float   sc_rows;
-    float   sc_cols;
-    int             i;
-    const char*   const usage = "[ -dpi n ] [ pbmfile ]";
-
-
-	pbm_init(&argc, argv);
-
-    i = 1;
-    if (i < argc && streq(argv[i], "-dpi")) {
-        if (i == argc - 1)
-            pm_usage(usage);
-        sscanf(argv[i + 1], "%f", &dpi);
-        i += 2;
-    }
+static void
+doRaster(FILE *       const ifP,
+         unsigned int const cols,
+         unsigned int const rows,
+         int          const format,
+         FILE *       const ofP) {
 
-    if (i < argc - 1)
-        pm_usage(usage);
+    bit *        bitrow;
+    unsigned int row;
+    unsigned int vertexCt;
+        /* Number of vertices drawn since last stroke command */
 
-    if (i == argc) {
-        name = "noname";
-        fp = stdin;
-    } else {
-        name = argv[i];
-        fp = pm_openr(name);
-    }
-    pbm_readpbminit(fp, &cols, &rows, &format);
-    bits = pbm_allocrow(cols);
-
-    sc_rows = (float)rows / dpi * 72.0;
-    sc_cols = (float)cols / dpi * 72.0;
-
-    puts("%!PS-Adobe-2.0 EPSF-2.0");
-    puts("%%Creator: pbmtolps");
-    printf("%%%%Title: %s\n", name);
-    printf("%%%%BoundingBox: %d %d %d %d\n",
-           (int)(305.5 - sc_cols / 2.0),
-           (int)(395.5 - sc_rows / 2.0),
-           (int)(306.5 + sc_cols / 2.0),
-           (int)(396.5 + sc_rows / 2.0));
-    puts("%%EndComments");
-    puts("%%EndProlog");
-    puts("gsave");
-
-    printf("%f %f translate\n", 306.0 - sc_cols / 2.0, 396.0 + sc_rows / 2.0);
-    printf("72 %f div dup neg scale\n", dpi);
-    puts("/a { 0 rmoveto 0 rlineto } def");
-    puts("/b { 0 row 1 add dup /row exch def moveto } def");
-    puts("/c { a b } def");
-    puts("/m { currentpoint stroke newpath moveto a } def");
-    puts("/n { currentpoint stroke newpath moveto b } def");
-    puts("/o { currentpoint stroke newpath moveto c } def");
-    puts("/row 0 def");
-    puts("newpath 0 0 moveto");
-
-    for (row = 0; row < rows; row++) {
-        pbm_readpbmrow(fp, bits, cols, format);
-        /* output white-strip+black-strip sequences */
-        for (col = 0; col < cols; ) {
-            for (white = 0; col < cols && bits[col] == PBM_WHITE; col++)
-                white++;
-            for (black = 0; col < cols && bits[col] == PBM_BLACK; col++)
-                black++;
+    bitrow = pbm_allocrow(cols);
+
+    for (row = 0, vertexCt = 0; row < rows; ++row) {
+        unsigned int col;
+        bool firstRun;
+
+        firstRun = true;  /* initial value */
+
+        pbm_readpbmrow(ifP, bitrow, cols, format);
+
+        /* output white-strip + black-strip sequences */
 
-            if (black != 0)
-                addstrip(white, black);
+        for (col = 0; col < cols; ) {
+            unsigned int whiteCt;
+            unsigned int blackCt;
+
+            for (whiteCt = 0; col < cols && bitrow[col] == PBM_WHITE; ++col)
+                ++whiteCt;
+            for (blackCt = 0; col < cols && bitrow[col] == PBM_BLACK; ++col)
+                ++blackCt;
+
+            if (blackCt > 0) {
+                if (vertexCt > MAX_PATH_VERTICES) {
+                    printf("m ");
+                    vertexCt = 0;
+                }
+
+                if (firstRun) {
+                    printf("%u %u moveto %u 0 rlineto\n",
+                           whiteCt, row, blackCt);
+                    firstRun = false;
+                } else
+                    printf("%u %u a\n", blackCt, whiteCt);
+
+                vertexCt += 2;
+            }
         }
-        nextline();
     }
-    puts("stroke grestore showpage");
-    puts("%%Trailer");
+    pbm_freerow(bitrow);
+}
+
+
+
+static void
+pbmtolps(FILE *             const ifP,
+         FILE *             const ofP,
+         struct CmdlineInfo const cmdline) {
+
+    const char * const psName =
+        cmdline.inputFileSpec ? cmdline.inputFileName : "noname";
+
+    int          rows;
+    int          cols;
+    int          format;
+    float        scRows, scCols;
+        /* Dimensions of the printed image in points */
+
+    pbm_readpbminit(ifP, &cols, &rows, &format);
+
+    scRows = (float) rows / (cmdline.dpi / 72.0);
+    scCols = (float) cols / (cmdline.dpi / 72.0);
+
+    if (cmdline.lineWidthSpec)
+        validateLineWidth(scCols, scRows, cmdline.lineWidth);
+
+    fputs("%!PS-Adobe-2.0 EPSF-2.0\n", ofP);
+    fputs("%%Creator: pbmtolps\n", ofP);
+    fprintf(ofP, "%%%%Title: %s\n", psName);
+    fprintf(ofP, "%%%%BoundingBox: %d %d %d %d\n",
+           (int)(305.5 - scCols / 2.0),
+           (int)(395.5 - scRows / 2.0),
+           (int)(306.5 + scCols / 2.0),
+           (int)(396.5 + scRows / 2.0));
+    fputs("%%EndComments\n", ofP);
+    fputs("%%EndProlog\n", ofP);
+    fputs("gsave\n", ofP);
+
+    fprintf(ofP, "%f %f translate\n",
+            306.0 - scCols / 2.0, 396.0 + scRows / 2.0);
+    fprintf(ofP, "72 %f div dup neg scale\n", cmdline.dpi);
+
+    if (cmdline.lineWidthSpec)
+        fprintf(ofP, "%f setlinewidth\n", cmdline.lineWidth);
+
+    fputs("/a { 0 rmoveto 0 rlineto } def\n", ofP);
+    fputs("/m { currentpoint stroke newpath moveto } def\n", ofP);
+    fputs("newpath 0 0 moveto\n", ofP);
+
+    doRaster(ifP, cols, rows, format, ofP);
+
+    fputs("stroke grestore showpage\n", ofP);
+    fputs("%%Trailer\n", ofP);
+}
+
+
+
+int
+main(int argc, const char *argv[]) {
+    FILE *  ifP;
+    struct CmdlineInfo cmdline;
+
+    pm_proginit(&argc, argv);
+
+    parseCommandLine(argc, argv, &cmdline);
+
+    ifP = pm_openr(cmdline.inputFileName);
+
+    pbmtolps(ifP, stdout, cmdline);
 
-    pm_close(fp);
+    pm_close(ifP);
 
-    exit(0);
+    return 0;
 }
diff --git a/converter/pbm/pbmtomacp.c b/converter/pbm/pbmtomacp.c
index e02f5559..4897e6d0 100644
--- a/converter/pbm/pbmtomacp.c
+++ b/converter/pbm/pbmtomacp.c
@@ -18,7 +18,7 @@
 
 /*
 
-  Implemention notes
+  Implementation notes
 
   Header size is 512 bytes.  There is no MacBinary header.
 
diff --git a/converter/pbm/pbmtomgr.c b/converter/pbm/pbmtomgr.c
index 0e529740..faa56d8f 100644
--- a/converter/pbm/pbmtomgr.c
+++ b/converter/pbm/pbmtomgr.c
@@ -33,7 +33,7 @@ putinit(unsigned int const rows,
     head._reserved = ' ';
     writtenCount = fwrite(&head, sizeof(head), 1, stdout);
     if (writtenCount != 1)
-        pm_error("fwrite() failed to write the MGR header.");    
+        pm_error("fwrite() failed to write the MGR header.");
 }
 
 
@@ -63,7 +63,7 @@ main(int argc,
         inputFileName = argv[1];
     else
         inputFileName = "-";
-    
+
     ifP = pm_openr(inputFileName);
 
     pbm_readpbminit(ifP, &cols, &rows, &format);
@@ -71,14 +71,14 @@ main(int argc,
         pm_error("Image width too large: %u (max: %u)", cols, maxDimension);
     if (rows > maxDimension)
         pm_error("Image height too large: %u (max: %u)", rows, maxDimension);
-    
+
     bitrow = pbm_allocrow_packed(cols);
     bytesPerRow = pbm_packed_bytes(cols);
 
     putinit(rows, cols);
-    
+
     for (row = 0; row < rows; ++row) {
-        /* The raster formats are identical. 
+        /* The raster formats are identical.
            The row end pad bits are set to 0 in mgr.
         */
         size_t bytesWritten;
@@ -89,7 +89,7 @@ main(int argc,
         bytesWritten = fwrite(bitrow, 1, bytesPerRow, stdout);
         if (bytesWritten != bytesPerRow )
             pm_error("fwrite() failed to write MGR bitmap "
-                     "to Standard Output.");    
+                     "to Standard Output.");
     }
     pm_close(ifP);
     return 0;
@@ -102,7 +102,7 @@ main(int argc,
    pbm_readpbmrow_packed(), write function from putc() to fwrite().
 
    Retired bitwise transformation functions.
-   
+
    Produces only new style bitmap (8 bit padding.)  See mgrtopbm.c .
 */
 
diff --git a/converter/pbm/pbmtonokia.c b/converter/pbm/pbmtonokia.c
index 80b0bd59..4604064a 100644
--- a/converter/pbm/pbmtonokia.c
+++ b/converter/pbm/pbmtonokia.c
@@ -83,7 +83,7 @@ parseCommandLine(int argc, char ** argv,
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0, "fmt",     OPT_STRING, &fmtOpt, 
+    OPTENT3(0, "fmt",     OPT_STRING, &fmtOpt,
             &fmtSpec, 0);
     OPTENT3(0, "net",     OPT_STRING, &netOpt,
             &netSpec, 0);
@@ -135,7 +135,7 @@ parseCommandLine(int argc, char ** argv,
                  "the 120 characters allowed by the format.",
                  (unsigned)strlen(cmdlineP->txt));
 
-    if (argc-1 == 0) 
+    if (argc-1 == 0)
         cmdlineP->inputFileName = "-";
     else if (argc-1 != 1)
         pm_error("Program takes zero or one argument (filename).  You "
@@ -180,7 +180,7 @@ convertToHexNol(bit **       const image,
 
     /* header */
     fprintf(ofP, "06050415820000%s00%02X%02X01", networkCode, cols, rows);
-    
+
     /* image */
     for (row = 0; row < rows; ++row) {
         unsigned int col;
@@ -245,7 +245,7 @@ convertToHexNpm(bit **       const image,
                 FILE *       const ofP) {
 
     unsigned int row;
-    
+
     /* header */
     fprintf(ofP, "060504158A0000");
 
@@ -293,7 +293,7 @@ convertToNol(bit **       const image,
     unsigned int row;
     char header[32];
     unsigned int it;
-    
+
     /* header - this is a hack */
 
     header[ 0] = 'N';
@@ -318,7 +318,7 @@ convertToNol(bit **       const image,
     header[19] = 0;
 
     fwrite(header, 20, 1, ofP);
-    
+
     /* image */
     for (row = 0; row < rows; ++row) {
         unsigned int col;
@@ -368,7 +368,7 @@ convertToNgg(bit **       const image,
     header[15] = 0;
 
     fwrite(header, 16, 1, ofP);
-    
+
     /* image */
 
     for (row = 0; row < rows; ++row) {
@@ -395,35 +395,56 @@ convertToNpm(bit **       const image,
              const char * const text,
              FILE *       const ofP) {
 
+    size_t const textLen = text ? strlen(text) : 0;
+
     unsigned int row;
     char header[132];
-    size_t len;
-
-    if (text) 
-        len = strlen(text);
-    else
-        len = 0;
 
     /* header and optional text */
 
-    header[       0] = 'N';
-    header[       1] = 'P';
-    header[       2] = 'M';
-    header[       3] = 0;
-    header[       4] = len;
-    header[       5] = 0;
-    if (text)
-        memcpy(&header[6], text, len);
-    header[ 6 + len] = cols;
-    header[ 7 + len] = rows;
-    header[ 8 + len] = 1;
-    header[ 9 + len] = 1;
-    header[10 + len] = 0; /* unknown */
-
-    assert(10 + len < sizeof(header));
-
-    fwrite(header, 11 + len, 1, ofP);
-    
+    /* Our entry condition is that 'text' be a legal text field, which means
+       no more than 120 characters:
+    */
+    assert(textLen <= 120);
+
+    /* We don't have any specification of this format, but in May 2020, we
+       found what looks like a bug: the memcpy of the text field started at
+       &header[5] (overwriting the previous setting of header[5] and leaving
+       header[6+len-1] not set to anything).  Nobody ever complained about
+       this, so maybe somehow it worked better than the sensible code we have
+       now, where the text field starts in the 7th byte.
+    */
+
+    /* The code below that deliberately avoids using 'text' as an argument to
+       memcpy when 'text' is null looks like it should have no practical
+       effect, because with a zero length memcpy, it shouldn't matter what the
+       from and to arguments are.  But it's logically correct - a null pointer
+       just doesn't point anywhere.  And believe it or not, it has a practical
+       effect - a truly bizarre one.  This code used to be simpler and just
+       pass that null pointer to memcpy, with length 0, and as reported in May
+       2020, a new optimizing compiler caused header[3] to contain random
+       values.  That's right: 3.  Skipping that presumed no-op memcpy stopped
+       the behavior.
+    */
+
+    header[           0] = 'N';
+    header[           1] = 'P';
+    header[           2] = 'M';
+    header[           3] = 0;
+    header[           4] = textLen;
+    header[           5] = 0;
+    if (text)  /* see above */
+        memcpy(&header[6], text, textLen);
+    header[ 6 + textLen] = cols;
+    header[ 7 + textLen] = rows;
+    header[ 8 + textLen] = 1;
+    header[ 9 + textLen] = 1;
+    header[10 + textLen] = 0; /* unknown */
+
+    assert(10 + textLen < sizeof(header));
+
+    fwrite(header, 11 + textLen, 1, ofP);
+
     /* image: stream of bits, each row padded to a byte boundary
        inspired by gnokii/common/gsm-filesystems.c
      */
@@ -453,7 +474,7 @@ convertToNpm(bit **       const image,
 
 
 
-int 
+int
 main(int    argc,
      char * argv[]) {
 
@@ -521,6 +542,6 @@ Testing:
   The data was send with EMI/UCP protocol over TCP/IP.
 
   - 7.6.2001: tested with Nokia 3210: 72x14 Operator Logo
-  - 7.6.2001: tested with Nokia 6210: 72x14 Operator Logo and 
+  - 7.6.2001: tested with Nokia 6210: 72x14 Operator Logo and
               72x14 Group Graphic
 */
diff --git a/converter/pbm/pbmtopk.c b/converter/pbm/pbmtopk.c
index 2f05d449..3f54254c 100644
--- a/converter/pbm/pbmtopk.c
+++ b/converter/pbm/pbmtopk.c
@@ -1,8 +1,8 @@
 /*
   pbmtopk, adapted from "pxtopk.c by tomas rokicki" by AJCD 1/8/90
-  
+
   References (retrieved May 31 2015):
-  Packed (PK) Font File Format 
+  Packed (PK) Font File Format
   https://www.tug.org/TUGboat/tb06-3/tb13pk.pdf
 
   Tex Font Metric Files (TFM)
@@ -148,7 +148,7 @@ compute_checksum()
             temp_width:=memory[char_wd[c]];
             if design_units<>unity then
                temp_width:=round((temp_width/design_units)*1048576.0);
-            temp_width:=temp_width + (c+4)*@'20000000; 
+            temp_width:=temp_width + (c+4)*@'20000000;
                 {this should be positive}
             c0:=(c0+c0+temp_width) mod 255;
             c1:=(c1+c1+temp_width) mod 253;
@@ -173,12 +173,12 @@ compute_checksum()
 
 
 static byte
-add_tfmtable(int *        const table, 
-             int *        const count, 
-             int          const value, 
-             int          const max_count, 
+add_tfmtable(int *        const table,
+             int *        const count,
+             int          const value,
+             int          const max_count,
              const char * const name) {
-    
+
     integer i;
     for (i = 0; i < *count; i++) /* search for value in tfm table */
         if (table[i] == value) return (byte)i;
@@ -194,8 +194,8 @@ add_tfmtable(int *        const table,
 
 
 /* add a suffix to a filename in an allocated space */
-static void 
-pbmtopk_add_suffix(char * const name, 
+static void
+pbmtopk_add_suffix(char * const name,
                    const char * const suffix) {
 
     char *slash = strrchr(name, '/');
@@ -208,7 +208,7 @@ pbmtopk_add_suffix(char * const name,
 
 
 /* initialize the PK parameters */
-static void 
+static void
 initialize_pk(void) {
     integer i ;
     pm_message("This is PBMtoPK, version 2.4") ;
@@ -225,13 +225,13 @@ initialize_pk(void) {
 
 
 /* write a single byte to the PK file */
-static void 
+static void
 pbmtopk_pkbyte(integer const b_in) {
     integer b;
 
     b = b_in;  /* initial value */
 
-    if (b < 0) 
+    if (b < 0)
         b += 256 ;
     putc(b, pkfile) ;
     pbmtopk_pkloc++ ;
@@ -240,13 +240,13 @@ pbmtopk_pkbyte(integer const b_in) {
 
 
 /* write two bytes to the PK file */
-static void 
+static void
 pkhalfword(integer const a_in) {
     integer a;
 
     a = a_in;
 
-    if (a < 0) 
+    if (a < 0)
         a += 65536 ;
     pbmtopk_pkbyte(a >> 8) ;
     pbmtopk_pkbyte(a & 255) ;
@@ -255,7 +255,7 @@ pkhalfword(integer const a_in) {
 
 
 /* write three bytes to the PK file */
-static void 
+static void
 pkthreebytes(integer const a) {
 
     pbmtopk_pkbyte((a>>16) & 255) ;
@@ -266,7 +266,7 @@ pkthreebytes(integer const a) {
 
 
 /* write four bytes to the PK file */
-static void 
+static void
 pkword(integer const a) {
     pbmtopk_pkbyte((a>>24) & 255) ;
     pbmtopk_pkbyte((a>>16) & 255) ;
@@ -277,7 +277,7 @@ pkword(integer const a) {
 
 
 /* write a nibble to the PK file */
-static void 
+static void
 pknyb(integer const a) {
 
     if (bitweight == 16) {
@@ -292,15 +292,15 @@ pknyb(integer const a) {
 
 
 /* write preamble to PK file */
-static void 
+static void
 writepreamble(void) {
     integer i ;
     const char * const comment = "PBMtoPK 2.4 output" ;
-   
+
     pbmtopk_pkbyte(247) ;                /* PRE command */
     pbmtopk_pkbyte(89) ;             /* PK file type */
     pbmtopk_pkbyte(strlen(comment)) ;            /* output comment */
-    for (i = 0 ; i < strlen(comment); i++) 
+    for (i = 0 ; i < strlen(comment); i++)
         pbmtopk_pkbyte(xord[(int)comment[i]]) ;
     pkword(designsize) ;             /* write designsize */
     pkword(checksum) ;       /* write checksum; calculate if possible */
@@ -311,7 +311,7 @@ writepreamble(void) {
 
 
 /* write postamble to PK file, padded to word length */
-static void 
+static void
 writepostamble(void) {
     pbmtopk_pkbyte(245) ;                /* POST command */
     while (pbmtopk_pkloc % 4)
@@ -322,7 +322,7 @@ writepostamble(void) {
 
 
 /* write a byte to the TFM file */
-static void 
+static void
 tfmbyte(integer const b_in) {
     integer b;
 
@@ -335,9 +335,9 @@ tfmbyte(integer const b_in) {
 
 
 /* write a half word to the TFM file */
-static void 
+static void
 tfmhalfword(integer const a_in) {
-    
+
     integer a;
 
     a = a_in;
@@ -350,7 +350,7 @@ tfmhalfword(integer const a_in) {
 
 
 /* write a word to the TFM file */
-static void 
+static void
 tfmword(integer const a) {
     tfmbyte((a>>24) & 255) ;
     tfmbyte((a>>16) & 255) ;
@@ -361,12 +361,12 @@ tfmword(integer const a) {
 
 
 /* write the whole TFM file for the font */
-static void 
+static void
 writetfmfile(void) {
     integer totallength ;
     integer headersize = 17;
     integer i ;
-   
+
     if (largestch - smallestch < 0) {
         largestch = 0;
         smallestch = 1;
@@ -406,23 +406,23 @@ writetfmfile(void) {
     /* header */
     tfmword(checksum) ;              /* write checksum */
     tfmword(designsize) ;            /* write designsize */
-    if (strlen(codingscheme) > 39) 
+    if (strlen(codingscheme) > 39)
         tfmbyte(39) ; /* write coding scheme len */
-    else 
+    else
         tfmbyte(strlen(codingscheme)) ;
     for (i = 0; i < 39; i++)         /* write coding scheme */
-        if 
+        if
             (*codingscheme) tfmbyte(xord[(int)(*codingscheme++)]) ;
         else
             tfmbyte(0) ;
-    if (strlen(familyname) > 19) 
+    if (strlen(familyname) > 19)
         tfmbyte(19) ;   /* write family length */
-    else 
+    else
         tfmbyte(strlen(familyname)) ;
     for (i = 0; i < 19; i++)         /* write family */
-        if (*familyname) 
+        if (*familyname)
             tfmbyte(xord[(int)(*familyname++)]) ;
-        else 
+        else
             tfmbyte(0) ;
     /* char_info */
     for (car = smallestch; car <= largestch; car++)
@@ -441,7 +441,7 @@ writetfmfile(void) {
     for (i = 0; i < numdepth; i++) tfmword(depthtab[i]) ;
     /* italic correction table */
     for (i = 0; i < numitalic; i++) tfmword(italictab[i]) ;
-    /* no lig_kern, kern, or exten tables */
+    /* no lig_kern, kern, or extent tables */
     /* fontdimen table */
     for (i = 0; i < numparam; i++)
         if (i && !fixrange(parameters[i]))
@@ -456,11 +456,11 @@ writetfmfile(void) {
 /* read a character from a PBM file */
 static void readcharacter(void) {
     FILE *fp;
-   
+
     fp = pm_openr(filename[car]);
     bitmap = pbm_readpbm(fp, &width, &height) ;
     pm_close(fp) ;
-   
+
     if ((charflags[car] & HORZESC) == 0) horzesc[car] = width ;
     if ((charflags[car] & VERTESC) == 0) vertesc[car] = 0;
     if ((charflags[car] & XOFFSET) == 0) xoffset[car] = 0;
@@ -470,10 +470,10 @@ static void readcharacter(void) {
     if ((charflags[car] & TFMHEIGHT) == 0)
         hgtindex[car] = add_tfmheight(fixword(designunits(yoffset[car]+1)));
     if ((charflags[car] & TFMDEPTH) == 0)
-        depindex[car] = 
+        depindex[car] =
             add_tfmdepth(fixword(designunits(height-1-yoffset[car])));
     if ((charflags[car] & TFMITALIC) == 0) italindex[car] = 0;
-   
+
     if (car < smallestch) smallestch = car;
     if (car > largestch) largestch = car;
     if (width > emwidth) emwidth = width ;
@@ -482,14 +482,14 @@ static void readcharacter(void) {
 
 
 /* test if two rows of the PBM are the same */
-static int 
-equal(const bit * const row1, 
+static int
+equal(const bit * const row1,
       const bit * const row2) {
 
     integer i ;
-   
+
     for (i = 0; i < width; i++)
-        if (row1[i] != row2[i]) 
+        if (row1[i] != row2[i])
             return (0) ;
 
     return(1) ;
@@ -497,7 +497,7 @@ equal(const bit * const row1,
 
 
 
-static void 
+static void
 shipcharacter(void) {
 
     integer compsize ;
@@ -526,13 +526,13 @@ shipcharacter(void) {
     integer max2 ;
     integer predpkloc ;
     integer buff ;
-   
+
     integer tfwid = widthtab[tfmindex[car]] ;
     integer hesc = horzesc[car] ;
     integer vesc = vertesc[car] ;
     integer xoff = xoffset[car] ;
     integer yoff = yoffset[car] ;
-   
+
     MALLOCARRAY(repeatptr, height + 1);
     MALLOCARRAY(bitcounts, height * width);
     if (repeatptr == NULL || bitcounts == NULL)
@@ -781,8 +781,8 @@ shipcharacter(void) {
     }
     if (predpkloc != pbmtopk_pkloc)
         pm_error("bad predicted character length: character %d", car);
-    pbm_freerow(zerorow); 
-    pbm_freerow(onesrow); 
+    pbm_freerow(zerorow);
+    pbm_freerow(onesrow);
     free((char *)repeatptr);
     free((char *)bitcounts);
 }
@@ -790,7 +790,7 @@ shipcharacter(void) {
 
 
 /* check that character is in valid range */
-static void 
+static void
 checkchar(void) {
     if (car < 0 || car >= MAXPKCHAR)
         pm_error("character must be in range 0 to %d", MAXPKCHAR-1) ;
@@ -799,16 +799,16 @@ checkchar(void) {
 
 
 /* read character information from an option file */
-static void 
+static void
 optionfile(const char * const name) {
 
     FILE *fp ;
     char buffer[MAXOPTLINE] ;
-   
+
     fp = pm_openr(name);
     while (!feof(fp)) {
         char *here = buffer;
-      
+
         if (fgets(buffer, MAXOPTLINE, fp) == NULL) break ;
         while (ISSPACE(*here)) here++ ;
         if (*here && *here == '=') {
@@ -817,7 +817,7 @@ optionfile(const char * const name) {
         } else if (*here && *here != '%' && *here != '#') {
             char str[NAMELENGTH] ;
             integer i, n;
-     
+
             checkchar() ;
             if (sscanf(here, "%s%n", str, &n) != 1)
                 pm_error("bad option file line %s", buffer) ;
@@ -881,26 +881,26 @@ main(int argc, char *argv[]) {
 
     pbm_init(&argc, argv);
     initialize_pk() ;
-   
+
     if (--argc < 1) pm_usage(usage) ;
     ++argv;
     if(strlen(*argv) + 4 > NAMELENGTH)
         pm_error("pkname is too long");
     strcpy(pkname, *argv) ;
     pbmtopk_add_suffix(pkname, ".pk") ;
-   
+
     if (--argc < 1) pm_usage(usage);
     ++argv;
     if(strlen(*argv) + 4 > NAMELENGTH)
         pm_error("tfmname is too long");
     strcpy(tfmname, *argv) ;
     pbmtopk_add_suffix(tfmname, ".tfm") ;
-   
+
     if (--argc < 1) pm_usage(usage) ;
     resolution = atoi(*++argv) ;
     if (resolution < 1 || resolution > 32767)
         pm_error("unlikely resolution %d dpi", resolution);
-   
+
     car = flags = hesc = vesc = xoff = yoff = tfwid = 0;
     while (++argv, --argc) {
         if (argv[0][0] == '-' && argv[0][1]) {
@@ -922,7 +922,7 @@ main(int argc, char *argv[]) {
             case 's':
                 designsize = fixword(atof(p));
                 if (designsize < 1048576)
-                    pm_error("design size %f out of range", 
+                    pm_error("design size %f out of range",
                              unfixword(designsize));
             case 'h':
                 hesc = atoi(p) ;
@@ -1009,3 +1009,5 @@ main(int argc, char *argv[]) {
     return 0;
 }
 
+
+
diff --git a/converter/pbm/pbmtoppa/README.REDHAT b/converter/pbm/pbmtoppa/README.REDHAT
index 3586aea2..e7b30490 100644
--- a/converter/pbm/pbmtoppa/README.REDHAT
+++ b/converter/pbm/pbmtoppa/README.REDHAT
@@ -17,7 +17,7 @@ StartEntry: DeskJet720C
            It does does not support color printing. \
            IMPORTANT! Insert \
                 "- | pbm2ppa -" \
-           in the "Extra GS Otions" field.\
+           in the "Extra GS Options" field.\
          }
   Resolution: {600} {600} {}
 EndEntry
diff --git a/converter/pbm/pbmtoppa/ppa.c b/converter/pbm/pbmtoppa/ppa.c
index aa30d684..69e7bb79 100644
--- a/converter/pbm/pbmtoppa/ppa.c
+++ b/converter/pbm/pbmtoppa/ppa.c
@@ -207,7 +207,7 @@ void ppa_init_job(ppa_stat* prn)
     scp3_put (prn->fptr, 0x018f, sizeof(init3), 7, 2, 4, init3);
     break;
   default:
-    fprintf(stderr,"ppa_init_job(): unknown printer verson\n");
+    fprintf(stderr,"ppa_init_job(): unknown printer version\n");
   }
 }
 
@@ -238,7 +238,7 @@ void ppa_init_page(ppa_stat* prn)
     scp3_put (prn->fptr, 0x0183, sizeof(pageA), 5, 1, 0, pageA);
     break;
   default:
-    fprintf(stderr,"ppa_init_page(): unknown printer verson\n");
+    fprintf(stderr,"ppa_init_page(): unknown printer version\n");
   }
 }
 
@@ -260,7 +260,7 @@ void ppa_load_page(ppa_stat* prn)
     scp3_put (prn->fptr, 0x0181, sizeof(loadC), 7, 1, 0, loadC);
     break;
   default:
-    fprintf(stderr,"ppa_load_page(): unknown printer verson\n");
+    fprintf(stderr,"ppa_load_page(): unknown printer version\n");
   }
 }
 
@@ -282,7 +282,7 @@ void ppa_eject_page(ppa_stat* prn)
     scp3_put (prn->fptr, 0x0181, sizeof(loadC), 7, 1, 0, loadC);
     break;
   default:
-    fprintf(stderr,"ppa_eject_page(): unknown printer verson\n");
+    fprintf(stderr,"ppa_eject_page(): unknown printer version\n");
   }
 }
 
@@ -440,7 +440,7 @@ void ppa_print_sweep(ppa_stat* prn,ppa_sweep_data* data)
     MF=1;
     break;
   default:
-    fprintf(stderr,"ppa_print_sweep(): unknown printer verson\n");
+    fprintf(stderr,"ppa_print_sweep(): unknown printer version\n");
     return;
   }
 
diff --git a/converter/pbm/pbmtoptx.c b/converter/pbm/pbmtoptx.c
index c0fb0f80..69f1707a 100644
--- a/converter/pbm/pbmtoptx.c
+++ b/converter/pbm/pbmtoptx.c
@@ -12,10 +12,10 @@
 
 #include "pbm.h"
 
-/* Follwing is obtained by reversing bit order (MFS-LFS) and adding 64. */
+/* Following is obtained by reversing bit order (MFS-LFS) and adding 64. */
 /* Note the two escape sequences: \\ and \x7f . */
 
-static unsigned char const ptxchar[64] = 
+static unsigned char const ptxchar[64] =
   "@`PpHhXxDdTtLl\\|BbRrJjZzFfVvNn^~AaQqIiYyEeUuMm]}CcSsKk[{GgWwOo_\x7f";
 
 
@@ -32,7 +32,7 @@ putBitrow(const bit *  const bitrow,
         unsigned int const byteCnt = (itemCnt * 6) / 8;
         bit const byteCur  = bitrow[byteCnt];
         bit const byteNext = bitrow[byteCnt + 1];
-        
+
         unsigned int item;
 
         switch (itemCnt % 4) {
@@ -62,7 +62,7 @@ main(int argc, const char ** argv)  {
         ifP = stdin;
     else {
         ifP = pm_openr(argv[1]);
-        
+
         if (argc-1 > 1)
             pm_error("Too many arguments.  The only possible argument is "
                      "the input fil name");
@@ -82,9 +82,8 @@ main(int argc, const char ** argv)  {
 
     pbm_freerow_packed(bitrow);
     pm_close(ifP);
-    
+
     return 0;
 }
 
 
-
diff --git a/converter/pbm/pbmtox10bm b/converter/pbm/pbmtox10bm
index deb3aeab..ca82fcd2 100644
--- a/converter/pbm/pbmtox10bm
+++ b/converter/pbm/pbmtox10bm
@@ -37,6 +37,16 @@ exec perl -w -x -S -- "$0" "$@"
 use strict;
 use File::Basename;
 use Cwd 'abs_path';
+use IO::Handle;
+
+
+
+sub pm_message($) {
+    STDERR->print("pbmtox10bm: $_[0]\n");
+}
+
+
+
 
 sub doVersionHack($) {
     my ($argvR) = @_;
@@ -56,13 +66,12 @@ my $infile;
 foreach (@ARGV) {
     if (/^-/) {
         # It's an option.  But Pbmtox10bm didn't have any options.
-        print(STDERR "Invalid option '$_'\n");
+        pm_message("Invalid option '$_'");
         exit(10);
     } else {
         # It's a parameter
         if (defined($infile)) {
-            print(STDERR
-                  "You may specify at most one non-option parameter.\n");
+            pm_message("You may specify at most one non-option parameter.");
             exit(10);
         } else {
             $infile = $_;
diff --git a/converter/pbm/xbmtopbm.c b/converter/pbm/xbmtopbm.c
index bbf4e395..1f5384ed 100644
--- a/converter/pbm/xbmtopbm.c
+++ b/converter/pbm/xbmtopbm.c
@@ -109,25 +109,35 @@ parseDeclaration(const char * const line,
 -----------------------------------------------------------------------------*/
     char nameAndType[MAX_LINE];
     int rc;
-        
+
     rc = sscanf(line, "static short %s = {", nameAndType);
     if (rc == 1) {
         *version10P     = TRUE;
         *isDeclarationP = TRUE;
     } else {
         int rc;
-        rc = sscanf(line, "static char %s = {", nameAndType);
+        rc = sscanf(line, "static unsigned short %s = {", nameAndType);
         if (rc == 1) {
-            *version10P     = FALSE;
+            /* This is apparently not legal X10 XBM; we recognize it as an
+               extension.  Many non-Netpbm programs won't.
+            */
+            *version10P     = TRUE;
             *isDeclarationP = TRUE;
         } else {
             int rc;
-            rc = sscanf(line, "static unsigned char %s = {", nameAndType);
+            rc = sscanf(line, "static char %s = {", nameAndType);
             if (rc == 1) {
                 *version10P     = FALSE;
                 *isDeclarationP = TRUE;
-            } else
-                *isDeclarationP = FALSE;
+            } else {
+                int rc;
+                rc = sscanf(line, "static unsigned char %s = {", nameAndType);
+                if (rc == 1) {
+                    *version10P     = FALSE;
+                    *isDeclarationP = TRUE;
+                } else
+                    *isDeclarationP = FALSE;
+            }
         }
     }
 }
@@ -178,7 +188,7 @@ getXbmHeader(FILE *         const ifP,
         }
     }
 
-    if (!foundDeclaration) 
+    if (!foundDeclaration)
         pm_error("Unable to find a line in the file containing the start "
                  "of C array declaration (\"static char\" or whatever)");
 
@@ -208,7 +218,7 @@ getHexByte(FILE *         const ifP,
 
     assert(c1 >= 0); assert(c1 < 256);
     assert(c2 >= 0); assert(c2 < 256);
-    
+
     value = (hexTable[c1] << 4) + hexTable[c2];
     if (value >= 256)
         pm_error("Invalid XBM input.  What should be a two digit "
@@ -218,7 +228,7 @@ getHexByte(FILE *         const ifP,
 }
 
 
-                     
+
 static void
 readX10Raster(FILE *          const ifP,
               unsigned int    const rasterLength,
@@ -301,7 +311,7 @@ readBitmapFile(FILE *           const ifP,
     mustPad = (width % 16 >= 1 && width % 16 <= 8 && version10);
 
     bytesPerLine = (width + 7) / 8 + (mustPad ? 1 : 0);
-    
+
     rasterLength = bytesPerLine * height;
 
     MALLOCARRAY(data, rasterLength);
@@ -331,7 +341,7 @@ main(int    argc,
     const char * inputFileName;
     unsigned char * p;
         /* Cursor in raster data data[] */
-    
+
     initHexTable();
 
     pbm_init(&argc, argv);
@@ -339,7 +349,7 @@ main(int    argc,
     if (argc-1 > 1)
         pm_error("The only possible argument is the input file name.  "
                  "You specified %u arguments", argc-1);
-    
+
     if (argc-1 > 0)
         inputFileName = argv[1];
     else
@@ -359,7 +369,7 @@ main(int    argc,
     for (row = 0; row < rows; ++row) {
         unsigned int const bytesPerRow = pbm_packed_bytes(cols);
         unsigned int i;
-        
+
         for (i = 0; i < bytesPerRow; ++i)
             bitrow[i] = bitreverse[*p++];
 
diff --git a/converter/pbm/ybmtopbm.c b/converter/pbm/ybmtopbm.c
index ea7e66a7..36f2dee7 100644
--- a/converter/pbm/ybmtopbm.c
+++ b/converter/pbm/ybmtopbm.c
@@ -19,7 +19,7 @@ static short const ybmMagic = ( ( '!' << 8 ) | '!' );
 
 
 static void
-getinit(FILE *  const ifP,
+getinit(FILE *         const ifP,
         unsigned int * const colsP,
         unsigned int * const rowsP,
         int *          const depthP) {
@@ -80,7 +80,7 @@ main(int argc, const char * argv[]) {
     getinit(ifP, &cols, &rows, &depth);
     if (depth != 1)
         pm_error("YBM file has depth of %u, must be 1", (unsigned int) depth);
-    
+
     pbm_writepbminit(stdout, cols, rows, 0);
 
     bitrow = pbm_allocrow_packed(cols + 8);
@@ -95,7 +95,7 @@ main(int argc, const char * argv[]) {
         for (i = 0; i < itemCt; ++i) {
             short int item;
             pm_readbigshort(ifP, &item);
-            itemrow[i] = (uint16_t) item; 
+            itemrow[i] = (uint16_t) item;
         }
 
         for (i = 0; i < pbm_packed_bytes(cols); ++i)
diff --git a/converter/pgm/rawtopgm.c b/converter/pgm/rawtopgm.c
index 2e5fbb7d..7eb68694 100644
--- a/converter/pgm/rawtopgm.c
+++ b/converter/pgm/rawtopgm.c
@@ -10,6 +10,7 @@
 ** implied warranty.
 */
 
+#include <stdbool.h>
 #include <math.h>
 
 #include "pm_c_util.h"
@@ -17,7 +18,7 @@
 #include "shhopt.h"
 #include "pgm.h"
 
-struct cmdline_info {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
@@ -37,8 +38,8 @@ struct cmdline_info {
 
 
 static void
-parse_command_line(int argc, char ** argv,
-                   struct cmdline_info *cmdlineP) {
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that the file spec array we return is stored in the storage that
    was passed to us as the argv array.
@@ -73,7 +74,7 @@ parse_command_line(int argc, char ** argv,
             NULL,   0);
 
     /* Set the defaults */
-    cmdlineP->bottomfirst = FALSE;
+    cmdlineP->bottomfirst = false;
     cmdlineP->headerskip = 0;
     cmdlineP->rowskip = 0.0;
     cmdlineP->bpp = 1;
@@ -81,33 +82,33 @@ parse_command_line(int argc, char ** argv,
     cmdlineP->maxval = -1;
 
     opt.opt_table = option_def;
-    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
-    opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;  /* We may have parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
+    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
     if (argc-1 == 0) {
         cmdlineP->inputFileName = "-";
-        cmdlineP->autosize = TRUE;
+        cmdlineP->autosize = true;
     } else if (argc-1 == 1) {
         cmdlineP->inputFileName = argv[1];
-        cmdlineP->autosize = TRUE;
+        cmdlineP->autosize = true;
     } else if (argc-1 == 2) {
         cmdlineP->inputFileName = "-";
-        cmdlineP->autosize = FALSE;
+        cmdlineP->autosize = false;
         cmdlineP->width = pm_parse_width(argv[1]);
         cmdlineP->height = pm_parse_height(argv[2]);
     } else if (argc-1 == 3) {
         cmdlineP->inputFileName = argv[3];
-        cmdlineP->autosize = FALSE;
+        cmdlineP->autosize = false;
         cmdlineP->width = pm_parse_width(argv[1]);
         cmdlineP->height = pm_parse_height(argv[2]);
     } else
         pm_error("Program takes zero, one, two, or three arguments.  You "
                  "specified %d", argc-1);
 
-    if (cmdlineP->bpp != 1 && cmdlineP->bpp != 2) 
+    if (cmdlineP->bpp != 1 && cmdlineP->bpp != 2)
         pm_error("Bytes per pixel (-bpp) must be 1 or 2.  You specified %d.",
                  cmdlineP->bpp);
 
@@ -125,7 +126,7 @@ parse_command_line(int argc, char ** argv,
         pm_error("If you specify -rowskip, you must also give the image "
                  "dimensions.");
     if (cmdlineP->rowskip && cmdlineP->bottomfirst)
-        pm_error("You canot specify both -rowskip and -bottomfirst.  This is "
+        pm_error("You cannot specify both -rowskip and -bottomfirst.  This is "
                  "a limitation of this program.");
 
 }
@@ -133,52 +134,59 @@ parse_command_line(int argc, char ** argv,
 
 
 static void
-compute_image_size(const struct cmdline_info cmdline, const long nread,
-                   int * const rows_p, int * const cols_p) {
+computeImageSize(struct CmdlineInfo const cmdline,
+                 long               const nRead,
+                 unsigned int *     const rowsP,
+                 unsigned int *     const colsP) {
 
     if (cmdline.autosize) {
-        int sqrt_trunc = 
-            (int) sqrt((double) (nread-cmdline.headerskip));
-        if (sqrt_trunc*sqrt_trunc+cmdline.headerskip != nread) 
+        int sqrtTrunc =
+            (int) sqrt((double) (nRead - cmdline.headerskip));
+        if (sqrtTrunc * sqrtTrunc + cmdline.headerskip != nRead)
             pm_error( "You must specify the dimensions of the image unless "
                       "it is a quadratic image.  This one is not quadratic: "
                       "The number of "
                       "pixels in the input is %ld, which is not a perfect "
-                      "square.", nread-cmdline.headerskip);
-        *rows_p = *cols_p = sqrt_trunc;
-        pm_message( "Image size: %d cols, %d rows", *cols_p, *rows_p);
+                      "square.", nRead - cmdline.headerskip);
+        *rowsP = *colsP = sqrtTrunc;
+        pm_message( "Image size: %u cols, %u rows", *colsP, *rowsP);
     } else {
-        *rows_p = cmdline.height;
-        *cols_p = cmdline.width;
+        *rowsP = cmdline.height;
+        *colsP = cmdline.width;
     }
 }
 
 
 
 static void
-skip_header(FILE *ifp, const int headerskip) {
+skipHeader(FILE *       const ifP,
+           unsigned int const headerskip) {
+
     int i;
 
-    for ( i = 0; i < headerskip; ++i ) {
+    for (i = 0; i < headerskip; ++i) {
         /* Read a byte out of the file */
         int val;
-        val = getc( ifp );
-        if ( val == EOF )
-            pm_error("EOF / read error reading Byte %d in the header", i );
+        val = getc(ifP);
+        if (val == EOF)
+            pm_error("EOF / read error reading Byte %u in the header", i );
     }
 }
 
 
 
 static gray
-read_from_file(FILE *ifp, const int bpp, const int row, const int col,
-               const int littleendian) {
+readFromFile(FILE *        const ifP,
+             unsigned int  const bpp,
+             unsigned int  const row,
+             unsigned int  const col,
+             bool          const littleEndian) {
 /*----------------------------------------------------------------------------
-   Return the next sample value from the input file 'ifp', assuming the
+   Return the next sample value from the input file *ifP, assuming the
    input stream is 'bpp' bytes per pixel (1 or 2).  In the case of two
-   bytes, if 'littleendian', assume least significant byte is first.
+   bytes, if 'littleEndian', assume least significant byte is first.
    Otherwise, assume MSB first.
-   
+
    In error messages, say this is Column 'col', Row 'row'.  Exit program if
    error.
 -----------------------------------------------------------------------------*/
@@ -186,18 +194,18 @@ read_from_file(FILE *ifp, const int bpp, const int row, const int col,
 
     if (bpp == 1) {
         int val;
-        val = getc(ifp);
+        val = getc(ifP);
         if (val == EOF)
-            pm_error( "EOF / read error at Row %d Column %d",
+            pm_error( "EOF / read error at Row %u Column %u",
                       row, col);
         retval = (gray) val;
     } else {
         short val;
         int rc;
-        rc = littleendian ? 
-            pm_readlittleshort(ifp, &val) : pm_readbigshort(ifp, &val);
+        rc = littleEndian ?
+            pm_readlittleshort(ifP, &val) : pm_readbigshort(ifP, &val);
         if (rc != 0)
-            pm_error( "EOF / read error at Row %d Column %d",
+            pm_error( "EOF / read error at Row %u Column %u",
                       row, col);
         retval = (gray) val;
     }
@@ -207,87 +215,93 @@ read_from_file(FILE *ifp, const int bpp, const int row, const int col,
 
 
 int
-main(int argc, char *argv[] ) {
+main(int argc, const char ** argv) {
 
-    struct cmdline_info cmdline;
-    FILE* ifp;
-    gray* grayrow;
-    int rows, cols;
+    struct CmdlineInfo cmdline;
+    FILE * ifP;
+    gray * grayrow;
+    unsigned int rows, cols;
     gray maxval;
-    char* buf;
-    /* pixels_1 and pixels_2 are the array of pixels in the input buffer
-       (assuming we are using an input buffer).  pixels_1 is the array
-       as if the pixels are one byte each.  pixels_2 is the array as if
+    char * buf;
+    /* pixels1 and pixels2 are the array of pixels in the input buffer
+       (assuming we are using an input buffer).  pixels1 is the array
+       as if the pixels are one byte each.  pixels2 is the array as if
        they are two bytes each.
        */
-    unsigned char *pixels_1;  
-    unsigned short *pixels_2;
-    long nread;
-    int row;
+    unsigned char * pixels1;
+    unsigned short * pixels2;
+    long nRead;
+    unsigned int row;
     float toskip;
 
-    pgm_init( &argc, argv );
+    pm_proginit(&argc, argv);
 
-    parse_command_line(argc, argv, &cmdline);
+    parseCommandLine(argc, argv, &cmdline);
 
-    ifp = pm_openr(cmdline.inputFileName);
+    ifP = pm_openr(cmdline.inputFileName);
 
     if (cmdline.autosize || cmdline.bottomfirst) {
-        buf = pm_read_unknown_size( ifp, &nread );
-        pixels_1 = (unsigned char *) buf;
-        pixels_2 = (unsigned short *) buf;
+        buf = pm_read_unknown_size(ifP, &nRead);
+        pixels1 = (unsigned char *) buf;
+        pixels2 = (unsigned short *) buf;
     } else
         buf = NULL;
 
-    compute_image_size(cmdline, nread, &rows, &cols);
+    computeImageSize(cmdline, nRead, &rows, &cols);
 
     if (!buf)
-        skip_header(ifp, cmdline.headerskip);
+        skipHeader(ifP, cmdline.headerskip);
 
     toskip = 0.00001;
 
     if (cmdline.maxval == -1)
         maxval = (cmdline.bpp == 1 ? (gray) 255 : (gray) 65535);
     else
-        maxval = (gray) cmdline.maxval;
+        maxval = cmdline.maxval;
 
-    pgm_writepgminit( stdout, cols, rows, maxval, 0 );
-    grayrow = pgm_allocrow( cols );
+    pgm_writepgminit(stdout, cols, rows, maxval, 0);
 
-    for ( row = 0; row < rows; ++row) {
-        int col;
+    grayrow = pgm_allocrow(cols);
+
+    for (row = 0; row < rows; ++row) {
+        unsigned int col;
         unsigned int rowpos; /* index of this row in pixel array */
+
         if (cmdline.bottomfirst)
             rowpos = (rows-row-1) * cols;
         else
             rowpos = row * cols;
 
-        for ( col = 0; col < cols; ++col )
+        for (col = 0; col < cols; ++col) {
             if (buf) {
                 if (cmdline.bpp == 1)
-                    grayrow[col] = pixels_1[rowpos+col];
+                    grayrow[col] = pixels1[rowpos+col];
                 else
-                    grayrow[col] = pixels_2[rowpos+col];
+                    grayrow[col] = pixels2[rowpos+col];
             } else {
-                grayrow[col] = read_from_file(ifp, cmdline.bpp, 
-                                              row, col,
-                                              cmdline.littleendian);
+                grayrow[col] = readFromFile(ifP, cmdline.bpp,
+                                            row, col,
+                                            cmdline.littleendian > 0);
             }
-        for ( toskip += cmdline.rowskip; toskip >= 1.0; toskip -= 1.0 ) {
+        }
+        for (toskip += cmdline.rowskip; toskip >= 1.0; toskip -= 1.0) {
             /* Note that if we're using a buffer, cmdline.rowskip is zero */
             int val;
-            val = getc( ifp );
-            if ( val == EOF )
-                pm_error( "EOF / read error skipping bytes at the end "
-                          "of Row %d.", row);
+            val = getc(ifP);
+            if (val == EOF)
+                pm_error("EOF / read error skipping bytes at the end "
+                         "of Row %u.", row);
         }
-        pgm_writepgmrow( stdout, grayrow, cols, maxval, 0 );
+        pgm_writepgmrow(stdout, grayrow, cols, maxval, 0);
     }
-    
+
     if (buf)
         free(buf);
-    pm_close( ifp );
-    pm_close( stdout );
+    pm_close(ifP);
+    pm_close(stdout);
 
-    exit( 0 );
+    return 0;
 }
+
+
+
diff --git a/converter/pgm/st4topgm.c b/converter/pgm/st4topgm.c
index 8e4660a3..791184b7 100644
--- a/converter/pgm/st4topgm.c
+++ b/converter/pgm/st4topgm.c
@@ -69,11 +69,11 @@ writeRaster(FILE *       const ifP,
         unsigned int col;
 
         for (col = 0; col < st4Width; ++col) {
-            char c;
+            unsigned char c;
 
-            pm_readchar(ifP, &c);
+            pm_readcharu(ifP, &c);
 
-            tuplerow[col][0] = (unsigned char)c;
+            tuplerow[col][0] = c;
         }
         pnm_writepamrow(pamP, tuplerow);
     }
@@ -149,7 +149,7 @@ readFooter(FILE *             const ifP,
        109  10 Calibration factor
        119  73 Reserved
 
-       Note tha the footer is the same length as a raster row.
+       Note that the footer is the same length as a raster row.
     */
 
     bytesReadCt = fread(buffer, 1, sizeof(buffer), ifP);
diff --git a/converter/ppm/hpcdtoppm/Makefile b/converter/ppm/hpcdtoppm/Makefile
index 5777a84f..9633017e 100644
--- a/converter/ppm/hpcdtoppm/Makefile
+++ b/converter/ppm/hpcdtoppm/Makefile
@@ -7,11 +7,29 @@ VPATH=.:$(SRCDIR)/$(SUBDIR)
 
 include $(BUILDDIR)/config.mk
 
-all: hpcdtoppm
+SCRIPTS =  pcdovtoppm
+
+ifeq ($(file <hpcdtoppm-import/Makefile)x,x)
+  # The file does not exist, which means user did not augment the
+  # Netpbm source tree by adding hpcdtoppm source code.
+  #
+  # Therefore, we package the dummy 'hpcdtoppm' program that just tells the
+  # user how to get the real one.
+  #
+  # See README in this directory.
+  #
+  # (Note that empty file and nonexistent file look the same with
+  # $(file)).
+  SCRIPTS += hpcdtoppm
+else
+  SUBDIRS += hpcdtoppm-import
+endif
 
-SCRIPTS = hpcdtoppm pcdovtoppm
 MERGE_OBJECTS =
 
+.PHONY: all
+all: $(BINARIES) $(SUBDIRS:%=%/all)
+
 include $(SRCDIR)/common.mk
 
 install.bin install.merge: install.bin.local
diff --git a/converter/ppm/hpcdtoppm/README b/converter/ppm/hpcdtoppm/README
index a1c7c8c2..ec23ec1b 100644
--- a/converter/ppm/hpcdtoppm/README
+++ b/converter/ppm/hpcdtoppm/README
@@ -1,20 +1,25 @@
-This 'hpcdtoppm' directory is really just a placeholder for the real
-Hpcdtoppm source code.  
+The 'hpcdtoppm' code in this directory is just a dummy version of the program
+that tells you where to get the real code.
 
-The real Hpcdtoppm source code cannot be distributed on Sourceforge
-because a copyright holder does not license it in a way open enough to
-meet Sourceforge's requirements.
+The real "hpcdtoppm' source code cannot be distributed on Sourceforge because
+a copyright holder does not license it in a way open enough to meet
+Sourceforge's requirements.
 
-Therefore, the Netpbm maintainer distributes Hpcdtoppm via another channel
-and distributes this dummy directory in the main Netpbm source tree on 
-Sourceforge.  When you run the program named 'hpcdtoppm' in this directory,
-it tells you how to get the real Hpcdtoppm.
+Therefore, the Netpbm maintainer distributes 'hpcdtoppm' via another channel
+and distributes this dummy directory in the main Netpbm source tree on
+Sourceforge.
 
-When you get the real Hpcdtoppm tarball, just unpack it and replace
-this entire 'hpcdtoppm' directory with its contents.  Then build
-Netpbm normally.
+The code is at 
+
+  http://ibiblio.org/pub/Linux/apps/graphics/convert/hpcdtoppm-netpbm.tgz
+
+When you get the real 'hpcdtoppm' tarball, just unpack its contents into the
+'hpcdtoppm-import' subdirectory.  Then build Netpbm normally.  The build
+detects the presence of the code and builds and packages the real 'hpcdtoppm'
+program instead of the dummy one.
+
+Bear in mind when you get the real 'hpcdtoppm' that it is not as openly
+licensed as what's in the rest of the Netpbm source tree.  As you'll see in
+the license that comes with 'hpcdtoppm', you may _not_ sell it to someone
+else.)
 
-Bear in mind when you get the real Hpcdtoppm, that it is not as openly
-licensed as what's in the rest of the Netpbm source tree.  As you'll
-see in the license that comes with Hpcdtoppm, you may _not_ sell it to
-someone else.)
diff --git a/converter/ppm/hpcdtoppm/hpcdtoppm b/converter/ppm/hpcdtoppm/hpcdtoppm
index 2af4a384..2a61aa9d 100755
--- a/converter/ppm/hpcdtoppm/hpcdtoppm
+++ b/converter/ppm/hpcdtoppm/hpcdtoppm
@@ -8,18 +8,16 @@ The real 'hpcdtoppm' is a program that converts an image from Photo CD format
 to PPM format.  The program you are running now just issues the message you
 are reading.
 
-Please get a copy of Hpcdtoppm from 
-
-  http://terasaur.org/item/show/hpcdtoppm-netpbm-convert-photo-cd/4967
-
-and replace this stand-in program with the real one.
+Instructions for getting the 'hpcdtoppm' source code and building it into
+Netpbm are in the file converter/ppm/hpcdtoppm/README in the distributed
+Netpbm source tree.
 
 The point of this is that this stand-in 'hpcdtoppm' is distributed with Netpbm
-on Sourceforge.  Hpcdtoppm does not meet the requirements to be distributed on
-Sourceforge because a copyright holder does not permit people to sell copies.
-At one time, the real Hpcdtoppm was distributed with Netpbm on Sourceforge by
-mistake.
+on Sourceforge.  'hpcdtoppm' does not meet the requirements to be distributed
+on Sourceforge because a copyright holder does not permit people to sell
+copies.  At one time, the real 'hpcdtoppm' was distributed with Netpbm on
+Sourceforge by mistake.
 
 EOF
 
-exit 1
\ No newline at end of file
+exit 1
diff --git a/converter/ppm/hpcdtoppm/pcdovtoppm b/converter/ppm/hpcdtoppm/pcdovtoppm
index 01a68313..2a875690 100755
--- a/converter/ppm/hpcdtoppm/pcdovtoppm
+++ b/converter/ppm/hpcdtoppm/pcdovtoppm
@@ -19,12 +19,16 @@
 # Rewritten in sh by Steve McIntyre <93sam@debian.org>, 2001
 
 # You may want to change the default values in the next 6 lines:
-maxwidth=1152   # maximum width of the index image
-size=192                # make the images about this big
-across=6                # show this many images per row
-colors="noquant"        # maximum amount of colors or noquant (no quantization)
-back="-black"   # default background color
-font=" "                # default font or none (pbmtext's internal font)
+maxwidth=1152     # maximum width of the index image
+size=192          # make the images about this big
+across=6          # show this many images per row
+colors="noquant"  # maximum amount of colors or noquant (no quantization)
+back="-black"     # default background color
+font=" "          # default font or none (pbmtext's internal font)
+
+plainopt=""       # output plain ppm
+quietopt=""       # quiet operation (currently no effect)
+versionopt=0
 
 usage ()
 {
@@ -47,79 +51,108 @@ usage ()
     exit 1
 }
 
+version ()
+{
+    # report version using pnmscale
+    pnmscale -version $quietopt
+    exit 0
+}
+
 # Parse the options
 while :; do
     case "$1" in 
-        -m*)
+        -m|-ma|-max|-maxw|-maxwi|-maxwid|-maxwidt|-maxwidth )
              if [ $# -lt 2 ] ; then usage; fi
              maxwidth="$2"
              shift
              shift
              ;;
 
-        -s*)
+        -s|-si|-siz|-size )
              if [ $# -lt 2 ] ; then usage; fi
              size="$2"
              shift
              shift
              ;;
 
-            -a*)
-                if [ $# -lt 2 ] ; then usage; fi
-                across="$2"
-                shift
-                shift
-                ;;
-
-            -c*)
-                if [ $# -lt 2 ] ; then usage; fi
-                colors="$2"
-                shift
-                shift
-                ;;
-
-            -f*)
-                if [ $# -lt 2 ] ; then usage; fi
-                font="-font $2"
-                shift
-                shift
-                ;;
-
-            -b*)
-                back="-black"
-                shift
-                ;;
-
-            -w*)
-                back="-white"
-                shift
-                ;;
-
-            -*)
-                echo "$0 : Unknown option $1"
-                echo " "
-                usage
-                ;;
-
-            *)
-                break
-                ;;
+         -a|-ac|-acr|-acro|-acros|-across )
+             if [ $# -lt 2 ] ; then usage; fi
+             across="$2"
+             shift
+             shift
+             ;;
+
+         -c|-co|-col|-colo|-color|-colors )
+             if [ $# -lt 2 ] ; then usage; fi
+             colors="$2"
+             shift
+             shift
+             ;;
+
+         -f|-fo|-fon|-font )
+             if [ $# -lt 2 ] ; then usage; fi
+             font="-font $2"
+             shift
+             shift
+             ;;
+
+         -b|-bl|-bla|-blac|-black )
+             back="-black"
+             shift
+             ;;
+
+         -w|-wh|-whi|-whit|-white )
+             back="-white"
+             shift
+             ;;
+             
+         -p|-pl|-pla|-plai|-plain )
+             plainopt="-plain"
+             shift
+             ;;
+            
+         -q|-qu|-qui|-quie|-quiet )
+             quietopt="-quiet"
+             shift
+             ;;
+             
+         -v|-ve|-ver|-vers|-versi|-versio|-version )
+             versionopt="1"
+             shift
+             ;;
+                    
+         -*)
+             echo "$0 : Unknown option $1" 1>&2
+             echo " " 1>&2
+             usage
+             ;;
+
+         *)
+             break
+             ;;
 
     esac
 done
 
-if [ $# = 0 ]; then
+if [ $versionopt -eq 1 ] ; then
+    version
+elif [ $# -eq 0 ] ; then
     usage
 fi
 
-tmpfile=`tempfile -p pi -m 600`
+tempdir=$(mktemp -d "${TMPDIR:-/tmp}/pcdovtoppm.XXXXXXXX") ||
+    { echo "Could not create temporary file. Exiting." 1>&2; exit 1; }
+trap 'rm -rf $tempdir' 0
+
+tmpfile=$(mktemp --tmpdir piXXXXXX)
 
 # Convert the PCD overview file to many PPM images
 if [ -f $1 ] ; then
-    hpcdtoppm -Overview $1 $tmpfile
+    hpcdtoppm -Overview $1 $tmpfile ||
+        { echo "$0: Hpcdtoppm failed. Exiting" 1>&2 ; exit 1; }
 else
-    echo "$0 : Could not access $1"
-    echo " "
+    echo "$0 : Could not access $1" 1>&2
+    echo " " 1>&2
     usage
 fi
 
@@ -145,16 +178,17 @@ do
             fi
         fi
     fi
-    imagefile=pi.${row}.${col}.$$
+    imagefile=${tempdir}/pi.${row}.${col}
     rm -f $imagefile
     ttext="$i:t"
 
     if [ "$back" = "-white" ] ; then
-        pbmtext $font "$ttext" | pnmcrop -quiet | pnmmargin -white 2| \
-        pnmcat $back -tb $tmpfile - > $imagefile
+        pbmtext $font "$ttext" | pnmcrop -quiet | pnmmargin -white 2 | \
+        pamcat $back -topbottom $tmpfile - > $imagefile
     else
         pbmtext $font "$ttext" | pnmcrop -quiet | pnmmargin -white 2 | \
-        pnminvert | pnmcat $back -tb $tmpfile - > $imagefile
+          pnminvert | \
+          pamcat $back -topbottom $tmpfile - > $imagefile
     fi
 
     rm -f $tmpfile
@@ -163,12 +197,12 @@ do
     imagefiles="$imagefiles $imagefile"
 
     if [ $col -ge $across -o $width -gt $maxwidth ] ; then
-        rowfile=pi.${row}.$$
+        rowfile=${tempdir}/pi.${row}
         rm -f $rowfile
     if [ "$colors" = "n" ] ; then
-        pnmcat $back -lr -jbottom $imagefiles > $rowfile
+        pamcat $back -leftright -jbottom $imagefiles > $rowfile
     else
-        pnmcat $back -lr -jbottom $imagefiles | \
+        pamcat $back -leftright -jbottom $imagefiles | \
         ppmquant -quiet $colors > $rowfile
     fi
     rm -f $imagefiles
@@ -183,25 +217,27 @@ do
 done
 
 if [ -n $imagefiles ] ; then
-    rowfile=pi.${row}.$$
+    rowfile=${tempdir}/pi.${row}
     rm -f $rowfile
     if [ "$colors" = "n" ] ; then
-        pnmcat $back -lr -jbottom $imagefiles > $rowfile
+        pamcat $back -leftright -jbottom $imagefiles > $rowfile
     else
-        pnmcat $back -lr -jbottom $imagefiles | \
-        ppmquant -quiet $colors > $rowfile
+        pamcat $back -leftright -jbottom $imagefiles | \
+          ppmquant -quiet $colors > $rowfile
     fi
     rm -f $imagefiles
     rowfiles="$rowfiles $rowfile"
 fi
 
 if [ $(echo $rowfiles|wc -w) -eq 1 ] ; then
-    cat $rowfiles
+    ppmtoppm $plainopt < $rowfiles
 else
     if [ "$colors" = "n" ] ; then
-        pnmcat $back -tb $rowfiles
+        pamcat $back -topbottom $rowfiles | \
+          ppmtoppm $plainopt
     else
-        pnmcat $back -tb $rowfiles | ppmquant -quiet $colors
+        pamcat $back -tb $rowfiles | \
+          ppmquant $plainopt -quiet $colors
     fi
 fi
 
@@ -210,5 +246,3 @@ rm -f $rowfiles
 exit 0
 
 
-
-
diff --git a/converter/ppm/ilbm.h b/converter/ppm/ilbm.h
index dbe47758..c0fac7d2 100644
--- a/converter/ppm/ilbm.h
+++ b/converter/ppm/ilbm.h
@@ -25,8 +25,8 @@ typedef struct {
 #define mskHasTransparentColor  2
 #define mskLasso                3       /* can't handle this */
 #define mskMAXKNOWN             mskLasso
-static const char * mskNAME[] = { 
-    "none", "mask plane", "transparent color", "lasso" 
+static const char * mskNAME[] = {
+    "none", "mask plane", "transparent color", "lasso"
 };
 
 #define cmpNone                 0
@@ -147,98 +147,98 @@ typedef unsigned long   IFF_ID;
 #define MAKE_ID(a, b, c, d) \
     ((IFF_ID)(a)<<24 | (IFF_ID)(b)<<16 | (IFF_ID)(c)<<8 | (IFF_ID)(d))
 
-#define ID_FORM     MAKE_ID('F', 'O', 'R', 'M')     
+#define ID_FORM     MAKE_ID('F', 'O', 'R', 'M')
     /* EA IFF 85 group identifier */
-#define ID_CAT      MAKE_ID('C', 'A', 'T', ' ')     
+#define ID_CAT      MAKE_ID('C', 'A', 'T', ' ')
     /* EA IFF 85 group identifier */
-#define ID_LIST     MAKE_ID('L', 'I', 'S', 'T')     
+#define ID_LIST     MAKE_ID('L', 'I', 'S', 'T')
     /* EA IFF 85 group identifier */
-#define ID_PROP     MAKE_ID('P', 'R', 'O', 'P')     
+#define ID_PROP     MAKE_ID('P', 'R', 'O', 'P')
     /* EA IFF 85 group identifier */
-#define ID_END      MAKE_ID('E', 'N', 'D', ' ')     
+#define ID_END      MAKE_ID('E', 'N', 'D', ' ')
     /* unofficial END-of-FORM identifier (see Amiga RKM Devices Ed.3
        page 376) */
-#define ID_ILBM     MAKE_ID('I', 'L', 'B', 'M')     
+#define ID_ILBM     MAKE_ID('I', 'L', 'B', 'M')
     /* EA IFF 85 raster bitmap form */
-#define ID_DEEP     MAKE_ID('D', 'E', 'E', 'P')     
+#define ID_DEEP     MAKE_ID('D', 'E', 'E', 'P')
     /* Chunky pixel image files (Used in TV Paint) */
-#define ID_RGB8     MAKE_ID('R', 'G', 'B', '8')     
+#define ID_RGB8     MAKE_ID('R', 'G', 'B', '8')
     /* RGB image forms, Turbo Silver (Impulse) */
-#define ID_RGBN     MAKE_ID('R', 'G', 'B', 'N')     
+#define ID_RGBN     MAKE_ID('R', 'G', 'B', 'N')
     /* RGB image forms, Turbo Silver (Impulse) */
-#define ID_PBM      MAKE_ID('P', 'B', 'M', ' ')     
+#define ID_PBM      MAKE_ID('P', 'B', 'M', ' ')
     /* 256-color chunky format (DPaint 2 ?) */
-#define ID_ACBM     MAKE_ID('A', 'C', 'B', 'M')     
+#define ID_ACBM     MAKE_ID('A', 'C', 'B', 'M')
     /* Amiga Contiguous Bitmap (AmigaBasic) */
 
 /* generic */
 
-#define ID_FVER     MAKE_ID('F', 'V', 'E', 'R')     
+#define ID_FVER     MAKE_ID('F', 'V', 'E', 'R')
     /* AmigaOS version string */
-#define ID_JUNK     MAKE_ID('J', 'U', 'N', 'K')     
+#define ID_JUNK     MAKE_ID('J', 'U', 'N', 'K')
     /* always ignore this chunk */
-#define ID_ANNO     MAKE_ID('A', 'N', 'N', 'O')     
+#define ID_ANNO     MAKE_ID('A', 'N', 'N', 'O')
     /* EA IFF 85 Generic Annotation chunk */
-#define ID_AUTH     MAKE_ID('A', 'U', 'T', 'H')     
+#define ID_AUTH     MAKE_ID('A', 'U', 'T', 'H')
     /* EA IFF 85 Generic Author chunk */
-#define ID_CHRS     MAKE_ID('C', 'H', 'R', 'S')     
+#define ID_CHRS     MAKE_ID('C', 'H', 'R', 'S')
     /* EA IFF 85 Generic character string chunk */
-#define ID_NAME     MAKE_ID('N', 'A', 'M', 'E')     
+#define ID_NAME     MAKE_ID('N', 'A', 'M', 'E')
     /* EA IFF 85 Generic Name of art, music, etc. chunk */
-#define ID_TEXT     MAKE_ID('T', 'E', 'X', 'T')     
+#define ID_TEXT     MAKE_ID('T', 'E', 'X', 'T')
     /* EA IFF 85 Generic unformatted ASCII text chunk */
-#define ID_copy     MAKE_ID('(', 'c', ')', ' ')     
+#define ID_copy     MAKE_ID('(', 'c', ')', ' ')
 /* EA IFF 85 Generic Copyright text chunk */
 
 /* ILBM chunks */
 
-#define ID_BMHD     MAKE_ID('B', 'M', 'H', 'D')     
+#define ID_BMHD     MAKE_ID('B', 'M', 'H', 'D')
     /* ILBM BitmapHeader */
-#define ID_CMAP     MAKE_ID('C', 'M', 'A', 'P')     
+#define ID_CMAP     MAKE_ID('C', 'M', 'A', 'P')
     /* ILBM 8bit RGB colormap */
-#define ID_GRAB     MAKE_ID('G', 'R', 'A', 'B')     
-    /* ILBM "hotspot" coordiantes */
-#define ID_DEST     MAKE_ID('D', 'E', 'S', 'T')     
+#define ID_GRAB     MAKE_ID('G', 'R', 'A', 'B')
+    /* ILBM "hotspot" coordinates */
+#define ID_DEST     MAKE_ID('D', 'E', 'S', 'T')
     /* ILBM destination image info */
-#define ID_SPRT     MAKE_ID('S', 'P', 'R', 'T')     
+#define ID_SPRT     MAKE_ID('S', 'P', 'R', 'T')
     /* ILBM sprite identifier */
-#define ID_CAMG     MAKE_ID('C', 'A', 'M', 'G')     
+#define ID_CAMG     MAKE_ID('C', 'A', 'M', 'G')
     /* Amiga viewportmodes */
-#define ID_BODY     MAKE_ID('B', 'O', 'D', 'Y')     
+#define ID_BODY     MAKE_ID('B', 'O', 'D', 'Y')
     /* ILBM image data */
-#define ID_CRNG     MAKE_ID('C', 'R', 'N', 'G')     
+#define ID_CRNG     MAKE_ID('C', 'R', 'N', 'G')
     /* color cycling */
-#define ID_CCRT     MAKE_ID('C', 'C', 'R', 'T')     
+#define ID_CCRT     MAKE_ID('C', 'C', 'R', 'T')
     /* color cycling */
-#define ID_CLUT     MAKE_ID('C', 'L', 'U', 'T')     
+#define ID_CLUT     MAKE_ID('C', 'L', 'U', 'T')
     /* Color Lookup Table chunk */
-#define ID_DPI      MAKE_ID('D', 'P', 'I', ' ')     
+#define ID_DPI      MAKE_ID('D', 'P', 'I', ' ')
     /* Dots per inch chunk */
-#define ID_DPPV     MAKE_ID('D', 'P', 'P', 'V')     
+#define ID_DPPV     MAKE_ID('D', 'P', 'P', 'V')
     /* DPaint perspective chunk (EA) */
-#define ID_DRNG     MAKE_ID('D', 'R', 'N', 'G')     
+#define ID_DRNG     MAKE_ID('D', 'R', 'N', 'G')
     /* DPaint IV enhanced color cycle chunk (EA) */
-#define ID_EPSF     MAKE_ID('E', 'P', 'S', 'F')     
+#define ID_EPSF     MAKE_ID('E', 'P', 'S', 'F')
     /* Encapsulated Postscript chunk */
-#define ID_CMYK     MAKE_ID('C', 'M', 'Y', 'K')     
+#define ID_CMYK     MAKE_ID('C', 'M', 'Y', 'K')
     /* Cyan, Magenta, Yellow, & Black color map (Soft-Logik) */
-#define ID_CNAM     MAKE_ID('C', 'N', 'A', 'M')     
+#define ID_CNAM     MAKE_ID('C', 'N', 'A', 'M')
     /* Color naming chunk (Soft-Logik) */
-#define ID_PCHG     MAKE_ID('P', 'C', 'H', 'G')     
+#define ID_PCHG     MAKE_ID('P', 'C', 'H', 'G')
     /* Line by line palette control information (Sebastiano Vigna) */
-#define ID_PRVW     MAKE_ID('P', 'R', 'V', 'W')     
+#define ID_PRVW     MAKE_ID('P', 'R', 'V', 'W')
     /* A mini duplicate ILBM used for preview (Gary Bonham) */
-#define ID_XBMI     MAKE_ID('X', 'B', 'M', 'I')     
+#define ID_XBMI     MAKE_ID('X', 'B', 'M', 'I')
     /* eXtended BitMap Information (Soft-Logik) */
-#define ID_CTBL     MAKE_ID('C', 'T', 'B', 'L')     
+#define ID_CTBL     MAKE_ID('C', 'T', 'B', 'L')
     /* Newtek Dynamic Ham color chunk */
-#define ID_DYCP     MAKE_ID('D', 'Y', 'C', 'P')     
+#define ID_DYCP     MAKE_ID('D', 'Y', 'C', 'P')
     /* Newtek Dynamic Ham chunk */
-#define ID_SHAM     MAKE_ID('S', 'H', 'A', 'M')     
+#define ID_SHAM     MAKE_ID('S', 'H', 'A', 'M')
     /* Sliced HAM color chunk */
-#define ID_ABIT     MAKE_ID('A', 'B', 'I', 'T')     
+#define ID_ABIT     MAKE_ID('A', 'B', 'I', 'T')
     /* ACBM body chunk */
-#define ID_DCOL     MAKE_ID('D', 'C', 'O', 'L')     
+#define ID_DCOL     MAKE_ID('D', 'C', 'O', 'L')
     /* unofficial direct color */
 #define ID_DPPS     MAKE_ID('D', 'P', 'P', 'S')
     /* ? */
diff --git a/converter/ppm/ilbmtoppm.c b/converter/ppm/ilbmtoppm.c
index 92d4d6f2..b9b89862 100644
--- a/converter/ppm/ilbmtoppm.c
+++ b/converter/ppm/ilbmtoppm.c
@@ -1597,8 +1597,8 @@ rgbn_to_ppm(FILE *         const ifP,
  Multipalette chunk reader
 
     Currently there are three multipalette formats:
-        SHAM - sliced HAM (obselete)
-        CTBL - dynamic HAM/Hires (obselete)
+        SHAM - sliced HAM (obsolete)
+        CTBL - dynamic HAM/Hires (obsolete)
         PCHG - palette change
     There is no official documentation available for SHAM and CTBL, so
    this is mostly guesswork from other sources and hexdumps of pictures...
diff --git a/converter/ppm/picttoppm.c b/converter/ppm/picttoppm.c
index be6a3f97..ec701cfc 100644
--- a/converter/ppm/picttoppm.c
+++ b/converter/ppm/picttoppm.c
@@ -35,6 +35,7 @@
 #include "pbmfont.h"
 #include "mallocvar.h"
 #include "nstring.h"
+#include "shhopt.h"
 
 
 /*
@@ -46,31 +47,115 @@ typedef unsigned short Word;
 typedef unsigned long Longword;
 
 
+struct CmdlineInfo {
+    /* All the information the user supplied in the command line,
+       in a form easy for the program to use.
+    */
+    const char * inputFileName;  /* File name of input file */
+
+    unsigned int fullres;
+    unsigned int noheader;
+    unsigned int quickdraw;
+    const char * fontdir;  /* Null if not specified */
+    unsigned int verbose;
+};
+
+
+
+static void
+parseCommandLine(int argc,
+                 const char ** argv,
+                 struct CmdlineInfo  * const cmdlineP) {
+/* --------------------------------------------------------------------------
+   Parse program command line described in Unix standard form by argc
+   and argv.  Return the information in the options as *cmdlineP.
+
+   If command line is internally inconsistent (invalid options, etc.),
+   issue error message to stderr and abort program.
+
+   Note that the strings we return are stored in the storage that
+   was passed to us as the argv array.  We also trash *argv.
+--------------------------------------------------------------------------*/
+    optEntry * option_def;
+    optStruct3 opt;
+        /* Instructions to pm_optParseOptions3 on how to parse our options. */
+
+    unsigned int option_def_index;
+
+    unsigned int fontdirSpec, verboseSpec;
+
+    MALLOCARRAY_NOFAIL(option_def, 100);
+
+    option_def_index = 0;   /* incremented by OPTENT3 */
+    OPTENT3(0, "fontdir",     OPT_STRING,    &cmdlineP->fontdir,
+            &fontdirSpec,                     0);
+    OPTENT3(0, "fullres",     OPT_FLAG,      NULL,
+            &cmdlineP->fullres,               0);
+    OPTENT3(0, "noheader",    OPT_FLAG,      NULL,
+            &cmdlineP->noheader,              0);
+    OPTENT3(0, "quickdraw",   OPT_FLAG,      NULL,
+            &cmdlineP->quickdraw,             0);
+    OPTENT3(0, "verbose",     OPT_UINT,      &cmdlineP->verbose,
+            &verboseSpec,               0);
+
+    opt.opt_table = option_def;
+    opt.short_allowed = false;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = false;   /* We have no parms that are negative numbers */
+
+    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
+        /* Uses and sets argc, argv, and some of *cmdlineP and others. */
+
+    if (!fontdirSpec)
+        cmdlineP->fontdir = NULL;
+
+    if (!verboseSpec)
+        cmdlineP->verbose = 0;
+
+    if (argc-1 < 1)
+        cmdlineP->inputFileName = "-";
+    else {
+        cmdlineP->inputFileName = argv[1];
+        if (argc-1 > 1)
+            pm_error("Too many arguments: %u.  The only possible non-option "
+                     "argument is the input file name", argc-1);
+    }
+}
+
+
+
 /*
  * Data structures for QuickDraw (and hence PICT) stuff.
  */
 
 struct Rect {
-    Word top;
-    Word left;
-    Word bottom;
-    Word right;
+/*----------------------------------------------------------------------------
+   A rectangle - description of a region of an image raster.
+
+   If last row or column is before first, it is a null rectangle - it
+   describes no pixels.
+-----------------------------------------------------------------------------*/
+    Word top;     /* Start row */
+    Word left;    /* Start column */
+    Word bottom;  /* End row */
+    Word right;   /* End column */
+
+    /* "End" means last plus one */
 };
 
-struct pixMap {
+struct PixMap {
     struct Rect Bounds;
-    Word version;
-    Word packType;
-    Longword packSize;
-    Longword hRes;
-    Longword vRes;
-    Word pixelType;
-    Word pixelSize;
-    Word cmpCount;
-    Word cmpSize;
-    Longword planeBytes;
-    Longword pmTable;
-    Longword pmReserved;
+    Word        version;
+    Word        packType;
+    Longword    packSize;
+    Longword    hRes;
+    Longword    vRes;
+    Word        pixelType;
+    Word        pixelSize;
+    Word        cmpCount;
+    Word        cmpSize;
+    Longword    planeBytes;
+    Longword    pmTable;
+    Longword    pmReserved;
 };
 
 struct RGBColor {
@@ -88,14 +173,21 @@ struct Pattern {
     Byte pix[64];
 };
 
-struct rgbPlanes {
+struct RgbPlanes {
+/*----------------------------------------------------------------------------
+   A raster, as three planes: red, green, blue.
+
+   Each plane is an array in row-major order.
+-----------------------------------------------------------------------------*/
+    unsigned int width;
+    unsigned int height;
     Word * red;
     Word * grn;
     Word * blu;
 };
 
-struct canvas {
-    struct rgbPlanes planes;
+struct Canvas {
+    struct RgbPlanes planes;
 };
 
 typedef void (*transfer_func) (struct RGBColor* src, struct RGBColor* dst);
@@ -105,7 +197,6 @@ static struct Rect picFrame;
 static Word rowlen;
 static Word collen;
 static int verbose;
-static int fullres;
 static int recognize_comment;
 
 static struct RGBColor black = { 0, 0, 0 };
@@ -142,7 +233,7 @@ static int ps_cent_x;
 static int ps_cent_y;
 static int ps_cent_set;
 
-struct raster {
+struct Raster {
 /*----------------------------------------------------------------------------
    An image raster.  May be either truecolor or paletted.
 
@@ -173,7 +264,7 @@ struct raster {
 
 
 static void
-allocateRaster(struct raster * const rasterP,
+allocateRaster(struct Raster * const rasterP,
                unsigned int    const width,
                unsigned int    const height,
                unsigned int    const bitsPerPixel) {
@@ -186,9 +277,9 @@ allocateRaster(struct raster * const rasterP,
    multiple of 16, because we've seen many images in which the PICT raster
    does contain that much padding on the right.  I don't know why; I could
    understand a multiple of 8, since in 1 bpp image, the smallest unit
-   expressable in PICT is 8 pixels.  But why 16?  The images we saw came
+   expressible in PICT is 8 pixels.  But why 16?  The images we saw came
    from Adobe Illustrator 10 in March 2007, supplied by
-   Guillermo Gómez Valcárcel.
+   Guillermo Gomez Valcarcel.
 -----------------------------------------------------------------------------*/
     unsigned int const allocWidth = ROUNDUP(width, 16);
 
@@ -202,19 +293,24 @@ allocateRaster(struct raster * const rasterP,
         /* TODO: I'm still trying to figure out this format.
 
            My theory today:
-           The row data is in plane order (a row consists of red
-           plane, then, green, then blue, then some 4th plane).
 
-           The old hack code said 3 bytes per pixel here, and could get
-           away with it because it never got to decoding the 4th plane.
+           The row data is in plane order (a row consists of red plane, then,
+           green, then blue, then some 4th plane).
 
-           But the new clean code needs to tell it like it is and allocate
-           4 bytes per pixel.  If we say 3 bytes per pixel here, we get an
-           "invalid PICT" error because the image actually contains 4
-           bytes per pixel and as we decompress it, we run out of place
-           to put the data.
+           If the image is compressed, each row is compressed separately, with
+           the planes opaque to the compressor.
 
-           We have yet to see if we can properly interpret the data.
+           The old hack code said 3 bytes per pixel here, and could get away
+           with it because it never got to decoding the 4th plane.
+
+           But the new clean code needs to tell it like it is and allocate 4
+           bytes per pixel.  If we say 3 bytes per pixel here, we get an
+           "invalid PICT" error on one image because the image actually
+           contains 4 bytes per pixel and as we decompress it, we run out of
+           place to put the data.
+
+           On another image we've seen, the decompressor generates 3 bytes per
+           pixel.
         */
 
         rasterP->rowSize = allocWidth * 4;
@@ -244,37 +340,37 @@ allocateRaster(struct raster * const rasterP,
 
 
 static void
-freeRaster(struct raster const raster) {
+freeRaster(struct Raster const raster) {
 
     free(raster.bytes);
 }
 
 
-struct blit_info {
-    struct Rect        srcRect;
-    struct Rect        srcBounds;
-    struct raster      srcplane;
-    int                pixSize;
-    struct Rect        dstRect;
-    struct RGBColor *  colorMap;
-    int                mode;
-    struct blit_info * next;
+struct BlitInfo {
+    struct Rect       srcRect;
+    struct Rect       srcBounds;
+    struct Raster     srcplane;
+    int               pixSize;
+    struct Rect       dstRect;
+    struct RGBColor * colorMap;
+    int               mode;
+    struct BlitInfo * next;
 };
 
 typedef struct {
-    struct blit_info * firstP;
-    struct blit_info ** connectorP;
+    struct BlitInfo * firstP;
+    struct BlitInfo ** connectorP;
     bool unblittableText;
         /* The image contains text opcodes, and we don't know how to put that
            in a blit list (I really don't even know what a blit _is_), so
            the image information here is incomplete.
         */
-} blitList;
+} BlitList;
 
 
-typedef void (drawFn)(struct canvas *, blitList *, int);
+typedef void (drawFn)(FILE *, struct Canvas *, BlitList *, int);
 
-struct opdef {
+struct Opdef {
     const char* name;
     int len;
         /* If non-negative, this is the length of the argument of the
@@ -307,16 +403,15 @@ struct opdef {
 #define RGB_LEN (6)
 
 
-static FILE* ifp;
 static int align = 0;
 
 
 
 static Byte
-readByte(void) {
+readByte(FILE * const ifP) {
     int c;
 
-    if ((c = fgetc(ifp)) == EOF)
+    if ((c = fgetc(ifP)) == EOF)
         pm_error("EOF / read error while %s", stage);
 
     ++align;
@@ -326,27 +421,29 @@ readByte(void) {
 
 
 static Word
-readWord(void) {
+readWord(FILE * const ifP) {
 
-    Byte const hi = readByte();
-    Byte const lo = readByte();
+    Byte const hi = readByte(ifP);
+    Byte const lo = readByte(ifP);
 
     return (hi << 8) | (lo << 0);
 }
 
 
 
-static void readPoint(struct Point * const p) {
-    p->y = readWord();
-    p->x = readWord();
+static void readPoint(FILE *         const ifP,
+                      struct Point * const p) {
+    p->y = readWord(ifP);
+    p->x = readWord(ifP);
 }
 
 
 
 static Longword
-readLong(void) {
-    Word const hi = readWord();
-    Word const lo = readWord();
+readLong(FILE * const ifP) {
+
+    Word const hi = readWord(ifP);
+    Word const lo = readWord(ifP);
 
     return (hi << 16) | (lo << 0);
 }
@@ -354,40 +451,45 @@ readLong(void) {
 
 
 static SignedByte
-readSignedByte(void) {
-    return (SignedByte)readByte();
+readSignedByte(FILE * const ifP) {
+    return (SignedByte)readByte(ifP);
 }
 
 
 
 static void
-readShortPoint(struct Point * const p) {
-    p->x = readSignedByte();
-    p->y = readSignedByte();
+readShortPoint(FILE *         const ifP,
+               struct Point * const p) {
+
+    p->x = readSignedByte(ifP);
+    p->y = readSignedByte(ifP);
 }
 
 
 
 static void
-skip(int const byteCount) {
-    static Byte buf[1024];
+skip(FILE *       const ifP,
+     unsigned int const byteCount) {
+
+    Byte buf[1024];
     int n;
 
     align += byteCount;
 
-    for (n = byteCount; n > 0; n -= 1024)
-        if (fread(buf, n > 1024 ? 1024 : n, 1, ifp) != 1)
+    for (n = byteCount; n > 0; n -= 1024) {
+        if (fread(buf, n > 1024 ? 1024 : n, 1, ifP) != 1)
             pm_error("EOF / read error while %s", stage);
+    }
 }
 
 
 
-struct const_name {
+struct ConstName {
     int value;
     const char * name;
 };
 
-struct const_name const transfer_name[] = {
+struct ConstName const transfer_name[] = {
     { 0,    "srcCopy" },
     { 1,    "srcOr" },
     { 2,    "srcXor" },
@@ -407,7 +509,7 @@ struct const_name const transfer_name[] = {
     { -1,   0 }
 };
 
-struct const_name font_name[] = {
+struct ConstName font_name[] = {
     { 0,    "systemFont" },
     { 1,    "applFont" },
     { 2,    "newYork" },
@@ -428,7 +530,7 @@ struct const_name font_name[] = {
     { -1,   0 }
 };
 
-struct const_name ps_just_name[] = {
+struct ConstName ps_just_name[] = {
     { 0,    "no" },
     { 1,    "left" },
     { 2,    "center" },
@@ -437,7 +539,7 @@ struct const_name ps_just_name[] = {
     { -1,   0 }
 };
 
-struct const_name ps_flip_name[] = {
+struct ConstName ps_flip_name[] = {
     { 0,    "no" },
     { 1,    "horizontal" },
     { 2,    "vertical" },
@@ -447,8 +549,8 @@ struct const_name ps_flip_name[] = {
 
 
 static const char*
-const_name(const struct const_name * const table,
-           unsigned int              const ct) {
+constName(const struct ConstName * const table,
+          unsigned int             const ct) {
 
     static char numbuf[32];
 
@@ -465,8 +567,9 @@ const_name(const struct const_name * const table,
 
 
 static void
-picComment(Word const type,
-           int const length) {
+picComment(FILE * const ifP,
+           Word   const type,
+           int    const length) {
 
     unsigned int remainingLength;
 
@@ -474,10 +577,10 @@ picComment(Word const type,
     case 150:
         if (verbose) pm_message("TextBegin");
         if (length >= 6) {
-            ps_just = readByte();
-            ps_flip = readByte();
-            ps_rotation = readWord();
-            ps_linespace = readByte();
+            ps_just = readByte(ifP);
+            ps_flip = readByte(ifP);
+            ps_rotation = readWord(ifP);
+            ps_linespace = readByte(ifP);
             remainingLength = length - 5;
             if (recognize_comment)
                 ps_text = 1;
@@ -485,8 +588,8 @@ picComment(Word const type,
             if (verbose) {
                 pm_message("%s justification, %s flip, %d degree rotation, "
                            "%d/2 linespacing",
-                           const_name(ps_just_name, ps_just),
-                           const_name(ps_flip_name, ps_flip),
+                           constName(ps_just_name, ps_just),
+                           constName(ps_flip_name, ps_flip),
                            ps_rotation, ps_linespace);
             }
         } else
@@ -510,14 +613,14 @@ picComment(Word const type,
         if (length < 8)
             remainingLength = length;
         else {
-            ps_cent_y = readWord();
+            ps_cent_y = readWord(ifP);
             if (ps_cent_y > 32767)
                 ps_cent_y -= 65536;
-            skip(2); /* ignore fractional part */
-            ps_cent_x = readWord();
+            skip(ifP, 2); /* ignore fractional part */
+            ps_cent_x = readWord(ifP);
             if (ps_cent_x > 32767)
                 ps_cent_x -= 65536;
-            skip(2); /* ignore fractional part */
+            skip(ifP, 2); /* ignore fractional part */
             remainingLength = length - 8;
             if (verbose)
                 pm_message("offset %d %d", ps_cent_x, ps_cent_y);
@@ -613,7 +716,7 @@ picComment(Word const type,
         break;
     }
     if (remainingLength > 0)
-        skip(remainingLength);
+        skip(ifP, remainingLength);
 }
 
 
@@ -621,11 +724,12 @@ picComment(Word const type,
 static drawFn ShortComment;
 
 static void
-ShortComment(struct canvas * const canvasP,
-             blitList *      const blitListP,
+ShortComment(FILE *          const ifP,
+             struct Canvas * const canvasP,
+             BlitList *      const blitListP,
              int             const version) {
 
-    picComment(readWord(), 0);
+    picComment(ifP, readWord(ifP), 0);
 }
 
 
@@ -633,27 +737,29 @@ ShortComment(struct canvas * const canvasP,
 static drawFn LongComment;
 
 static void
-LongComment(struct canvas * const canvasP,
-            blitList *      const blitListP,
+LongComment(FILE *          const ifP,
+            struct Canvas * const canvasP,
+            BlitList *      const blitListP,
             int             const version) {
 
     Word type;
 
-    type = readWord();
-    picComment(type, readWord());
+    type = readWord(ifP);
+    picComment(ifP, type, readWord(ifP));
 }
 
 
 
-static drawFn skip_poly_or_region;
+static drawFn skipPolyOrRegion;
 
 static void
-skip_poly_or_region(struct canvas * const canvasP,
-                    blitList *      const blitListP,
-                    int             const version) {
+skipPolyOrRegion(FILE *          const ifP,
+                 struct Canvas * const canvasP,
+                 BlitList *      const blitListP,
+                 int             const version) {
 
     stage = "skipping polygon or region";
-    skip(readWord() - 2);
+    skip(ifP, readWord(ifP) - 2);
 }
 
 
@@ -669,17 +775,17 @@ skip_poly_or_region(struct canvas * const canvasP,
 
 /* Some font searching routines */
 
-struct fontinfo {
+struct FontInfo {
     int font;
     int size;
     int style;
     char* filename;
     struct font* loaded;
-    struct fontinfo* next;
+    struct FontInfo* next;
 };
 
-static struct fontinfo* fontlist = 0;
-static struct fontinfo** fontlist_ins = &fontlist;
+static struct FontInfo* fontlist = 0;
+static struct FontInfo** fontlist_ins = &fontlist;
 
 
 
@@ -714,9 +820,9 @@ tokenize(char *         const s,
 
 static void
 parseFontLine(const char **      const token,
-              struct fontinfo ** const fontinfoPP) {
+              struct FontInfo ** const fontinfoPP) {
 
-    struct fontinfo * fontinfoP;
+    struct FontInfo * fontinfoP;
 
     MALLOCVAR(fontinfoP);
     if (fontinfoP == NULL)
@@ -737,7 +843,7 @@ parseFontLine(const char **      const token,
 
 
 static int
-load_fontdir(const char * const dirfile) {
+loadFontdir(const char * const dirfile) {
 /*----------------------------------------------------------------------------
    Load the font directory from file named 'dirfile'.  Add its contents
    to the global list of fonts 'fontlist'.
@@ -762,7 +868,7 @@ load_fontdir(const char * const dirfile) {
         } else if (nToken != 4) {
             /* Unrecognized format - ignore */
         } else {
-            struct fontinfo * fontinfoP;
+            struct FontInfo * fontinfoP;
 
             parseFontLine(token, &fontinfoP);
 
@@ -780,6 +886,23 @@ load_fontdir(const char * const dirfile) {
 
 
 static void
+loadDefaultFontDir(void) {
+/*----------------------------------------------------------------------------
+   Load the fonts from the font directory file "fontdir" (in the current
+   directory), if it exists.
+-----------------------------------------------------------------------------*/
+    struct stat statbuf;
+    int rc;
+
+    rc = stat("fontdir", &statbuf);
+
+    if (rc == 0)
+        loadFontdir("fontdir");
+}
+
+
+
+static void
 dumpRect(const char * const label,
          struct Rect  const rectangle) {
 
@@ -792,7 +915,8 @@ dumpRect(const char * const label,
 
 
 static void
-readRect(struct Rect * const r) {
+readRect(FILE *        const ifP,
+         struct Rect * const r) {
 
     /* We don't have a formal specification for the Pict format, but we have
        seen samples that have the rectangle corners either in top left, bottom
@@ -804,10 +928,10 @@ readRect(struct Rect * const r) {
        So now we accept all 4 possibilities.
     */
 
-    Word const y1 = readWord();
-    Word const x1 = readWord();
-    Word const y2 = readWord();
-    Word const x2 = readWord();
+    Word const y1 = readWord(ifP);
+    Word const x1 = readWord(ifP);
+    Word const y2 = readWord(ifP);
+    Word const x2 = readWord(ifP);
 
     r->top    = MIN(y1, y2);
     r->left   = MIN(x1, x2);
@@ -818,14 +942,36 @@ readRect(struct Rect * const r) {
 
 
 static int
+rectisnull(struct Rect * const r) {
+
+    return r->top >= r->bottom || r->left >= r->right;
+}
+
+
+
+static int
 rectwidth(const struct Rect * const r) {
+
     return r->right - r->left;
 }
 
 
 
+static bool
+rectequal(const struct Rect * const comparand,
+          const struct Rect * const comparator) {
+
+    return
+        comparand->top    == comparator->top &&
+        comparand->bottom == comparator->bottom &&
+        comparand->left   == comparator->left &&
+        comparand->right  == comparator->right;
+}
+
+
 static int
 rectheight(const struct Rect * const r) {
+
     return r->bottom - r->top;
 }
 
@@ -834,6 +980,7 @@ rectheight(const struct Rect * const r) {
 static bool
 rectsamesize(struct Rect const r1,
              struct Rect const r2) {
+
     return r1.right - r1.left == r2.right - r2.left &&
            r1.bottom - r1.top == r2.bottom - r2.top ;
 }
@@ -841,14 +988,18 @@ rectsamesize(struct Rect const r1,
 
 
 static void
-rectinter(struct Rect   const r1,
-          struct Rect   const r2,
-          struct Rect * const intersectionP) {
+rectintersect(const struct Rect * const r1P,
+              const struct Rect * const r2P,
+              struct Rect *       const intersectionP) {
+/*----------------------------------------------------------------------------
+   Compute the intersection of two rectangles.
 
-    intersectionP->left   = MAX(r1.left,   r2.left);
-    intersectionP->top    = MAX(r1.top,    r2.top);
-    intersectionP->right  = MIN(r1.right,  r2.right);
-    intersectionP->bottom = MIN(r1.bottom, r2.bottom);
+   Note that if the rectangles are disjoint, the result is a null rectangle.
+-----------------------------------------------------------------------------*/
+    intersectionP->left   = MAX(r1P->left,   r2P->left);
+    intersectionP->top    = MAX(r1P->top,    r2P->top);
+    intersectionP->right  = MIN(r1P->right,  r2P->right);
+    intersectionP->bottom = MIN(r1P->bottom, r2P->bottom);
 }
 
 
@@ -857,16 +1008,17 @@ static void
 rectscale(struct Rect * const r,
           double        const xscale,
           double        const yscale) {
-    r->left *= xscale;
-    r->right *= xscale;
-    r->top *= yscale;
+
+    r->left   *= xscale;
+    r->right  *= xscale;
+    r->top    *= yscale;
     r->bottom *= yscale;
 }
 
 
 
 static void
-    initBlitList(blitList * const blitListP) {
+initBlitList(BlitList * const blitListP) {
 
     blitListP->firstP          = NULL;
     blitListP->connectorP      = &blitListP->firstP;
@@ -876,16 +1028,16 @@ static void
 
 
 static void
-addBlitList(blitList *        const blitListP,
+addBlitList(BlitList *        const blitListP,
             struct Rect       const srcRect,
             struct Rect       const srcBounds,
-            struct raster     const srcplane,
+            struct Raster     const srcplane,
             int               const pixSize,
             struct Rect       const dstRect,
             struct RGBColor * const colorMap,
             int               const mode) {
 
-    struct blit_info * biP;
+    struct BlitInfo * biP;
 
     MALLOCVAR(biP);
     if (biP == NULL)
@@ -902,7 +1054,7 @@ addBlitList(blitList *        const blitListP,
         biP->next = NULL;
 
         *blitListP->connectorP = biP;
-        blitListP->connectorP = &biP->next;
+        blitListP->connectorP  = &biP->next;
     }
 }
 
@@ -927,12 +1079,15 @@ rgbAllSame(const struct RGBColor * const colorP,
 }
 
 
+
 static bool
 rgbIsWhite(const struct RGBColor * const colorP) {
 
     return rgbAllSame(colorP, 0xffff);
 }
 
+
+
 static bool
 rgbIsBlack(const struct RGBColor * const colorP) {
 
@@ -940,122 +1095,133 @@ rgbIsBlack(const struct RGBColor * const colorP) {
 }
 
 
+
 static void
-srcCopy(struct RGBColor * const src,
-        struct RGBColor * const dst) {
+srcCopy(struct RGBColor * const srcP,
+        struct RGBColor * const dstP) {
 
-    if (rgbIsBlack(src))
-        *dst = foreground;
+    if (rgbIsBlack(srcP))
+        *dstP = foreground;
     else
-        *dst = background;
+        *dstP = background;
 }
 
 
 
 static void
-srcOr(struct RGBColor * const src,
-      struct RGBColor * const dst) {
-    if (rgbIsBlack(src))
-        *dst = foreground;
+srcOr(struct RGBColor * const srcP,
+      struct RGBColor * const dstP) {
+
+    if (rgbIsBlack(srcP))
+        *dstP = foreground;
 }
 
 
 
 static void
-srcXor(struct RGBColor * const src,
-       struct RGBColor * const dst) {
-    dst->red ^= ~src->red;
-    dst->grn ^= ~src->grn;
-    dst->blu ^= ~src->blu;
+srcXor(struct RGBColor * const srcP,
+       struct RGBColor * const dstP) {
+
+    dstP->red ^= ~srcP->red;
+    dstP->grn ^= ~srcP->grn;
+    dstP->blu ^= ~srcP->blu;
 }
 
 
 
 static void
-srcBic(struct RGBColor * const src,
-       struct RGBColor * const dst) {
-    if (rgbIsBlack(src))
-        *dst = background;
+srcBic(struct RGBColor * const srcP,
+       struct RGBColor * const dstP) {
+
+    if (rgbIsBlack(srcP))
+        *dstP = background;
 }
 
 
 
 static void
-notSrcCopy(struct RGBColor * const src,
-           struct RGBColor * const dst) {
-    if (rgbIsWhite(src))
-        *dst = foreground;
-    else if (rgbIsBlack(src))
-        *dst = background;
+notSrcCopy(struct RGBColor * const srcP,
+           struct RGBColor * const dstP) {
+
+    if (rgbIsWhite(srcP))
+        *dstP = foreground;
+    else if (rgbIsBlack(srcP))
+        *dstP = background;
 }
 
 
 
 static void
-notSrcOr(struct RGBColor * const src,
-         struct RGBColor * const dst) {
-    if (rgbIsWhite(src))
-        *dst = foreground;
+notSrcOr(struct RGBColor * const srcP,
+         struct RGBColor * const dstP) {
+
+    if (rgbIsWhite(srcP))
+        *dstP = foreground;
 }
 
 
 
 static void
-notSrcBic(struct RGBColor * const src,
-          struct RGBColor * const dst) {
-    if (rgbIsWhite(src))
-        *dst = background;
+notSrcBic(struct RGBColor * const srcP,
+          struct RGBColor * const dstP) {
+
+    if (rgbIsWhite(srcP))
+        *dstP = background;
 }
 
 
 
 static void
-notSrcXor(struct RGBColor * const src,
-          struct RGBColor * const dst) {
-    dst->red ^= src->red;
-    dst->grn ^= src->grn;
-    dst->blu ^= src->blu;
+notSrcXor(struct RGBColor * const srcP,
+          struct RGBColor * const dstP) {
+
+    dstP->red ^= srcP->red;
+    dstP->grn ^= srcP->grn;
+    dstP->blu ^= srcP->blu;
 }
 
 
 
 static void
-addOver(struct RGBColor * const src,
-        struct RGBColor * const dst) {
-    dst->red += src->red;
-    dst->grn += src->grn;
-    dst->blu += src->blu;
+addOver(struct RGBColor * const srcP,
+        struct RGBColor * const dstP) {
+
+    dstP->red += srcP->red;
+    dstP->grn += srcP->grn;
+    dstP->blu += srcP->blu;
 }
 
 
 
 static void
-addPin(struct RGBColor * const src,
-       struct RGBColor * const dst) {
-    if ((long)dst->red + (long)src->red > (long)op_color.red)
-        dst->red = op_color.red;
+addPin(struct RGBColor * const srcP,
+       struct RGBColor * const dstP) {
+
+    if ((long)dstP->red + (long)srcP->red > (long)op_color.red)
+        dstP->red = op_color.red;
     else
-        dst->red = dst->red + src->red;
+        dstP->red = dstP->red + srcP->red;
 
-    if ((long)dst->grn + (long)src->grn > (long)op_color.grn)
-        dst->grn = op_color.grn;
+    if ((long)dstP->grn + (long)srcP->grn > (long)op_color.grn)
+        dstP->grn = op_color.grn;
     else
-        dst->grn = dst->grn + src->grn;
+        dstP->grn = dstP->grn + srcP->grn;
 
-    if ((long)dst->blu + (long)src->blu > (long)op_color.blu)
-        dst->blu = op_color.blu;
+    if ((long)dstP->blu + (long)srcP->blu > (long)op_color.blu)
+        dstP->blu = op_color.blu;
     else
-        dst->blu = dst->blu + src->blu;
+        dstP->blu = dstP->blu + srcP->blu;
 }
 
 
 
 static void
-subOver(struct RGBColor * const src,
-        struct RGBColor * const dst) {
-    dst->red -= src->red;
-    dst->grn -= src->grn;
-    dst->blu -= src->blu;
+subOver(struct RGBColor * const srcP,
+        struct RGBColor * const dstP) {
+
+    dstP->red -= srcP->red;
+    dstP->grn -= srcP->grn;
+    dstP->blu -= srcP->blu;
 }
 
 
@@ -1064,74 +1230,81 @@ subOver(struct RGBColor * const src,
 
 
 static void
-subPin(struct RGBColor * const src,
-       struct RGBColor * const dst) {
-    if ((long)dst->red - (long)src->red < (long)op_color.red)
-        dst->red = op_color.red;
+subPin(struct RGBColor * const srcP,
+       struct RGBColor * const dstP) {
+
+    if ((long)dstP->red - (long)srcP->red < (long)op_color.red)
+        dstP->red = op_color.red;
     else
-        dst->red = dst->red - src->red;
+        dstP->red = dstP->red - srcP->red;
 
-    if ((long)dst->grn - (long)src->grn < (long)op_color.grn)
-        dst->grn = op_color.grn;
+    if ((long)dstP->grn - (long)srcP->grn < (long)op_color.grn)
+        dstP->grn = op_color.grn;
     else
-        dst->grn = dst->grn - src->grn;
+        dstP->grn = dstP->grn - srcP->grn;
 
-    if ((long)dst->blu - (long)src->blu < (long)op_color.blu)
-        dst->blu = op_color.blu;
+    if ((long)dstP->blu - (long)srcP->blu < (long)op_color.blu)
+        dstP->blu = op_color.blu;
     else
-        dst->blu = dst->blu - src->blu;
+        dstP->blu = dstP->blu - srcP->blu;
 }
 
 
 
 static void
-adMax(struct RGBColor * const src,
-      struct RGBColor * const dst) {
-    if (src->red > dst->red) dst->red = src->red;
-    if (src->grn > dst->grn) dst->grn = src->grn;
-    if (src->blu > dst->blu) dst->blu = src->blu;
+adMax(struct RGBColor * const srcP,
+      struct RGBColor * const dstP) {
+
+    if (srcP->red > dstP->red) dstP->red = srcP->red;
+    if (srcP->grn > dstP->grn) dstP->grn = srcP->grn;
+    if (srcP->blu > dstP->blu) dstP->blu = srcP->blu;
 }
 
 
 
 static void
-adMin(struct RGBColor * const src,
-      struct RGBColor * const dst) {
-    if (src->red < dst->red) dst->red = src->red;
-    if (src->grn < dst->grn) dst->grn = src->grn;
-    if (src->blu < dst->blu) dst->blu = src->blu;
+adMin(struct RGBColor * const srcP,
+      struct RGBColor * const dstP) {
+
+    if (srcP->red < dstP->red) dstP->red = srcP->red;
+    if (srcP->grn < dstP->grn) dstP->grn = srcP->grn;
+    if (srcP->blu < dstP->blu) dstP->blu = srcP->blu;
 }
 
 
 
 static void
-blend(struct RGBColor * const src,
-      struct RGBColor * const dst) {
+blend(struct RGBColor * const srcP,
+      struct RGBColor * const dstP) {
+
 #define blend_component(cmp)    \
-    ((long)src->cmp * (long)op_color.cmp) / 65536 +    \
-    ((long)dst->cmp * (long)(65536 - op_color.cmp) / 65536)
+    ((long)srcP->cmp * (long)op_color.cmp) / 65536 +    \
+    ((long)dstP->cmp * (long)(65536 - op_color.cmp) / 65536)
 
-    dst->red = blend_component(red);
-    dst->grn = blend_component(grn);
-    dst->blu = blend_component(blu);
+    dstP->red = blend_component(red);
+    dstP->grn = blend_component(grn);
+    dstP->blu = blend_component(blu);
 }
 
 
 
 static void
-transparent(struct RGBColor * const src,
-            struct RGBColor * const dst) {
-    if (src->red != background.red ||
-        src->grn != background.grn ||
-        src->blu != background.blu) {
-        *dst = *src;
+transparent(struct RGBColor * const srcP,
+            struct RGBColor * const dstP) {
+
+    if (srcP->red != background.red ||
+        srcP->grn != background.grn ||
+        srcP->blu != background.blu) {
+
+        *dstP = *srcP;
     }
 }
 
 
 
 static transfer_func
-transfer(int const mode) {
+transferFunctionForMode(unsigned int const mode) {
+
     switch (mode) {
     case  0: return srcCopy;
     case  1: return srcOr;
@@ -1150,9 +1323,8 @@ transfer(int const mode) {
     case 38: return subOver;
     case 39: return adMin;
     default:
-        if (mode != 0)
-            pm_message("no transfer function for code %s, using srcCopy",
-                const_name(transfer_name, mode));
+        pm_message("no transfer function for code %s, using srcCopy",
+                   constName(transfer_name, mode));
         return srcCopy;
     }
 }
@@ -1192,43 +1364,122 @@ decode16(unsigned char * const sixteen) {
 
 
 static void
-doDiffSize(struct Rect       const clipsrc,
-           struct Rect       const clipdst,
-           int               const pixSize,
-           int               const xsize,
-           int               const ysize,
+closeValidatePamscalePipe(FILE * const pipeP) {
+
+    int rc;
+
+    rc = pclose(pipeP);
+
+    if (rc != 0)
+        pm_error("pamscale failed.  pclose() returned Errno %s (%d)",
+                 strerror(errno), errno);
+}
+
+
+
+static void
+convertScaledPpm(const char *      const scaledFilename,
+                 transfer_func     const trf,
+                 struct RgbPlanes  const dst,
+                 unsigned int      const dstadd) {
+
+    Word * reddst;
+    Word * grndst;
+    Word * bludst;
+    FILE * scaledP;
+    int cols, rows, format;
+    pixval maxval;
+    pixel * pixrow;
+
+    reddst = &dst.red[0];  /* initial value */
+    grndst = &dst.grn[0];  /* initial value */
+    bludst = &dst.blu[0];  /* initial value */
+
+    scaledP = pm_openr(scaledFilename);
+
+    ppm_readppminit(scaledP, &cols, &rows, &maxval, &format);
+
+    pixrow = ppm_allocrow(cols);
+
+    if (trf) {
+        unsigned int row;
+
+        for (row = 0; row < rows; ++row) {
+            unsigned int col;
+
+            ppm_readppmrow(scaledP, pixrow, cols, maxval, format);
+
+            for (col = 0; col < cols; ++col) {
+                struct RGBColor dst_c, src_c;
+                dst_c.red = *reddst;
+                dst_c.grn = *grndst;
+                dst_c.blu = *bludst;
+                src_c.red = PPM_GETR(pixrow[col]) * 65536L / (maxval + 1);
+                src_c.grn = PPM_GETG(pixrow[col]) * 65536L / (maxval + 1);
+                src_c.blu = PPM_GETB(pixrow[col]) * 65536L / (maxval + 1);
+                (*trf)(&src_c, &dst_c);
+                *reddst++ = dst_c.red;
+                *grndst++ = dst_c.grn;
+                *bludst++ = dst_c.blu;
+            }
+            reddst += dstadd;
+            grndst += dstadd;
+            bludst += dstadd;
+        }
+    } else {
+        unsigned int row;
+
+        for (row = 0; row < rows; ++row) {
+            unsigned int col;
+
+            ppm_readppmrow(scaledP, pixrow, cols, maxval, format);
+
+            for (col = 0; col < cols; ++col) {
+                *reddst++ = PPM_GETR(pixrow[col]) * 65536L / (maxval + 1);
+                *grndst++ = PPM_GETG(pixrow[col]) * 65536L / (maxval + 1);
+                *bludst++ = PPM_GETB(pixrow[col]) * 65536L / (maxval + 1);
+            }
+            reddst += dstadd;
+            grndst += dstadd;
+            bludst += dstadd;
+        }
+    }
+    assert(reddst == &dst.red[dst.height * dst.width]);
+    assert(grndst == &dst.grn[dst.height * dst.width]);
+    assert(bludst == &dst.blu[dst.height * dst.width]);
+
+    ppm_freerow(pixrow);
+    pm_close(scaledP);
+}
+
+
+
+static void
+doDiffSize(struct Rect       const srcRect,
+           struct Rect       const dstRect,
+           unsigned int      const pixSize,
            transfer_func     const trf,
            struct RGBColor * const color_map,
            unsigned char *   const src,
-           int               const srcwid,
-           struct rgbPlanes  const dst,
-           unsigned int      const dstwid) {
-
-    unsigned int const dstadd = dstwid - rectwidth(&clipdst);
+           unsigned int      const srcwid,
+           struct RgbPlanes  const dst) {
+/*----------------------------------------------------------------------------
+   Generate the raster in the plane buffers indicated by 'dst'.
 
+   'src' is the source pixels as a row-major array with rows 'srcwid' bytes
+   long.
+-----------------------------------------------------------------------------*/
     FILE * pamscalePipeP;
     const char * command;
-    FILE * scaled;
-    int cols, rows, format;
-    pixval maxval;
-    pixel * row;
-    pixel * rowp;
     FILE * tempFileP;
     const char * tempFilename;
-    Word * reddst;
-    Word * grndst;
-    Word * bludst;
-
-    reddst = dst.red;  /* initial value */
-    grndst = dst.grn;  /* initial value */
-    bludst = dst.blu;  /* initial value */
 
     pm_make_tmpfile(&tempFileP, &tempFilename);
 
     pm_close(tempFileP);
 
-    pm_asprintf(&command, "pamscale -xsize %d -ysize %d > %s",
-                rectwidth(&clipdst), rectheight(&clipdst), tempFilename);
+    pm_asprintf(&command, "pamscale -xsize %u -ysize %u > %s",
+                rectwidth(&dstRect), rectheight(&dstRect), tempFilename);
 
     pm_message("running command '%s'", command);
 
@@ -1239,108 +1490,61 @@ doDiffSize(struct Rect       const clipsrc,
 
     pm_strfree(command);
 
-    fprintf(pamscalePipeP, "P6\n%d %d\n%d\n",
-            rectwidth(&clipsrc), rectheight(&clipsrc), PPM_MAXMAXVAL);
+    fprintf(pamscalePipeP, "P6\n%u %u\n%u\n",
+            rectwidth(&srcRect), rectheight(&srcRect), PPM_MAXMAXVAL);
 
     switch (pixSize) {
     case 8: {
-        unsigned int rowNumber;
-        for (rowNumber = 0; rowNumber < ysize; ++rowNumber) {
-            unsigned char * const row = &src[rowNumber * srcwid];
-            unsigned int colNumber;
-            for (colNumber = 0; colNumber < xsize; ++colNumber) {
-                unsigned int const colorIndex = row[colNumber];
+        unsigned int row;
+        for (row = 0; row < rectheight(&srcRect); ++row) {
+            unsigned char * const rowBytes = &src[row * srcwid];
+            unsigned int col;
+            for (col = 0; col < rectwidth(&srcRect); ++col) {
+                unsigned int const colorIndex = rowBytes[col];
                 struct RGBColor * const ct = &color_map[colorIndex];
                 fputc(redepth(ct->red, 65535L), pamscalePipeP);
                 fputc(redepth(ct->grn, 65535L), pamscalePipeP);
                 fputc(redepth(ct->blu, 65535L), pamscalePipeP);
             }
         }
-    }
-    break;
+    } break;
     case 16: {
-        unsigned int rowNumber;
-        for (rowNumber = 0; rowNumber < ysize; ++rowNumber) {
-            unsigned char * const row = &src[rowNumber * srcwid];
-            unsigned int colNumber;
-            for (colNumber = 0; colNumber < xsize; ++colNumber) {
-                struct RGBColor const color = decode16(&row[colNumber * 2]);
+        unsigned int row;
+        for (row = 0; row < rectheight(&srcRect); ++row) {
+            unsigned char * const rowBytes = &src[row * srcwid];
+            unsigned int col;
+            for (col = 0; col < rectwidth(&srcRect); ++col) {
+                struct RGBColor const color = decode16(&rowBytes[col * 2]);
                 fputc(redepth(color.red, 32), pamscalePipeP);
                 fputc(redepth(color.grn, 32), pamscalePipeP);
                 fputc(redepth(color.blu, 32), pamscalePipeP);
             }
         }
-    }
-    break;
+    } break;
     case 32: {
-        unsigned int const planeSize = rectwidth(&clipsrc);
-        unsigned int rowNumber;
-
-        for (rowNumber = 0; rowNumber < ysize; ++rowNumber) {
-            unsigned char * const row = &src[rowNumber * srcwid];
-            unsigned char * const redPlane = &row[planeSize * 0];
-            unsigned char * const grnPlane = &row[planeSize * 1];
-            unsigned char * const bluPlane = &row[planeSize * 2];
-
-            unsigned int colNumber;
-            for (colNumber = 0; colNumber < xsize; ++colNumber) {
-                fputc(redepth(redPlane[colNumber], 256), pamscalePipeP);
-                fputc(redepth(grnPlane[colNumber], 256), pamscalePipeP);
-                fputc(redepth(bluPlane[colNumber], 256), pamscalePipeP);
+        unsigned int const planeSize = rectwidth(&srcRect);
+        unsigned int row;
+
+        for (row = 0; row < rectheight(&srcRect); ++row) {
+            unsigned char * const rowBytes = &src[row * srcwid];
+            unsigned char * const redPlane = &rowBytes[planeSize * 0];
+            unsigned char * const grnPlane = &rowBytes[planeSize * 1];
+            unsigned char * const bluPlane = &rowBytes[planeSize * 2];
+
+            unsigned int col;
+            for (col = 0; col < rectwidth(&srcRect); ++col) {
+                fputc(redepth(redPlane[col], 256), pamscalePipeP);
+                fputc(redepth(grnPlane[col], 256), pamscalePipeP);
+                fputc(redepth(bluPlane[col], 256), pamscalePipeP);
             }
         }
-    }
-    break;
-    }
+    } break;
+    } /* switch */
 
-    if (pclose(pamscalePipeP))
-        pm_error("pamscale failed.  pclose() returned Errno %s (%d)",
-                 strerror(errno), errno);
+    closeValidatePamscalePipe(pamscalePipeP);
 
-    ppm_readppminit(scaled = pm_openr(tempFilename), &cols, &rows,
-                    &maxval, &format);
-    row = ppm_allocrow(cols);
-    /* couldn't hurt to assert cols, rows and maxval... */
-
-    if (trf == NULL) {
-        while (rows-- > 0) {
-            unsigned int i;
-            ppm_readppmrow(scaled, row, cols, maxval, format);
-            for (i = 0, rowp = row; i < cols; ++i, ++rowp) {
-                *reddst++ = PPM_GETR(*rowp) * 65536L / (maxval + 1);
-                *grndst++ = PPM_GETG(*rowp) * 65536L / (maxval + 1);
-                *bludst++ = PPM_GETB(*rowp) * 65536L / (maxval + 1);
-            }
-            reddst += dstadd;
-            grndst += dstadd;
-            bludst += dstadd;
-        }
-    }
-    else {
-        while (rows-- > 0) {
-            unsigned int i;
-            ppm_readppmrow(scaled, row, cols, maxval, format);
-            for (i = 0, rowp = row; i < cols; i++, rowp++) {
-                struct RGBColor dst_c, src_c;
-                dst_c.red = *reddst;
-                dst_c.grn = *grndst;
-                dst_c.blu = *bludst;
-                src_c.red = PPM_GETR(*rowp) * 65536L / (maxval + 1);
-                src_c.grn = PPM_GETG(*rowp) * 65536L / (maxval + 1);
-                src_c.blu = PPM_GETB(*rowp) * 65536L / (maxval + 1);
-                (*trf)(&src_c, &dst_c);
-                *reddst++ = dst_c.red;
-                *grndst++ = dst_c.grn;
-                *bludst++ = dst_c.blu;
-            }
-            reddst += dstadd;
-            grndst += dstadd;
-            bludst += dstadd;
-        }
-    }
+    convertScaledPpm(tempFilename, trf, dst, dst.width-rectwidth(&dstRect));
 
-    pm_close(scaled);
-    ppm_freerow(row);
     pm_strfree(tempFilename);
     unlink(tempFilename);
 }
@@ -1348,7 +1552,7 @@ doDiffSize(struct Rect       const clipsrc,
 
 
 static void
-getRgb(struct rgbPlanes  const planes,
+getRgb(struct RgbPlanes  const planes,
        unsigned int      const index,
        struct RGBColor * const rgbP) {
 
@@ -1362,7 +1566,7 @@ getRgb(struct rgbPlanes  const planes,
 static void
 putRgb(struct RGBColor  const rgb,
        unsigned int     const index,
-       struct rgbPlanes const planes) {
+       struct RgbPlanes const planes) {
 
     planes.red[index] = rgb.red;
     planes.grn[index] = rgb.grn;
@@ -1372,182 +1576,171 @@ putRgb(struct RGBColor  const rgb,
 
 
 static void
-doSameSize(transfer_func           trf,
-           int               const pixSize,
-           int               const xsize,
-           int               const ysize,
-           unsigned char *   const src,
-           unsigned int      const srcwid,
-           struct RGBColor * const color_map,
-           struct rgbPlanes  const dst,
-           unsigned int      const dstwid) {
-/*----------------------------------------------------------------------------
-   Transfer pixels from 'src' to 'dst', applying the transfer function
-   'trf'.
+doSameSize8bpp(transfer_func           trf,
+               unsigned int      const xsize,
+               unsigned int      const ysize,
+               unsigned char *   const src,
+               unsigned int      const srcwid,
+               struct RGBColor * const colorMap,
+               struct RgbPlanes  const dst,
+               unsigned int      const dstwid) {
+
+    unsigned int rowNumber;
+
+    for (rowNumber = 0; rowNumber < ysize; ++rowNumber) {
+        unsigned char * const srcrow = &src[rowNumber * srcwid];
+        unsigned int const dstRowCurs = rowNumber * dstwid;
+
+        unsigned int colNumber;
+        for (colNumber = 0; colNumber < xsize; ++colNumber) {
+            unsigned int const dstCursor = dstRowCurs + colNumber;
+            unsigned int const colorIndex = srcrow[colNumber];
+
+            if (trf) {
+                struct RGBColor dstColor;
 
-   'src' has the same format as the 'bytes' member of struct raster.
-   'srcwid' is the size in bytes of each row, like raster.rowSize.
+                getRgb(dst, dstCursor, &dstColor);
+                (*trf)(&colorMap[colorIndex], &dstColor);
+                putRgb(dstColor, dstCursor, dst);
+            } else
+                putRgb(colorMap[colorIndex], dstCursor, dst);
+        }
+    }
+}
 
-   We use only the first 'ysize' rows and only the first 'xsize'
-   pixels of each row.
 
-   We really should clean this up so that we can take pixels out of
-   the middle of a row and rows out of the middle of the raster.  As
-   it stands, Caller achieves the same result by passing as 'src'
-   a pointer into the middle of a raster -- the upper left corner of
-   the rectangle he wants.  But that is messy and nonobvious.
 
-   Each plane of 'dst' is one word per pixel and contains actual
-   colors, never a palette index.  It is an array in row-major order
-   with 'dstwid' words per row.
------------------------------------------------------------------------------*/
-    switch (pixSize) {
-    case 8: {
-        unsigned int rowNumber;
+static void
+doSameSize16bpp(transfer_func           trf,
+                unsigned int      const xsize,
+                unsigned int      const ysize,
+                unsigned char *   const src,
+                unsigned int      const srcwid,
+                struct RgbPlanes  const dst,
+                unsigned int      const dstwid) {
 
-        for (rowNumber = 0; rowNumber < ysize; ++rowNumber) {
-            unsigned char * const srcrow = &src[rowNumber * srcwid];
-            unsigned int const dstRowCurs = rowNumber * dstwid;
+    unsigned int rowNumber;
 
-            unsigned int colNumber;
-            for (colNumber = 0; colNumber < xsize; ++colNumber) {
-                unsigned int const dstCursor = dstRowCurs + colNumber;
-                unsigned int const colorIndex = srcrow[colNumber];
-                struct RGBColor dstColor;
-                getRgb(dst, dstCursor, &dstColor);
-                (*trf)(&color_map[colorIndex], &dstColor);
-                putRgb(dstColor, dstCursor, dst);
-            }
-        }
-    } break;
-    case 16: {
-        unsigned int rowNumber;
+    for (rowNumber = 0; rowNumber < ysize; ++rowNumber) {
+        unsigned char * const row = &src[rowNumber * srcwid];
+        unsigned int const dstRowCurs = rowNumber * dstwid;
+
+        unsigned int colNumber;
+        for (colNumber = 0; colNumber < xsize; ++colNumber) {
+            unsigned int const dstCursor = dstRowCurs + colNumber;
+            struct RGBColor const srcColor = decode16(&row[colNumber*2]);
+
+            struct RGBColor scaledSrcColor;
 
-        for (rowNumber = 0; rowNumber < ysize; ++rowNumber) {
-            unsigned char * const row = &src[rowNumber * srcwid];
-            unsigned int const dstRowCurs = rowNumber * dstwid;
+            scaledSrcColor.red = srcColor.red << 11;
+            scaledSrcColor.grn = srcColor.grn << 11;
+            scaledSrcColor.blu = srcColor.blu << 11;
 
-            unsigned int colNumber;
-            for (colNumber = 0; colNumber < xsize; ++colNumber) {
-                unsigned int const dstCursor = dstRowCurs + colNumber;
-                struct RGBColor const srcColor = decode16(&row[colNumber*2]);
+            if (trf) {
                 struct RGBColor dstColor;
-                struct RGBColor scaledSrcColor;
-                scaledSrcColor.red = srcColor.red << 11;
-                scaledSrcColor.grn = srcColor.grn << 11;
-                scaledSrcColor.blu = srcColor.blu << 11;
+
                 getRgb(dst, dstCursor, &dstColor);
                 (*trf)(&scaledSrcColor, &dstColor);
                 putRgb(dstColor, dstCursor, dst);
-            }
+            } else
+                putRgb(scaledSrcColor, dstCursor, dst);
         }
-    } break;
-    case 32: {
-        unsigned int const planeSize = xsize;
-        unsigned int rowNumber;
+    }
+}
+
+
+
+static void
+doSameSize32bpp(transfer_func           trf,
+                unsigned int      const xsize,
+                unsigned int      const ysize,
+                unsigned char *   const src,
+                unsigned int      const srcwid,
+                struct RgbPlanes  const dst,
+                unsigned int      const dstwid) {
+
+    unsigned int const planeSize = xsize;
+
+    unsigned int rowNumber;
+
+    for (rowNumber = 0; rowNumber < ysize; ++rowNumber) {
+        unsigned char * const row = &src[rowNumber * srcwid];
+        unsigned char * const redPlane = &row[planeSize * 0];
+        unsigned char * const grnPlane = &row[planeSize * 1];
+        unsigned char * const bluPlane = &row[planeSize * 2];
+        unsigned int const dstRowCurs = rowNumber * dstwid;
+
+        unsigned int colNumber;
+
+        for (colNumber = 0; colNumber < xsize; ++colNumber) {
+            unsigned int const dstCursor = dstRowCurs + colNumber;
 
-        for (rowNumber = 0; rowNumber < ysize; ++rowNumber) {
-            unsigned char * const row = &src[rowNumber * srcwid];
-            unsigned char * const redPlane = &row[planeSize * 0];
-            unsigned char * const grnPlane = &row[planeSize * 1];
-            unsigned char * const bluPlane = &row[planeSize * 2];
-            unsigned int const dstRowCurs = rowNumber * dstwid;
+            struct RGBColor srcColor;
 
-            unsigned int colNumber;
+            srcColor.red = redPlane[colNumber] << 8;
+            srcColor.grn = grnPlane[colNumber] << 8;
+            srcColor.blu = bluPlane[colNumber] << 8;
+
+            if (trf) {
+                struct RGBColor dstColor;
 
-            for (colNumber = 0; colNumber < xsize; ++colNumber) {
-                unsigned int const dstCursor = dstRowCurs + colNumber;
-                struct RGBColor srcColor, dstColor;
                 getRgb(dst, dstCursor, &dstColor);
-                srcColor.red = redPlane[colNumber] << 8;
-                srcColor.grn = grnPlane[colNumber] << 8;
-                srcColor.blu = bluPlane[colNumber] << 8;
                 (*trf)(&srcColor, &dstColor);
                 putRgb(dstColor, dstCursor, dst);
-            }
+            } else
+                putRgb(srcColor, dstCursor, dst);
         }
-    } break;
-    default:
-        pm_error("Impossible value of pixSize: %u", pixSize);
     }
 }
 
 
 
 static void
-blitIdempotent(unsigned int          const pixSize,
-               unsigned int          const xsize,
-               unsigned int          const ysize,
-               unsigned char *       const src,
-               unsigned int          const srcwid,
-               struct RGBColor *     const colorMap,
-               struct rgbPlanes      const dst,
-               unsigned int          const dstwid) {
+doSameSize(transfer_func           trf,
+           int               const pixSize,
+           struct Rect       const srcRect,
+           unsigned char *   const src,
+           unsigned int      const srcwid,
+           struct RGBColor * const colorMap,
+           struct RgbPlanes  const dst,
+           unsigned int      const dstwid) {
 /*----------------------------------------------------------------------------
-  This is the same as doSameSize(), except optimized for the case that
-  the transfer function is idempotent (i.e. it's just a straight copy).
-  The original author's comments suggest that this optimization isn't
-  all that important -- that he just wrote this first and instead of
-  expanding it to handle arbitrary transfer functions, added functions
-  for that.
+   Transfer pixels from 'src' to 'dst', applying the transfer function
+   'trf'.
+
+   'src' has the same format as the 'bytes' member of struct Raster.
+   'srcwid' is the size in bytes of each row, like raster.rowSize.
+   Note that there may be padding in there; there isn't necessarily
+   'srcwid' bytes of information in a row.
+
+   We use only the first 'ysize' rows and only the first 'xsize'
+   pixels of each row.
+
+   We really should clean this up so that we can take pixels out of
+   the middle of a row and rows out of the middle of the raster.  As
+   it stands, Caller achieves the same result by passing as 'src'
+   a pointer into the middle of a raster -- the upper left corner of
+   the rectangle he wants.  But that is messy and nonobvious.
+
+   Each plane of 'dst' is one word per pixel and contains actual
+   colors, never a palette index.  It is an array in row-major order
+   with 'dstwid' words per row.
 -----------------------------------------------------------------------------*/
+    unsigned int const xsize = rectwidth(&srcRect);
+    unsigned int const ysize = rectheight(&srcRect);
+
     switch (pixSize) {
-    case 8: {
-        unsigned int rowNumber;
-
-        for (rowNumber = 0; rowNumber < ysize; ++rowNumber) {
-            unsigned char * const srcrow = &src[rowNumber * srcwid];
-            unsigned int const dstRowCurs = rowNumber * dstwid;
-            unsigned int colNumber;
-            for (colNumber = 0; colNumber < xsize; ++colNumber) {
-                unsigned int const dstCursor = dstRowCurs + colNumber;
-                struct RGBColor * const ct = colorMap + srcrow[colNumber];
-                dst.red[dstCursor] = ct->red;
-                dst.grn[dstCursor] = ct->grn;
-                dst.blu[dstCursor] = ct->blu;
-            }
-        }
-    } break;
-    case 16: {
-        unsigned int rowNumber;
-
-        for (rowNumber = 0; rowNumber < ysize; ++rowNumber) {
-            unsigned char * const srcrow = &src[rowNumber * srcwid];
-            unsigned int const dstRowCurs = rowNumber * dstwid;
-            unsigned int colNumber;
-            for (colNumber = 0; colNumber < xsize; ++colNumber) {
-                unsigned int const dstCursor = dstRowCurs + colNumber;
-                struct RGBColor const srcColor =
-                    decode16(&srcrow[colNumber * 2]);
-                dst.red[dstCursor] = srcColor.red << 11;
-                dst.grn[dstCursor] = srcColor.grn << 11;
-                dst.blu[dstCursor] = srcColor.blu << 11;
-            }
-        }
-    } break;
-    case 32: {
-        unsigned int const planeSize = xsize;
-        unsigned int rowNumber;
-
-        for (rowNumber = 0; rowNumber < ysize; ++rowNumber) {
-            unsigned char * const srcrow = &src[rowNumber * srcwid];
-            unsigned char * const redPlane = &srcrow[planeSize * 0];
-            unsigned char * const grnPlane = &srcrow[planeSize * 1];
-            unsigned char * const bluPlane = &srcrow[planeSize * 2];
-            unsigned int const dstRowCurs = rowNumber * dstwid;
-
-            unsigned int colNumber;
-            for (colNumber = 0; colNumber < xsize; ++colNumber) {
-                unsigned int const dstCursor = dstRowCurs + colNumber;
-                dst.red[dstCursor] = redPlane[colNumber] << 8;
-                dst.grn[dstCursor] = grnPlane[colNumber] << 8;
-                dst.blu[dstCursor] = bluPlane[colNumber] << 8;
-            }
-        }
-    } break;
+    case 8:
+        doSameSize8bpp(trf, xsize, ysize, src, srcwid, colorMap, dst, dstwid);
+        break;
+    case 16:
+        doSameSize16bpp(trf, xsize, ysize, src, srcwid, dst, dstwid);
+        break;
+    case 32:
+        doSameSize32bpp(trf, xsize, ysize, src, srcwid, dst, dstwid);
+        break;
     default:
-        pm_error("INTERNAL ERROR: invalid bits per pixel (%u) in "
-                 "blitIdempotent()", pixSize);
+        pm_error("Impossible value of pixSize: %u", pixSize);
     }
 }
 
@@ -1557,16 +1750,15 @@ static void
 doBlit(struct Rect       const srcRect,
        struct Rect       const dstRect,
        struct Rect       const srcBounds,
-       struct raster     const srcplane,
+       struct Raster     const srcplane,
        struct Rect       const dstBounds,
-       struct rgbPlanes  const canvasPlanes,
+       struct RgbPlanes  const canvasPlanes,
        int               const pixSize,
        int               const dstwid,
-       struct RGBColor * const color_map,
-       int               const mode) {
+       struct RGBColor * const colorMap,
+       unsigned int      const mode) {
 /*----------------------------------------------------------------------------
-   Transfer some pixels from 'srcplane' to 'canvasPlanes', applying the
-   transfer function 'trf'.
+   Transfer some pixels from 'srcplane' to 'canvasPlanes'.
 
    'srcplane' contains the rectangle 'srcBounds' of the image.
    'canvasPlanes' contains the rectangle 'dstRect' of the image.
@@ -1579,11 +1771,12 @@ doBlit(struct Rect       const srcRect,
    with 'dstwid' words per row.
 -----------------------------------------------------------------------------*/
     unsigned char * src;
-    struct rgbPlanes dst;
+    struct RgbPlanes dst;
     int dstoff;
-    int xsize;
-    int ysize;
     transfer_func trf;
+        /* A transfer function to use as we transfer the pixels.
+           NULL for none.
+        */
 
     if (verbose) {
         dumpRect("copying from:", srcRect);
@@ -1601,12 +1794,17 @@ doBlit(struct Rect       const srcRect,
         assert(srcRowNumber < srcplane.rowCount);
         assert(srcRowOffset < srcplane.rowSize);
         src = srcplane.bytes + srcRowNumber * srcplane.rowSize + srcRowOffset;
-        xsize = rectwidth(&srcRect);
-        ysize = rectheight(&srcRect);
     }
 
+    /* This 'dstoff'/'dstadd' abomination has to be fixed.  We need to pass to
+       'doDiffSize' the whole actual canvas, 'canvasPlanes', and tell it to
+       what part of the canvas to write.  It can compute the location of each
+       destination row as it comes to it.
+     */
     dstoff = (dstRect.top - dstBounds.top) * dstwid +
         (dstRect.left - dstBounds.left);
+    dst.height = canvasPlanes.height - (dstRect.top - dstBounds.top);
+    dst.width  = canvasPlanes.width;
     dst.red = canvasPlanes.red + dstoff;
     dst.grn = canvasPlanes.grn + dstoff;
     dst.blu = canvasPlanes.blu + dstoff;
@@ -1615,35 +1813,31 @@ doBlit(struct Rect       const srcRect,
     if ((mode & ~64) == 0)
         trf = NULL;    /* optimized srcCopy */
     else
-        trf = transfer(mode & ~64);
+        trf = transferFunctionForMode(mode & ~64);
 
     if (!rectsamesize(srcRect, dstRect))
-        doDiffSize(srcRect, dstRect, pixSize, xsize, ysize,
-                   trf, color_map, src, srcplane.rowSize, dst, dstwid);
+        doDiffSize(srcRect, dstRect, pixSize,
+                   trf, colorMap, src, srcplane.rowSize, dst);
     else {
-        if (trf == NULL)
-            blitIdempotent(pixSize, xsize, ysize, src, srcplane.rowSize,
-                           color_map, dst, dstwid);
-        else
-            doSameSize(trf, pixSize, xsize, ysize, src, srcplane.rowSize,
-                       color_map, dst, dstwid);
+        doSameSize(trf, pixSize, srcRect, src, srcplane.rowSize,
+                   colorMap, dst, dstwid);
     }
 }
 
 
 
-static int
+static void
 blit(struct Rect       const srcRect,
      struct Rect       const srcBounds,
-     struct raster     const srcplane,
-     struct canvas *   const canvasP,
-     blitList *        const blitListP,
+     struct Raster     const srcplane,
+     struct Canvas *   const canvasP,
+     BlitList *        const blitListP,
      int               const pixSize,
      struct Rect       const dstRect,
      struct Rect       const dstBounds,
      int               const dstwid,
      struct RGBColor * const color_map,
-     int               const mode) {
+     unsigned int      const mode) {
 /*----------------------------------------------------------------------------
    'srcplane' contains the rectangle 'srcBounds' of the image.
 
@@ -1652,43 +1846,27 @@ blit(struct Rect       const srcRect,
    if 'blitListP' is non-null, we don't draw anything on 'canvasP'; instead,
    we add to the list *blitlistP a description of what needs to be drawn.
 -----------------------------------------------------------------------------*/
-
-    /* I can't tell what the result value of this function is supposed to mean,
-       but I found several return statements that did not set it to anything,
-       and several calls that examine it.  I'm guessing that "1" is the
-       appropriate thing to return in those cases, so I made it so.
-       -Bryan 00.03.02
-    */
-
-    int retval;
-
-    if (ps_text)
-        retval = 1;
-    else {
+    if (ps_text) {
+    } else {
         /* Almost got it.  Clip source rect with source bounds.
            clip dest rect with dest bounds.
         */
         struct Rect clipsrc;
         struct Rect clipdst;
 
-        rectinter(srcBounds, srcRect, &clipsrc);
-        rectinter(dstBounds, dstRect, &clipdst);
+        rectintersect(&srcBounds, &srcRect, &clipsrc);
+        rectintersect(&dstBounds, &dstRect, &clipdst);
 
         if (blitListP) {
             addBlitList(blitListP,
                         clipsrc, srcBounds, srcplane, pixSize,
                         clipdst, color_map, mode);
-
-            retval = 0;
         } else {
             doBlit(clipsrc, clipdst,
                    srcBounds, srcplane, dstBounds, canvasP->planes,
                    pixSize, dstwid, color_map, mode);
-
-            retval = 1;
         }
     }
-    return retval;
 }
 
 
@@ -1702,11 +1880,14 @@ blit(struct Rect       const srcRect,
 static void
 allocPlanes(unsigned int       const width,
             unsigned int       const height,
-            struct rgbPlanes * const planesP) {
+            struct RgbPlanes * const planesP) {
 
     unsigned int const planelen = width * height;
 
-    struct rgbPlanes planes;
+    struct RgbPlanes planes;
+
+    planes.width  = width;
+    planes.height = height;
 
     MALLOCARRAY(planes.red, planelen);
     MALLOCARRAY(planes.grn, planelen);
@@ -1725,7 +1906,7 @@ allocPlanes(unsigned int       const width,
 
 
 static void
-freePlanes(struct rgbPlanes const planes) {
+freePlanes(struct RgbPlanes const planes) {
 
     free(planes.red);
     free(planes.grn);
@@ -1743,11 +1924,11 @@ compact(Word const input) {
 
 
 static void
-reportBlitList(blitList * const blitListP) {
+reportBlitList(BlitList * const blitListP) {
 
     if (verbose) {
         unsigned int count;
-        struct blit_info * biP;
+        struct BlitInfo * biP;
 
         for (count = 0, biP = blitListP->firstP; biP; biP = biP->next)
             ++count;
@@ -1759,15 +1940,15 @@ reportBlitList(blitList * const blitListP) {
 
 
 static void
-doBlitList(struct canvas * const canvasP,
-           blitList *      const blitListP) {
+doBlitList(struct Canvas * const canvasP,
+           BlitList *      const blitListP) {
 /*----------------------------------------------------------------------------
    Do the list of blits *blitListP, drawing on canvas *canvasP.
 
    We allocate new plane data structures in *canvasP.  We assume it doesn't
    have them already.
 -----------------------------------------------------------------------------*/
-    struct blit_info * bi;
+    struct BlitInfo * bi;
     int srcwidth, dstwidth, srcheight, dstheight;
     double  scale, scalelow, scalehigh;
     double  xscale = 1.0;
@@ -1777,8 +1958,6 @@ doBlitList(struct canvas * const canvasP,
 
     reportBlitList(blitListP);
 
-    fullres = 0;
-
     for (bi = blitListP->firstP; bi; bi = bi->next) {
         srcwidth = rectwidth(&bi->srcRect);
         dstwidth = rectwidth(&bi->dstRect);
@@ -1855,7 +2034,7 @@ doBlitList(struct canvas * const canvasP,
     }
 
     if (xscale != 1.0 || yscale != 1.0) {
-        struct blit_info * biP;
+        struct BlitInfo * biP;
 
         for (biP = blitListP->firstP; biP; biP = biP->next)
             rectscale(&biP->dstRect, xscale, yscale);
@@ -1882,7 +2061,7 @@ doBlitList(struct canvas * const canvasP,
 
 static void
 outputPpm(FILE *           const ofP,
-          struct rgbPlanes const planes) {
+          struct RgbPlanes const planes) {
 
     unsigned int width;
     unsigned int height;
@@ -1922,18 +2101,20 @@ outputPpm(FILE *           const ofP,
  * is padded with a null.
  */
 static Word
-get_op(int const version) {
-    if ((align & 1) && version == 2) {
+nextOp(FILE *       const ifP,
+       unsigned int const version) {
+
+    if ((align & 0x1) && version == 2) {
         stage = "aligning for opcode";
-        readByte();
+        readByte(ifP);
     }
 
     stage = "reading opcode";
 
     if (version == 1)
-        return readByte();
+        return readByte(ifP);
     else
-        return readWord();
+        return readWord(ifP);
 }
 
 
@@ -1941,11 +2122,12 @@ get_op(int const version) {
 static drawFn ClipRgn;
 
 static void
-ClipRgn(struct canvas * const canvasP,
-        blitList *      const blitListP,
+ClipRgn(FILE *          const ifP,
+        struct Canvas * const canvasP,
+        BlitList *      const blitListP,
         int             const version) {
 
-    Word const len = readWord();
+    Word const len = readWord(ifP);
         /* Length in bytes of the parameter (including this word) */
 
     if (len == 10) {    /* null rgn */
@@ -1958,14 +2140,23 @@ ClipRgn(struct canvas * const canvasP,
            it to accept this clip rectangle, this program found the image to
            have an invalid raster.
         */
+        struct Rect clipRgnParm;
+
+        readRect(ifP, &clipRgnParm);
+
+        rectintersect(&clipRgnParm, &picFrame, &clip_rect);
 
-        readRect(&clip_rect);
-        rectinter(clip_rect, picFrame, &clip_rect);
-        /* XXX should clip this by picFrame */
+        if (!rectequal(&clipRgnParm, &clip_rect)) {
+            pm_message("ClipRgn opcode says to clip to a region which "
+                       "is not contained within the picture frame.  "
+                       "Ignoring the part outside the picture frame.");
+            dumpRect("ClipRgn:", clipRgnParm);
+            dumpRect("Picture frame:", picFrame);
+        }
         if (verbose)
             dumpRect("clipping to", clip_rect);
     } else
-        skip(len - 2);
+        skip(ifP, len - 2);
 }
 
 
@@ -1973,35 +2164,37 @@ ClipRgn(struct canvas * const canvasP,
 static drawFn OpColor;
 
 static void
-OpColor(struct canvas * const canvasP,
-        blitList *      const blitListP,
+OpColor(FILE *          const ifP,
+        struct Canvas * const canvasP,
+        BlitList *      const blitListP,
         int             const version) {
 
-    op_color.red = readWord();
-    op_color.grn = readWord();
-    op_color.blu = readWord();
+    op_color.red = readWord(ifP);
+    op_color.grn = readWord(ifP);
+    op_color.blu = readWord(ifP);
 }
 
 
 
 static void
-readPixmap(struct pixMap * const p) {
+readPixmap(FILE *          const ifP,
+           struct PixMap * const p) {
 
     stage = "getting pixMap header";
 
-    readRect(&p->Bounds);
-    p->version    = readWord();
-    p->packType   = readWord();
-    p->packSize   = readLong();
-    p->hRes       = readLong();
-    p->vRes       = readLong();
-    p->pixelType  = readWord();
-    p->pixelSize  = readWord();
-    p->cmpCount   = readWord();
-    p->cmpSize    = readWord();
-    p->planeBytes = readLong();
-    p->pmTable    = readLong();
-    p->pmReserved = readLong();
+    readRect(ifP, &p->Bounds);
+    p->version    = readWord(ifP);
+    p->packType   = readWord(ifP);
+    p->packSize   = readLong(ifP);
+    p->hRes       = readLong(ifP);
+    p->vRes       = readLong(ifP);
+    p->pixelType  = readWord(ifP);
+    p->pixelSize  = readWord(ifP);
+    p->cmpCount   = readWord(ifP);
+    p->cmpSize    = readWord(ifP);
+    p->planeBytes = readLong(ifP);
+    p->pmTable    = readLong(ifP);
+    p->pmReserved = readLong(ifP);
 
     if (verbose) {
         pm_message("pixelType: %d", p->pixelType);
@@ -2024,19 +2217,20 @@ readPixmap(struct pixMap * const p) {
 
 
 static struct RGBColor*
-readColorTable(void) {
+readColorTable(FILE * const ifP) {
+
     Longword ctSeed;
     Word ctFlags;
     Word ctSize;
     Word val;
     int i;
-    struct RGBColor* color_table;
+    struct RGBColor* colorTable;
 
     stage = "getting color table info";
 
-    ctSeed = readLong();
-    ctFlags = readWord();
-    ctSize = readWord();
+    ctSeed  = readLong(ifP);
+    ctFlags = readWord(ifP);
+    ctSize  = readWord(ifP);
 
     if (verbose) {
         pm_message("ctSeed:  %ld", ctSeed);
@@ -2046,12 +2240,12 @@ readColorTable(void) {
 
     stage = "reading color table";
 
-    MALLOCARRAY(color_table, ctSize + 1);
-    if (color_table == NULL)
+    MALLOCARRAY(colorTable, ctSize + 1);
+    if (!colorTable)
         pm_error("no memory for color table");
 
-    for (i = 0; i <= ctSize; i++) {
-        val = readWord();
+    for (i = 0; i <= ctSize; ++i) {
+        val = readWord(ifP);
         /* The indices in a device color table are bogus and usually == 0.
          * so I assume we allocate up the list of colors in order.
          */
@@ -2059,18 +2253,19 @@ readColorTable(void) {
             val = i;
         if (val > ctSize)
             pm_error("pixel value greater than color table size");
-        color_table[val].red = readWord();
-        color_table[val].grn = readWord();
-        color_table[val].blu = readWord();
+
+        colorTable[val].red = readWord(ifP);
+        colorTable[val].grn = readWord(ifP);
+        colorTable[val].blu = readWord(ifP);
 
         if (verbose > 1)
             pm_message("Color %3u: [%u,%u,%u]", val,
-                color_table[val].red,
-                color_table[val].grn,
-                color_table[val].blu);
+                colorTable[val].red,
+                colorTable[val].grn,
+                colorTable[val].blu);
     }
 
-    return color_table;
+    return colorTable;
 }
 
 
@@ -2166,7 +2361,7 @@ expand1Bit(unsigned char * const packed,
 static void
 unpackBuf(unsigned char *  const packed,
           unsigned int     const packedLen,
-          int              const bitsPerPixel,
+          unsigned int     const bitsPerPixel,
           unsigned char ** const expandedP,
           unsigned int *   const expandedLenP) {
 /*----------------------------------------------------------------------------
@@ -2222,7 +2417,7 @@ unpackBuf(unsigned char *  const packed,
 
 static void
 unpackUncompressedBits(FILE *          const ifP,
-                       struct raster   const raster,
+                       struct Raster   const raster,
                        unsigned int    const rowBytes,
                        unsigned int    const bitsPerPixel) {
 /*----------------------------------------------------------------------------
@@ -2237,6 +2432,9 @@ unpackUncompressedBits(FILE *          const ifP,
     unsigned int rowOfRect;
     unsigned char * linebuf;
 
+    if (verbose)
+        pm_message("Bits are not packed");
+
     MALLOCARRAY(linebuf, rowBytes + 100);
     if (linebuf == NULL)
         pm_error("can't allocate memory for line buffer");
@@ -2269,13 +2467,15 @@ reportValidateCompressedLineLen(unsigned int const row,
                                 unsigned int const linelen,
                                 unsigned int const rowSize) {
 /*----------------------------------------------------------------------------
-   'row' is a row number in the raster.
+  Report the line length and fail the program if it is obviously wrong.
+
+ 'row' is a row number in the raster.
 
-   'linelen' is the number of bytes of PICT that the PICT says hold the
-   compressed version of that row.
+ 'linelen' is the number of bytes of PICT that the PICT says hold the
+ compressed version of that row.
 
-   'rowSize' is the number of bytes we expect the uncompressed line to
-   be (includes pad pixels on the right).
+ 'rowSize' is the number of bytes we expect the uncompressed line to
+ be (includes pad pixels on the right).
 -----------------------------------------------------------------------------*/
     if (verbose > 1)
         pm_message("Row %u: %u-byte compressed line", row, linelen);
@@ -2333,7 +2533,7 @@ expandRun(unsigned char * const block,
 
         assert(block[0] & 0x80);  /* It's a run */
 
-        if (verbose > 1)
+        if (verbose > 2)
             pm_message("Block: run of %u packed %u-byte units",
                        runLength, pkpixsize);
 
@@ -2412,7 +2612,7 @@ copyPixelGroup(unsigned char * const block,
         assert(blockLimit >= 1);  /* block[0] exists */
         assert((block[0] & 0x80) == 0);  /* It's not a run */
 
-        if (verbose > 1)
+        if (verbose > 2)
             pm_message("Block: %u explicit packed %u-byte units",
                        groupLen, pkpixsize);
 
@@ -2474,10 +2674,6 @@ interpretOneRasterBlock(unsigned char * const block,
 
 
 
-static unsigned int const maxPixelBytesPerBlock = 1024;
-
-
-
 static void
 interpretCompressedLine(unsigned char * const linebuf,
                         unsigned int    const linelen,
@@ -2485,13 +2681,13 @@ interpretCompressedLine(unsigned char * const linebuf,
                         unsigned int    const rowSize,
                         unsigned int    const bitsPerPixel) {
 /*----------------------------------------------------------------------------
-   linebuf[] contains 'linelen' bytes from the PICT image that represents
-   one row of the image, in compressed format.  Return the
-   uncompressed pixels of that row as rowRaster[].
+   linebuf[] contains 'linelen' bytes from the PICT image that represents one
+   row of the image, in compressed format.  Return the uncompressed pixels of
+   that row as rowRaster[].
 
-   rowRaster[] has 'rowSize' bytes of space.  Caller ensures that
-   linebuf[] does not contain more pixels than that, unless the PICT
-   image from which it comes is corrupt.
+   rowRaster[] has 'rowSize' bytes of space.  Caller ensures that linebuf[]
+   does not contain more pixels than that, unless the PICT image from which it
+   comes is corrupt.
 -----------------------------------------------------------------------------*/
     unsigned int lineCursor;
         /* Cursor into linebuf[] -- the compressed data */
@@ -2518,7 +2714,8 @@ interpretCompressedLine(unsigned char * const linebuf,
         assert(rasterCursor <= rowSize);
     }
     if (verbose > 1)
-        pm_message("Got %u pixels for row", rasterCursor);
+        pm_message("Decompressed %u bytes into %u bytes for row",
+                   lineCursor, rasterCursor);
 }
 
 
@@ -2551,11 +2748,11 @@ interpretCompressedLine(unsigned char * const linebuf,
 
 static void
 unpackCompressedBits(FILE *          const ifP,
-                     struct raster   const raster,
+                     struct Raster   const raster,
                      unsigned int    const rowBytes,
                      unsigned int    const bitsPerPixel) {
 /*----------------------------------------------------------------------------
-   Read the raster on file *ifP and place it in 'raster'.
+   Set the raster bytes of 'raster' with bytes read from *ifP.
 
    The data in the file is compressed with run length encoding and
    possibly packed multiple pixels per byte as well.
@@ -2574,6 +2771,9 @@ unpackCompressedBits(FILE *          const ifP,
     unsigned char * linebuf;
     unsigned int linebufSize;
 
+    if (verbose)
+        pm_message("Bits are packed");
+
     linebufSize = rowBytes;
     MALLOCARRAY(linebuf, linebufSize);
     if (linebuf == NULL)
@@ -2585,9 +2785,9 @@ unpackCompressedBits(FILE *          const ifP,
         unsigned int linelen;
 
         if (llsize == 2)
-            linelen = readWord();
+            linelen = readWord(ifP);
         else
-            linelen = readByte();
+            linelen = readByte(ifP);
 
         reportValidateCompressedLineLen(row, linelen, raster.rowSize);
 
@@ -2611,19 +2811,19 @@ static void
 unpackbits(FILE *           const ifP,
            struct Rect *    const boundsP,
            Word             const rowBytesArg,
-           int              const bitsPerPixel,
-           struct raster *  const rasterP) {
+           unsigned int     const bitsPerPixel,
+           struct Raster *  const rasterP) {
 
     unsigned int const rectHeight = boundsP->bottom - boundsP->top;
     unsigned int const rectWidth  = boundsP->right  - boundsP->left;
 
-    struct raster raster;
+    struct Raster raster;
     unsigned int rowBytes;
 
     stage = "unpacking packbits";
 
     if (verbose)
-        pm_message("rowBytes = %u, bitsPerPixel = %d",
+        pm_message("rowBytes = %u, bitsPerPixel = %u",
                    rowBytesArg, bitsPerPixel);
 
     allocateRaster(&raster, rectWidth, rectHeight, bitsPerPixel);
@@ -2663,33 +2863,33 @@ interpretRowBytesWord(Word           const rowBytesWord,
  * a pattern in the fabled complete version.
  */
 static void
-readPattern(void) {
+readPattern(FILE * const ifP) {
 
     Word PatType;
 
     stage = "Reading a pattern";
 
-    PatType = readWord();
+    PatType = readWord(ifP);
 
     switch (PatType) {
     case 2:
-        skip(8); /* old pattern data */
-        skip(5); /* RGB for pattern */
+        skip(ifP, 8); /* old pattern data */
+        skip(ifP, 5); /* RGB for pattern */
         break;
     case 1: {
         Word rowBytesWord;
         bool pixMap;
         unsigned int rowBytes;
-        struct pixMap p;
-        struct raster raster;
+        struct PixMap p;
+        struct Raster raster;
         struct RGBColor * ct;
 
-        skip(8); /* old pattern data */
-        rowBytesWord = readWord();
+        skip(ifP, 8); /* old pattern data */
+        rowBytesWord = readWord(ifP);
         interpretRowBytesWord(rowBytesWord, &pixMap, &rowBytes);
-        readPixmap(&p);
-        ct = readColorTable();
-        unpackbits(ifp, &p.Bounds, rowBytes, p.pixelSize, &raster);
+        readPixmap(ifP, &p);
+        ct = readColorTable(ifP);
+        unpackbits(ifP, &p.Bounds, rowBytes, p.pixelSize, &raster);
         freeRaster(raster);
         free(ct);
     } break;
@@ -2700,16 +2900,17 @@ readPattern(void) {
 
 
 
-/* these 3 do nothing but skip over their data! */
+/* These three do nothing but skip over their data! */
 
 static drawFn BkPixPat;
 
 static void
-BkPixPat(struct canvas * const canvasP,
-         blitList *      const blitListP,
+BkPixPat(FILE *          const ifP,
+         struct Canvas * const canvasP,
+         BlitList *      const blitListP,
          int             const version) {
 
-    readPattern();
+    readPattern(ifP);
 }
 
 
@@ -2717,11 +2918,12 @@ BkPixPat(struct canvas * const canvasP,
 static drawFn PnPixPat;
 
 static void
-PnPixPat(struct canvas * const canvasP,
-         blitList *      const blitListP,
+PnPixPat(FILE *          const ifP,
+         struct Canvas * const canvasP,
+         BlitList *      const blitListP,
          int             const version) {
 
-    readPattern();
+    readPattern(ifP);
 }
 
 
@@ -2729,17 +2931,20 @@ PnPixPat(struct canvas * const canvasP,
 static drawFn FillPixPat;
 
 static void
-FillPixPat(struct canvas * const canvasP,
-           blitList *      const blitListP,
+FillPixPat(FILE *          const ifP,
+           struct Canvas * const canvasP,
+           BlitList *      const blitListP,
            int             const version) {
 
-    readPattern();
+    readPattern(ifP);
 }
 
 
 
 static void
-read8x8Pattern(struct Pattern * const pat) {
+read8x8Pattern(FILE *           const ifP,
+               struct Pattern * const pat) {
+
     unsigned char buf[8];
     unsigned char * exp;
     unsigned int len;
@@ -2747,7 +2952,7 @@ read8x8Pattern(struct Pattern * const pat) {
     unsigned int i;
 
     len = 8;  /* initial value */
-    readBytes(ifp, len, buf);
+    readBytes(ifP, len, buf);
     if (verbose) {
         pm_message("pattern: %02x%02x%02x%02x",
                    buf[0], buf[1], buf[2], buf[3]);
@@ -2764,11 +2969,12 @@ read8x8Pattern(struct Pattern * const pat) {
 static drawFn BkPat;
 
 static void
-BkPat(struct canvas * const canvasP,
-      blitList *      const blitListP,
+BkPat(FILE *          const ifP,
+      struct Canvas * const canvasP,
+      BlitList *      const blitListP,
       int             const version) {
 
-    read8x8Pattern(&bkpat);
+    read8x8Pattern(ifP, &bkpat);
 }
 
 
@@ -2776,11 +2982,12 @@ BkPat(struct canvas * const canvasP,
 static drawFn PnPat;
 
 static void
-PnPat(struct canvas * const canvasP,
-      blitList *      const blitListP,
+PnPat(FILE *          const ifP,
+      struct Canvas * const canvasP,
+      BlitList *      const blitListP,
       int             const version) {
 
-    read8x8Pattern(&pen_pat);
+    read8x8Pattern(ifP, &pen_pat);
 }
 
 
@@ -2788,11 +2995,12 @@ PnPat(struct canvas * const canvasP,
 static drawFn FillPat;
 
 static void
-FillPat(struct canvas * const canvasP,
-        blitList *      const blitListP,
+FillPat(FILE *          const ifP,
+        struct Canvas * const canvasP,
+        BlitList *      const blitListP,
         int             const version) {
 
-    read8x8Pattern(&fillpat);
+    read8x8Pattern(ifP, &fillpat);
 }
 
 
@@ -2800,12 +3008,14 @@ FillPat(struct canvas * const canvasP,
 static drawFn PnSize;
 
 static void
-PnSize(struct canvas * const canvasP,
-       blitList *      const blitListP,
+PnSize(FILE *          const ifP,
+       struct Canvas * const canvasP,
+       BlitList *      const blitListP,
        int             const version) {
 
-    pen_height = readWord();
-    pen_width = readWord();
+    pen_height = readWord(ifP);
+    pen_width  = readWord(ifP);
+
     if (verbose)
         pm_message("pen size %d x %d", pen_width, pen_height);
 }
@@ -2815,28 +3025,31 @@ PnSize(struct canvas * const canvasP,
 static drawFn PnSize;
 
 static void
-PnMode(struct canvas * const canvasP,
-       blitList *      const blitListP,
+PnMode(FILE *          const ifP,
+       struct Canvas * const canvasP,
+       BlitList *      const blitListP,
        int             const version) {
 
-    pen_mode = readWord();
+    pen_mode = readWord(ifP);
 
     if (pen_mode >= 8 && pen_mode < 15)
         pen_mode -= 8;
     if (verbose)
         pm_message("pen transfer mode = %s",
-            const_name(transfer_name, pen_mode));
+            constName(transfer_name, pen_mode));
 
-    pen_trf = transfer(pen_mode);
+    pen_trf = transferFunctionForMode(pen_mode);
 }
 
 
 
 static void
-readRgb(struct RGBColor * const rgb) {
-    rgb->red = readWord();
-    rgb->grn = readWord();
-    rgb->blu = readWord();
+readRgb(FILE *            const ifP,
+        struct RGBColor * const rgb) {
+
+    rgb->red = readWord(ifP);
+    rgb->grn = readWord(ifP);
+    rgb->blu = readWord(ifP);
 }
 
 
@@ -2844,11 +3057,13 @@ readRgb(struct RGBColor * const rgb) {
 static drawFn RGBFgCol;
 
 static void
-RGBFgCol(struct canvas * const canvasP,
-         blitList *      const blitListP,
+RGBFgCol(FILE *          const ifP,
+         struct Canvas * const canvasP,
+         BlitList *      const blitListP,
          int             const version) {
 
-    readRgb(&foreground);
+    readRgb(ifP, &foreground);
+
     if (verbose)
         pm_message("foreground now [%d,%d,%d]",
             foreground.red, foreground.grn, foreground.blu);
@@ -2859,11 +3074,13 @@ RGBFgCol(struct canvas * const canvasP,
 static drawFn RGBBkCol;
 
 static void
-RGBBkCol(struct canvas * const canvasP,
-         blitList *      const blitListP,
+RGBBkCol(FILE *          const ifP,
+         struct Canvas * const canvasP,
+         BlitList *      const blitListP,
          int             const version) {
 
-    readRgb(&background);
+    readRgb(ifP, &background);
+
     if (verbose)
         pm_message("background now [%d,%d,%d]",
             background.red, background.grn, background.blu);
@@ -2871,19 +3088,32 @@ RGBBkCol(struct canvas * const canvasP,
 
 
 
-#define PIXEL_INDEX(x,y) ((y) - picFrame.top) * rowlen + (x) - picFrame.left
+static unsigned int
+pixelIndex(struct Rect  const picFrame,
+           unsigned int const x,
+           unsigned int const y) {
+
+    unsigned int const rowLen = picFrame.right - picFrame.left;
+
+    assert(y >= picFrame.top  && y < picFrame.bottom);
+    assert(x >= picFrame.left && x < picFrame.right);
+
+    return (y - picFrame.top) * rowLen + (x - picFrame.left);
+}
+
+
 
 static void
-draw_pixel(struct canvas *   const canvasP,
-           int               const x,
-           int               const y,
-           struct RGBColor * const clr,
-           transfer_func           trf) {
+drawPixel(struct Canvas *   const canvasP,
+          int               const x,
+          int               const y,
+          struct RGBColor * const clr,
+          transfer_func           trf) {
 
     if (x < clip_rect.left || x >= clip_rect.right ||
         y < clip_rect.top  || y >= clip_rect.bottom) {
     } else {
-        unsigned int const i = PIXEL_INDEX(x, y);
+        unsigned int const i = pixelIndex(picFrame, x, y);
 
         struct RGBColor dst;
 
@@ -2902,55 +3132,66 @@ draw_pixel(struct canvas *   const canvasP,
 
 
 static void
-draw_pen_rect(struct canvas * const canvasP,
-              struct Rect *   const r) {
+drawPenRect(struct Canvas * const canvasP,
+            struct Rect *   const rP) {
 
-    int const rowadd = rowlen - (r->right - r->left);
+    if (!rectisnull(rP)) {
+        unsigned int const rowadd = rowlen - (rP->right - rP->left);
 
-    int i;
-    int x, y;
-    struct RGBColor dst;
+        unsigned int i;
+        unsigned int y;
 
-    i = PIXEL_INDEX(r->left, r->top);  /* initial value */
+        dumpRect("BRYAN: drawing rectangle ", *rP);
+        i = pixelIndex(picFrame, rP->left, rP->top);  /* initial value */
 
-    for (y = r->top; y < r->bottom; y++) {
-        for (x = r->left; x < r->right; x++) {
-            dst.red = canvasP->planes.red[i];
-            dst.grn = canvasP->planes.grn[i];
-            dst.blu = canvasP->planes.blu[i];
+        for (y = rP->top; y < rP->bottom; ++y) {
 
-            if (pen_pat.pix[(x & 7) + (y & 7) * 8])
-                (*pen_trf)(&black, &dst);
-            else
-                (*pen_trf)(&white, &dst);
+            unsigned int x;
+
+            for (x = rP->left; x < rP->right; ++x) {
 
-            canvasP->planes.red[i] = dst.red;
-            canvasP->planes.grn[i] = dst.grn;
-            canvasP->planes.blu[i] = dst.blu;
+                struct RGBColor dst;
 
-            i++;
+                assert(i < canvasP->planes.height * canvasP->planes.width);
+
+                dst.red = canvasP->planes.red[i];
+                dst.grn = canvasP->planes.grn[i];
+                dst.blu = canvasP->planes.blu[i];
+
+                if (pen_pat.pix[(x & 7) + (y & 7) * 8])
+                    (*pen_trf)(&black, &dst);
+                else
+                    (*pen_trf)(&white, &dst);
+
+                canvasP->planes.red[i] = dst.red;
+                canvasP->planes.grn[i] = dst.grn;
+                canvasP->planes.blu[i] = dst.blu;
+
+                ++i;
+            }
+            i += rowadd;
         }
-        i += rowadd;
     }
 }
 
 
 
 static void
-draw_pen(struct canvas * const canvasP,
-         int             const x,
-         int             const y) {
+drawPen(struct Canvas * const canvasP,
+        int             const x,
+        int             const y) {
 
-    struct Rect penrect;
+    struct Rect unclippedPenrect;
+    struct Rect clippedPenrect;
 
-    penrect.left = x;
-    penrect.right = x + pen_width;
-    penrect.top = y;
-    penrect.bottom = y + pen_height;
+    unclippedPenrect.left = x;
+    unclippedPenrect.right = x + pen_width;
+    unclippedPenrect.top = y;
+    unclippedPenrect.bottom = y + pen_height;
 
-    rectinter(penrect, clip_rect, &penrect);
+    rectintersect(&unclippedPenrect, &clip_rect, &clippedPenrect);
 
-    draw_pen_rect(canvasP, &penrect);
+    drawPenRect(canvasP, &clippedPenrect);
 }
 
 /*
@@ -2967,11 +3208,11 @@ draw_pen(struct canvas * const canvasP,
  * Paul Heckbert    3 Sep 85
  */
 static void
-scan_line(struct canvas * const canvasP,
-          short           const x1,
-          short           const y1,
-          short           const x2,
-          short           const y2) {
+scanLine(struct Canvas * const canvasP,
+         short           const x1,
+         short           const y1,
+         short           const x2,
+         short           const y2) {
 
     int d, x, y, ax, ay, sx, sy, dx, dy;
 
@@ -2985,7 +3226,7 @@ scan_line(struct canvas * const canvasP,
         if (ax>ay) {        /* x dominant */
             d = ay-(ax>>1);
             for (;;) {
-                draw_pen(canvasP, x, y);
+                drawPen(canvasP, x, y);
                 if (x==x2) return;
                 if ((x > rowlen) && (sx > 0)) return;
                 if (d>=0) {
@@ -2999,7 +3240,7 @@ scan_line(struct canvas * const canvasP,
         else {          /* y dominant */
             d = ax-(ay>>1);
             for (;;) {
-                draw_pen(canvasP, x, y);
+                drawPen(canvasP, x, y);
                 if (y==y2) return;
                 if ((y > collen) && (sy > 0)) return;
                 if (d>=0) {
@@ -3018,17 +3259,20 @@ scan_line(struct canvas * const canvasP,
 static drawFn Line;
 
 static void
-Line(struct canvas * const canvasP,
-     blitList *      const blitListP,
+Line(FILE *          const ifP,
+     struct Canvas * const canvasP,
+     BlitList *      const blitListP,
      int             const version) {
 
   struct Point p1;
-  readPoint(&p1);
-  readPoint(&current);
+  readPoint(ifP, &p1);
+  readPoint(ifP, &current);
+
   if (verbose)
     pm_message("(%d,%d) to (%d, %d)",
            p1.x,p1.y,current.x,current.y);
-  scan_line(canvasP, p1.x,p1.y,current.x,current.y);
+
+  scanLine(canvasP, p1.x,p1.y,current.x,current.y);
 }
 
 
@@ -3036,17 +3280,20 @@ Line(struct canvas * const canvasP,
 static drawFn LineFrom;
 
 static void
-LineFrom(struct canvas * const canvasP,
-         blitList *      const blitListP,
+LineFrom(FILE *          const ifP,
+         struct Canvas * const canvasP,
+         BlitList *      const blitListP,
          int             const version) {
 
     struct Point p1;
-    readPoint(&p1);
+
+    readPoint(ifP, &p1);
+
     if (verbose)
         pm_message("(%d,%d) to (%d, %d)", current.x, current.y, p1.x, p1.y);
 
     if (!blitListP)
-        scan_line(canvasP, current.x, current.y, p1.x, p1.y);
+        scanLine(canvasP, current.x, current.y, p1.x, p1.y);
 
     current.x = p1.x;
     current.y = p1.y;
@@ -3057,20 +3304,24 @@ LineFrom(struct canvas * const canvasP,
 static drawFn ShortLine;
 
 static void
-ShortLine(struct canvas * const canvasP,
-          blitList *      const blitListP,
+ShortLine(FILE *          const ifP,
+          struct Canvas * const canvasP,
+          BlitList *      const blitListP,
           int             const version) {
 
     struct Point p1;
-    readPoint(&p1);
-    readShortPoint(&current);
+
+    readPoint(ifP,&p1);
+    readShortPoint(ifP, &current);
+
     if (verbose)
         pm_message("(%d,%d) delta (%d, %d)", p1.x, p1.y, current.x, current.y);
+
     current.x += p1.x;
     current.y += p1.y;
 
     if (!blitListP)
-        scan_line(canvasP, p1.x, p1.y, current.x, current.y);
+        scanLine(canvasP, p1.x, p1.y, current.x, current.y);
 }
 
 
@@ -3078,19 +3329,25 @@ ShortLine(struct canvas * const canvasP,
 static drawFn ShortLineFrom;
 
 static void
-ShortLineFrom(struct canvas * const canvasP,
-              blitList *      const blitListP,
+ShortLineFrom(FILE *          const ifP,
+              struct Canvas * const canvasP,
+              BlitList *      const blitListP,
               int             const version) {
 
     struct Point p1;
-    readShortPoint(&p1);
+
+    readShortPoint(ifP, &p1);
+
     if (verbose)
         pm_message("(%d,%d) delta (%d, %d)",
                    current.x,current.y,p1.x,p1.y);
+
     p1.x += current.x;
     p1.y += current.y;
+
     if (!blitListP)
-        scan_line(canvasP, current.x, current.y, p1.x, p1.y);
+        scanLine(canvasP, current.x, current.y, p1.x, p1.y);
+
     current.x = p1.x;
     current.y = p1.y;
 }
@@ -3098,17 +3355,17 @@ ShortLineFrom(struct canvas * const canvasP,
 
 
 static void
-do_paintRect(struct canvas * const canvasP,
-             struct Rect     const prect) {
+doPaintRect(struct Canvas * const canvasP,
+            struct Rect     const prect) {
 
     struct Rect rect;
 
     if (verbose)
         dumpRect("painting", prect);
 
-    rectinter(clip_rect, prect, &rect);
+    rectintersect(&clip_rect, &prect, &rect);
 
-    draw_pen_rect(canvasP, &rect);
+    drawPenRect(canvasP, &rect);
 }
 
 
@@ -3116,13 +3373,15 @@ do_paintRect(struct canvas * const canvasP,
 static drawFn paintRect;
 
 static void
-paintRect(struct canvas * const canvasP,
-          blitList *      const blitListP,
+paintRect(FILE *          const ifP,
+          struct Canvas * const canvasP,
+          BlitList *      const blitListP,
           int             const version) {
 
-    readRect(&cur_rect);
+    readRect(ifP, &cur_rect);
+
     if (!blitListP)
-        do_paintRect(canvasP, cur_rect);
+        doPaintRect(canvasP, cur_rect);
 }
 
 
@@ -3130,19 +3389,20 @@ paintRect(struct canvas * const canvasP,
 static drawFn paintSameRect;
 
 static void
-paintSameRect(struct canvas * const canvasP,
-              blitList *      const blitListP,
+paintSameRect(FILE *          const ifP,
+              struct Canvas * const canvasP,
+              BlitList *      const blitListP,
               int             const version) {
 
     if (!blitListP)
-        do_paintRect(canvasP, cur_rect);
+        doPaintRect(canvasP, cur_rect);
 }
 
 
 
 static void
-do_frameRect(struct canvas * const canvasP,
-             struct Rect     const rect) {
+doFrameRect(struct Canvas * const canvasP,
+            struct Rect     const rect) {
 
     if (verbose)
         dumpRect("framing", rect);
@@ -3151,13 +3411,13 @@ do_frameRect(struct canvas * const canvasP,
         unsigned int x, y;
 
         for (x = rect.left; x <= rect.right - pen_width; x += pen_width) {
-            draw_pen(canvasP, x, rect.top);
-            draw_pen(canvasP, x, rect.bottom - pen_height);
+            drawPen(canvasP, x, rect.top);
+            drawPen(canvasP, x, rect.bottom - pen_height);
         }
 
         for (y = rect.top; y <= rect.bottom - pen_height ; y += pen_height) {
-            draw_pen(canvasP, rect.left, y);
-            draw_pen(canvasP, rect.right - pen_width, y);
+            drawPen(canvasP, rect.left, y);
+            drawPen(canvasP, rect.right - pen_width, y);
         }
     }
 }
@@ -3167,13 +3427,15 @@ do_frameRect(struct canvas * const canvasP,
 static drawFn frameRect;
 
 static void
-frameRect(struct canvas * const canvasP,
-          blitList *      const blitListP,
+frameRect(FILE *          const ifP,
+          struct Canvas * const canvasP,
+          BlitList *      const blitListP,
           int             const version) {
 
-    readRect(&cur_rect);
+    readRect(ifP, &cur_rect);
+
     if (!blitListP)
-        do_frameRect(canvasP, cur_rect);
+        doFrameRect(canvasP, cur_rect);
 }
 
 
@@ -3181,12 +3443,13 @@ frameRect(struct canvas * const canvasP,
 static drawFn frameSameRect;
 
 static void
-frameSameRect(struct canvas * const canvasP,
-              blitList *      const blitListP,
+frameSameRect(FILE *          const ifP,
+              struct Canvas * const canvasP,
+              BlitList *      const blitListP,
               int             const version) {
 
     if (!blitListP)
-        do_frameRect(canvasP, cur_rect);
+        doFrameRect(canvasP, cur_rect);
 }
 
 
@@ -3194,7 +3457,7 @@ frameSameRect(struct canvas * const canvasP,
 /* a stupid shell sort - I'm so embarrassed  */
 
 static void
-poly_sort(int const sort_index, struct Point points[]) {
+polySort(int const sort_index, struct Point points[]) {
   int d, i, j, temp;
 
   /* initialize and set up sort interval */
@@ -3227,9 +3490,9 @@ poly_sort(int const sort_index, struct Point points[]) {
 /* Watch out for the lack of error checking in the next two functions ... */
 
 static void
-scan_poly(struct canvas * const canvasP,
-          int             const np,
-          struct Point          pts[]) {
+scanPoly(struct Canvas * const canvasP,
+         int             const np,
+         struct Point          pts[]) {
 
   int dx,dy,dxabs,dyabs,i,scan_index,j,k,px,py;
   int sdx,sdy,x,y,toggle,old_sdy,sy0;
@@ -3283,7 +3546,7 @@ scan_poly(struct canvas * const canvasP,
         scan_index++;
       }
       px += sdx;
-      draw_pen(canvasP, px, py);
+      drawPen(canvasP, px, py);
     }
       }
     else
@@ -3299,7 +3562,7 @@ scan_poly(struct canvas * const canvasP,
         old_sdy = sdy;
         if (sdy != 0) scan_index--;
       }
-      draw_pen(canvasP, px,py);
+      drawPen(canvasP, px,py);
       coord[scan_index].x = px;
       coord[scan_index].y = py;
       scan_index++;
@@ -3312,14 +3575,14 @@ scan_poly(struct canvas * const canvasP,
   scan_index--;
   if (sy0 + sdy == 0) scan_index--;
 
-  poly_sort(scan_index, coord);
+  polySort(scan_index, coord);
 
   toggle = 0;
   for (i = 0; i < scan_index; i++) {
     if ((coord[i].y == coord[i+1].y) && (toggle == 0))
       {
     for (j = coord[i].x; j <= coord[i+1].x; j++)
-      draw_pen(canvasP, j, coord[i].y);
+      drawPen(canvasP, j, coord[i].y);
     toggle = 1;
       }
     else
@@ -3332,21 +3595,26 @@ scan_poly(struct canvas * const canvasP,
 static drawFn paintPoly;
 
 static void
-paintPoly(struct canvas * const canvasP,
-          blitList *      const blitListP,
+paintPoly(FILE *          const ifP,
+          struct Canvas * const canvasP,
+          BlitList *      const blitListP,
           int             const version) {
 
   struct Rect bb;
   struct Point pts[100];
-  int i, np = (readWord() - 10) >> 2;
+  int i;
+  int np;
+
+  np = (readWord(ifP) - 10) >> 2;
+
+  readRect(ifP, &bb);
 
-  readRect(&bb);
-  for (i=0; i<np; ++i)
-    readPoint(&pts[i]);
+  for (i = 0; i < np; ++i)
+      readPoint(ifP, &pts[i]);
 
   /* scan convert poly ... */
   if (!blitListP)
-      scan_poly(canvasP, np, pts);
+      scanPoly(canvasP, np, pts);
 }
 
 
@@ -3354,11 +3622,14 @@ paintPoly(struct canvas * const canvasP,
 static drawFn PnLocHFrac;
 
 static void
-PnLocHFrac(struct canvas * const canvasP,
-           blitList *      const blitListP,
+PnLocHFrac(FILE *          const ifP,
+           struct Canvas * const canvasP,
+           BlitList *      const blitListP,
            int             const version) {
 
-    Word frac = readWord();
+    Word frac;
+
+    frac = readWord(ifP);
 
     if (verbose)
         pm_message("PnLocHFrac = %d", frac);
@@ -3369,20 +3640,21 @@ PnLocHFrac(struct canvas * const canvasP,
 static drawFn TxMode;
 
 static void
-TxMode(struct canvas * const canvasP,
-       blitList *      const blitListP,
+TxMode(FILE *          const ifP,
+       struct Canvas * const canvasP,
+       BlitList *      const blitListP,
        int             const version) {
 
-    text_mode = readWord();
+    text_mode = readWord(ifP);
 
     if (text_mode >= 8 && text_mode < 15)
         text_mode -= 8;
     if (verbose)
         pm_message("text transfer mode = %s",
-            const_name(transfer_name, text_mode));
+            constName(transfer_name, text_mode));
 
     /* ignore the text mask bit 'cause we don't handle it yet */
-    text_trf = transfer(text_mode & ~64);
+    text_trf = transferFunctionForMode(text_mode & ~64);
 }
 
 
@@ -3390,13 +3662,15 @@ TxMode(struct canvas * const canvasP,
 static drawFn TxFont;
 
 static void
-TxFont(struct canvas * const canvasP,
-       blitList *      const blitListP,
+TxFont(FILE *          const ifP,
+       struct Canvas * const canvasP,
+       BlitList *      const blitListP,
        int             const version) {
 
-    text_font = readWord();
+    text_font = readWord(ifP);
+
     if (verbose)
-        pm_message("text font %s", const_name(font_name, text_font));
+        pm_message("text font %s", constName(font_name, text_font));
 }
 
 
@@ -3404,11 +3678,13 @@ TxFont(struct canvas * const canvasP,
 static drawFn TxFace;
 
 static void
-TxFace(struct canvas * const canvasP,
-       blitList *      const blitListP,
+TxFace(FILE *          const ifP,
+       struct Canvas * const canvasP,
+       BlitList *      const blitListP,
        int             const version) {
 
-    text_face = readByte();
+    text_face = readByte(ifP);
+
     if (verbose)
         pm_message("text face %d", text_face);
 }
@@ -3418,11 +3694,13 @@ TxFace(struct canvas * const canvasP,
 static drawFn TxSize;
 
 static void
-TxSize(struct canvas * const canvasP,
-       blitList *      const blitListP,
+TxSize(FILE *          const ifP,
+       struct Canvas * const canvasP,
+       BlitList *      const blitListP,
        int             const version) {
 
-    text_size = readWord();
+    text_size = readWord(ifP);
+
     if (verbose)
         pm_message("text size %d", text_size);
 }
@@ -3430,9 +3708,10 @@ TxSize(struct canvas * const canvasP,
 
 
 static void
-skip_text(blitList * const blitListP) {
+skipText(FILE *     const ifP,
+         BlitList * const blitListP) {
 
-    skip(readByte());
+    skip(ifP, readByte(ifP));
 
     blitListP->unblittableText = true;
 }
@@ -3440,7 +3719,7 @@ skip_text(blitList * const blitListP) {
 
 
 static int
-abs_value(int const x) {
+absValue(int const x) {
     if (x < 0)
         return -x;
     else
@@ -3450,18 +3729,18 @@ abs_value(int const x) {
 
 
 static struct font*
-get_font(int const font,
-         int const size,
-         int const style) {
+getFont(int const font,
+        int const size,
+        int const style) {
 
     int closeness, bestcloseness;
-    struct fontinfo* fi, *best;
+    struct FontInfo* fi, *best;
 
     best = 0;
     for (fi = fontlist; fi; fi = fi->next) {
-        closeness = abs_value(fi->font - font) * 10000 +
-            abs_value(fi->size - size) * 100 +
-            abs_value(fi->style - style);
+        closeness = absValue(fi->font - font) * 10000 +
+            absValue(fi->size - size) * 100 +
+            absValue(fi->style - style);
         if (!best || closeness < bestcloseness) {
             best = fi;
             bestcloseness = closeness;
@@ -3515,9 +3794,10 @@ rotate(int * const x,
 
 
 static void
-do_ps_text(struct canvas * const canvasP,
-           Word            const tx,
-           Word            const ty) {
+doPsText(FILE *          const ifP,
+         struct Canvas * const canvasP,
+         Word            const tx,
+         Word            const ty) {
 
     int len, width, i, w, h, x, y, rx, ry, o;
     Byte str[256], ch;
@@ -3532,12 +3812,12 @@ do_ps_text(struct canvas * const canvasP,
         ps_cent_set = 1;
     }
 
-    len = readByte();
+    len = readByte(ifP);
 
     /* XXX this width calculation is not completely correct */
     width = 0;
     for (i = 0; i < len; i++) {
-        ch = str[i] = readByte();
+        ch = str[i] = readByte(ifP);
         if (tfont->glyph[ch])
             width += tfont->glyph[ch]->xadd;
     }
@@ -3567,7 +3847,7 @@ do_ps_text(struct canvas * const canvasP,
                 if ((rx >= picFrame.left) && (rx < picFrame.right) &&
                     (ry >= picFrame.top) && (ry < picFrame.bottom))
                 {
-                    o = PIXEL_INDEX(rx, ry);
+                    o = pixelIndex(picFrame, rx, ry);
                     if (glyph->bmap[h * glyph->width + w]) {
                         canvasP->planes.red[o] = foreground.red;
                         canvasP->planes.grn[o] = foreground.grn;
@@ -3584,27 +3864,28 @@ do_ps_text(struct canvas * const canvasP,
 
 
 static void
-do_text(struct canvas *  const canvasP,
-        blitList *       const blitListP,
-        Word             const startx,
-        Word             const starty) {
+doText(FILE *           const ifP,
+       struct Canvas *  const canvasP,
+       BlitList *       const blitListP,
+       Word             const startx,
+       Word             const starty) {
 
     if (blitListP)
-        skip_text(blitListP);
+        skipText(ifP, blitListP);
     else {
-        if (!(tfont = get_font(text_font, text_size, text_face)))
+        if (!(tfont = getFont(text_font, text_size, text_face)))
             tfont = pbm_defaultfont("bdf");
 
         if (ps_text)
-            do_ps_text(canvasP, startx, starty);
+            doPsText(ifP, canvasP, startx, starty);
         else {
             int len;
             Word x, y;
 
             x = startx;
             y = starty;
-            for (len = readByte(); len > 0; --len) {
-                struct glyph* const glyph = tfont->glyph[readByte()];
+            for (len = readByte(ifP); len > 0; --len) {
+                struct glyph* const glyph = tfont->glyph[readByte(ifP)];
                 if (glyph) {
                     int dy;
                     int h;
@@ -3616,8 +3897,8 @@ do_text(struct canvas *  const canvasP,
                             struct RGBColor * const colorP =
                                 glyph->bmap[h * glyph->width + w] ?
                                 &black : &white;
-                            draw_pixel(canvasP,
-                                       x + w + glyph->x, dy, colorP, text_trf);
+                            drawPixel(canvasP,
+                                      x + w + glyph->x, dy, colorP, text_trf);
                         }
                     }
                     x += glyph->xadd;
@@ -3634,15 +3915,16 @@ do_text(struct canvas *  const canvasP,
 static drawFn LongText;
 
 static void
-LongText(struct canvas * const canvasP,
-         blitList *      const blitListP,
+LongText(FILE *          const ifP,
+         struct Canvas * const canvasP,
+         BlitList *      const blitListP,
          int             const version) {
 
     struct Point p;
 
-    readPoint(&p);
+    readPoint(ifP, &p);
 
-    do_text(canvasP, blitListP, p.x, p.y);
+    doText(ifP, canvasP, blitListP, p.x, p.y);
 }
 
 
@@ -3650,13 +3932,14 @@ LongText(struct canvas * const canvasP,
 static drawFn DHText;
 
 static void
-DHText(struct canvas * const canvasP,
-       blitList *      const blitListP,
+DHText(FILE *          const ifP,
+       struct Canvas * const canvasP,
+       BlitList *      const blitListP,
        int             const version) {
 
-    current.x += readByte();
+    current.x += readByte(ifP);
 
-    do_text(canvasP, blitListP, current.x, current.y);
+    doText(ifP, canvasP, blitListP, current.x, current.y);
 }
 
 
@@ -3664,13 +3947,14 @@ DHText(struct canvas * const canvasP,
 static drawFn DVText;
 
 static void
-DVText(struct canvas * const canvasP,
-       blitList *      const blitListP,
+DVText(FILE *          const ifP,
+       struct Canvas * const canvasP,
+       BlitList *      const blitListP,
        int             const version) {
 
-    current.y += readByte();
+    current.y += readByte(ifP);
 
-    do_text(canvasP, blitListP, current.x, current.y);
+    doText(ifP, canvasP, blitListP, current.x, current.y);
 }
 
 
@@ -3678,13 +3962,15 @@ DVText(struct canvas * const canvasP,
 static drawFn DHDVText;
 
 static void
-DHDVText(struct canvas * const canvasP,
-         blitList *      const blitListP,
+DHDVText(FILE *          const ifP,
+         struct Canvas * const canvasP,
+         BlitList *      const blitListP,
          int             const version) {
+
     Byte dh, dv;
 
-    dh = readByte();
-    dv = readByte();
+    dh = readByte(ifP);
+    dv = readByte(ifP);
 
     if (verbose)
         pm_message("dh, dv = %d, %d", dh, dv);
@@ -3692,7 +3978,7 @@ DHDVText(struct canvas * const canvasP,
     current.x += dh;
     current.y += dv;
 
-    do_text(canvasP, blitListP, current.x, current.y);
+    doText(ifP, canvasP, blitListP, current.x, current.y);
 }
 
 
@@ -3702,50 +3988,51 @@ DHDVText(struct canvas * const canvasP,
  */
 
 static void
-directBits(struct canvas * const canvasP,
-           blitList *      const blitListP,
+directBits(FILE *          const ifP,
+           struct Canvas * const canvasP,
+           BlitList *      const blitListP,
            unsigned int    const pictVersion,
            bool            const skipRegion) {
 
-    struct pixMap   p;
+    struct PixMap   p;
     struct Rect     srcRect;
     struct Rect     dstRect;
-    struct raster   raster;
+    struct Raster   raster;
     Word            mode;
 
     /* skip fake len, and fake EOF */
-    skip(4);    /* Ptr baseAddr == 0x000000ff */
-    readWord();    /* version */
-    readRect(&p.Bounds);
-    p.packType = readWord();
-    p.packSize = readLong();
-    p.hRes = readLong();
-    p.vRes = readLong();
-    p.pixelType = readWord();
-    p.pixelSize = readWord();
-    p.pixelSize = readWord();    /* XXX twice??? */
-    p.cmpCount = readWord();
-    p.cmpSize = readWord();
-    p.planeBytes = readLong();
-    p.pmTable = readLong();
-    p.pmReserved = readLong();
-
-    readRect(&srcRect);
+    skip(ifP, 4);    /* Ptr baseAddr == 0x000000ff */
+    readWord(ifP);    /* version */
+    readRect(ifP, &p.Bounds);
+    p.packType   = readWord(ifP);
+    p.packSize   = readLong(ifP);
+    p.hRes       = readLong(ifP);
+    p.vRes       = readLong(ifP);
+    p.pixelType  = readWord(ifP);
+    p.pixelSize  = readWord(ifP);
+    p.pixelSize  = readWord(ifP);    /* XXX twice??? */
+    p.cmpCount   = readWord(ifP);
+    p.cmpSize    = readWord(ifP);
+    p.planeBytes = readLong(ifP);
+    p.pmTable    = readLong(ifP);
+    p.pmReserved = readLong(ifP);
+
+    readRect(ifP, &srcRect);
     if (verbose)
         dumpRect("source rectangle:", srcRect);
 
-    readRect(&dstRect);
+    readRect(ifP, &dstRect);
     if (verbose)
         dumpRect("destination rectangle:", dstRect);
 
-    mode = readWord();
+    mode = readWord(ifP);
     if (verbose)
-        pm_message("transfer mode = %s", const_name(transfer_name, mode));
+        pm_message("transfer mode = %s", constName(transfer_name, mode));
 
     if (skipRegion)
-        skip_poly_or_region(canvasP, blitListP, pictVersion);
+        skipPolyOrRegion(ifP, canvasP, blitListP, pictVersion);
 
-    unpackbits(ifp, &p.Bounds, 0, p.pixelSize, &raster);
+    unpackbits(ifP, &p.Bounds, 0, p.pixelSize, &raster);
 
     blit(srcRect, p.Bounds, raster, canvasP, blitListP, p.pixelSize,
          dstRect, picFrame, rowlen, NULL, mode);
@@ -3761,11 +4048,12 @@ directBits(struct canvas * const canvasP,
 static drawFn DirectBitsRect;
 
 static void
-DirectBitsRect(struct canvas * const canvasP,
-               blitList *      const blitListP,
+DirectBitsRect(FILE *          const ifP,
+               struct Canvas * const canvasP,
+               BlitList *      const blitListP,
                int             const version) {
 
-    directBits(canvasP, blitListP, version, SKIP_REGION_FALSE);
+    directBits(ifP, canvasP, blitListP, version, SKIP_REGION_FALSE);
 }
 
 
@@ -3773,78 +4061,80 @@ DirectBitsRect(struct canvas * const canvasP,
 static drawFn DirectBitsRgn;
 
 static void
-DirectBitsRgn(struct canvas * const canvasP,
-              blitList *      const blitListP,
+DirectBitsRgn(FILE *          const ifP,
+              struct Canvas * const canvasP,
+              BlitList *      const blitListP,
               int             const version) {
 
-    directBits(canvasP, blitListP, version, SKIP_REGION_TRUE);
+    directBits(ifP, canvasP, blitListP, version, SKIP_REGION_TRUE);
 }
 
 
 
 static void
-do_pixmap(struct canvas * const canvasP,
-          blitList *      const blitListP,
-          int             const version,
-          Word            const rowBytes,
-          int             const is_region) {
+doPixmap(FILE *          const ifP,
+         struct Canvas * const canvasP,
+         BlitList *      const blitListP,
+         int             const version,
+         Word            const rowBytes,
+         int             const is_region) {
 /*----------------------------------------------------------------------------
    Do a paletted image.
 -----------------------------------------------------------------------------*/
     Word mode;
-    struct pixMap p;
-    struct raster raster;
-    struct RGBColor * color_table;
+    struct PixMap p;
+    struct Raster raster;
+    struct RGBColor * colorTable;
     struct Rect srcRect;
     struct Rect dstRect;
 
-    readPixmap(&p);
+    readPixmap(ifP, &p);
 
     if (verbose)
         pm_message("%u x %u paletted image",
                    p.Bounds.right - p.Bounds.left,
                    p.Bounds.bottom - p.Bounds.top);
 
-    color_table = readColorTable();
+    colorTable = readColorTable(ifP);
 
-    readRect(&srcRect);
+    readRect(ifP, &srcRect);
 
     if (verbose)
         dumpRect("source rectangle:", srcRect);
 
-    readRect(&dstRect);
+    readRect(ifP, &dstRect);
 
     if (verbose)
         dumpRect("destination rectangle:", dstRect);
 
-    mode = readWord();
+    mode = readWord(ifP);
 
     if (verbose)
-        pm_message("transfer mode = %s", const_name(transfer_name, mode));
+        pm_message("transfer mode = %s", constName(transfer_name, mode));
 
     if (is_region)
-        skip_poly_or_region(canvasP, blitListP, version);
+        skipPolyOrRegion(ifP, canvasP, blitListP, version);
 
     stage = "unpacking rectangle";
 
-    unpackbits(ifp, &p.Bounds, rowBytes, p.pixelSize, &raster);
+    unpackbits(ifP, &p.Bounds, rowBytes, p.pixelSize, &raster);
 
     blit(srcRect, p.Bounds, raster, canvasP, blitListP, 8,
-         dstRect, picFrame, rowlen, color_table, mode);
+         dstRect, picFrame, rowlen, colorTable, mode);
 
-    free(color_table);
+    free(colorTable);
     freeRaster(raster);
 }
 
 
 
 static void
-do_bitmap(FILE *          const ifP,
-          struct canvas * const canvasP,
-          blitList *      const blitListP,
-          int             const version,
-          int             const rowBytes,
-          int             const is_region) {
+doBitmap(FILE *          const ifP,
+         struct Canvas * const canvasP,
+         BlitList *      const blitListP,
+         int             const version,
+         int             const rowBytes,
+         int             const is_region) {
 /*----------------------------------------------------------------------------
    Do a bitmap.  That's one bit per pixel, 0 is white, 1 is black.
 
@@ -3854,22 +4144,22 @@ do_bitmap(FILE *          const ifP,
     struct Rect srcRect;
     struct Rect dstRect;
     Word mode;
-    struct raster raster;
+    struct Raster raster;
         /* This raster contains padding on the right to make a multiple
            of 16 pixels per row.
         */
     static struct RGBColor color_table[] = {
         {65535L, 65535L, 65535L}, {0, 0, 0} };
 
-    readRect(&Bounds);
-    readRect(&srcRect);
-    readRect(&dstRect);
-    mode = readWord();
+    readRect(ifP, &Bounds);
+    readRect(ifP, &srcRect);
+    readRect(ifP, &dstRect);
+    mode = readWord(ifP);
     if (verbose)
-        pm_message("transfer mode = %s", const_name(transfer_name, mode));
+        pm_message("transfer mode = %s", constName(transfer_name, mode));
 
     if (is_region)
-        skip_poly_or_region(canvasP, blitListP, version);
+        skipPolyOrRegion(ifP, canvasP, blitListP, version);
 
     stage = "unpacking rectangle";
 
@@ -3886,8 +4176,9 @@ do_bitmap(FILE *          const ifP,
 static drawFn BitsRect;
 
 static void
-BitsRect(struct canvas * const canvasP,
-         blitList *      const blitListP,
+BitsRect(FILE *          const ifP,
+         struct Canvas * const canvasP,
+         BlitList *      const blitListP,
          int             const version) {
 
     Word rowBytesWord;
@@ -3895,14 +4186,14 @@ BitsRect(struct canvas * const canvasP,
     unsigned int rowBytes;
 
     stage = "Reading rowBytes word for bitsrect";
-    rowBytesWord = readWord();
+    rowBytesWord = readWord(ifP);
 
     interpretRowBytesWord(rowBytesWord, &pixMap, &rowBytes);
 
     if (pixMap)
-        do_pixmap(canvasP, blitListP, version, rowBytes, 0);
+        doPixmap(ifP, canvasP, blitListP, version, rowBytes, 0);
     else
-        do_bitmap(ifp, canvasP, blitListP, version, rowBytes, 0);
+        doBitmap(ifP, canvasP, blitListP, version, rowBytes, 0);
 }
 
 
@@ -3910,8 +4201,9 @@ BitsRect(struct canvas * const canvasP,
 static drawFn BitsRegion;
 
 static void
-BitsRegion(struct canvas * const canvasP,
-           blitList *      const blitListP,
+BitsRegion(FILE *          const ifP,
+           struct Canvas * const canvasP,
+           BlitList *      const blitListP,
            int             const version) {
 
     Word rowBytesWord;
@@ -3919,14 +4211,14 @@ BitsRegion(struct canvas * const canvasP,
     unsigned int rowBytes;
 
     stage = "Reading rowBytes for bitsregion";
-    rowBytesWord = readWord();
+    rowBytesWord = readWord(ifP);
 
     interpretRowBytesWord(rowBytesWord, &pixMap, &rowBytes);
 
     if (pixMap)
-        do_pixmap(canvasP, blitListP, version, rowBytes, 1);
+        doPixmap(ifP, canvasP, blitListP, version, rowBytes, 1);
     else
-        do_bitmap(ifp, canvasP, blitListP, version, rowBytes, 1);
+        doBitmap(ifP, canvasP, blitListP, version, rowBytes, 1);
 }
 
 
@@ -3935,7 +4227,7 @@ BitsRegion(struct canvas * const canvasP,
   * See http://developer.apple.com/techpubs/mac/QuickDraw/QuickDraw-461.html
   * for opcode description
   */
-static struct opdef const optable[] = {
+static struct Opdef const optable[] = {
 /* 0x00 */  { "NOP", 0, NULL, "nop" },
 /* 0x01 */  { "ClipRgn", NA, ClipRgn, "clip region" },
 /* 0x02 */  { "BkPat", 8, BkPat, "background pattern" },
@@ -4051,14 +4343,14 @@ static struct opdef const optable[] = {
 /* 0x6d */  RESERVED_OP(4),
 /* 0x6e */  RESERVED_OP(4),
 /* 0x6f */  RESERVED_OP(4),
-/* 0x70 */  { "framePoly", NA, skip_poly_or_region, "poly" },
+/* 0x70 */  { "framePoly", NA, skipPolyOrRegion, "poly" },
 /* 0x71 */  { "paintPoly", NA, paintPoly, "poly" },
-/* 0x72 */  { "erasePoly", NA, skip_poly_or_region, "poly" },
-/* 0x73 */  { "invertPoly", NA, skip_poly_or_region, "poly" },
-/* 0x74 */  { "fillPoly", NA, skip_poly_or_region, "poly" },
-/* 0x75 */  RESERVED_OP_F(skip_poly_or_region),
-/* 0x76 */  RESERVED_OP_F(skip_poly_or_region),
-/* 0x77 */  RESERVED_OP_F(skip_poly_or_region),
+/* 0x72 */  { "erasePoly", NA, skipPolyOrRegion, "poly" },
+/* 0x73 */  { "invertPoly", NA, skipPolyOrRegion, "poly" },
+/* 0x74 */  { "fillPoly", NA, skipPolyOrRegion, "poly" },
+/* 0x75 */  RESERVED_OP_F(skipPolyOrRegion),
+/* 0x76 */  RESERVED_OP_F(skipPolyOrRegion),
+/* 0x77 */  RESERVED_OP_F(skipPolyOrRegion),
 /* 0x78 */  { "frameSamePoly", 0, NULL, "poly (NYI)" },
 /* 0x79 */  { "paintSamePoly", 0, NULL, "poly (NYI)" },
 /* 0x7a */  { "eraseSamePoly", 0, NULL, "poly (NYI)" },
@@ -4067,14 +4359,14 @@ static struct opdef const optable[] = {
 /* 0x7d */  RESERVED_OP(0),
 /* 0x7e */  RESERVED_OP(0),
 /* 0x7f */  RESERVED_OP(0),
-/* 0x80 */  { "frameRgn", NA, skip_poly_or_region, "region" },
-/* 0x81 */  { "paintRgn", NA, skip_poly_or_region, "region" },
-/* 0x82 */  { "eraseRgn", NA, skip_poly_or_region, "region" },
-/* 0x83 */  { "invertRgn", NA, skip_poly_or_region, "region" },
-/* 0x84 */  { "fillRgn", NA, skip_poly_or_region, "region" },
-/* 0x85 */  RESERVED_OP_F(skip_poly_or_region),
-/* 0x86 */  RESERVED_OP_F(skip_poly_or_region),
-/* 0x87 */  RESERVED_OP_F(skip_poly_or_region),
+/* 0x80 */  { "frameRgn", NA, skipPolyOrRegion, "region" },
+/* 0x81 */  { "paintRgn", NA, skipPolyOrRegion, "region" },
+/* 0x82 */  { "eraseRgn", NA, skipPolyOrRegion, "region" },
+/* 0x83 */  { "invertRgn", NA, skipPolyOrRegion, "region" },
+/* 0x84 */  { "fillRgn", NA, skipPolyOrRegion, "region" },
+/* 0x85 */  RESERVED_OP_F(skipPolyOrRegion),
+/* 0x86 */  RESERVED_OP_F(skipPolyOrRegion),
+/* 0x87 */  RESERVED_OP_F(skipPolyOrRegion),
 /* 0x88 */  { "frameSameRgn", 0, NULL, "region (NYI)" },
 /* 0x89 */  { "paintSameRgn", 0, NULL, "region (NYI)" },
 /* 0x8a */  { "eraseSameRgn", 0, NULL, "region (NYI)" },
@@ -4109,9 +4401,10 @@ static struct opdef const optable[] = {
 
 
 static void
-processOpcode(Word            const opcode,
-              struct canvas * const canvasP,
-              blitList *      const blitListP,
+processOpcode(FILE *          const ifP,
+              Word            const opcode,
+              struct Canvas * const canvasP,
+              BlitList *      const blitListP,
               unsigned int    const version) {
 
     if (opcode < 0xa2) {
@@ -4124,15 +4417,15 @@ processOpcode(Word            const opcode,
         }
 
         if (optable[opcode].impl != NULL)
-            (*optable[opcode].impl)(canvasP, blitListP, version);
+            (*optable[opcode].impl)(ifP, canvasP, blitListP, version);
         else if (optable[opcode].len >= 0)
-            skip(optable[opcode].len);
+            skip(ifP, optable[opcode].len);
         else {
             /* It's a special length code */
             switch (optable[opcode].len) {
             case WORD_LEN: {
-                Word const len = readWord();
-                skip(len);
+                Word const len = readWord(ifP);
+                skip(ifP, len);
             } break;
             default:
                 pm_error("can't do length %d", optable[opcode].len);
@@ -4142,12 +4435,12 @@ processOpcode(Word            const opcode,
         if (verbose)
             pm_message("HeaderOp");
         stage = "HeaderOp";
-        skip(24);
+        skip(ifP, 24);
     } else if (opcode >= 0xa2 && opcode <= 0xaf) {
         stage = "skipping reserved";
         if (verbose)
             pm_message("%s 0x%x", stage, opcode);
-        skip(readWord());
+        skip(ifP, readWord(ifP));
     } else if (opcode >= 0xb0 && opcode <= 0xcf) {
         /* just a reserved opcode, no data */
         if (verbose)
@@ -4156,12 +4449,12 @@ processOpcode(Word            const opcode,
         stage = "skipping reserved";
         if (verbose)
             pm_message("%s 0x%x", stage, opcode);
-        skip(readLong());
+        skip(ifP, readLong(ifP));
     } else if (opcode >= 0x100 && opcode <= 0x7fff) {
         stage = "skipping reserved";
         if (verbose)
             pm_message("%s 0x%x", stage, opcode);
-        skip((opcode >> 7) & 255);
+        skip(ifP, (opcode >> 7) & 255);
     } else if (opcode >= 0x8000 && opcode <= 0x80ff) {
         /* just a reserved opcode, no data */
         if (verbose)
@@ -4170,7 +4463,7 @@ processOpcode(Word            const opcode,
         stage = "skipping reserved";
         if (verbose)
             pm_message("%s 0x%x", stage, opcode);
-        skip(readLong());
+        skip(ifP, readLong(ifP));
     } else
         pm_error("This program does not understand opcode 0x%04x", opcode);
 }
@@ -4178,15 +4471,23 @@ processOpcode(Word            const opcode,
 
 
 static void
-interpretPict(FILE * const ofP) {
+interpretPict(FILE *       const ifP,
+              FILE *       const ofP,
+              bool         const noheader,
+              bool         const fullres,
+              bool         const quickdraw,
+              unsigned int const verboseArg) {
 
     Byte ch;
     Word picSize;
     Word opcode;
     unsigned int version;
     unsigned int i;
-    struct canvas canvas;
-    blitList blitList;
+    struct Canvas canvas;
+    BlitList blitList;
+
+    verbose = verboseArg;
+    recognize_comment = !quickdraw;
 
     initBlitList(&blitList);
 
@@ -4194,18 +4495,24 @@ interpretPict(FILE * const ofP) {
         pen_pat.pix[i] = bkpat.pix[i] = fillpat.pix[i] = 1;
     pen_width = pen_height = 1;
     pen_mode = 0; /* srcCopy */
-    pen_trf = transfer(pen_mode);
+    pen_trf = transferFunctionForMode(pen_mode);
     text_mode = 0; /* srcCopy */
-    text_trf = transfer(text_mode);
+    text_trf = transferFunctionForMode(text_mode);
+
+    if (!noheader) {
+        stage = "Reading 512 byte header";
+        /* Note that the "header" in PICT is entirely comment! */
+        skip(ifP, 512);
+    }
 
     stage = "Reading picture size";
-    picSize = readWord();
+    picSize = readWord(ifP);
 
     if (verbose)
         pm_message("picture size = %u (0x%x)", picSize, picSize);
 
     stage = "reading picture frame";
-    readRect(&picFrame);
+    readRect(ifP, &picFrame);
 
     if (verbose) {
         dumpRect("Picture frame:", picFrame);
@@ -4223,18 +4530,18 @@ interpretPict(FILE * const ofP) {
         clip_rect = picFrame;
     }
 
-    while ((ch = readByte()) == 0)
+    while ((ch = readByte(ifP)) == 0)
         ;
     if (ch != 0x11)
         pm_error("No version number");
 
-    version = readByte();
+    version = readByte(ifP);
 
     switch (version) {
     case 1:
         break;
     case 2: {
-        unsigned char const subcode = readByte();
+        unsigned char const subcode = readByte(ifP);
         if (subcode != 0xff)
             pm_error("The only Version 2 PICT images this program "
                      "undertands are subcode 0xff.  This image has "
@@ -4247,8 +4554,9 @@ interpretPict(FILE * const ofP) {
     if (verbose)
         pm_message("PICT version %u", version);
 
-    while((opcode = get_op(version)) != 0xff)
-        processOpcode(opcode, &canvas, fullres ? &blitList : NULL, version);
+    while((opcode = nextOp(ifP, version)) != 0xff)
+        processOpcode(ifP, opcode, &canvas, fullres ? &blitList : NULL,
+                      version);
 
     if (fullres) {
         if (blitList.unblittableText)
@@ -4263,79 +4571,30 @@ interpretPict(FILE * const ofP) {
 
 
 
-static void
-loadDefaultFontDir(void) {
-/*----------------------------------------------------------------------------
-   Load the fonts from the font directory file "fontdir" (in the current
-   directory), if it exists.
------------------------------------------------------------------------------*/
-    struct stat statbuf;
-    int rc;
-
-    rc = stat("fontdir", &statbuf);
-
-    if (rc == 0)
-        load_fontdir("fontdir");
-}
+int
+main(int argc, const char *argv[]) {
 
+    struct CmdlineInfo cmdline;
+    FILE * ifP;
 
+    pm_proginit(&argc, argv);
 
-int
-main(int argc, char * argv[]) {
-    int argn;
-    int header;
-    const char* const usage =
-"[-verbose] [-fullres] [-noheader] [-quickdraw] [-fontdir file] [pictfile]";
-
-    ppm_init( &argc, argv );
-
-    argn = 1;
-    verbose = 0;
-    fullres = 0;
-    header = 1;
-    recognize_comment = 1;
-
-    while (argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0') {
-        if (pm_keymatch(argv[argn], "-verbose", 2))
-            verbose++;
-        else if (pm_keymatch(argv[argn], "-fullres", 3))
-            fullres = 1;
-        else if (pm_keymatch(argv[argn], "-noheader", 2))
-            header = 0;
-        else if (pm_keymatch(argv[argn], "-quickdraw", 2))
-            recognize_comment = 0;
-        else if (pm_keymatch(argv[argn], "-fontdir", 3)) {
-            argn++;
-            if (!argv[argn])
-                pm_usage(usage);
-            else
-                load_fontdir(argv[argn]);
-        }
-        else
-            pm_usage(usage);
-        ++argn;
-    }
+    parseCommandLine(argc, argv, &cmdline);
 
-    if (argn < argc) {
-        ifp = pm_openr(argv[argn]);
-        ++argn;
-    } else
-        ifp = stdin;
+    ifP = pm_openr(cmdline.inputFileName);
 
-    if (argn != argc)
-        pm_usage(usage);
+    if (cmdline.fontdir)
+        loadFontdir(cmdline.fontdir);
 
     loadDefaultFontDir();
 
-    if (header) {
-        stage = "Reading 512 byte header";
-        /* Note that the "header" in PICT is entirely comment! */
-        skip(512);
-    }
-
-    interpretPict(stdout);
+    interpretPict(ifP, stdout, cmdline.noheader,
+                  cmdline.fullres, cmdline.quickdraw, cmdline.verbose);
 
     pm_close(stdout);
 
     return 0;
 }
+
+
+
diff --git a/converter/ppm/pjtoppm.c b/converter/ppm/pjtoppm.c
index b0c879a0..e556803f 100644
--- a/converter/ppm/pjtoppm.c
+++ b/converter/ppm/pjtoppm.c
@@ -161,7 +161,7 @@ main(int argc, const char ** argv) {
                 switch (c) {
                 case 'M':   /* transmission mode */
                     if (val != 0 && val != 1)
-                        pm_error("unimplemented trasmission mode %d", val);
+                        pm_error("unimplemented transmission mode %d", val);
                     mode = val;
                     modeIsSet = true;
                     break;
diff --git a/converter/ppm/ppmtoapplevol.c b/converter/ppm/ppmtoapplevol.c
index eb4b6b2a..1e979de9 100644
--- a/converter/ppm/ppmtoapplevol.c
+++ b/converter/ppm/ppmtoapplevol.c
@@ -78,7 +78,7 @@ main (int argc, const char * argv[]) {
 
     for (row = 0; row < rows; row++) {
         unsigned int col;
-        
+
         ppm_readppmrow(ifP, pixelrow, cols, maxval, format);
 
         for (col = 0; col < cols; ++col) {
diff --git a/converter/ppm/ppmtoarbtxt.c b/converter/ppm/ppmtoarbtxt.c
index 6d4ed04e..6d4c6eac 100644
--- a/converter/ppm/ppmtoarbtxt.c
+++ b/converter/ppm/ppmtoarbtxt.c
@@ -1079,7 +1079,7 @@ readSkeletonFile(const char *      const filename,
                 int rc;
                 rc = getc(sklfileP);
                 if (rc == EOF) {
-                    /* Not a replacement sequence, just an escape caharacter
+                    /* Not a replacement sequence, just an escape character
                        at the end of the file.
                     */
                     Buffer_add(&buffer, escape);
diff --git a/converter/ppm/ppmtobmp.c b/converter/ppm/ppmtobmp.c
index f89cec8d..41cee482 100644
--- a/converter/ppm/ppmtobmp.c
+++ b/converter/ppm/ppmtobmp.c
@@ -138,7 +138,7 @@ parseCommandLine(int argc, const char ** argv,
         cmdlineP->inputFilename = pm_strdup(argv[1]);
     else
         pm_error("Too many arguments.  The only argument accepted "
-                 "is the input file specificaton");
+                 "is the input file specification");
 
     free(option_def);
 }
diff --git a/converter/ppm/ppmtoilbm.c b/converter/ppm/ppmtoilbm.c
index c5fa4d00..ad07f9fb 100644
--- a/converter/ppm/ppmtoilbm.c
+++ b/converter/ppm/ppmtoilbm.c
@@ -73,7 +73,6 @@
 #include "pm_c_util.h"
 #include "mallocvar.h"
 #include "ppm.h"
-#include "ppmfloyd.h"
 #include "pbm.h"
 #include "runlength.h"
 #include "ilbm.h"
@@ -118,13 +117,13 @@
 static unsigned char *coded_rowbuf; /* buffer for uncompressed scanline */
 static unsigned char *compr_rowbuf; /* buffer for compressed scanline */
 static pixel **pixels;  /* PPM image (NULL for row-by-row operation) */
-static pixel *pixrow;   
+static pixel *pixrow;
     /* current row in PPM image (pointer into pixels array, or buffer
-       for row-by-row operation) 
+       for row-by-row operation)
     */
 
 static long viewportmodes = 0;
-static int slicesize = 1; 
+static int slicesize = 1;
     /* rows per slice for multipalette images - NOT USED */
 
 static unsigned char compmethod = DEF_COMPRESSION;   /* default compression */
@@ -155,9 +154,8 @@ static bodyblock *cur_block = &firstblock;
 static char *anno_chunk, *auth_chunk, *name_chunk, *text_chunk, *copyr_chunk;
 
 /* flags */
-static short compr_force = 0;   
+static short compr_force = 0;
     /* force compressed output, even if the image got larger  - NOT USED */
-static short floyd = 0;         /* apply floyd-steinberg error diffusion */
 static short gen_camg = 0;      /* write CAMG chunk */
 
 #define WORSTCOMPR(bytes)       ((bytes) + (bytes)/128 + 1)
@@ -360,7 +358,7 @@ writeCmap(pixel * const colormap,
     pm_writebiglong(stdout, cmapsize);
     if( maxval != MAXCOLVAL ) {
         int *table;
-        pm_message("maxval is not %d - automatically rescaling colors", 
+        pm_message("maxval is not %d - automatically rescaling colors",
                    MAXCOLVAL);
         table = makeValTable(maxval, MAXCOLVAL);
         for( i = 0; i < colors; i++ ) {
@@ -457,7 +455,7 @@ compressRow(unsigned int const bytes) {
                 &compressedByteCt);
             break;
         default:
-            pm_error("compressRow(): unknown compression method %d", 
+            pm_error("compressRow(): unknown compression method %d",
                      compmethod);
     }
     storeBodyrow(compr_rowbuf, compressedByteCt);
@@ -551,35 +549,35 @@ reportTooManyColors(int         const ifmode,
                     int         const hamplanes,
                     DirectColor const dcol,
                     int         const deepbits) {
-    
+
     int const maxcolors = 1 << maxplanes;
 
     switch( ifmode ) {
     case MODE_HAM:
         pm_message("too many colors for %d planes - "
-                   "proceeding to write a HAM%d file", 
+                   "proceeding to write a HAM%d file",
                    maxplanes, hamplanes);
-        pm_message("if you want a non-HAM file, try doing a 'pnmquant %d'", 
+        pm_message("if you want a non-HAM file, try doing a 'pnmquant %d'",
                    maxcolors);
         break;
     case MODE_DCOL:
         pm_message("too many colors for %d planes - "
-                   "proceeding to write a %d:%d:%d direct color ILBM", 
+                   "proceeding to write a %d:%d:%d direct color ILBM",
                    maxplanes, dcol.r, dcol.g, dcol.b);
         pm_message("if you want a non-direct color file, "
                    "try doing a 'pnmquant %d'", maxcolors);
         break;
     case MODE_DEEP:
         pm_message("too many colors for %d planes - "
-                   "proceeding to write a %d-bit \'deep\' ILBM", 
+                   "proceeding to write a %d-bit \'deep\' ILBM",
                    maxplanes, deepbits*3);
         pm_message("if you want a non-deep file, "
-                   "try doing a 'pnmquant %d'", 
+                   "try doing a 'pnmquant %d'",
                    maxcolors);
         break;
     default:
         pm_error("too many colors for %d planes - "
-                 "try doing a 'pnmquant %d'", 
+                 "try doing a 'pnmquant %d'",
                  maxplanes, maxcolors);
         break;
     }
@@ -599,7 +597,7 @@ getIntVal(const char * const string,
         pm_error("option \"%s\" needs integer argument", option);
 
     if (val < bot || val > top)
-        pm_error("option \"%s\" argument value out of range (%d..%d)", 
+        pm_error("option \"%s\" argument value out of range (%d..%d)",
                  option, bot, top);
 
     return val;
@@ -613,10 +611,10 @@ getComprMethod(const char * const string) {
     int retval;
     if( pm_keymatch(string, "none", 1) || pm_keymatch(string, "0", 1) )
         retval = cmpNone;
-    else if( pm_keymatch(string, "byterun1", 1) || 
+    else if( pm_keymatch(string, "byterun1", 1) ||
              pm_keymatch(string, "1", 1) )
         retval = cmpByteRun1;
-    else 
+    else
         pm_error("unknown compression method: %s", string);
     return retval;
 }
@@ -631,12 +629,12 @@ getMaskType(const char * const string) {
     if( pm_keymatch(string, "none", 1) || pm_keymatch(string, "0", 1) )
         retval = mskNone;
     else
-    if( pm_keymatch(string, "plane", 1) || 
+    if( pm_keymatch(string, "plane", 1) ||
         pm_keymatch(string, "maskplane", 1) ||
         pm_keymatch(string, "1", 1) )
         retval = mskHasMask;
     else
-    if( pm_keymatch(string, "transparentcolor", 1) || 
+    if( pm_keymatch(string, "transparentcolor", 1) ||
         pm_keymatch(string, "2", 1) )
         retval = mskHasTransparentColor;
     else
@@ -665,7 +663,7 @@ getHammapMode(const char * const string) {
     else
     if( pm_keymatch(string, "rgb5", 4) )
         retval = HAMMODE_RGB5;
-    else 
+    else
         pm_error("unknown HAM colormap selection mode: %s", string);
     return retval;
 }
@@ -726,7 +724,7 @@ hcmp(const void * const a,
     const hentry * const vaP = a;
     const hentry * const vbP = b;
 
-    return(vbP->count - vaP->count);  
+    return(vbP->count - vaP->count);
 }
 
 
@@ -801,17 +799,17 @@ computeHamCmap(int   const cols,
                     if( dist <= maxdist ) {
                         unsigned int sum = hmap[i].count + hmap[col].count;
 
-                        hmap[i].r = ROUNDDIV(hmap[i].r * hmap[i].count + 
+                        hmap[i].r = ROUNDDIV(hmap[i].r * hmap[i].count +
                                              r * hmap[col].count, sum);
-                        hmap[i].g = ROUNDDIV(hmap[i].g * hmap[i].count + 
+                        hmap[i].g = ROUNDDIV(hmap[i].g * hmap[i].count +
                                              g * hmap[col].count, sum);
-                        hmap[i].b = ROUNDDIV(hmap[i].b * hmap[i].count + 
+                        hmap[i].b = ROUNDDIV(hmap[i].b * hmap[i].count +
                                              b * hmap[col].count, sum);
                         hmap[i].count = sum;
 
                         hmap[col] = hmap[i];    /* temp store */
-                        for( tmp = i-1; 
-                             tmp >= 0 && hmap[tmp].count < hmap[col].count; 
+                        for( tmp = i-1;
+                             tmp >= 0 && hmap[tmp].count < hmap[col].count;
                              tmp-- )
                             hmap[tmp+1] = hmap[tmp];
                         hmap[tmp+1] = hmap[col];
@@ -878,7 +876,6 @@ doHamBody(FILE *  const ifP,
 
     int col, row, i;
     rawtype *raw_rowbuf;
-    ppm_fs_info *fi = NULL;
     colorhash_table cht, cht2;
     long bodysize = 0;
     int *itoh;      /* table image -> ham */
@@ -898,9 +895,6 @@ doHamBody(FILE *  const ifP,
 
     itoh = makeValTable(maxval, hammaxval);
 
-    if( floyd )
-        fi = ppm_fs_init(cols, maxval, 0);
-
     for( row = 0; row < rows; row++ ) {
         int noprev;
         int spr, spg, spb;   /* scaled values of previous pixel */
@@ -909,9 +903,7 @@ doHamBody(FILE *  const ifP,
 
         noprev = 1;
         prow = nextPixrow(ifP, row);
-        for( col = ppm_fs_startrow(fi, prow); 
-             col < cols; 
-             col = ppm_fs_next(fi, col) ) {
+        for( col = 0; col < cols; ++col ) {
 
             pixel const p = prow[col];
 
@@ -930,15 +922,15 @@ doHamBody(FILE *  const ifP,
                 int ucr, ucg, ucb;  /* unscaled values of colormap entry */
 
                 if(  hammapmode == HAMMODE_GRAY ) {
-                    if( maxval <= 255 ) 
-                        /* Use fast approximation to 
+                    if( maxval <= 255 )
+                        /* Use fast approximation to
                            0.299 r + 0.587 g + 0.114 b. */
                         i = (int)ppm_fastlumin(p);
-                    else 
-                        /* Can't use fast approximation, 
-                           so fall back on floats. 
+                    else
+                        /* Can't use fast approximation,
+                           so fall back on floats.
                         */
-                        i = (int)(PPM_LUMIN(p) + 0.5); 
+                        i = (int)(PPM_LUMIN(p) + 0.5);
                             /* -IUW added '+ 0.5' */
                     i = itoh[i];
                 }
@@ -956,8 +948,8 @@ doHamBody(FILE *  const ifP,
                         }
                     }
                 }
-                ucr = PPM_GETR(colormap[i]); 
-                ucg = PPM_GETG(colormap[i]); 
+                ucr = PPM_GETR(colormap[i]);
+                ucg = PPM_GETG(colormap[i]);
                 ucb = PPM_GETB(colormap[i]);
 
                 if( noprev ) {  /* no previous pixel, must use colormap */
@@ -985,21 +977,21 @@ doHamBody(FILE *  const ifP,
                         (sb - scb)*(sb - scb);
 #endif
 
-                    if( di <= dr && di <= dg && di <= db ) {    
+                    if( di <= dr && di <= dg && di <= db ) {
                         /* prefer colormap lookup */
-                        raw_rowbuf[col] = i; 
+                        raw_rowbuf[col] = i;
                         upr = ucr;  upg = ucg;  upb = ucb;
                         spr = scr;  spg = scg;  spb = scb;
                     }
                     else
                     if( db <= dr && db <= dg ) {
-                        raw_rowbuf[col] = sb + hamcode_blue; 
+                        raw_rowbuf[col] = sb + hamcode_blue;
                         spb = sb;
                         upb = ub;
                     }
                     else
                     if( dr <= dg ) {
-                        raw_rowbuf[col] = sr + hamcode_red;  
+                        raw_rowbuf[col] = sr + hamcode_red;
                         spr = sr;
                         upr = ur;
                     }
@@ -1012,19 +1004,17 @@ doHamBody(FILE *  const ifP,
             }
             else {  /* prefect match in cmap */
                 raw_rowbuf[col] = i;    /* + (HAMCODE_CMAP << colbits) */
-                upr = PPM_GETR(colormap[i]); 
-                upg = PPM_GETG(colormap[i]); 
+                upr = PPM_GETR(colormap[i]);
+                upg = PPM_GETG(colormap[i]);
                 upb = PPM_GETB(colormap[i]);
-                spr = itoh[upr];            
-                spg = itoh[upg];            
+                spr = itoh[upr];
+                spg = itoh[upg];
                 spb = itoh[upb];
             }
-            ppm_fs_update3(fi, col, upr, upg, upb);
         }
         bodysize += encodeRow(ofP, raw_rowbuf, cols, nPlanes);
         if( maskmethod == mskHasMask )
             bodysize += encodeMaskrow(ofP, raw_rowbuf, cols);
-        ppm_fs_endrow(fi);
     }
     if( ofP && ODD(bodysize) )
         putByte(0);
@@ -1033,7 +1023,6 @@ doHamBody(FILE *  const ifP,
 
     /* clean up */
     free(raw_rowbuf);
-    ppm_fs_free(fi);
 
     return bodysize;
 }
@@ -1113,12 +1102,12 @@ ppmToHam(FILE *  const ifP,
             }
             break;
             case HAMMODE_RGB4:
-                colormap = computeHamCmap(cols, rows, maxval, hamcolors, 
+                colormap = computeHamCmap(cols, rows, maxval, hamcolors,
                                           &colors, 4);
                 cmapmaxval = 15;
                 break;
             case HAMMODE_RGB5:
-                colormap = computeHamCmap(cols, rows, maxval, 
+                colormap = computeHamCmap(cols, rows, maxval,
                                           hamcolors, &colors, 5);
                 cmapmaxval = 31;
                 break;
@@ -1129,7 +1118,7 @@ ppmToHam(FILE *  const ifP,
     else {
         hammapmode = HAMMODE_MAPFILE;
         if( colors > hamcolors ) {
-            pm_message("colormap too large - using first %d colors", 
+            pm_message("colormap too large - using first %d colors",
                        hamcolors);
             colors = hamcolors;
         }
@@ -1142,9 +1131,9 @@ ppmToHam(FILE *  const ifP,
         newcmap = ppm_allocrow(colors);
         table = makeValTable(cmapmaxval, maxval);
         for( i = 0; i < colors; i++ )
-            PPM_ASSIGN(newcmap[i], 
-                       table[PPM_GETR(colormap[i])], 
-                       table[PPM_GETG(colormap[i])], 
+            PPM_ASSIGN(newcmap[i],
+                       table[PPM_GETR(colormap[i])],
+                       table[PPM_GETG(colormap[i])],
                        table[PPM_GETB(colormap[i])]);
         free(table);
         ppm_freerow(colormap);
@@ -1158,16 +1147,16 @@ ppmToHam(FILE *  const ifP,
 
     bodysize = oldsize = rows * TOTALPLANES(nPlanes) * RowBytes(cols);
     if( DO_COMPRESS ) {
-        bodysize = doHamBody(ifP, NULL, cols, rows, maxval, 
+        bodysize = doHamBody(ifP, NULL, cols, rows, maxval,
                                hammaxval, nPlanes, colormap, colors);
-        /*bodysize = doHamBody(ifP, NULL, cols, 
+        /*bodysize = doHamBody(ifP, NULL, cols,
           rows, maxval, hammaxval, nPlanes, colbits, nocolor);*/
         if( bodysize > oldsize )
             pm_message("warning - %s compression increases BODY size "
-                       "by %ld%%", 
+                       "by %ld%%",
                        cmpNAME[compmethod], 100*(bodysize-oldsize)/oldsize);
         else
-            pm_message("BODY compression (%s): %ld%%", 
+            pm_message("BODY compression (%s): %ld%%",
                        cmpNAME[compmethod], 100*(oldsize-bodysize)/oldsize);
     }
 
@@ -1195,7 +1184,7 @@ ppmToHam(FILE *  const ifP,
     if( DO_COMPRESS )
         writeBodyRows();
     else
-        doHamBody(ifP, stdout, cols, rows, maxval, hammaxval, 
+        doHamBody(ifP, stdout, cols, rows, maxval, hammaxval,
                   nPlanes, colormap, colors);
 }
 
@@ -1210,7 +1199,7 @@ doDeepBody(FILE * const ifP,
            FILE * const ofP,
            int    const cols,
            int    const rows,
-           pixval const maxval, 
+           pixval const maxval,
            int    const bitspercolor) {
 
     int row, col;
@@ -1226,7 +1215,7 @@ doDeepBody(FILE * const ifP,
 
     newmaxval = pm_bitstomaxval(bitspercolor);
     if( maxval != newmaxval ) {
-        pm_message("maxval is not %d - automatically rescaling colors", 
+        pm_message("maxval is not %d - automatically rescaling colors",
                    newmaxval);
         table = makeValTable(maxval, newmaxval);
     }
@@ -1294,7 +1283,7 @@ ppmToDeep(FILE * const ifP,
             pm_message("warning - %s compression increases BODY size by %ld%%",
                        cmpNAME[compmethod], 100*(bodysize-oldsize)/oldsize);
         else
-            pm_message("BODY compression (%s): %ld%%", 
+            pm_message("BODY compression (%s): %ld%%",
                        cmpNAME[compmethod], 100*(oldsize-bodysize)/oldsize);
     }
 
@@ -1335,7 +1324,7 @@ doDcolBody(FILE *        const ifP,
            FILE *        const ofP,
            int           const cols,
            int           const rows,
-           pixval        const maxval, 
+           pixval        const maxval,
            DirectColor * const dcol) {
 
     int row, col;
@@ -1405,10 +1394,10 @@ ppmToDcol(FILE *        const ifP,
         bodysize = doDcolBody(ifP, NULL, cols, rows, maxval, dcol);
         if( bodysize > oldsize )
             pm_message("warning - %s compression increases BODY size by %ld%%",
-                       cmpNAME[compmethod], 
+                       cmpNAME[compmethod],
                        100*(bodysize-oldsize)/oldsize);
         else
-            pm_message("BODY compression (%s): %ld%%", cmpNAME[compmethod], 
+            pm_message("BODY compression (%s): %ld%%", cmpNAME[compmethod],
                        100*(oldsize-bodysize)/oldsize);
     }
 
@@ -1467,35 +1456,30 @@ doStdBody(FILE *  const ifP,
     int row, col, i;
     pixel *pP;
     rawtype *raw_rowbuf;
-    ppm_fs_info *fi = NULL;
     long bodysize = 0;
     int usehash = 1;
     colorhash_table cht;
 
     MALLOCARRAY_NOFAIL(raw_rowbuf, cols);
     cht = ppm_colorrowtocolorhash(colormap, colors);
-    if( floyd )
-        fi = ppm_fs_init(cols, maxval, FS_ALTERNATE);
 
     for( row = 0; row < rows; row++ ) {
         pixel *prow;
         prow = nextPixrow(ifP, row);
 
-        for( col = ppm_fs_startrow(fi, prow); 
-             col < cols; 
-             col = ppm_fs_next(fi, col) ) {
+        for( col = 0; col < cols; ++col ) {
             pP = &prow[col];
 
-            if( maskmethod == mskHasTransparentColor && 
+            if( maskmethod == mskHasTransparentColor &&
                 maskrow[col] == PBM_WHITE )
                 i = transpIndex;
             else {
                 /* Check hash table to see if we have already matched
-                   this color. 
+                   this color.
                 */
                 i = ppm_lookupcolor(cht, pP);
                 if( i == -1 ) {
-                    i = ppm_findclosestcolor(colormap, colors, pP);    
+                    i = ppm_findclosestcolor(colormap, colors, pP);
                         /* No; search colormap for closest match. */
                     if( usehash ) {
                         if( ppm_addtocolorhash(cht, pP, i) < 0 ) {
@@ -1507,12 +1491,10 @@ doStdBody(FILE *  const ifP,
                 }
             }
             raw_rowbuf[col] = i;
-            ppm_fs_update(fi, col, &colormap[i]);
         }
         bodysize += encodeRow(ofP, raw_rowbuf, cols, nPlanes);
         if( maskmethod == mskHasMask )
             bodysize += encodeMaskrow(ofP, raw_rowbuf, cols);
-        ppm_fs_endrow(fi);
     }
     if( ofP && ODD(bodysize) )
         putByte(0);
@@ -1520,7 +1502,6 @@ doStdBody(FILE *  const ifP,
     /* clean up */
     ppm_freecolorhash(cht);
     free(raw_rowbuf);
-    ppm_fs_free(fi);
 
     return bodysize;
 }
@@ -1534,7 +1515,7 @@ ppmToStd(FILE *  const ifP,
          int     const maxval,
          pixel * const colormapArg,
          int     const colorsArg,
-         int     const cmapmaxvalArg, 
+         int     const cmapmaxvalArg,
          int     const maxcolors,
          int     const nPlanes) {
 
@@ -1550,7 +1531,7 @@ ppmToStd(FILE *  const ifP,
 
     if( maskmethod == mskHasTransparentColor ) {
         if( transpColor ) {
-            transpIndex = 
+            transpIndex =
                 ppm_addtocolorrow(colormap, &colors, maxcolors, transpColor);
         }
         else
@@ -1572,9 +1553,9 @@ ppmToStd(FILE *  const ifP,
         newcmap = ppm_allocrow(colors);
         table = makeValTable(cmapmaxval, maxval);
         for (i = 0; i < colors; ++i)
-            PPM_ASSIGN(newcmap[i], 
-                       table[PPM_GETR(colormap[i])], 
-                       table[PPM_GETG(colormap[i])], 
+            PPM_ASSIGN(newcmap[i],
+                       table[PPM_GETR(colormap[i])],
+                       table[PPM_GETG(colormap[i])],
                        table[PPM_GETB(colormap[i])]);
         free(table);
         colormap = newcmap;
@@ -1584,13 +1565,13 @@ ppmToStd(FILE *  const ifP,
 
     bodysize = oldsize = rows * TOTALPLANES(nPlanes) * RowBytes(cols);
     if( DO_COMPRESS ) {
-        bodysize = doStdBody(ifP, NULL, cols, rows, maxval, colormap, 
+        bodysize = doStdBody(ifP, NULL, cols, rows, maxval, colormap,
                              colors, nPlanes);
         if( bodysize > oldsize )
             pm_message("warning - %s compression increases BODY size by %ld%%",
                        cmpNAME[compmethod], 100*(bodysize-oldsize)/oldsize);
         else
-            pm_message("BODY compression (%s): %ld%%", 
+            pm_message("BODY compression (%s): %ld%%",
                        cmpNAME[compmethod], 100*(oldsize-bodysize)/oldsize);
     }
 
@@ -1659,7 +1640,7 @@ ppmToRgb8(FILE * const ifP,
         for( col1 = 0; col1 < cols; col1 = col2 ) {
             col2 = col1 + 1;
             if( maskrow ) {
-                while( col2 < cols && PPM_EQUAL(pP[col1], pP[col2]) && 
+                while( col2 < cols && PPM_EQUAL(pP[col1], pP[col2]) &&
                        maskrow[col1] == maskrow[col2] )
                     col2++;
             }
@@ -1750,7 +1731,7 @@ ppmToRgbn(FILE * const ifP,
         for( col1 = 0; col1 < cols; col1 = col2 ) {
             col2 = col1 + 1;
             if( maskrow ) {
-                while( col2 < cols && PPM_EQUAL(pP[col1], pP[col2]) && 
+                while( col2 < cols && PPM_EQUAL(pP[col1], pP[col2]) &&
                        maskrow[col1] == maskrow[col2] )
                     col2++;
             }
@@ -1782,14 +1763,14 @@ ppmToRgbn(FILE * const ifP,
                 else {
                     ++compr_len;                  /* 3 bit repeat count = 0 */
                     if( count <= 255 )
-                        compr_row[compr_len++] = (unsigned char)count;  
+                        compr_row[compr_len++] = (unsigned char)count;
                             /* byte repeat count */
                     else {
-                        compr_row[compr_len++] = (unsigned char)0;   
+                        compr_row[compr_len++] = (unsigned char)0;
                             /* byte repeat count = 0 */
-                        compr_row[compr_len++] = (count >> 8) & 0xff; 
+                        compr_row[compr_len++] = (count >> 8) & 0xff;
                             /* word repeat count MSB */
-                        compr_row[compr_len++] = count & 0xff;    
+                        compr_row[compr_len++] = count & 0xff;
                             /* word repeat count LSB */
                     }
                 }
@@ -1878,6 +1859,7 @@ main(int argc, char ** argv) {
     pixval cmapmaxval;      /* maxval of colors in cmap */
     const char * mapfile;
     const char * transpname;
+    unsigned int defunctArgs = 0;
 
     ppm_init(&argc, argv);
 
@@ -1902,7 +1884,7 @@ main(int argc, char ** argv) {
         if( pm_keymatch(argv[argn], "-rgbn", 5) )
             forcemode = MODE_RGBN;
         else
-        if( pm_keymatch(argv[argn], "-maxplanes", 4) || 
+        if( pm_keymatch(argv[argn], "-maxplanes", 4) ||
             pm_keymatch(argv[argn], "-mp", 3) ) {
             if( ++argn >= argc )
                 pm_error("-maxplanes requires a value");
@@ -1910,7 +1892,7 @@ main(int argc, char ** argv) {
             fixplanes = 0;
         }
         else
-        if( pm_keymatch(argv[argn], "-fixplanes", 4) || 
+        if( pm_keymatch(argv[argn], "-fixplanes", 4) ||
             pm_keymatch(argv[argn], "-fp", 3) ) {
             if( ++argn >= argc )
                 pm_error("-fixplanes requires a value");
@@ -1935,7 +1917,7 @@ main(int argc, char ** argv) {
                     break;
                 default:
                     pm_error("This program does not know how to handle "
-                             "masking method '%s'", 
+                             "masking method '%s'",
                              mskNAME[maskmethod]);
             }
         }
@@ -2014,7 +1996,7 @@ main(int argc, char ** argv) {
         if( pm_keymatch(argv[argn], "-hambits", 5) ) {
             if( ++argn >= argc )
                 pm_usage("-hambits requires a value");
-            hamplanes = 
+            hamplanes =
                 getIntVal(argv[argn], argv[argn-1], 3, HAMMAXPLANES-2) +2;
         }
         else
@@ -2118,7 +2100,7 @@ main(int argc, char ** argv) {
                 forcemode = MODE_NONE;
         }
         else
-        if( pm_keymatch(argv[argn], "-dcbits", 4) || 
+        if( pm_keymatch(argv[argn], "-dcbits", 4) ||
             pm_keymatch(argv[argn], "-dcplanes", 4) ) {
             if( argc - argn < 4 )
                 pm_error("-dcbits requires 4 arguments");
@@ -2154,13 +2136,9 @@ main(int argc, char ** argv) {
             compmethod = getComprMethod(argv[argn]);
         }
         else
-        if( pm_keymatch(argv[argn], "-floyd", 3) || 
-            pm_keymatch(argv[argn], "-fs", 3) )
-            floyd = 1;
-        else
-        if( pm_keymatch(argv[argn], "-nofloyd", 5) || 
+        if( pm_keymatch(argv[argn], "-nofloyd", 5) ||
             pm_keymatch(argv[argn], "-nofs", 5) )
-            floyd = 0;
+	    defunctArgs++;
         else
         if( pm_keymatch(argv[argn], "-annotation", 3) ) {
             if( ++argn >= argc )
@@ -2230,10 +2208,10 @@ main(int argc, char ** argv) {
         case MODE_CMAP:
             /* Figure out the colormap. */
             pm_message("computing colormap...");
-            colormap = ppm_mapfiletocolorrow(ifP, MAXCOLORS, &colors, 
+            colormap = ppm_mapfiletocolorrow(ifP, MAXCOLORS, &colors,
                                              &cmapmaxval);
             if (colormap == NULL)
-                pm_error("too many colors - try doing a 'pnmquant %d'", 
+                pm_error("too many colors - try doing a 'pnmquant %d'",
                          MAXCOLORS);
             pm_message("%d colors found", colors);
             break;
@@ -2241,11 +2219,11 @@ main(int argc, char ** argv) {
             if (mapfile)
                 initRead(ifP, &cols, &rows, &maxval, &format, 0);
             else {
-                initRead(ifP, &cols, &rows, &maxval, &format, 1);  
+                initRead(ifP, &cols, &rows, &maxval, &format, 1);
                     /* read file into memory */
                 pm_message("computing colormap...");
-                colormap = 
-                    ppm_computecolorrow(pixels, cols, rows, MAXCOLORS, 
+                colormap =
+                    ppm_computecolorrow(pixels, cols, rows, MAXCOLORS,
                                         &colors);
                 if (colormap) {
                     cmapmaxval = maxval;
@@ -2266,7 +2244,7 @@ main(int argc, char ** argv) {
 
         pm_message("reading colormap file...");
         mapfp = pm_openr(mapfile);
-        colormap = ppm_mapfiletocolorrow(mapfp, MAXCOLORS, &colors, 
+        colormap = ppm_mapfiletocolorrow(mapfp, MAXCOLORS, &colors,
                                          &cmapmaxval);
         pm_close(mapfp);
         if (colormap == NULL)
@@ -2302,11 +2280,11 @@ main(int argc, char ** argv) {
         if (DO_COMPRESS)
             pm_rlenc_allocoutbuf(&compr_rowbuf, RowBytes(cols), PM_RLE_PACKBITS);
     }
-    
+
     switch (mode) {
         case MODE_HAM:
             viewportmodes |= vmHAM;
-            ppmToHam(ifP, cols, rows, maxval, 
+            ppmToHam(ifP, cols, rows, maxval,
                      colormap, colors, cmapmaxval, hamplanes);
             break;
         case MODE_DEEP:
@@ -2325,9 +2303,7 @@ main(int argc, char ** argv) {
             ppmToCmap(colormap, colors, cmapmaxval);
             break;
         default:
-            if (mapfile == NULL)
-                floyd = 0;          /* would only slow down conversion */
-            ppmToStd(ifP, cols, rows, maxval, colormap, colors, 
+            ppmToStd(ifP, cols, rows, maxval, colormap, colors,
                      cmapmaxval, MAXCOLORS, nPlanes);
             break;
     }
diff --git a/converter/ppm/ppmtomitsu.c b/converter/ppm/ppmtomitsu.c
index 5b0b3245..50b790d6 100644
--- a/converter/ppm/ppmtomitsu.c
+++ b/converter/ppm/ppmtomitsu.c
@@ -705,7 +705,7 @@ main(int argc, char * argv[]) {
         for (row = 0; row < rows; ++row)
             ppm_readppmrow(ifP, pixels[row], cols, maxval, format);
 
-        /* first check wether we can use the lut transfer */
+        /* first check whether we can use the lut transfer */
 
         table = ppm_computecolorhist(pixels, cols, rows, MAXLUTCOL+1,
                                      &nColor);
diff --git a/converter/ppm/ppmtompeg/LOGIC b/converter/ppm/ppmtompeg/LOGIC
index 8c19dc8d..b346d597 100644
--- a/converter/ppm/ppmtompeg/LOGIC
+++ b/converter/ppm/ppmtompeg/LOGIC
@@ -45,7 +45,7 @@ is ready.
 
 When an encoder server finishes an assignment, it connects to the master
 server TCP listen port and tells the master it is done, and receives over
-the same connetion its next assignment.  If there is no more work to do,
+the same connection its next assignment.  If there is no more work to do,
 the master server instead tells the encoder server just to terminate.
 
 When the master server has told every encoder server to terminate, it
diff --git a/converter/ppm/ppmtompeg/Makefile b/converter/ppm/ppmtompeg/Makefile
index eeab9727..9ad09c77 100644
--- a/converter/ppm/ppmtompeg/Makefile
+++ b/converter/ppm/ppmtompeg/Makefile
@@ -124,7 +124,7 @@ profile: LDFLAGS_TARGET = \
 PERL = perl
 
 # The following stuff is for the Huffman encoding tables.  It's commented-out
-# because you probably don't want to change this.  If you do, then uncommment
+# because you probably don't want to change this.  If you do, then uncomment
 # it.
 #
 # huff.h: huff.c
diff --git a/converter/ppm/ppmtompeg/bsearch.c b/converter/ppm/ppmtompeg/bsearch.c
index c618bbd4..b825ef72 100644
--- a/converter/ppm/ppmtompeg/bsearch.c
+++ b/converter/ppm/ppmtompeg/bsearch.c
@@ -26,7 +26,7 @@
  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  */
 
-/*  
+/*
  *  $Header: /n/picasso/project/mpeg/mpeg_dist/mpeg_encode/RCS/bsearch.c,v 1.10 1995/08/07 21:49:01 smoot Exp $
  *  $Log: bsearch.c,v $
  *  Revision 1.10  1995/08/07 21:49:01  smoot
@@ -37,7 +37,7 @@
  *  (B frames which are backward P's at the start of a sequence)
  *
  *  Revision 1.8  1995/03/27 19:17:43  smoot
- *  killed useless type error messge (int32 defiend as int)
+ *  killed useless type error message (int32 defined as int)
  *
  * Revision 1.7  1995/01/19  23:07:20  eyhung
  * Changed copyrights
@@ -194,7 +194,7 @@ FindBestMatchExhaust(const LumBlock * const blockP,
 
     /* maybe should try spiral pattern centered around  prev motion vector? */
 
-    /* try a spiral pattern */    
+    /* try a spiral pattern */
     for (distance = stepSize;
          distance <= searchRange;
          distance += stepSize) {
@@ -212,7 +212,7 @@ FindBestMatchExhaust(const LumBlock * const blockP,
                         m.y = my; m.x = mx;
                         diff = LumAddMotionError(currentBlockP, blockP, prev,
                                                  by, bx, m, bestDiff);
-                        
+
                         if (diff < bestDiff) {
                             *motionP = m;
                             bestDiff = diff;
@@ -237,7 +237,7 @@ FindBestMatchExhaust(const LumBlock * const blockP,
                         diff = LumAddMotionError(currentBlockP, blockP, prev,
                                                  by, bx,
                                                  m, bestDiff);
-                        
+
                         if (diff < bestDiff) {
                             *motionP = m;
                             bestDiff = diff;
@@ -310,7 +310,7 @@ FindBestMatchTwoLevel(const LumBlock * const blockP,
     if (VALID_MOTION(*motionP)) {
         bestDiff = LumAddMotionError(currentBlockP, blockP, prev, by, bx,
                                      *motionP, bestSoFar);
-        
+
         if (bestSoFar < bestDiff)
             bestDiff = bestSoFar;
     } else {
@@ -323,7 +323,7 @@ FindBestMatchTwoLevel(const LumBlock * const blockP,
 
     /* maybe should try spiral pattern centered around  prev motion vector? */
 
-    /* try a spiral pattern */    
+    /* try a spiral pattern */
     for ( distance = 2; distance <= searchRange; distance += 2 ) {
         tempRightMY = MIN(distance, rightMY);
         tempRightMX = MIN(distance, rightMX);
@@ -339,7 +339,7 @@ FindBestMatchTwoLevel(const LumBlock * const blockP,
                         m.y = my; m.x = mx;
                         diff = LumAddMotionError(currentBlockP, blockP, prev,
                                                  by, bx, m, bestDiff);
-                        
+
                         if (diff < bestDiff) {
                             *motionP = m;
                             bestDiff = diff;
@@ -361,7 +361,7 @@ FindBestMatchTwoLevel(const LumBlock * const blockP,
                         m.y = my; m.x = mx;
                         diff = LumAddMotionError(currentBlockP, blockP, prev,
                                                  by, bx, m, bestDiff);
-                        
+
                         if (diff < bestDiff) {
                             *motionP = m;
                             bestDiff = diff;
@@ -423,7 +423,7 @@ trySpacing(int              const spacing,
            MpegFrame *      const prev,
            int              const by,
            int              const bx) {
-           
+
     int tempRightMY, tempRightMX;
     int my;
     int bestDiff;
@@ -435,7 +435,7 @@ trySpacing(int              const spacing,
 
     tempRightMY = MIN(rightMY, center.y + spacing + 1);
     tempRightMX = MIN(rightMX, center.x + spacing + 1);
-    
+
     for (my = center.y - spacing; my < tempRightMY; my += spacing) {
         if (my >= leftMY) {
             int mx;
@@ -446,7 +446,7 @@ trySpacing(int              const spacing,
                     m.y = my; m.x = mx;
                     diff = LumAddMotionError(currentBlockP, blockP, prev,
                                              by, bx, m, bestDiff);
-                    
+
                     if (diff < bestDiff) {
                         /* We have a new best */
                         newCenter = m;
@@ -466,7 +466,7 @@ static void
 chooseNewSpacing(int   const oldSpacing,
                  int   const stepSize,
                  int * const newSpacingP) {
-        
+
     if (stepSize == 2) {  /* make sure spacing is even */
         if (oldSpacing == 2)
             *newSpacingP = 0;
@@ -530,7 +530,7 @@ FindBestMatchLogarithmic(const LumBlock * const blockP,
 
     /* Start at (0,0) */
     center.y = center.x = 0;
-    
+
     while (spacing >= stepSize) {
         trySpacing(spacing, center, bestDiff,
                    &center, &bestDiff,
@@ -580,7 +580,7 @@ FindBestMatchSubSample(const LumBlock * const blockP,
                        int              const searchRange) {
 
     /* too lazy to write the code for this... */
-    
+
     return FindBestMatchExhaust(blockP, currentBlockP, prev,
                                 by, bx, motionP, bestSoFar,
                                 searchRange);
@@ -671,9 +671,9 @@ BMotionSearchNoInterp(const LumBlock * const currentBlockP,
     /* CALL SEARCH PROCEDURE */
     switch(psearchAlg) {
     case PSEARCH_SUBSAMPLE:
-        *forwardErrP = PSubSampleSearch(currentBlockP, prev, by, bx, 
+        *forwardErrP = PSubSampleSearch(currentBlockP, prev, by, bx,
                                         &motionP->fwd,searchRangeB);
-        *backErrP = PSubSampleSearch(currentBlockP, next, by, bx, 
+        *backErrP = PSubSampleSearch(currentBlockP, next, by, bx,
                                      &motionP->bwd, searchRangeB);
         break;
     case PSEARCH_EXHAUSTIVE:
@@ -690,9 +690,9 @@ BMotionSearchNoInterp(const LumBlock * const currentBlockP,
                                      *forwardErrP, searchRangeB);
         break;
     case PSEARCH_LOGARITHMIC:
-        *forwardErrP = PLogarithmicSearch(currentBlockP, prev, by, bx, 
+        *forwardErrP = PLogarithmicSearch(currentBlockP, prev, by, bx,
                                           &motionP->fwd, searchRangeB);
-        *backErrP = PLogarithmicSearch(currentBlockP, next, by, bx, 
+        *backErrP = PLogarithmicSearch(currentBlockP, next, by, bx,
                                        &motionP->bwd, searchRangeB);
         break;
     case PSEARCH_TWOLEVEL:
@@ -731,7 +731,7 @@ BMotionSearchNoInterp(const LumBlock * const currentBlockP,
  * *fmyP,fmxP,bmyP,bmxP are inputs as well as outputs.  We do not update
  * them if it would make the error worse than the existing values.  Otherwise,
  * we update them to the vectors we find to be best.
- * 
+ *
  *===========================================================================*/
 static int
 BMotionSearchSimple(const LumBlock * const currentBlockP,
@@ -750,7 +750,7 @@ BMotionSearchSimple(const LumBlock * const currentBlockP,
     /* STEP 1 */
     BMotionSearchNoInterp(currentBlockP, prev, next, by, bx, motionP,
                           &forwardErr, &backErr, TRUE);
-              
+
     /* STEP 2 */
 
     ComputeBMotionLumBlock(prev, next, by, bx, MOTION_INTERPOLATE,
@@ -799,7 +799,7 @@ BMotionSearchCross2(const LumBlock * const currentBlockP,
                     int              const bx,
                     motion *         const motionP,
                     int              const oldMode) {
-    
+
     int retval;
     LumBlock forwardBlock, backBlock;
     int32   forwardErr, backErr;
@@ -816,19 +816,19 @@ BMotionSearchCross2(const LumBlock * const currentBlockP,
 
     {
         /* STEP 2 */
-        
+
         struct motion motion;
         motion.fwd = motionP->fwd;
         motion.bwd.y = motion.bwd.x = 0;
         ComputeBMotionLumBlock(prev, next, by, bx, MOTION_FORWARD, motion,
                                &forwardBlock);
-        
+
         motion.fwd.y = motion.fwd.x = 0;
         motion.bwd = motionP->bwd;
         ComputeBMotionLumBlock(prev, next, by, bx, MOTION_BACKWARD, motion,
                                &backBlock);
     }
-    /* try a cross-search; total of 4 local searches */    
+    /* try a cross-search; total of 4 local searches */
     newMotion = *motionP;
 
     interpErrF = FindBestMatch(&forwardBlock, currentBlockP,
@@ -934,11 +934,11 @@ BMotionSearchExhaust(const LumBlock * const currentBlockP,
                                            motion, &forwardBlock);
 
                     newMotion = motion.fwd;
-                    
+
                     diff = FindBestMatch(&forwardBlock,
                                          currentBlockP, next, by, bx,
                                          &newMotion, bestDiff, searchRangeB);
-                    
+
                     if (diff < bestDiff) {
                         motionP->fwd = motion.fwd;
                         motionP->bwd = newMotion;
@@ -968,7 +968,7 @@ BMotionSearchExhaust(const LumBlock * const currentBlockP,
  *
  * PRECONDITIONS:   The relevant block in 'current' is valid (it has not
  *          been dct'd).  Thus, the data in 'current' can be
- *          accesed through y_blocks, cr_blocks, and cb_blocks.
+ *          accessed through y_blocks, cr_blocks, and cb_blocks.
  *          This is not the case for the blocks in 'prev' and
  *          'next.'  Therefore, references into 'prev' and 'next'
  *          should be done
@@ -1001,7 +1001,7 @@ BMotionSearch(const LumBlock * const currentBlockP,
         PMotionSearch(currentBlockP, next, by, bx, &motionP->bwd);
         return MOTION_BACKWARD;
     }
-  
+
     /* otherwise simply call the appropriate algorithm, based on user
        preference
     */
diff --git a/converter/ppm/ppmtompeg/docs/template.param b/converter/ppm/ppmtompeg/docs/template.param
index 78ad5300..fb837428 100644
--- a/converter/ppm/ppmtompeg/docs/template.param
+++ b/converter/ppm/ppmtompeg/docs/template.param
@@ -138,7 +138,7 @@ BQSCALE		25
 # this must be ORIGINAL or DECODED
 REFERENCE_FRAME	ORIGINAL
 
-# for parallel parameters see parallel.param in the exmaples subdirectory
+# for parallel parameters see parallel.param in the examples subdirectory
 
 # if you want constant bit-rate mode, specify it as follows (number is bits/sec):
 BIT_RATE  1000000
diff --git a/converter/ppm/ppmtompeg/examples/payam.param b/converter/ppm/ppmtompeg/examples/payam.param
index ce886914..e9287a89 100644
--- a/converter/ppm/ppmtompeg/examples/payam.param
+++ b/converter/ppm/ppmtompeg/examples/payam.param
@@ -16,7 +16,7 @@ kh*.pnm	[1-3]
 END_INPUT
 
 
-# motion vector search paramters
+# motion vector search parameters
 
 # MAD or MSE -- must be upper case
 ERROR		MAD
diff --git a/converter/ppm/ppmtompeg/examples/payam18.param b/converter/ppm/ppmtompeg/examples/payam18.param
index 7f7b767e..95839e83 100644
--- a/converter/ppm/ppmtompeg/examples/payam18.param
+++ b/converter/ppm/ppmtompeg/examples/payam18.param
@@ -15,7 +15,7 @@ kh*.pnm	[1-39]
 END_INPUT
 
 
-# motion vector search paramters
+# motion vector search parameters
 
 # FULL or HALF -- must be upper case
 PIXEL		HALF
diff --git a/converter/ppm/ppmtompeg/examples/template.param b/converter/ppm/ppmtompeg/examples/template.param
index 78ad5300..fb837428 100644
--- a/converter/ppm/ppmtompeg/examples/template.param
+++ b/converter/ppm/ppmtompeg/examples/template.param
@@ -138,7 +138,7 @@ BQSCALE		25
 # this must be ORIGINAL or DECODED
 REFERENCE_FRAME	ORIGINAL
 
-# for parallel parameters see parallel.param in the exmaples subdirectory
+# for parallel parameters see parallel.param in the examples subdirectory
 
 # if you want constant bit-rate mode, specify it as follows (number is bits/sec):
 BIT_RATE  1000000
diff --git a/converter/ppm/ppmtompeg/frame.c b/converter/ppm/ppmtompeg/frame.c
index f5a0d39d..09e35410 100644
--- a/converter/ppm/ppmtompeg/frame.c
+++ b/converter/ppm/ppmtompeg/frame.c
@@ -12,7 +12,7 @@
  *  Frame_AllocYCC                               *
  *  Frame_AllocDecoded                           *
  *  Frame_AllocHalf                                  *
- *  Frame_Resize                                     * 
+ *  Frame_Resize                                     *
  *                                       *
  *===========================================================================*/
 
@@ -52,7 +52,7 @@
  *===========*/
 
 /* The maximum number of B-Frames allowed between reference frames. */
-#define  B_FRAME_RUN  16    
+#define  B_FRAME_RUN  16
 
 /*==================*
  * GLOBAL VARIABLES *
@@ -64,13 +64,13 @@ static unsigned int numOfFrames;
 
 /*====================================================
 * Resize_Array_Width
-*    
+*
 *   This function will resize any array width up
 * or down in size.  The algorithm is based on the
 * least common multiple approach more commonly
 * used in audio frequency adjustments.
 *=====================================================*/
-static void 
+static void
 Resize_Array_Width(uint8 ** const inarray,
                    int      const in_x,
                    int      const in_y,
@@ -86,7 +86,7 @@ Resize_Array_Width(uint8 ** const inarray,
     uint8 pointA,pointB;
     double slope,diff;
 #endif
-    
+
     for (i = 0; i < in_y; ++i) {     /* For each row */
         unsigned int j;
         inptr = &inarray[i][0];
@@ -106,7 +106,7 @@ Resize_Array_Width(uint8 ** const inarray,
                     in_total = in_total - out_x;
                     --inptr;
                 }
-            } else {  
+            } else {
 #ifdef DOING_INTERPOLATION
                 pointA = *inptr;
 #endif
@@ -124,10 +124,10 @@ Resize_Array_Width(uint8 ** const inarray,
                 } else {
                     *outptr = (pointB -
                                (uint8)(slope*(((float)(out_x)) - diff)));
-                } 
+                }
 #endif
                 /* Non-Interpolative solution */
-                *outptr = *inptr;  
+                *outptr = *inptr;
 
                 ++outptr;
                 out_total = out_total + in_x;
@@ -153,7 +153,7 @@ Resize_Array_Width(uint8 ** const inarray,
 * Same as Resize_array_Width except pointer
 * manipulation must change.
 *===============================*/
-static void 
+static void
 Resize_Array_Height(uint8 ** const inarray,
                     int      const in_x,
                     int      const in_y,
@@ -176,7 +176,7 @@ Resize_Array_Height(uint8 ** const inarray,
         out_total = 0;
         k = 0;
         for(j=0; j < out_y; ++j){  /* for each output value */
-            if (in_total == out_total) {  
+            if (in_total == out_total) {
                 outarray[j][i] = inarray[k][i];
                 out_total=out_total+in_y;
                 while(in_total < out_total){
@@ -187,7 +187,7 @@ Resize_Array_Height(uint8 ** const inarray,
                     in_total = in_total - out_y;
                     --k;
                 }
-            } else {  
+            } else {
 #ifdef DOING_INTERPOLATION
                 pointA = inarray[k][i];
                 if (k != (in_y - 1)) {
@@ -210,7 +210,7 @@ Resize_Array_Height(uint8 ** const inarray,
                     in_total = in_total - out_y;
                     --k;
                 }
-            } 
+            }
         }
     }
 }
@@ -220,7 +220,7 @@ Resize_Array_Height(uint8 ** const inarray,
 /*========================================================
 * Resize_Width
 *======================================================*/
-static void  
+static void
 Resize_Width(MpegFrame * const omfrw,
              MpegFrame * const mfrw,
              int         const in_x,
@@ -274,12 +274,12 @@ Resize_Width(MpegFrame * const omfrw,
             free(mfrw->orig_y[i]);
         }
         free(mfrw->orig_y);
-        
+
         for (i = 0; i < in_y / 2; ++i) {
             free(mfrw->orig_cr[i]);
         }
         free(mfrw->orig_cr);
-        
+
         for (i = 0; i < in_y / 2; ++i) {
             free(mfrw->orig_cb[i]);
         }
@@ -300,9 +300,9 @@ Resize_Height(MpegFrame * const omfrh,
               int         const in_x,
               int         const in_y,
               int         const out_y) {
-    
-    unsigned int y; 
-    
+
+    unsigned int y;
+
     Fsize_y = out_y;
 
     /* Allocate new frame memory */
@@ -347,12 +347,12 @@ Resize_Height(MpegFrame * const omfrh,
             free(mfrh->orig_y[i]);
         }
         free(mfrh->orig_y);
-        
+
     for (i = 0; i < in_y / 2; ++i) {
         free(mfrh->orig_cr[i]);
     }
     free(mfrh->orig_cr);
-    
+
     for (i = 0; i < in_y / 2; ++i) {
         free(mfrh->orig_cb[i]);
     }
@@ -386,8 +386,8 @@ Frame_Init(unsigned int const numOfFramesRequested) {
     for (idx = 0; idx < numOfFrames; ++idx) {
         MALLOCVAR(frameMemory[idx]);
         frameMemory[idx]->inUse = FALSE;
-        frameMemory[idx]->orig_y = NULL;    
-        frameMemory[idx]->y_blocks = NULL; 
+        frameMemory[idx]->orig_y = NULL;
+        frameMemory[idx]->y_blocks = NULL;
         frameMemory[idx]->decoded_y = NULL;
         frameMemory[idx]->halfX = NULL;
         frameMemory[idx]->next = NULL;
@@ -458,11 +458,11 @@ FreeFrame(MpegFrame * const frameP) {
             for ( i = 0; i < Fsize_y; ++i )
                 free(frameP->halfX[i]);
             free(frameP->halfX);
-            
+
             for (i = 0; i < Fsize_y-1; ++i)
                 free(frameP->halfY[i]);
             free(frameP->halfY);
-            
+
             for (i = 0; i < Fsize_y-1; ++i)
                 free(frameP->halfBoth[i]);
             free(frameP->halfBoth);
@@ -542,7 +542,7 @@ GetUnusedFrame() {
                 "See the man page for help.\n");
         exit(1);
     }
-    return frameMemory[idx]; 
+    return frameMemory[idx];
 }
 
 
@@ -638,7 +638,7 @@ Frame_AllocBlocks(MpegFrame * const frameP) {
             MALLOCARRAY(frameP->y_blocks[i], dctx);
             ERRCHK(frameP->y_blocks[i], "malloc");
         }
-    
+
         MALLOCARRAY(frameP->cr_blocks, dcty / 2);
         ERRCHK(frameP->cr_blocks, "malloc");
         MALLOCARRAY(frameP->cb_blocks, dcty / 2);
@@ -672,7 +672,7 @@ Frame_AllocYCC(MpegFrame * const frameP) {
         /* already allocated */
     } else {
         unsigned int y;
-    
+
         DBG_PRINT(("ycc_calc:\n"));
         /*
          * first, allocate tons of memory
@@ -755,7 +755,7 @@ Frame_AllocHalf(MpegFrame * const frameP) {
  *
  *  allocate memory for decoded frame for the given frame, if required
  *  if makeReference == TRUE, then makes it reference frame
- * 
+ *
  * RETURNS: nothing
  *
  * SIDE EFFECTS:    none
@@ -781,14 +781,14 @@ Frame_AllocDecoded(MpegFrame * const frameP,
             MALLOCARRAY(frameP->decoded_y[y], Fsize_x);
             ERRCHK(frameP->decoded_y[y], "malloc");
         }
-        
+
         MALLOCARRAY(frameP->decoded_cr, Fsize_y / 2);
         ERRCHK(frameP->decoded_cr, "malloc");
         for (y = 0; y < (Fsize_y / 2); ++y) {
             MALLOCARRAY(frameP->decoded_cr[y], Fsize_x / 2);
             ERRCHK(frameP->decoded_cr[y], "malloc");
         }
-        
+
         MALLOCARRAY(frameP->decoded_cb, Fsize_y / 2);
         ERRCHK(frameP->decoded_cb, "malloc");
         for (y = 0; y < (Fsize_y / 2); ++y) {
@@ -810,7 +810,7 @@ Frame_AllocDecoded(MpegFrame * const frameP,
  *
  * Frame_Resize                  by James Boucher
  *                Boston University Multimedia Communications Lab
- *  
+ *
  *     This function takes the mf input frame, read in READFrame(),
  * and resizes all the input component arrays to the output
  * dimensions specified in the parameter file as OUT_SIZE.
@@ -828,11 +828,11 @@ Frame_Resize(MpegFrame * const omf,
     MpegFrame * frameAP;  /* intermediate frame */
 
     MALLOCVAR_NOFAIL(frameAP);
-    
+
     if (insize_x != outsize_x && insize_y != outsize_y) {
         Resize_Width(frameAP, mf, insize_x, insize_y, outsize_x);
         Resize_Height(omf, frameAP, outsize_x, insize_y, outsize_y);
-    } else 
+    } else
         if (insize_x ==outsize_x && insize_y != outsize_y) {
             Resize_Height(omf, mf, insize_x, insize_y, outsize_y);
         } else
@@ -843,3 +843,5 @@ Frame_Resize(MpegFrame * const omf,
 
     free(frameAP);
 }
+
+
diff --git a/converter/ppm/ppmtompeg/frametype.c b/converter/ppm/ppmtompeg/frametype.c
index 09afa403..debefcdc 100644
--- a/converter/ppm/ppmtompeg/frametype.c
+++ b/converter/ppm/ppmtompeg/frametype.c
@@ -13,7 +13,7 @@
  *	FType_FutureRef	returns the number of the future reference frame     *
  *	FType_PastRef	returns the number of the past reference frame	     *
  *									     *
- * 00.12.07 change malloc from frameTable to calloc to fix bug 
+ * 00.12.07 change malloc from frameTable to calloc to fix bug
  *===========================================================================*/
 
 /*
@@ -86,24 +86,24 @@ FType_Type(unsigned int const frameNum) {
 
     char retval;
 
-    if (use_cache) 
+    if (use_cache)
         return frameTable[frameNum].typ;
-  
+
     if (frameNum+1 == numFrames) {
         /* It's the last frame in the sequence.  If the pattern says it's
            a B, we convert it to I because a B frame makes no sense as the
            last frame of a sequence.
         */
-        if (patternedType == 'b') 
+        if (patternedType == 'b')
             retval = 'i';
-        else 
+        else
             retval = patternedType;
     } else {
         if (specificsOn) {
             static int lastI = -1;
             int newtype;
-      
-            if (lastI > frameNum) 
+
+            if (lastI > frameNum)
                 lastI = -1;
             newtype = SpecTypeLookup(frameNum);
             switch (newtype) {
@@ -119,13 +119,13 @@ FType_Type(unsigned int const frameNum) {
                 break;
             default:
                 if (lastI != -1) {
-                    unsigned int const pretendFrameNumber = 
+                    unsigned int const pretendFrameNumber =
                         (frameNum - lastI + firstI) % framePatternLen;
                     retval = framePattern[pretendFrameNumber];
-                } else 
+                } else
                     retval = patternedType;
             }
-        } else 
+        } else
             retval = patternedType;
     }
     return retval;
@@ -180,7 +180,7 @@ FType_PastRef(currFrameNum)
     } else {
       index = currFrameNum % framePatternLen;
       pastIndex = frameTable[index].prev->number;
-      
+
       return currFrameNum -
 	(((index-pastIndex)+framePatternLen) % framePatternLen);
     }
@@ -227,14 +227,14 @@ SetFramePattern(const char * const pattern) {
     firstI = -1;
     for (index = 0; index < len; index++) {
         switch( SIMPLE_ASCII_UPPER(pattern[index]) ) {
-        case 'I':	
+        case 'I':
             buf[index] = 'i';
             if (firstI == -1) firstI = index;
             break;
-        case 'P':	
-            buf[index] = 'p'; 
+        case 'P':
+            buf[index] = 'p';
             break;
-        case 'B':	
+        case 'B':
             buf[index] = 'b';
             break;
         default:
@@ -248,7 +248,7 @@ SetFramePattern(const char * const pattern) {
 
     framePattern = buf;
     framePatternLen = len;
-    
+
     /* Used to ComputeFrameTable(), but now must wait until param
        parsed. (STDIN or not)
     */
@@ -259,7 +259,7 @@ SetFramePattern(const char * const pattern) {
 void
 ComputeFrameTable(unsigned int const numFramesArg) {
 /*----------------------------------------------------------------------------
-  Compute a table of I, P, B frames to help in determining dependencie
+  Compute a table of I, P, B frames to help in determining dependency
 
   'numFrames' == 0 means number of frames is not known at this time.
 -----------------------------------------------------------------------------*/
@@ -339,7 +339,7 @@ ComputeFrameTable(unsigned int const numFramesArg) {
 	        break;
         }
     }
-    
+
     /* why? SRS */
     frameTable[table_size].number = framePatternLen;
     ptr = firstB;
@@ -362,3 +362,6 @@ ComputeFrameTable(unsigned int const numFramesArg) {
     if (numFrames)
         use_cache = TRUE;
 }
+
+
+
diff --git a/converter/ppm/ppmtompeg/jpeg.c b/converter/ppm/ppmtompeg/jpeg.c
index 24c9ae2d..4540f6f0 100644
--- a/converter/ppm/ppmtompeg/jpeg.c
+++ b/converter/ppm/ppmtompeg/jpeg.c
@@ -1,12 +1,12 @@
 /*===========================================================================*
- * jpeg.c                              
- *                                     
- *  procedures to deal with JPEG files 
- *                                     
- * EXPORTED PROCEDURES:                
- *  JMovie2JPEG                        
- *      ReadJPEG                      
- *                                    
+ * jpeg.c
+ *
+ *  procedures to deal with JPEG files
+ *
+ * EXPORTED PROCEDURES:
+ *  JMovie2JPEG
+ *      ReadJPEG
+ *
  *===========================================================================*/
 
 /* COPYRIGHT INFORMATION IS AT THE END OF THIS FILE */
@@ -20,7 +20,7 @@
 /* With the lossless jpeg patch applied to the Jpeg library
     (ftp://ftp.wizards.dupont.com/pub/ImageMagick/delegates/ljpeg-6b.tar.gz),
     the name of min_DCT_scaled_size changes to min_codec_data_unit,
-    for some reason.  With this macro, we change it back.  
+    for some reason.  With this macro, we change it back.
 */
 #define min_codec_data_unit min_DCT_scaled_size
 #include <jpeglib.h>
@@ -40,7 +40,7 @@
 /* make it happier.... */
 #undef DCTSIZE2
 
-/* jcopy_sample_rows() is an internal routine in the JPEG library, not 
+/* jcopy_sample_rows() is an internal routine in the JPEG library, not
    meant for use by us.  We should figure out what the official interface
    for this is and use it.  The following is copied out of jpegint.h, which
    is part of the JPEG library source code.
@@ -88,7 +88,7 @@ void
 JMovie2JPEG(const char * const infilename,
                 /* input filename string */
             const char * const obase,
-                /* output filename base string=>obase##.jpg */ 
+                /* output filename base string=>obase##.jpg */
             int          const start,
                 /* first frame to be extracted */
             int          const end
@@ -126,154 +126,154 @@ JMovie2JPEG(const char * const infilename,
        for the appending of the jpeg bitstream. It can be
        made smaller if you have a better idea of its expected size
     */
-    static unsigned char inbuffer[300000] = {    
-        0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46,  
+    static unsigned char inbuffer[300000] = {
+        0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46,
         0x49, 0x46, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01,
-        0x00, 0x01, 0x00, 0x00, 0xFF, 0xC0, 0x00, 0x11,  
+        0x00, 0x01, 0x00, 0x00, 0xFF, 0xC0, 0x00, 0x11,
         0x08, 0x00, 0xF0, 0x01, 0x40, 0x03, 0x01, 0x21,
-        0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xFF,  
+        0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xFF,
         0xDB, 0x00, 0x84, 0x00, 0x10, 0x0B, 0x0C, 0x0E,
-        0x0C, 0x0A, 0x10, 0x0E, 0x0D, 0x0E, 0x12,  
+        0x0C, 0x0A, 0x10, 0x0E, 0x0D, 0x0E, 0x12,
         0x11, 0x10, 0x13, 0x18, 0x28, 0x1A, 0x18, 0x16,
-        0x16, 0x18, 0x31, 0x23, 0x25, 0x1D, 0x28, 0x3A,  
+        0x16, 0x18, 0x31, 0x23, 0x25, 0x1D, 0x28, 0x3A,
         0x33, 0x3D, 0x3C, 0x39, 0x33, 0x38, 0x37, 0x40,
-        0x48, 0x5C, 0x4E, 0x40, 0x44, 0x57, 0x45, 0x37,  
+        0x48, 0x5C, 0x4E, 0x40, 0x44, 0x57, 0x45, 0x37,
         0x38, 0x50, 0x6D, 0x51, 0x57, 0x5F, 0x62, 0x67,
-        0x68, 0x67, 0x3E, 0x4D, 0x71, 0x79, 0x70, 0x64,  
+        0x68, 0x67, 0x3E, 0x4D, 0x71, 0x79, 0x70, 0x64,
         0x78, 0x5C, 0x65, 0x67, 0x63, 0x01, 0x11, 0x12,
-        0x12, 0x18, 0x15, 0x18, 0x2F, 0x1A, 0x1A, 0x2F,  
+        0x12, 0x18, 0x15, 0x18, 0x2F, 0x1A, 0x1A, 0x2F,
         0x63, 0x42, 0x38, 0x42, 0x63, 0x63, 0x63, 0x63,
-        0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,  
-        0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,  
-        0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,  
-        0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,  
-        0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,  
+        0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
+        0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
+        0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
+        0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
+        0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0x63,
         0x63, 0x63, 0x63, 0x63, 0x63, 0x63, 0xFF, 0xC4,
-        0x01, 0xA2, 0x00, 0x00, 0x01, 0x05, 0x01, 0x01,  
+        0x01, 0xA2, 0x00, 0x00, 0x01, 0x05, 0x01, 0x01,
         0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00,
-        0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04,  
+        0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04,
         0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
-        0x10, 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04,  
+        0x10, 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04,
         0x03, 0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01,
-        0x7D, 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05,  
+        0x7D, 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05,
         0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61,
-        0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1,  
+        0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xA1,
         0x08, 0x23, 0x42, 0xB1, 0xC1, 0x15, 0x52, 0xD1,
-        0xF0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09,   
+        0xF0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09,
         0x0A, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x25, 0x26,
-        0x27, 0x28, 0x29, 0x2A, 0x34, 0x35, 0x36, 0x37,  
+        0x27, 0x28, 0x29, 0x2A, 0x34, 0x35, 0x36, 0x37,
         0x38, 0x39, 0x3A, 0x43, 0x44, 0x45, 0x46, 0x47,
-        0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57,  
+        0x48, 0x49, 0x4A, 0x53, 0x54, 0x55, 0x56, 0x57,
         0x58, 0x59, 0x5A, 0x63, 0x64, 0x65, 0x66, 0x67,
-        0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77,  
+        0x68, 0x69, 0x6A, 0x73, 0x74, 0x75, 0x76, 0x77,
         0x78, 0x79, 0x7A, 0x83, 0x84, 0x85, 0x86, 0x87,
-        0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96,  
+        0x88, 0x89, 0x8A, 0x92, 0x93, 0x94, 0x95, 0x96,
         0x97, 0x98, 0x99, 0x9A, 0xA2, 0xA3, 0xA4, 0xA5,
-        0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4,  
+        0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xB2, 0xB3, 0xB4,
         0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xC2, 0xC3,
-        0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2,  
+        0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xD2,
         0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA,
-        0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8,  
+        0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8,
         0xE9, 0xEA, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6,
-        0xF7, 0xF8, 0xF9, 0xFA, 0x01, 0x00, 0x03, 0x01,  
+        0xF7, 0xF8, 0xF9, 0xFA, 0x01, 0x00, 0x03, 0x01,
         0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
-        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02,  
-        0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 
-        0x0A, 0x0B, 0x11, 0x00, 0x02, 0x01, 0x02, 0x04,  
+        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02,
+        0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
+        0x0A, 0x0B, 0x11, 0x00, 0x02, 0x01, 0x02, 0x04,
         0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04, 0x00,
-        0x01, 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11,  
+        0x01, 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11,
         0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51,
-        0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08,  
+        0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08,
         0x14, 0x42, 0x91, 0xA1, 0xB1, 0xC1, 0x09, 0x23,
-        0x33, 0x52, 0xF0, 0x15, 0x62, 0x72, 0xD1,   
+        0x33, 0x52, 0xF0, 0x15, 0x62, 0x72, 0xD1,
         0x0A, 0x16, 0x24, 0x34, 0xE1, 0x25, 0xF1, 0x17,
-        0x18, 0x19, 0x1A, 0x26, 0x27, 0x28, 0x29, 0x2A,  
+        0x18, 0x19, 0x1A, 0x26, 0x27, 0x28, 0x29, 0x2A,
         0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x43, 0x44,
-        0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54,  
+        0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x53, 0x54,
         0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x63, 0x64,
-        0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x73, 0x74,  
+        0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x73, 0x74,
         0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x82, 0x83,
-        0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x92,  
+        0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x92,
         0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A,
-        0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9,  
+        0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9,
         0xAA, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8,
-        0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7,  
+        0xB9, 0xBA, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7,
         0xC8, 0xC9, 0xCA, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6,
-        0xD7, 0xD8, 0xD9, 0xDA, 0xE2, 0xE3, 0xE4, 0xE5,  
+        0xD7, 0xD8, 0xD9, 0xDA, 0xE2, 0xE3, 0xE4, 0xE5,
         0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xF2, 0xF3, 0xF4,
-        0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFF, 0xDA,  
+        0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFF, 0xDA,
         0x00, 0x0C, 0x03, 0x01, 0x00, 0x02, 0x11, 0x03,
-        0x11, 0x00, 0x3F, 0x00  
+        0x11, 0x00, 0x3F, 0x00
 
     };
-    
+
     if (start > end) {
         fprintf(stderr,"bad frame numbers\n");
         exit(1);
     }
-    
+
     /* open J_Movie */
     inFile = fopen(infilename, "rb");
     if (inFile == NULL) {
         perror (infilename);
         exit(1);
     }
-    
-    /* get file descriptor */    
+
+    /* get file descriptor */
     fd = fileno(inFile);
-    
+
     /* The following lines parse the jpeg_movie header and recover the */
-    /* relavant information */
+    /* relevant information */
 
     fseek(inFile, 8 * sizeof(char), 0);
-    
+
     if (fread(&ver_no, sizeof(int), 1, inFile) != 1) {
         perror("Error in reading version");
         exit(1);
-    }  
+    }
     if (ver_no != 2) {
         perror("Unrecognized version - Quantization tables may be wrong\n");
     }
     if (fread(&fps, sizeof(int), 1, inFile) != 1) {
         perror("Error in reading fps");
         exit(1);
-    }  
+    }
     if (fread (&no_frames, sizeof(int), 1, inFile) != 1) {
         perror("Error in reading no_frames");
         exit(1);
-    }  
+    }
 
     MALLOCARRAY(inoffsets, no_frames);
-    
+
     if (fread(&width, sizeof(int), 1, inFile) != 1) {
         perror("Error in reading width");
         exit(1);
-    }  
+    }
     /* set image width in JFIF header */
     inbuffer[27] = (char)(0xFF & (width >> 8));
     inbuffer[28] = (char)(0xFF & width);
- 
+
     if (fread(&height, sizeof(int), 1, inFile) != 1) {
         perror("Error in reading height");
         exit(1);
-    }  
+    }
     /* set image height in JFIF header */
     inbuffer[25] = (char)(0xFF & (height >> 8));
     inbuffer[26] = (char)(0xFF & height);
-    
+
     if (fread(&bandwidth, sizeof(int), 1, inFile) != 1) {
         perror("Error in reading bandwidth");
         exit(1);
-    }  
-    
+    }
+
     if (fread(&qfactor, sizeof(int), 1, inFile) != 1) {
         perror("Error in reading qfactor");
         exit(1);
-    }  
+    }
     /* The default quality factor = 100, therefore, if
        our quality factor does not equal 100 we must
        scale the quantization matrices in the JFIF header
-    */    
+    */
     /* Note values are clipped to a max of 255 */
     if (qfactor != 100) {
         for (Temp = 44; Temp < 108; ++Temp) {
@@ -283,13 +283,13 @@ JMovie2JPEG(const char * const infilename,
         for (Temp = 109; Temp < 173; ++Temp) {
             temp = (inbuffer[Temp]*qfactor)/100;
             inbuffer[Temp] = (char)((temp<255) ? temp : 255);
-        }    
+        }
     }
-  
+
     if (fread(&mapsize, sizeof(int), 1, inFile) != 1) {
         perror("Error in reading mapsize");
         exit(1);
-    }  
+    }
     if (fread (&image_offset, sizeof(int), 1, inFile) != 1) {
         perror("Error in reading image offset");
         exit(1);
@@ -298,32 +298,32 @@ JMovie2JPEG(const char * const infilename,
         perror("Error in reading audio tracks");
         exit(1);
     }
-    
+
     fread(junk,sizeof(int),1,inFile);
-    
+
     if (fread (&audiosize, sizeof(int), 1, inFile) != 1) {
         perror("Error in reading audiosize");
         exit(1);
     }
-    
+
     fseek (inFile, image_offset, 0);
-    
+
     last = MIN(end, no_frames-1);
 
     for (i = 0; i < no_frames; ++i)  {
         fread(&(inoffsets[i]), sizeof(int), 1, inFile);
     } /* Reads in the frame sizes into the array */
-    
+
     rewind(inFile);
 
-    /* Extract JFIF files from J_Movie */    
+    /* Extract JFIF files from J_Movie */
     for (i = start; i <= last; ++i) {
         size = inoffsets[i] - inoffsets[i-1]- 5;
-        lseek(fd, inoffsets[i-1], 0); 
+        lseek(fd, inoffsets[i-1], 0);
         read(fd, &(op_code), 1);
         while (op_code !=  0xffffffec) {
             read(fd,junk,audiosize);
-            read(fd, &(op_code), 1);  
+            read(fd, &(op_code), 1);
             size = size - audiosize ;
         } /* To skip the audio bytes in each frame */
         read(fd, jpeg_size, 4);
@@ -331,7 +331,7 @@ JMovie2JPEG(const char * const infilename,
         sprintf(ofname, "%s%d.jpg", obase, i);
         outFile = fopen(ofname, "wb");
         fwrite(inbuffer, (size+607), sizeof(char), outFile);
-        fclose(outFile);        
+        fclose(outFile);
     }
     free(inoffsets);
     fclose(inFile);
@@ -413,50 +413,50 @@ ReadJPEG(MpegFrame * const mf,
             jpeg_stdio_src(&cinfo, fp);
         }
     }
-  
+
     /* specify data source (eg, a file) */
-  
+
     jpeg_stdio_src(&cinfo, fp);
-  
+
     /* read file parameters with jpeg_read_header() */
-  
-  
+
+
     (void) jpeg_read_header(&cinfo, TRUE);
     /* We can ignore the return value from jpeg_read_header since
      *   (a) suspension is not possible with the stdio data source, and
      *   (b) we passed TRUE to reject a tables-only JPEG file as an error.
      */
-  
+
     /* set parameters for decompression */
     cinfo.raw_data_out = TRUE;
     cinfo.out_color_space = JCS_YCbCr;
-  
+
     /* calculate image output dimensions */
     jpeg_calc_output_dimensions(&cinfo);
     /* the above calculation will set these soon */
     /* for now we'll set them ourselves */
-    
+
     /* tell mpeg_encode the size of the JPEG Image*/
     Fsize_Note(mf->id,(int)(cinfo.image_width),(int)(cinfo.image_height));
-  
+
     /* Allocate memory for the raw YCbCr data to occupy*/
     Frame_AllocYCC(mf);      /*allocate space for mpeg frame*/
-  
+
     /* copy pointers to array structure- this make the following
        code more compact
     */
     orig[0] = mf->orig_y;
     orig[1] = mf->orig_cb;
     orig[2] = mf->orig_cr;
-  
+
     /* Note that we can use the info obtained from jpeg_read_header.
      */
-  
+
     /* Start decompressor */
-  
+
     jpeg_start_decompress(&cinfo);
-  
-  
+
+
     /* JSAMPLEs per row in output buffer  */
     /* collect component subsample values*/
     for (cp=0, compptr = cinfo.comp_info;
@@ -470,28 +470,28 @@ ReadJPEG(MpegFrame * const mf,
     max_h_samp = (temp_h<h_samp[2]) ? h_samp[2]:temp_h;
     temp_v = (v_samp[0]<v_samp[1]) ? v_samp[1] : v_samp[0];
     max_v_samp = (temp_v<v_samp[2]) ? v_samp[2]:temp_v;
-  
+
     /* Make an 8-row-high sample array that will go away when done
        with image
     */
     buffer_height = cinfo.max_v_samp_factor * minDctVScaledSize(cinfo);
-  
+
     for(cp=0,compptr = cinfo.comp_info;cp<cinfo.num_components;
         cp++,compptr++) {
         ncols[cp] = (JDIMENSION)((cinfo.image_width*compptr->h_samp_factor)/
                                  max_h_samp);
-    
+
         nrows[cp] = (JDIMENSION)((buffer_height*compptr->v_samp_factor)/
                                  max_v_samp);
-    
+
         scanarray[cp] = (*cinfo.mem->alloc_sarray)
             ((j_common_ptr) &cinfo, JPOOL_IMAGE, ncols[cp], nrows[cp]);
     }
-  
+
     /*  while (scan lines remain to be read)
            jpeg_read_scanlines(...);
     */
-  
+
     /* Here we use the library's state variable cinfo.output_scanline as the
      * loop counter, so that we don't have to keep track ourselves.
      */
@@ -525,29 +525,29 @@ ReadJPEG(MpegFrame * const mf,
             }
         } else
             pm_error("Invalid subsampling ratio");
-    
+
         /* transfer data from jpeg buffer to MPEG frame */
         /* calculate the row we wish to output into */
         for (ci = 0, compptr = cinfo.comp_info;
              ci < cinfo.num_components;
              ++ci, ++compptr) {
             current_row[ci] =((cinfo.output_scanline - buffer_height)*
-                              (v_samp[ci])/max_v_samp);  
-      
+                              (v_samp[ci])/max_v_samp);
+
             jcopy_sample_rows(scanarray[ci],0,(JSAMPARRAY)(orig[ci]),
                               current_row[ci],nrows[ci],ncols[ci]);
         }
-    }  
-  
+    }
+
     /* Step 7: Finish decompression */
-  
+
     (void) jpeg_finish_decompress(&cinfo);
     /* We can ignore the return value since suspension is not possible
      * with the stdio data source.
      */
-  
+
     /* Step 8: Release JPEG decompression object */
-  
+
     /*
     ** DO NOT release the cinfo struct if we are reading from stdin, this
     ** is because the cinfo struct contains the read buffer, and the read
@@ -572,7 +572,7 @@ ReadJPEG(MpegFrame * const mf,
        think that jpeg_destroy can do an error exit, but why assume
        anything...)
     */
-  
+
     /* At this point you may want to check to see whether any corrupt-data
      * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
      * If you prefer to treat corrupt data as a fatal error, override the
diff --git a/converter/ppm/ppmtompeg/mheaders.c b/converter/ppm/ppmtompeg/mheaders.c
index 4cfe49ac..98e1b063 100644
--- a/converter/ppm/ppmtompeg/mheaders.c
+++ b/converter/ppm/ppmtompeg/mheaders.c
@@ -39,7 +39,7 @@
  *  $Header: /n/picasso/project/mpeg/mpeg_dist/mpeg_encode/RCS/mheaders.c,v 1.15 1995/08/07 21:45:19 smoot Exp $
  *  $Log: mheaders.c,v $
  *  Revision 1.15  1995/08/07 21:45:19  smoot
- *  check for illegal MVs (shouldnt ever be called, but....)
+ *  check for illegal MVs (shouldn't ever be called, but....)
  *  fix bug which made us not weite Iframe Qscale changes
  *  warns if writing a size=0 mpeg
  *
@@ -746,7 +746,7 @@ Mhead_GenSequenceHeader(BitBucket *   const bbPtr,
     }
     Bitio_Write(bbPtr, pratio, 4);
 
-    /* Wrtie picture rate, negative values default to 30 fps. */
+    /* Write picture rate, negative values default to 30 fps. */
 
     if (pict_rate < 0) {
         fprintf(stderr, "PROGRAMMER ERROR:  pict_rate = %d\n", pict_rate);
diff --git a/converter/ppm/ppmtompeg/mpeg.c b/converter/ppm/ppmtompeg/mpeg.c
index dd0e0dbc..e67eec1e 100644
--- a/converter/ppm/ppmtompeg/mpeg.c
+++ b/converter/ppm/ppmtompeg/mpeg.c
@@ -91,7 +91,7 @@ static boolean  frameCountsUnknown;
 
 
 /*==================*
- * GLOBAL VARIABLES *   
+ * GLOBAL VARIABLES *
  *==================*/
 
 /* important -- don't initialize anything here */
@@ -142,14 +142,14 @@ ShowRemainingTime(boolean const childProcess) {
         /* nothing */;
     } else if ( numI + numP + numB == 0 ) {
         /* no time left */
-    } else if ( timeMask != 0 ) {   
+    } else if ( timeMask != 0 ) {
         /* haven't encoded all types yet */
     } else {
         static int  lastTime = 0;
         float   total;
         time_t  nowTime;
         float   secondsPerFrame;
-        
+
         time(&nowTime);
         secondsPerFrame = (nowTime-timeStart)/(float)framesOutput;
         total = secondsPerFrame*(float)(numI+numP+numB);
@@ -174,7 +174,7 @@ static void
 initTCTime(unsigned int const firstFrameNumber) {
 
     unsigned int frameNumber;
-    
+
     tc_hrs = 0; tc_min = 0; tc_sec = 0; tc_pict = 0; tc_extra = 0;
     for (frameNumber = 0; frameNumber < firstFrameNumber; ++frameNumber)
         IncrementTCTime();
@@ -201,13 +201,13 @@ IncrementTCTime() {
        otherwise, it is the number of extra 1/1001 frames we've passed by
 
        so far; for example, if fps = 24000/1001, then 24 frames = 24024/24000
-       seconds = 1 second + 24/24000 seconds = 1 + 1/1000 seconds; similary,
+       seconds = 1 second + 24/24000 seconds = 1 + 1/1000 seconds; similarly,
        if fps = 30000/1001, then 30 frames = 30030/30000 = 1 + 1/1000 seconds
        and if fps = 60000/1001, then 60 frames = 1 + 1/1000 seconds
 
        if fps = 24000/1001, then 1/1000 seconds = 24/1001 frames
        if fps = 30000/1001, then 1/1000 seconds = 30/1001 frames
-       if fps = 60000/1001, then 1/1000 seconds = 60/1001 frames     
+       if fps = 60000/1001, then 1/1000 seconds = 60/1001 frames
      */
 
     totalFramesSent++;
@@ -250,7 +250,7 @@ initializeRateControl(bool const wantUnderflowWarning,
         */
     }
 }
-    
+
 
 
 /*===========================================================================*
@@ -294,16 +294,16 @@ finishFrameOutput(MpegFrame * const frameP,
                   boolean     const childProcess,
                   boolean     const remoteIO) {
 
-    if ((referenceFrame == DECODED_FRAME) && 
+    if ((referenceFrame == DECODED_FRAME) &&
         childProcess && NonLocalRefFrame(frameP->id)) {
         if (remoteIO)
             SendDecodedFrame(frameP);
         else
             WriteDecodedFrame(frameP);
-            
+
         NotifyDecodeServerReady(frameP->id);
     }
-    
+
     if (separateFiles) {
         if (remoteIO)
             SendRemoteFrame(frameP->id, bbP);
@@ -314,7 +314,7 @@ finishFrameOutput(MpegFrame * const frameP,
     }
 }
 
-    
+
 
 
 static void
@@ -324,41 +324,41 @@ outputIFrame(MpegFrame * const frameP,
              int         const realEnd,
              MpegFrame * const pastRefFrameP,
              boolean     const separateFiles) {
-      
+
     /* only start a new GOP with I */
     /* don't start GOP if only doing frames */
     if (!separateFiles && currentGOP >= gopSize) {
-        boolean const closed = 
+        boolean const closed =
             (totalFramesSent == frameP->id || pastRefFrameP == NULL);
 
         static int num_gop = 0;
-    
+
         /* first, check to see if closed GOP */
-    
+
         /* new GOP */
-        if (num_gop != 0 && mult_seq_headers && 
+        if (num_gop != 0 && mult_seq_headers &&
             num_gop % mult_seq_headers == 0) {
             if (!realQuiet) {
-                fprintf(stdout, 
+                fprintf(stdout,
                         "Creating new Sequence before GOP %d\n", num_gop);
                 fflush(stdout);
             }
-      
+
             Mhead_GenSequenceHeader(
                 bbP, Fsize_x, Fsize_y,
                 /* pratio */    aspectRatio,
                 /* pict_rate */ frameRate, /* bit_rate */ bit_rate,
                 /* buf_size */  buf_size,  /* c_param_flag */ 1,
-                /* iq_matrix */ customQtable, 
+                /* iq_matrix */ customQtable,
                 /* niq_matrix */ customNIQtable,
                 /* ext_data */ NULL,  /* ext_data_size */ 0,
                 /* user_data */ NULL, /* user_data_size */ 0);
         }
-    
+
         if (!realQuiet)
             pm_message("Creating new GOP (closed = %s) before frame %d\n",
                        closed ? "YES" : "NO", frameP->id);
-    
+
         ++num_gop;
         Mhead_GenGOPHeader(bbP,  /* drop_frame_flag */ 0,
                            tc_hrs, tc_min, tc_sec, tc_pict,
@@ -371,13 +371,13 @@ outputIFrame(MpegFrame * const frameP,
         else
             SetGOPStartTime(pastRefFrameP->id + 1);
     }
-      
+
     if (frameP->id >= realStart && frameP->id <= realEnd)
         GenIFrame(bbP, frameP);
-      
+
     --numI;
     timeMask &= 0x6;
-      
+
     ++currentGOP;
     IncrementTCTime();
 }
@@ -396,7 +396,7 @@ outputPFrame(MpegFrame * const frameP,
 
     --numP;
     timeMask &= 0x5;
-    
+
     ++currentGOP;
     IncrementTCTime();
 }
@@ -464,7 +464,7 @@ getBFrame(int                  const frameNum,
         *bFramePP = bFrameP;
     } else {
         /* As the frame input is serial, we can't read the B frame now.
-           Rather, Caller has already read it and chained it to 
+           Rather, Caller has already read it and chained it to
            the previous reference frame.  So we get that copy now.
         */
         *bFramePP = pastRefFrameP->next;
@@ -510,15 +510,15 @@ processBFrames(MpegFrame *          const pastRefFrameP,
 
     assert(pastRefFrameP != NULL);
     assert(futureRefFrameP != NULL);
-    
-    for (frameNum = MAX(realStart, firstBFrameNum); 
-         frameNum < MIN(realEnd, futureRefFrameP->id); 
+
+    for (frameNum = MAX(realStart, firstBFrameNum);
+         frameNum < MIN(realEnd, futureRefFrameP->id);
          ++frameNum) {
 
         MpegFrame * bFrame;
         BitBucket * bbP;
 
-        getBFrame(frameNum, inputSourceP, pastRefFrameP, childProcess, 
+        getBFrame(frameNum, inputSourceP, pastRefFrameP, childProcess,
                   remoteIO,
                   &bFrame, IOtimeP, framesReadP);
 
@@ -554,7 +554,7 @@ processBFrames(MpegFrame *          const pastRefFrameP,
 
 
 static void
-processRefFrame(MpegFrame *    const frameP, 
+processRefFrame(MpegFrame *    const frameP,
                 BitBucket *    const wholeStreamBbP,
                 int            const realStart,
                 int            const realEnd,
@@ -574,18 +574,18 @@ processRefFrame(MpegFrame *    const frameP,
 -----------------------------------------------------------------------------*/
     if (frameP->id >= realStart && frameP->id <= realEnd) {
         bool const separateFiles = (wholeStreamBbP == NULL);
-  
+
         BitBucket * bbP;
-  
+
         if (separateFiles)
             bbP = bitioNew(outputFileName, frameP->id, remoteIO);
         else
             bbP = wholeStreamBbP;
-  
+
         /* first, output this reference frame */
         switch (frameP->type) {
         case TYPE_IFRAME:
-            outputIFrame(frameP, bbP, realStart, realEnd, pastRefFrameP, 
+            outputIFrame(frameP, bbP, realStart, realEnd, pastRefFrameP,
                          separateFiles);
             break;
         case TYPE_PFRAME:
@@ -595,10 +595,10 @@ processRefFrame(MpegFrame *    const frameP,
         default:
             pm_error("INTERNAL ERROR: non-reference frame passed to "
                      "ProcessRefFrame()");
-        }  
-        
+        }
+
         ++(*framesOutputP);
-        
+
         finishFrameOutput(frameP, bbP, separateFiles, referenceFrame,
                           childProcess, remoteIO);
     }
@@ -620,7 +620,7 @@ countFrames(unsigned int const firstFrame,
 -----------------------------------------------------------------------------*/
     unsigned int numI, numP, numB;
     unsigned int timeMask;
-            
+
     numI = 0; numP = 0; numB = 0;
     timeMask = 0;
     if (stdinUsed) {
@@ -663,7 +663,7 @@ readAndSaveFrame(struct inputSource * const inputSourceP,
    type 'frameType'.
 
    Increment *framesReadP.
-   
+
    Add the time it took to read it, in seconds, to *iotimeP.
 
    Iff we can't read because we hit end of file, return
@@ -672,11 +672,11 @@ readAndSaveFrame(struct inputSource * const inputSourceP,
     /* This really should be part of ReadNthFrame.  The frame should be chained
        to the input object, not the past reference frame.
     */
-       
+
     MpegFrame * p;
     MpegFrame * frameP;
     time_t ioTimeStart, ioTimeEnd;
-    
+
     time(&ioTimeStart);
 
     frameP = Frame_New(frameNumber, frameType);
@@ -687,15 +687,15 @@ readAndSaveFrame(struct inputSource * const inputSourceP,
         Frame_Free(frameP);
     else {
         ++(*framesReadP);
-    
+
         time(&ioTimeEnd);
         *ioTimeP += (ioTimeEnd - ioTimeStart);
 
-        /* Add the B frame to the end of the queue of B-frames 
+        /* Add the B frame to the end of the queue of B-frames
            for later encoding.
         */
         assert(pastRefFrameP != NULL);
-        
+
         p = pastRefFrameP;
         while (p->next != NULL)
             p = p->next;
@@ -726,7 +726,7 @@ doFirstFrameStuff(enum frameContext const context,
 -----------------------------------------------------------------------------*/
     *inputFrameBitsP = 24 * Fsize_x * Fsize_y;
     SetBlocksPerSlice();
-          
+
     if (context == CONTEXT_WHOLESTREAM) {
         int32 const bitstreamMode = getRateMode();
         char * userData;
@@ -742,11 +742,11 @@ doFirstFrameStuff(enum frameContext const context,
             bit_rate = -1;
             buf_size = -1;
         }
-        
+
         if (strlen(userDataFileName) != 0) {
             struct stat statbuf;
             FILE *fp;
-          
+
             stat(userDataFileName,&statbuf);
             userDataSize = statbuf.st_size;
             userData = malloc(userDataSize);
@@ -771,7 +771,7 @@ doFirstFrameStuff(enum frameContext const context,
         } else { /* Put in our UserData Header */
             const char * userDataString;
             time_t now;
-                    
+
             time(&now);
             pm_asprintf(&userDataString,"MPEG stream encoded by UCB Encoder "
                         "(mpeg_encode) v%s on %s.",
@@ -782,11 +782,11 @@ doFirstFrameStuff(enum frameContext const context,
         }
         Mhead_GenSequenceHeader(bbP, Fsize_x, Fsize_y,
                                 /* pratio */ aspectRatio,
-                                /* pict_rate */ frameRate, 
+                                /* pict_rate */ frameRate,
                                 /* bit_rate */ bit_rate,
                                 /* buf_size */ buf_size,
                                 /*c_param_flag */ 1,
-                                /* iq_matrix */ qtable, 
+                                /* iq_matrix */ qtable,
                                 /* niq_matrix */ niqtable,
                                 /* ext_data */ NULL,
                                 /* ext_data_size */ 0,
@@ -844,9 +844,9 @@ getPreviousFrame(unsigned int         const frameStart,
                      separateConversion, slaveConversion, inputConversion,
                      frameP, &endOfStream);
         assert(!endOfStream);  /* Because Stdin causes failure above */
-    }            
+    }
     ++(*framesReadP);
-    
+
     time(&ioTimeEnd);
     *ioTimeP += (ioTimeEnd-ioTimeStart);
 
@@ -858,7 +858,7 @@ getPreviousFrame(unsigned int         const frameStart,
 static void
 computeFrameRange(unsigned int         const frameStart,
                   unsigned int         const frameEnd,
-                  enum frameContext    const context, 
+                  enum frameContext    const context,
                   struct inputSource * const inputSourceP,
                   unsigned int *       const firstFrameP,
                   unsigned int *       const lastFrameP) {
@@ -881,13 +881,13 @@ computeFrameRange(unsigned int         const frameStart,
             *firstFrameP = frameStart;
 
         /* if last frame is B, need to read in P or I frame after it */
-        if ((FType_Type(frameEnd) == 'b') && 
+        if ((FType_Type(frameEnd) == 'b') &&
             (frameEnd != inputSourceP->numInputFiles-1)) {
             /* can't find the next reference frame interactively */
             if (inputSourceP->stdinUsed)
                 pm_error("Cannot encode frames from Standard Input "
                          "when last frame is a B-frame.");
-            
+
             *lastFrameP = FType_FutureRef(frameEnd);
         } else
             *lastFrameP = frameEnd;
@@ -930,11 +930,11 @@ getFrame(MpegFrame **         const framePP,
     time_t ioTimeStart, ioTimeEnd;
     MpegFrame * frameP;
     bool endOfStream;
-    
+
     time(&ioTimeStart);
 
     frameP = Frame_New(frameNumber, frameType);
-            
+
     if ((referenceFrame == DECODED_FRAME) &&
         ((frameNumber < realStart) || (frameNumber > realEnd)) ) {
         WaitForDecodedFrame(frameNumber);
@@ -952,13 +952,13 @@ getFrame(MpegFrame **         const framePP,
         ReadNthFrame(inputSourceP, frameNumber, remoteIO, childProcess,
                      separateConversion, slaveConversion, inputConversion,
                      frameP, &endOfStream);
-    
+
     if (endOfStream) {
         Frame_Free(frameP);
         *framePP = NULL;
     } else {
         ++(*framesReadP);
-            
+
         time(&ioTimeEnd);
         *ioTimeP += (ioTimeEnd - ioTimeStart);
 
@@ -988,9 +988,9 @@ handleBitRate(unsigned int const realEnd,
 static void
 doAFrame(unsigned int         const frameNumber,
          struct inputSource * const inputSourceP,
-         enum frameContext    const context, 
-         unsigned int         const frameStart, 
-         unsigned int         const frameEnd, 
+         enum frameContext    const context,
+         unsigned int         const frameStart,
+         unsigned int         const frameEnd,
          unsigned int         const realStart,
          unsigned int         const realEnd,
          bool                 const childProcess,
@@ -1017,7 +1017,7 @@ doAFrame(unsigned int         const frameNumber,
    output each frame to its own individual file instead.
 -----------------------------------------------------------------------------*/
     char const frameType = FType_Type(frameNumber);
-    
+
     *endOfStreamP = FALSE;  /* initial assumption */
 
     if (frameType == 'b') {
@@ -1026,44 +1026,44 @@ doAFrame(unsigned int         const frameNumber,
            just read it later.
         */
         *newPastRefFramePP = pastRefFrameP;
-        if (inputSourceP->stdinUsed) 
+        if (inputSourceP->stdinUsed)
             readAndSaveFrame(inputSourceP,
                              frameNumber, frameType, inputConversion,
                              pastRefFrameP, framesReadP, &IOtime,
                              endOfStreamP);
     } else {
         MpegFrame * frameP;
-        
+
         getFrame(&frameP, inputSourceP, frameNumber, frameType,
                  realStart, realEnd, referenceFrame, childProcess,
                  remoteIO,
                  separateConversion, slaveConversion, inputConversion,
                  framesReadP, &IOtime);
-        
+
         if (frameP) {
             *endOfStreamP = FALSE;
 
             if (!*firstFrameDoneP) {
                 doFirstFrameStuff(context, userDataFileName, wholeStreamBbP,
                                   Fsize_x, Fsize_y, aspectRatio,
-                                  frameRate, qtable, niqtable, 
+                                  frameRate, qtable, niqtable,
                                   inputFrameBitsP);
-            
+
                 *firstFrameDoneP = TRUE;
             }
             processRefFrame(frameP, wholeStreamBbP, frameStart, frameEnd,
-                            pastRefFrameP, childProcess, outputFileName, 
+                            pastRefFrameP, childProcess, outputFileName,
                             framesReadP, framesOutputP);
-                
+
             if (pastRefFrameP) {
                 processBFrames(pastRefFrameP, frameP, realStart, realEnd,
-                               inputSourceP, remoteIO, childProcess, 
+                               inputSourceP, remoteIO, childProcess,
                                &IOtime, wholeStreamBbP, outputFileName,
                                framesReadP, framesOutputP, &currentGOP);
             }
             if (pastRefFrameP != NULL)
                 Frame_Free(pastRefFrameP);
-        
+
             *newPastRefFramePP = frameP;
         } else
             *endOfStreamP = TRUE;
@@ -1074,13 +1074,13 @@ doAFrame(unsigned int         const frameNumber,
 
 void
 GenMPEGStream(struct inputSource * const inputSourceP,
-              enum frameContext    const context, 
-              unsigned int         const frameStart, 
-              unsigned int         const frameEnd, 
-              int32                const qtable[], 
-              int32                const niqtable[], 
+              enum frameContext    const context,
+              unsigned int         const frameStart,
+              unsigned int         const frameEnd,
+              int32                const qtable[],
+              int32                const niqtable[],
               bool                 const childProcess,
-              FILE *               const ofP, 
+              FILE *               const ofP,
               const char *         const outputFileName,
               bool                 const wantVbvUnderflowWarning,
               bool                 const wantVbvOverflowWarning,
@@ -1129,7 +1129,7 @@ GenMPEGStream(struct inputSource * const inputSourceP,
                  "(%u frames)", frameEnd, inputSourceP->numInputFiles);
 
     if (context == CONTEXT_WHOLESTREAM &&
-        !inputSourceP->stdinUsed && 
+        !inputSourceP->stdinUsed &&
         FType_Type(inputSourceP->numInputFiles-1) == 'b')
         pm_message("WARNING:  "
                    "One or more B-frames at end will not be encoded.  "
@@ -1188,27 +1188,27 @@ GenMPEGStream(struct inputSource * const inputSourceP,
          frameNumber <= lastFrame && !endOfStream;
          ++frameNumber) {
 
-        doAFrame(frameNumber, inputSourceP, context, 
+        doAFrame(frameNumber, inputSourceP, context,
                  frameStart, frameEnd, realStart, realEnd,
                  childProcess, outputFileName,
                  pastRefFrameP, &pastRefFrameP,
                  &framesRead, &framesOutput, &firstFrameDone, streamBbP,
                  inputFrameBitsP, &endOfStream);
     }
-    
+
     if (pastRefFrameP != NULL)
         Frame_Free(pastRefFrameP);
-    
+
     /* SEQUENCE END CODE */
     if (context == CONTEXT_WHOLESTREAM)
         Mhead_GenSequenceEnder(streamBbP);
-    
+
     if (streamBbP)
         numBits = streamBbP->cumulativeBits;
     else {
         /* What should the correct value be?  Most likely 1.  "numBits" is
-           used below, so we need to make sure it's properly initialized 
-           to somthing (anything).  
+           used below, so we need to make sure it's properly initialized
+           to something (anything).
         */
         numBits = 1;
     }
@@ -1272,9 +1272,9 @@ SetGOPSize(size)
  *
  *===========================================================================*/
 void
-PrintStartStats(time_t               const startTime, 
+PrintStartStats(time_t               const startTime,
                 bool                 const specificFrames,
-                unsigned int         const firstFrame, 
+                unsigned int         const firstFrame,
                 unsigned int         const lastFrame,
                 struct inputSource * const inputSourceP) {
 
@@ -1296,7 +1296,7 @@ PrintStartStats(time_t               const startTime,
             fprintf(stdout, "\n\n");
         }
     }
-    
+
     for (i = 0; i < 2; ++i) {
         if ( ( i == 0 ) && (! realQuiet) ) {
             fpointer = stdout;
@@ -1322,15 +1322,15 @@ PrintStartStats(time_t               const startTime,
             fprintf(fpointer, "INPUT FROM FILES:\n");
 
             GetNthInputFileName(inputSourceP, 0, &inputFileName);
-            fprintf(fpointer, "FIRST FILE:  %s/%s\n", 
+            fprintf(fpointer, "FIRST FILE:  %s/%s\n",
                     currentPath, inputFileName);
             pm_strfree(inputFileName);
-            GetNthInputFileName(inputSourceP, inputSourceP->numInputFiles-1, 
+            GetNthInputFileName(inputSourceP, inputSourceP->numInputFiles-1,
                                 &inputFileName);
-            fprintf(fpointer, "LAST FILE:  %s/%s\n", 
+            fprintf(fpointer, "LAST FILE:  %s/%s\n",
                     currentPath, inputFileName);
             pm_strfree(inputFileName);
-        }    
+        }
         fprintf(fpointer, "OUTPUT:  %s\n", outputFileName);
 
         if (resizeFrame)
@@ -1341,15 +1341,15 @@ PrintStartStats(time_t               const startTime,
         fprintf(fpointer, "SLICES PER FRAME:  %d\n", slicesPerFrame);
         if (searchRangeP==searchRangeB)
             fprintf(fpointer, "RANGE:  +/-%d\n", searchRangeP/2);
-        else fprintf(fpointer, "RANGES:  +/-%d %d\n", 
+        else fprintf(fpointer, "RANGES:  +/-%d %d\n",
                      searchRangeP/2,searchRangeB/2);
-        fprintf(fpointer, "PIXEL SEARCH:  %s\n", 
+        fprintf(fpointer, "PIXEL SEARCH:  %s\n",
                 pixelFullSearch ? "FULL" : "HALF");
         fprintf(fpointer, "PSEARCH:  %s\n", PSearchName());
         fprintf(fpointer, "BSEARCH:  %s\n", BSearchName());
-        fprintf(fpointer, "QSCALE:  %d %d %d\n", qscaleI, 
+        fprintf(fpointer, "QSCALE:  %d %d %d\n", qscaleI,
                 GetPQScale(), GetBQScale());
-        if (specificsOn) 
+        if (specificsOn)
             fprintf(fpointer, "(Except as modified by Specifics file)\n");
         if ( referenceFrame == DECODED_FRAME ) {
             fprintf(fpointer, "REFERENCE FRAME:  DECODED\n");
@@ -1386,22 +1386,22 @@ NonLocalRefFrame(int const id) {
     boolean retval;
 
     int const lastIPid = FType_PastRef(id);
-    
+
     /* might be accessed by B-frame */
-    
+
     if (lastIPid+1 < realStart)
         retval = TRUE;
     else {
         unsigned int const nextIPid = FType_FutureRef(id);
-        
+
         /* if B-frame is out of range, then current frame can be
-           ref'd by it 
+           ref'd by it
         */
-        
+
         /* might be accessed by B-frame */
         if (nextIPid > realEnd+1)
             retval = TRUE;
-        
+
         /* might be accessed by P-frame */
         if ((nextIPid > realEnd) && (FType_Type(nextIPid) == 'p'))
             retval = TRUE;
@@ -1410,7 +1410,7 @@ NonLocalRefFrame(int const id) {
 }
 
 
- 
+
 /*===========================================================================*
  *
  * SetFrameRate
@@ -1508,9 +1508,9 @@ ComputeDHMSTime(someTime, timeText)
 
 
 void
-ComputeGOPFrames(int            const whichGOP, 
-                 unsigned int * const firstFrameP, 
-                 unsigned int * const lastFrameP, 
+ComputeGOPFrames(int            const whichGOP,
+                 unsigned int * const firstFrameP,
+                 unsigned int * const lastFrameP,
                  unsigned int   const numFrames) {
 /*----------------------------------------------------------------------------
    Figure out which frames are in GOP number 'whichGOP'.
@@ -1537,7 +1537,7 @@ ComputeGOPFrames(int            const whichGOP,
         if (gopNum == whichGOP) {
             foundGop = TRUE;
             firstFrame = frameNum;
-        }           
+        }
 
         /* go past one gop */
         /* must go past at least one frame */
@@ -1551,7 +1551,7 @@ ComputeGOPFrames(int            const whichGOP,
                 ++frameNum;
                 ++passedB;
             }
-        } while ((frameNum < numFrames) && 
+        } while ((frameNum < numFrames) &&
                  ((FType_Type(frameNum) != 'i') || (currGOP < gopSize)));
 
         currGOP -= gopSize;
@@ -1583,7 +1583,7 @@ doEndStats(FILE *       const fpointer,
 
     fprintf(fpointer, "TIME COMPLETED:  %s", ctime(&endTime));
     fprintf(fpointer, "%s\n\n", timeText);
-        
+
     ShowIFrameSummary(inputFrameBits, totalBits, fpointer);
     ShowPFrameSummary(inputFrameBits, totalBits, fpointer);
     ShowBFrameSummary(inputFrameBits, totalBits, fpointer);
@@ -1595,7 +1595,7 @@ doEndStats(FILE *       const fpointer,
     if (diffTime > 0) {
         fprintf(fpointer, "Total Frames Per Sec Elapsed:  %f (%ld mps)\n",
                 (float)framesOutput/(float)diffTime,
-                (long)((float)framesOutput * 
+                (long)((float)framesOutput *
                        (float)inputFrameBits /
                        (256.0*24.0*(float)diffTime)));
     } else {
@@ -1613,7 +1613,7 @@ doEndStats(FILE *       const fpointer,
             frameRateRounded, frameRateRounded*totalBits/framesOutput);
     fprintf(fpointer, "MPEG file created in :  %s\n", outputFileName);
     fprintf(fpointer, "\n\n");
-        
+
     if ( computeMVHist ) {
         ShowPMVHistogram(fpointer);
         ShowBBMVHistogram(fpointer);
@@ -1637,7 +1637,7 @@ doEndStats(FILE *       const fpointer,
 void
 PrintEndStats(time_t       const startTime,
               time_t       const endTime,
-              unsigned int const inputFrameBits, 
+              unsigned int const inputFrameBits,
               unsigned int const totalBits) {
 
     float   totalCPU;
@@ -1652,7 +1652,7 @@ PrintEndStats(time_t       const startTime,
         doEndStats(stdout, startTime, endTime, inputFrameBits,
                    totalBits, totalCPU);
     }
-    
+
     if (statFile) {
         doEndStats(statFile, startTime, endTime, inputFrameBits,
                    totalBits, totalCPU);
@@ -1664,7 +1664,7 @@ PrintEndStats(time_t       const startTime,
 
 
 void
-ReadDecodedRefFrame(MpegFrame *  const frameP, 
+ReadDecodedRefFrame(MpegFrame *  const frameP,
                     unsigned int const frameNumber) {
 
     FILE    *fpointer;
@@ -1689,7 +1689,7 @@ ReadDecodedRefFrame(MpegFrame *  const frameP,
         }}
 
     Frame_AllocDecoded(frameP, TRUE);
-    
+
     for ( y = 0; y < height; y++ ) {
         size_t bytesRead;
 
@@ -1697,7 +1697,7 @@ ReadDecodedRefFrame(MpegFrame *  const frameP,
         if (bytesRead != width)
             pm_error("Could not read enough bytes from '%s;", fileName);
     }
-    
+
     for (y = 0; y < (height >> 1); y++) {           /* U */
         size_t const bytesToRead = width/2;
         size_t bytesRead;
@@ -1706,7 +1706,7 @@ ReadDecodedRefFrame(MpegFrame *  const frameP,
         if (bytesRead != bytesToRead)
             pm_message("Could not read enough bytes from '%s'", fileName);
     }
-    
+
     for (y = 0; y < (height >> 1); y++) {           /* V */
         size_t const bytesToRead = width/2;
         size_t bytesRead;
@@ -1724,7 +1724,7 @@ static void
 OpenBitRateFile() {
     bitRateFile = fopen(bitRateFileName, "w");
     if ( bitRateFile == NULL ) {
-        pm_message("ERROR:  Could not open bit rate file:  '%s'", 
+        pm_message("ERROR:  Could not open bit rate file:  '%s'",
                    bitRateFileName);
         showBitRatePerFrame = FALSE;
     }
@@ -1736,3 +1736,6 @@ static void
 CloseBitRateFile() {
     fclose(bitRateFile);
 }
+
+
+
diff --git a/converter/ppm/ppmtompeg/opts.c b/converter/ppm/ppmtompeg/opts.c
index 553e29d0..6f5f9816 100644
--- a/converter/ppm/ppmtompeg/opts.c
+++ b/converter/ppm/ppmtompeg/opts.c
@@ -1,29 +1,29 @@
 /*===========================================================================*
- * opts.c								     *
- *									     *
+ * opts.c                                                                    *
+ *                                                                           *
  *      Special C code to handle TUNEing options                             *
- *									     *
- * EXPORTED PROCEDURES:							     *
+ *                                                                           *
+ * EXPORTED PROCEDURES:                                                      *
  *      Tune_Init                                                            *
  *      CollectQuantStats                                                    *
- *									     *
+ *                                                                           *
  *===========================================================================*/
 
 
 /*
  * Copyright (c) 1995 The Regents of the University of California.
  * All rights reserved.
- * 
+ *
  * Permission to use, copy, modify, and distribute this software and its
  * documentation for any purpose, without fee, and without written agreement is
  * hereby granted, provided that the above copyright notice and the following
  * two paragraphs appear in all copies of this software.
- * 
+ *
  * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
  * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
  * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
+ *
  * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
  * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
@@ -95,9 +95,9 @@ boolean BSkipBlocks = TRUE;
  *
  * SkipSpacesTabs
  *
- *	skip all spaces and tabs
+ *      skip all spaces and tabs
  *
- * RETURNS:	point to next character not a space or tab
+ * RETURNS:     point to next character not a space or tab
  *
  * SIDE EFFECTS:    none
  *
@@ -120,12 +120,12 @@ SkipSpacesTabs(const char * const start) {
  *
  *     Setup variables to collect statistics on quantization values
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    sets collect_quant and collect_quant_fp
  *
  *===========================================================================*/
-static void 
+static void
 SetupCollectQuantStats(const char * const charPtr)
 {
   char fname[256];
@@ -164,23 +164,23 @@ SetupCollectQuantStats(const char * const charPtr)
  *
  *     Do a transform on small lum values
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    sets kill_dim, kill_dim_break, kill_dim_end
  *
  *===========================================================================*/
-static void 
+static void
 SetupKillDimAreas(const char * const charPtr)
 {
   int items_scanned;
 
   kill_dim = TRUE;
-  items_scanned = sscanf(charPtr, "%d %d %f", 
-			 &kill_dim_break, &kill_dim_end, &kill_dim_slope);
+  items_scanned = sscanf(charPtr, "%d %d %f",
+                         &kill_dim_break, &kill_dim_end, &kill_dim_slope);
   if (items_scanned != 3) {
     kill_dim_slope = 0.25;
-    items_scanned = sscanf(charPtr, "%d %d", 
-			   &kill_dim_break, &kill_dim_end);
+    items_scanned = sscanf(charPtr, "%d %d",
+                           &kill_dim_break, &kill_dim_end);
     if (items_scanned != 2) {
       /* Use defaults */
       kill_dim_break = 20;
@@ -206,12 +206,12 @@ SetupKillDimAreas(const char * const charPtr)
  *
  *     Setup encoder to squash small changes in Y or Cr/Cb values
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
- * SIDE EFFECTS:    sets squash_max_differences SquashMaxLum SquashMaxChr 
+ * SIDE EFFECTS:    sets squash_max_differences SquashMaxLum SquashMaxChr
  *
  *===========================================================================*/
-static void 
+static void
 SetupSquashSmall(const char * const charPtr)
 {
   squash_small_differences = TRUE;
@@ -229,13 +229,13 @@ SetupSquashSmall(const char * const charPtr)
  *
  *     Setup encoder to use DCT for rate-distortion estimat ein Psearches
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    sets SearchCompareMode and
  *                        can change LocalDCTRateScale, LocalDCTDistortScale
  *
  *===========================================================================*/
-static void 
+static void
 SetupLocalDCT(const char * const charPtr)
 {
   int num_scales=0;
@@ -260,12 +260,12 @@ SetupLocalDCT(const char * const charPtr)
  *
  *     Setup encoder to find distribution for I-frames, and use for -snr
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    sets DoLaplace, L1, L2, and Lambdas
  *
  *===========================================================================*/
-static void 
+static void
 SetupLaplace()
 {
   int i;
@@ -339,18 +339,18 @@ SetupWriteDistortions(const char * const charPtr)
     default:
       fprintf(stderr, "Unknown TUNE parameter setting format %s\n", cp);
     }}
-}  
+}
 
 /*=====================*
  * EXPORTED PROCEDURES *
  *=====================*/
 
-void 
+void
 CalcLambdas(void) {
 
   int i,j,n;
   double var;
-  
+
   n = LaplaceNum;
   for (i = 0;   i < 3;  i++) {
     for (j = 0;  j < 64;  j++) {
@@ -365,10 +365,10 @@ CalcLambdas(void) {
  *
  * Mpost_UnQuantZigBlockLaplace
  *
- *	unquantize and zig-zag (decode) a single block, using the distrib to get vals
+ *      unquantize and zig-zag (decode) a single block, using the distrib to get vals
  *      Iblocks only now
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:    none
  *
@@ -381,22 +381,22 @@ Mpost_UnQuantZigBlockLaplace(in, out, qscale, iblock)
     boolean iblock;
 {
     register int index;
-    int	    position;
-    register int	    qentry;
-    int	    level, coeff;
+    int     position;
+    register int            qentry;
+    int     level, coeff;
     double low, high;
     double mid,lam;
 
     /* qtable[0] must be 8 */
     out[0][0] = (int16)(in[0] * 8);
-    
+
     for ( index = 1;  index < DCTSIZE_SQ;  index++ ) {
       position = ZAG[index];
       level = in[index];
-      
+
       if (level == 0) {
-	((int16 *)out)[position] = 0;
-	continue;
+        ((int16 *)out)[position] = 0;
+        continue;
       }
       qentry = qtable[position] * qscale;
       coeff = (level*qentry)/8;
@@ -406,25 +406,25 @@ Mpost_UnQuantZigBlockLaplace(in, out, qscale, iblock)
       mid = (1.0/lam) * log(0.5*(exp(-lam*low)+exp(-lam*high)));
       mid = ABS(mid);
       if (mid - floor(mid) > .4999) {
-	mid = ceil(mid);
+        mid = ceil(mid);
       } else {
-	mid = floor(mid);
+        mid = floor(mid);
       }
       if (level<0) {mid = -mid;}
 /*printf("(%2.1lf-%2.1lf): old: %d vs %d\n",low,high,coeff,(int) mid);*/
       coeff = mid;
       if ( (coeff & 1) == 0 ) {
-	if ( coeff < 0 ) {
-	  coeff++;
-	} else if ( coeff > 0 ) {
-	  coeff--;
-	}
+        if ( coeff < 0 ) {
+          coeff++;
+        } else if ( coeff > 0 ) {
+          coeff--;
+        }
       }
       ((int16 *)out)[position] = coeff;
     }
 }
 
-int 
+int
 mse(Block blk1, Block blk2)
 {
   register int index, error, tmp;
@@ -449,7 +449,7 @@ mse(Block blk1, Block blk2)
  *
  *     Do any setup needed before coding stream
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:  varies
  *
@@ -458,7 +458,7 @@ void Tune_Init()
 {
   int i;
 
-  /* Just check for each, and do whats needed */
+  /* Just check for each, and do what's needed */
   if (collect_quant) {
     if (!pureDCT) {
       pureDCT = TRUE;
@@ -467,14 +467,14 @@ void Tune_Init()
     }
     fprintf(collect_quant_fp, "# %s\n", outputFileName);
     fprintf(collect_quant_fp, "#");
-    for (i=0; i<64; i++) 
+    for (i=0; i<64; i++)
       fprintf(collect_quant_fp, " %d", qtable[i]);
     fprintf(collect_quant_fp, "\n#");
-    for (i=0; i<64; i++) 
+    for (i=0; i<64; i++)
       fprintf(collect_quant_fp, " %d", niqtable[i]);
-    fprintf(collect_quant_fp, "\n# %d %d %d\n\n", 
-	    GetIQScale(), GetPQScale(), GetBQScale());
-    
+    fprintf(collect_quant_fp, "\n# %d %d %d\n\n",
+            GetIQScale(), GetPQScale(), GetBQScale());
+
   }
 
   if (DoLaplace) {
@@ -486,7 +486,7 @@ void Tune_Init()
     decodeRefFrames = TRUE;
     printSNR = TRUE;
   }
-    
+
 }
 
 /*===========================================================================*
@@ -495,7 +495,7 @@ void Tune_Init()
  *
  *     Handle the strings following TUNE
  *
- * RETURNS:	nothing
+ * RETURNS:     nothing
  *
  * SIDE EFFECTS:  varies
  *
@@ -503,7 +503,7 @@ void Tune_Init()
 void ParseTuneParam(const char * const charPtr)
 {
   switch (ASCII_TOUPPER(*charPtr)) {
-  case 'B': 
+  case 'B':
     if (1 != sscanf(charPtr+2, "%d", &block_bound)) {
       fprintf(stderr, "Invalid tuning parameter (b) in parameter file.\n");
     }
diff --git a/converter/ppm/ppmtompeg/parallel.c b/converter/ppm/ppmtompeg/parallel.c
index e3bcec1a..0fe635ed 100644
--- a/converter/ppm/ppmtompeg/parallel.c
+++ b/converter/ppm/ppmtompeg/parallel.c
@@ -1,8 +1,8 @@
 /*===========================================================================*
- * parallel.c              
- *                         
- *  Procedures to make encoder run in parallel   
- *                             
+ * parallel.c
+ *
+ *  Procedures to make encoder run in parallel
+ *
  *===========================================================================*/
 
 /* COPYRIGHT INFORMATION IS AT THE END OF THIS FILE */
@@ -13,8 +13,8 @@
  *==============*/
 
 #define _XOPEN_SOURCE 500 /* Make sure stdio.h contains pclose() */
-/* _ALL_SOURCE is needed on AIX to make the C library include the 
-   socket services (e.g. define struct sockaddr) 
+/* _ALL_SOURCE is needed on AIX to make the C library include the
+   socket services (e.g. define struct sockaddr)
 
    Note that AIX standards.h actually sets feature declaration macros such
    as _XOPEN_SOURCE, unless they are already set.
@@ -93,7 +93,8 @@ struct scheduler {
  * CONSTANTS        *
  *==================*/
 
-#define TERMINATE_PID_SIGNAL    SIGTERM  /* signal used to terminate forked childs */
+#define TERMINATE_PID_SIGNAL    SIGTERM
+  /* signal used to terminate forked children */
 #ifndef MAXARGS
 #define MAXARGS     1024   /* Max Number of arguments in safe_fork command */
 #endif
@@ -187,8 +188,8 @@ errorExit(const char format[], ...) {
 
 
 static void
-TransmitPortNum(const char * const hostName, 
-                int          const portNum, 
+TransmitPortNum(const char * const hostName,
+                int          const portNum,
                 int          const newPortNum) {
 /*----------------------------------------------------------------------------
    Transmit the port number 'newPortNum' to the master on port 'portNum'
@@ -196,15 +197,15 @@ TransmitPortNum(const char * const hostName,
 -----------------------------------------------------------------------------*/
     int clientSocket;
     const char * error;
-    
+
     ConnectToSocket(hostName, portNum, &hostEntry, &clientSocket, &error);
-    
+
     if (error)
         errorExit("Can't connect in order to transmit port number.  %s",
                   error);
 
     WriteInt(clientSocket, newPortNum);
-    
+
     close(clientSocket);
 }
 
@@ -215,19 +216,19 @@ readYUVDecoded(int          const socketFd,
                unsigned int const Fsize_x,
                unsigned int const Fsize_y,
                MpegFrame *  const frameP) {
-    
+
     unsigned int y;
-    
+
     for (y = 0; y < Fsize_y; ++y)         /* Y */
-        ReadBytes(socketFd, 
+        ReadBytes(socketFd,
                   (unsigned char *)frameP->decoded_y[y], Fsize_x);
-    
+
     for (y = 0; y < (Fsize_y >> 1); ++y)  /* U */
-        ReadBytes(socketFd, 
+        ReadBytes(socketFd,
                   (unsigned char *)frameP->decoded_cb[y], (Fsize_x >> 1));
-    
+
     for (y = 0; y < (Fsize_y >> 1); ++y)  /* V */
-        ReadBytes(socketFd, 
+        ReadBytes(socketFd,
                   (unsigned char *)frameP->decoded_cr[y], (Fsize_x >> 1));
 }
 
@@ -238,19 +239,19 @@ writeYUVDecoded(int          const socketFd,
                 unsigned int const Fsize_x,
                 unsigned int const Fsize_y,
                 MpegFrame *  const frameP) {
-    
+
     unsigned int y;
-    
+
     for (y = 0; y < Fsize_y; ++y)         /* Y */
-        WriteBytes(socketFd, 
+        WriteBytes(socketFd,
                   (unsigned char *)frameP->decoded_y[y], Fsize_x);
-    
+
     for (y = 0; y < (Fsize_y >> 1); ++y)  /* U */
-        WriteBytes(socketFd, 
+        WriteBytes(socketFd,
                    (unsigned char *)frameP->decoded_cb[y], (Fsize_x >> 1));
-    
+
     for (y = 0; y < (Fsize_y >> 1); ++y)  /* V */
-        WriteBytes(socketFd, 
+        WriteBytes(socketFd,
                    (unsigned char *)frameP->decoded_cr[y], (Fsize_x >> 1));
 }
 
@@ -261,19 +262,19 @@ writeYUVOrig(int          const socketFd,
              unsigned int const Fsize_x,
              unsigned int const Fsize_y,
              MpegFrame *  const frameP) {
-    
+
     unsigned int y;
-    
+
     for (y = 0; y < Fsize_y; ++y)         /* Y */
-        WriteBytes(socketFd, 
+        WriteBytes(socketFd,
                   (unsigned char *)frameP->orig_y[y], Fsize_x);
-    
+
     for (y = 0; y < (Fsize_y >> 1); ++y)  /* U */
-        WriteBytes(socketFd, 
+        WriteBytes(socketFd,
                    (unsigned char *)frameP->orig_cb[y], (Fsize_x >> 1));
-    
+
     for (y = 0; y < (Fsize_y >> 1); ++y)  /* V */
-        WriteBytes(socketFd, 
+        WriteBytes(socketFd,
                    (unsigned char *)frameP->orig_cr[y], (Fsize_x >> 1));
 }
 
@@ -284,19 +285,19 @@ readYUVOrig(int          const socketFd,
             unsigned int const Fsize_x,
             unsigned int const Fsize_y,
             MpegFrame *  const frameP) {
-    
+
     unsigned int y;
-    
+
     for (y = 0; y < Fsize_y; ++y)         /* Y */
-        ReadBytes(socketFd, 
+        ReadBytes(socketFd,
                   (unsigned char *)frameP->orig_y[y], Fsize_x);
-    
+
     for (y = 0; y < (Fsize_y >> 1); ++y)  /* U */
-        ReadBytes(socketFd, 
+        ReadBytes(socketFd,
                   (unsigned char *)frameP->orig_cb[y], (Fsize_x >> 1));
-    
+
     for (y = 0; y < (Fsize_y >> 1); ++y)  /* V */
-        ReadBytes(socketFd, 
+        ReadBytes(socketFd,
                   (unsigned char *)frameP->orig_cr[y], (Fsize_x >> 1));
 }
 
@@ -340,20 +341,20 @@ NotifyDecodeServerReady(int const id) {
     int   clientSocket;
     time_t  tempTimeStart, tempTimeEnd;
     const char * error;
-    
+
     time(&tempTimeStart);
-    
+
     ConnectToSocket(IOhostName, decodePortNumber, &hostEntry, &clientSocket,
                     &error);
-    
+
     if (error)
         errorExit("CHILD: Can't connect to decode server to tell it a frame "
                 "is ready.  %s", error);
-    
+
     WriteInt(clientSocket, id);
-    
+
     close(clientSocket);
-    
+
     time(&tempTimeEnd);
     IOtime += (tempTimeEnd-tempTimeStart);
 }
@@ -461,23 +462,23 @@ SendDecodedFrame(MpegFrame * const frameP) {
    Send frame *frameP to the decode server.
 -----------------------------------------------------------------------------*/
     int const negativeTwo = -2;
-    
+
     int clientSocket;
     const char * error;
-    
+
     /* send to IOServer */
     ConnectToSocket(IOhostName, ioPortNumber, &hostEntry,
                     &clientSocket, &error);
     if (error)
         errorExit("CHILD: Can't connect to decode server to "
                   "give it a decoded frame.  %s", error);
-    
+
     WriteInt(clientSocket, negativeTwo);
-    
+
     WriteInt(clientSocket, frameP->id);
 
     writeYUVDecoded(clientSocket, Fsize_x, Fsize_y, frameP);
-    
+
     close(clientSocket);
 }
 
@@ -490,11 +491,11 @@ SendDecodedFrame(MpegFrame * const frameP) {
  *
  * RETURNS: nothing
  *
- * SIDE EFFECTS:   
+ * SIDE EFFECTS:
  *
  *===========================================================================*/
 void
-GetRemoteDecodedRefFrame(MpegFrame * const frameP, 
+GetRemoteDecodedRefFrame(MpegFrame * const frameP,
                          int         const frameNumber) {
 /*----------------------------------------------------------------------------
    Get decoded frame number 'frameNumber' *frameP from the decode server.
@@ -551,7 +552,7 @@ static void cleanup_fork( dummy )       /* try to kill all child processes */
 #endif
 
     if (kill(ClientPid[i], TERMINATE_PID_SIGNAL)) {
-      fprintf(stderr, "cleanup_fork: killed PID=%d failed (errno %d)\n", 
+      fprintf(stderr, "cleanup_fork: killed PID=%d failed (errno %d)\n",
           ClientPid[i], errno);
     }
   }
@@ -574,24 +575,24 @@ static int safe_fork(command)       /* fork child process and remember its PID *
   static int init=0;
   char *argis[MAXARGS];
   register int i=1;
-  
+
   if (!(argis[0] = strtok(command, " \t"))) return(0); /* tokenize */
   while ((argis[i] = strtok(NULL, " \t")) && i < MAXARGS) ++i;
   argis[i] = NULL;
-  
+
 #ifdef DEBUG_FORK
-  {register int i=0; 
+  {register int i=0;
    fprintf(stderr, "Command %s becomes:\n", command);
    while(argis[i]) {fprintf(stderr, "--%s--\n", argis[i]); ++i;} }
 #endif
-  
+
   if (!init) {          /* register clean-up routine */
     signal (SIGQUIT, cleanup_fork);
     signal (SIGTERM, cleanup_fork);
     signal (SIGINT , cleanup_fork);
     init=1;
   }
-  
+
   if (-1 == (ClientPid[current_max_forked_pid] = fork()) )  {
     perror("safe_fork: fork failed ");
     return(-1);
@@ -682,25 +683,25 @@ decodedFrameToDisk(int const otherSock) {
     MpegFrame * frameP;
 
     ReadInt(otherSock, &frameNumber);
-    
+
     if (debugSockets) {
-        fprintf(stdout, "INPUT SERVER:  GETTING DECODED FRAME %d\n", 
+        fprintf(stdout, "INPUT SERVER:  GETTING DECODED FRAME %d\n",
                 frameNumber);
         fflush(stdout);
     }
 
     /* should read frame from socket, then write to disk */
     frameP = Frame_New(frameNumber, 'i');
-    
+
     Frame_AllocDecoded(frameP, TRUE);
-    
+
     readYUVDecoded(otherSock, Fsize_x, Fsize_y, frameP);
 
     /* now output to disk */
     WriteDecodedFrame(frameP);
 
     Frame_Free(frameP);
-}        
+}
 
 
 
@@ -708,12 +709,12 @@ static void
 decodedFrameFromDisk(int const otherSock) {
 
     /* request for decoded frame from disk */
-            
+
     int frameNumber;
     MpegFrame * frameP;
 
     ReadInt(otherSock, &frameNumber);
-    
+
     if (debugSockets) {
         fprintf(stdout, "INPUT SERVER:  READING DECODED FRAME %d "
                 "from DISK\n", frameNumber);
@@ -722,15 +723,15 @@ decodedFrameFromDisk(int const otherSock) {
 
     /* should read frame from disk, then write to socket */
     frameP = Frame_New(frameNumber, 'i');
-    
+
     Frame_AllocDecoded(frameP, TRUE);
-    
+
     ReadDecodedRefFrame(frameP, frameNumber);
-    
+
     writeYUVDecoded(otherSock, Fsize_x, Fsize_y, frameP);
-    
+
     Frame_Free(frameP);
-}        
+}
 
 
 
@@ -762,10 +763,10 @@ routeFromSocketToDisk(int              const otherSock,
 
         MALLOCARRAY_NOFAIL(bigBuffer, bigBufferSize);
     }
-    
+
     /* now read in the bytes */
     ReadBytes(otherSock, bigBuffer, numBytes);
-    
+
     /* open file to output this stuff to */
     pm_asprintf(&fileName, "%s.frame.%d", outputFileName, frameNumber);
     filePtr = fopen(fileName, "wb");
@@ -777,9 +778,9 @@ routeFromSocketToDisk(int              const otherSock,
 
     /* now write the bytes here */
     fwrite(bigBuffer, sizeof(char), numBytes, filePtr);
-    
+
     fclose(filePtr);
-    
+
     if (debugSockets) {
         fprintf(stdout, "====I/O SERVER:  WROTE FRAME %d to disk\n",
                 frameNumber);
@@ -788,7 +789,7 @@ routeFromSocketToDisk(int              const otherSock,
 
     *bigBufferP     = bigBuffer;
     *bigBufferSizeP = bigBufferSize;
-}        
+}
 
 
 
@@ -803,7 +804,7 @@ readConvertWriteToSocket(struct inputSource * const inputSourceP,
    the "base format" result to socket 'otherSock'.
 -----------------------------------------------------------------------------*/
     FILE * convertedFileP;
-    
+
     convertedFileP = ReadIOConvert(inputSourceP, frameNumber);
     if (convertedFileP) {
         bool eof;
@@ -811,21 +812,21 @@ readConvertWriteToSocket(struct inputSource * const inputSourceP,
         while (!eof) {
             unsigned char buffer[1024];
             unsigned int numBytes;
-            
+
             numBytes = fread(buffer, 1, sizeof(buffer), convertedFileP);
-            
+
             if (numBytes > 0) {
                 WriteInt(otherSock, numBytes);
                 WriteBytes(otherSock, buffer, numBytes);
             } else
                 eof = TRUE;
         }
-        
+
         if (strcmp(ioConversion, "*") == 0 )
             fclose(convertedFileP);
         else
             pclose(convertedFileP);
-        
+
         *endOfStreamP = FALSE;
     } else
         *endOfStreamP = TRUE;
@@ -848,13 +849,13 @@ readWriteYuvToSocket(struct inputSource * const inputSourceP,
     MpegFrame * frameP;
 
     frameP = Frame_New(frameNumber, 'i');
-    
+
     ReadFrame(frameP, inputSourceP, frameNumber, inputConversion,
               endOfStreamP);
-    
+
     if (!*endOfStreamP) {
         writeYUVOrig(otherSock, Fsize_x, Fsize_y, frameP);
-        
+
         {
             /* Make sure we don't leave until other processor read
                everything
@@ -907,7 +908,7 @@ processNextConnection(int                  const serverSocket,
     int          otherSock;
     int          command;
     const char * error;
-    
+
     AcceptConnection(serverSocket, &otherSock, &error);
     if (error)
         errorExit("I/O SERVER: Failed to accept next connection.  %s", error);
@@ -948,12 +949,12 @@ processNextConnection(int                  const serverSocket,
     }
     close(otherSock);
 }
- 
+
 
 
 void
 IoServer(struct inputSource * const inputSourceP,
-         const char *         const parallelHostName, 
+         const char *         const parallelHostName,
          int                  const portNum) {
 /*----------------------------------------------------------------------------
    Execute an I/O server.
@@ -979,7 +980,7 @@ IoServer(struct inputSource * const inputSourceP,
 
     bigBufferSize = 0;  /* Start with no buffer */
     bigBuffer = NULL;
-    
+
     /* once we get IO port num, should transmit it to parallel server */
 
     CreateListeningSocket(&serverSocket, &ioPortNum, &error);
@@ -1043,12 +1044,12 @@ SendRemoteFrame(int const frameNumber, BitBucket * const bb) {
     WriteInt(clientSocket, negativeFour);
 
     WriteInt(clientSocket, frameNumber);
-    
+
     if (frameNumber != -1) {
         /* send number of bytes */
-        
+
         WriteInt(clientSocket, (bb->totalbits+7)>>3);
-    
+
         /* now send the bytes themselves */
         Bitio_WriteToSocket(bb, clientSocket);
     }
@@ -1062,11 +1063,11 @@ SendRemoteFrame(int const frameNumber, BitBucket * const bb) {
 
 
 void
-GetRemoteFrame(MpegFrame * const frameP, 
+GetRemoteFrame(MpegFrame * const frameP,
                int         const frameNumber) {
 /*----------------------------------------------------------------------------
    Get a frame from the I/O server.
-   
+
    This is intended for use by a child.
 -----------------------------------------------------------------------------*/
     int           clientSocket;
@@ -1084,7 +1085,7 @@ GetRemoteFrame(MpegFrame * const frameP,
                     &clientSocket, &error);
 
     if (error)
-        errorExit("CHILD: Can't connect to I/O server to get a frame.  %s", 
+        errorExit("CHILD: Can't connect to I/O server to get a frame.  %s",
                   error);
 
     WriteInt(clientSocket, frameNumber);
@@ -1104,7 +1105,7 @@ GetRemoteFrame(MpegFrame * const frameP,
 
                 if (numBytes > sizeof(buffer))
                     errorExit("Invalid message received: numBytes = %d, "
-                              "which is greater than %u", 
+                              "which is greater than %u",
                               numBytes, (unsigned)sizeof(numBytes));
                 ReadBytes(clientSocket, buffer, numBytes);
 
@@ -1162,9 +1163,9 @@ getAndProcessACombineConnection(int const outputServerSocket) {
     if (error)
         errorExit("COMBINE SERVER: "
                   "Failed to accept next connection.  %s", error);
-    
+
     ReadInt(otherSock, &command);
-    
+
     if (command == -2) {
         /* this is notification from non-remote process that a
            frame is done.
@@ -1173,7 +1174,7 @@ getAndProcessACombineConnection(int const outputServerSocket) {
 
         ReadInt(otherSock, &frameStart);
         ReadInt(otherSock, &frameEnd);
-            
+
         machineDebug("COMBINE_SERVER: Frames %d - %d done",
                      frameStart, frameEnd);
         {
@@ -1199,7 +1200,7 @@ openInputFile(const char * const fileName,
 
     FILE * inputFileP;
     unsigned int attempts;
-    
+
     inputFileP = NULL;
     attempts = 0;
 
@@ -1207,14 +1208,14 @@ openInputFile(const char * const fileName,
         inputFileP = fopen(fileName, "rb");
         if (inputFileP == NULL) {
             pm_message("ERROR  Couldn't read frame file '%s' errno = %d (%s)"
-                       "attempt %d", 
+                       "attempt %d",
                        fileName, errno, strerror(errno), attempts);
             pm_sleep(1000);
         }
         ++attempts;
     }
     if (inputFileP == NULL)
-        pm_error("Unable to open file '%s' after %d attempts.", 
+        pm_error("Unable to open file '%s' after %d attempts.",
                  fileName, attempts);
 
     *inputFilePP = inputFileP;
@@ -1239,7 +1240,7 @@ waitForOutputFile(void *        const inputHandle,
         const char * fileName;
 
         while (!frameDone[frameNumber]) {
-            machineDebug("COMBINE_SERVER: Waiting for frame %u done", 
+            machineDebug("COMBINE_SERVER: Waiting for frame %u done",
                          frameNumber);
 
             getAndProcessACombineConnection(outputServerSocket);
@@ -1274,8 +1275,8 @@ unlinkFile(void *       const inputHandle,
 
 
 void
-CombineServer(int          const numFrames, 
-              const char * const masterHostName, 
+CombineServer(int          const numFrames,
+              const char * const masterHostName,
               int          const masterPortNum,
               const char * const outputFileName) {
 /*----------------------------------------------------------------------------
@@ -1287,17 +1288,17 @@ CombineServer(int          const numFrames,
   FILE * ofP;
   const char * error;
   struct combineControl combineControl;
-  
+
   /* once we get Combine port num, should transmit it to parallel server */
-  
+
   CreateListeningSocket(&outputServerSocket, &combinePortNum, &error);
   if (error)
       errorExit("Unable to create socket on which to listen.  %s", error);
 
   machineDebug("COMBINE SERVER: LISTENING ON PORT %d", combinePortNum);
-  
+
   TransmitPortNum(masterHostName, masterPortNum, combinePortNum);
-  
+
   MALLOCARRAY_NOFAIL(frameDone, numFrames);
   {
       unsigned int i;
@@ -1305,16 +1306,16 @@ CombineServer(int          const numFrames,
           frameDone[i] = FALSE;
   }
   ofP = pm_openw(outputFileName);
-  
+
   combineControl.numFrames = numFrames;
 
   FramesToMPEG(ofP, &combineControl, &waitForOutputFile, &unlinkFile);
 
   machineDebug("COMBINE SERVER: Shutting down");
-  
+
   /* tell Master server we are done */
   TransmitPortNum(masterHostName, masterPortNum, combinePortNum);
-  
+
   close(outputServerSocket);
 
   fclose(ofP);
@@ -1340,18 +1341,18 @@ startCombineServer(const char * const encoderName,
     int          otherSock;
     const char * error;
 
-    pm_snprintf(command, sizeof(command), 
+    pm_snprintf(command, sizeof(command),
                 "%s %s -max_machines %d -output_server %s %d %d %s",
-                encoderName, 
+                encoderName,
                 debugMachines ? "-debug_machines" : "",
-                numMachines, masterHostName, masterPortNum, 
+                numMachines, masterHostName, masterPortNum,
                 numInputFiles, paramFileName);
-    
+
     machineDebug("MASTER: Starting combine server with shell command '%s'",
                  command);
 
     safe_fork(command);
-    
+
     machineDebug("MASTER: Listening for connection back from "
                  "new Combine server");
 
@@ -1382,9 +1383,9 @@ startDecodeServer(const char * const encoderName,
     int          otherSock;
     const char * error;
 
-    pm_snprintf(command, sizeof(command), 
+    pm_snprintf(command, sizeof(command),
                 "%s %s -max_machines %d -decode_server %s %d %d %s",
-                encoder_name, 
+                encoder_name,
                 debugMachines ? "-debug_machines" : "",
                 numMachines, masterHostName, masterPortNum,
                 numInputFiles, paramFileName);
@@ -1404,9 +1405,9 @@ startDecodeServer(const char * const encoderName,
                   "decode server.  %s", error);
 
     ReadInt(otherSock, decodePortNumP);
-    
+
     close(otherSock);
-    
+
     machineDebug("MASTER:  Decode port number = %d", *decodePortNumP);
 }
 
@@ -1420,11 +1421,11 @@ startIoServer(const char *   const encoderName,
               int            const masterSocket,
               const char *   const paramFileName,
               int *          const ioPortNumP) {
-              
+
     char         command[1024];
     int          otherSock;
     const char * error;
-    
+
     sprintf(command, "%s -max_machines %d -io_server %s %d %s",
             encoderName, numChildren, masterHostName, masterPortNum,
             paramFileName);
@@ -1433,7 +1434,7 @@ startIoServer(const char *   const encoderName,
                  command);
 
     safe_fork(command);
-    
+
     machineDebug("MASTER: Listening for connection back from "
                  "new I/O server");
 
@@ -1442,14 +1443,14 @@ startIoServer(const char *   const encoderName,
         errorExit("MASTER SERVER: "
                   "Failed to accept connection back from the new "
                   "I/O server.  %s", error);
-    
+
     ReadInt(otherSock, ioPortNumP);
     close(otherSock);
-    
+
     machineDebug("MASTER:  I/O port number = %d", *ioPortNumP);
-}    
-    
-    
+}
+
+
 
 static void
 extendToEndOfPattern(unsigned int * const nFramesP,
@@ -1458,7 +1459,7 @@ extendToEndOfPattern(unsigned int * const nFramesP,
                      unsigned int   const numFramesInStream) {
 
     assert(framePatternLen >= 1);
-        
+
     while (startFrame + *nFramesP < numFramesInStream &&
            (startFrame + *nFramesP) % framePatternLen != 0)
         ++(*nFramesP);
@@ -1478,7 +1479,7 @@ allocateInitialFrames(struct scheduler * const schedulerP,
 /*----------------------------------------------------------------------------
    Choose which frames, to hand out to the new child numbered 'childNum'.
 -----------------------------------------------------------------------------*/
-    unsigned int const framesPerChild = 
+    unsigned int const framesPerChild =
         MAX(1, ((schedulerP->numFramesInJob - schedulerP->nextFrame) /
                 (schedulerP->numMachines - childNum)));
 
@@ -1507,7 +1508,7 @@ allocateInitialFrames(struct scheduler * const schedulerP,
 static float
 taperedGoalTime(struct childState const childState[],
                 unsigned int      const remainingFrameCount) {
-        
+
     float        goalTime;
     float        allChildrenFPS;
     float        remainingJobTime;
@@ -1515,9 +1516,9 @@ taperedGoalTime(struct childState const childState[],
     float        sum;
     int          numMachinesToEstimate;
     unsigned int childNum;
-    
+
     /* frames left = lastFrameInStream - startFrame + 1 */
-    for (childNum = 0, sum = 0.0, numMachinesToEstimate = 0; 
+    for (childNum = 0, sum = 0.0, numMachinesToEstimate = 0;
          childNum < numMachines; ++childNum) {
         if (!childState[childNum].finished) {
             if (childState[childNum].fps < 0.0 )
@@ -1526,12 +1527,12 @@ taperedGoalTime(struct childState const childState[],
                 sum += childState[childNum].fps;
         }
     }
-    
+
     allChildrenFPS = (float)numMachines *
         (sum/(float)(numMachines-numMachinesToEstimate));
-    
+
     remainingJobTime = (float)remainingFrameCount/allChildrenFPS;
-    
+
     goalTime = MAX(5.0, remainingJobTime/2);
 
     return goalTime;
@@ -1575,23 +1576,23 @@ allocateMoreFrames(struct scheduler * const schedulerP,
 
     if (!goalTimeSpecified) {
         goalTime = taperedGoalTime(childState,
-                                   schedulerP->numFramesInJob - 
+                                   schedulerP->numFramesInJob -
                                    schedulerP->nextFrame);
-    
+
         pm_message("MASTER: ASSIGNING %s %.2f seconds of work",
                    machineName[childNum], goalTime);
     } else
         goalTime = goalTimeArg;
-    
+
     if (childState[childNum].numSeconds != 0)
-        avgFps = (float)childState[childNum].numFrames / 
+        avgFps = (float)childState[childNum].numFrames /
             childState[childNum].numSeconds;
     else
         avgFps = 0.1;       /* arbitrary small value */
 
     nFrames = MAX(1u, (unsigned int)(goalTime * avgFps + 0.5));
-    
-    nFrames = MIN(nFrames, 
+
+    nFrames = MIN(nFrames,
                   schedulerP->numFramesInJob - schedulerP->nextFrame);
 
     if (forceIalign)
@@ -1648,7 +1649,7 @@ startChildren(struct scheduler *   const schedulerP,
     MALLOCARRAY_NOFAIL(childState, schedulerP->numMachines);
 
     childrenLeftCurrentIoServer = 0;  /* No current I/O server yet */
-    
+
     numIoServers = 0;  /* None created yet */
 
     for (childNum = 0; childNum < schedulerP->numMachines; ++childNum) {
@@ -1669,17 +1670,17 @@ startChildren(struct scheduler *   const schedulerP,
                          machineName[childNum]);
         } else {
             childState[childNum].finished   = FALSE;
-        
+
             if (remote[childNum]) {
                 if (childrenLeftCurrentIoServer == 0) {
-                    startIoServer(encoderName, schedulerP->numMachines, 
+                    startIoServer(encoderName, schedulerP->numMachines,
                                   masterHostName, masterPortNum, masterSocket,
                                   paramFileName, &ioPortNum[numIoServers++]);
-                    
+
                     childrenLeftCurrentIoServer = SOMAXCONN;
                 }
                 --childrenLeftCurrentIoServer;
-            } 
+            }
             pm_snprintf(command, sizeof(command),
                         "%s %s -l %s %s "
                         "%s %s -child %s %d %d %d %d %d %d "
@@ -1689,22 +1690,22 @@ startChildren(struct scheduler *   const schedulerP,
                         beNice ? "nice" : "",
                         executable[childNum],
                         debugMachines ? "-debug_machines" : "",
-                        masterHostName, masterPortNum, 
+                        masterHostName, masterPortNum,
                         remote[childNum] ? ioPortNum[numIoServers-1] : 0,
                         combinePortNum, decodePortNum, childNum,
                         remote[childNum] ? 1 : 0,
                         startFrame, startFrame + nFrames - 1,
-                        remote[childNum] ? 
+                        remote[childNum] ?
                           remoteParamFile[childNum] : paramFileName
                 );
-        
+
             machineDebug("MASTER: Starting child server "
                          "with shell command '%s'", command);
 
             safe_fork(command);
 
             machineDebug("MASTER: Frames %d-%d assigned to new child %s",
-                         startFrame, startFrame + nFrames - 1, 
+                         startFrame, startFrame + nFrames - 1,
                          machineName[childNum]);
         }
         childState[childNum].startFrame = startFrame;
@@ -1720,7 +1721,7 @@ startChildren(struct scheduler *   const schedulerP,
 static void
 noteFrameDone(const char * const combineHostName,
               int          const combinePortNum,
-              unsigned int const frameStart, 
+              unsigned int const frameStart,
               unsigned int const frameEnd) {
 /*----------------------------------------------------------------------------
    Tell the Combine server that frames 'frameStart' through 'frameEnd'
@@ -1738,7 +1739,7 @@ noteFrameDone(const char * const combineHostName,
 
     ConnectToSocket(combineHostName, combinePortNum, &hostEntP,
                     &clientSocket, &error);
-    
+
     if (error)
         errorExit("MASTER: Can't connect to Combine server to tell it frames "
                   "are done.  %s", error);
@@ -1775,7 +1776,7 @@ feedTheChildren(struct scheduler * const schedulerP,
    As children finish assignments, inform the combine server at
    'combineHostName':'combinePortNum' of such.
 
-   Note that the children got initial assigments when they were created.
+   Note that the children got initial assignments when they were created.
    So the first thing we do is wait for them to finish those.
 -----------------------------------------------------------------------------*/
     unsigned int numFinished;
@@ -1808,7 +1809,7 @@ feedTheChildren(struct scheduler * const schedulerP,
         ReadInt(otherSock, &seconds);
 
         csP = &childState[childNum];
-        
+
         csP->numSeconds += seconds;
         csP->fps = (float)csP->numFrames / (float)csP->numSeconds;
 
@@ -1818,7 +1819,7 @@ feedTheChildren(struct scheduler * const schedulerP,
             framesPerSecond = (float)csP->lastNumFrames * 2.0;
 
         machineDebug("MASTER: Child %s FINISHED ASSIGNMENT.  "
-                     "%f frames per second", 
+                     "%f frames per second",
                      machineName[childNum], framesPerSecond);
 
         noteFrameDone(combineHostName, combinePortNum, csP->startFrame,
@@ -1855,7 +1856,7 @@ feedTheChildren(struct scheduler * const schedulerP,
         close(otherSock);
 
         machineDebug("MASTER: %d/%d DONE; %d ARE ASSIGNED",
-                     framesDone, schedulerP->numFramesInJob, 
+                     framesDone, schedulerP->numFramesInJob,
                      schedulerP->nextFrame - framesDone);
     }
 }
@@ -1898,7 +1899,7 @@ waitForCombineServerToTerminate(int const masterSocket) {
     }
     close(otherSock);
 }
-    
+
 
 
 static void
@@ -1932,46 +1933,46 @@ printFinalStats(FILE *            const statfileP,
                     (unsigned int)(startUpEnd - startUpBegin));
             fprintf(fileP, "SHUT DOWN TIME:  %u seconds\n",
                     (unsigned int)(shutDownEnd - shutDownBegin));
-            
-            fprintf(fileP, 
+
+            fprintf(fileP,
                     "%14.14s %8.8s %8.8s %12.12s %9.9s\n",
                     "MACHINE", "Frames", "Seconds", "Frames/Sec",
                     "Self Time");
 
-            fprintf(fileP, 
+            fprintf(fileP,
                     "%14.14s %8.8s %8.8s %12.12s %9.9s\n",
                     "--------------", "--------", "--------", "------------",
                     "---------");
 
             totalFPS = 0.0;
             for (childNum = 0; childNum < numChildren; ++childNum) {
-                float const localFPS = 
+                float const localFPS =
                     (float)childState[childNum].numFrames /
                     childState[childNum].numSeconds;
                 fprintf(fileP, "%14.14s %8u %8u %12.4f %8u\n",
-                        machineName[childNum], 
-                        childState[childNum].numFrames, 
+                        machineName[childNum],
+                        childState[childNum].numFrames,
                         childState[childNum].numSeconds,
-                        localFPS, 
+                        localFPS,
                         (unsigned int)((float)numFrames/localFPS));
                 totalFPS += localFPS;
             }
 
-            fprintf(fileP, 
+            fprintf(fileP,
                     "%14.14s %8.8s %8.8s %12.12s %9.9s\n",
                     "--------------", "--------", "--------", "------------",
                     "---------");
 
-            fprintf(fileP, "%14s %8.8s %8u %12.4f\n", 
-                    "OPTIMAL", "", 
+            fprintf(fileP, "%14s %8.8s %8u %12.4f\n",
+                    "OPTIMAL", "",
                     (unsigned int)((float)numFrames/totalFPS),
                     totalFPS);
-            
+
             {
                 unsigned int const diffTime = shutDownEnd - startUpBegin;
-                
-                fprintf(fileP, "%14s %8.8s %8u %12.4f\n", 
-                        "ACTUAL", "", diffTime, 
+
+                fprintf(fileP, "%14s %8.8s %8u %12.4f\n",
+                        "ACTUAL", "", diffTime,
                         (float)numFrames / diffTime);
             }
             fprintf(fileP, "\n\n");
@@ -1983,7 +1984,7 @@ printFinalStats(FILE *            const statfileP,
 
 void
 MasterServer(struct inputSource * const inputSourceP,
-             const char *         const paramFileName, 
+             const char *         const paramFileName,
              const char *         const outputFileName) {
 /*----------------------------------------------------------------------------
    Execute the master server function.
@@ -2025,21 +2026,21 @@ MasterServer(struct inputSource * const inputSourceP,
         fprintf(stdout, "---MASTER USING PORT %d\n", portNum);
 
     startCombineServer(encoder_name, numMachines, hostName, portNum,
-                       inputSourceP->numInputFiles, 
-                       paramFileName, masterSocket, 
+                       inputSourceP->numInputFiles,
+                       paramFileName, masterSocket,
                        &combinePortNum);
 
     if (referenceFrame == DECODED_FRAME)
         startDecodeServer(encoder_name, numMachines, hostName, portNum,
-                          inputSourceP->numInputFiles, 
+                          inputSourceP->numInputFiles,
                           paramFileName, masterSocket,
                           &decodePortNum);
 
     startChildren(&scheduler, encoder_name, hostName, portNum,
                   paramFileName, parallelPerfect, forceIalign,
-                  framePatternLen, parallelTestFrames, 
+                  framePatternLen, parallelTestFrames,
                   niceProcesses,
-                  masterSocket, combinePortNum, decodePortNum, 
+                  masterSocket, combinePortNum, decodePortNum,
                   ioPortNum, &numIoServers,
                   &childState);
 
@@ -2076,10 +2077,10 @@ MasterServer(struct inputSource * const inputSourceP,
 
 
 void
-NotifyMasterDone(const char * const masterHostName, 
-                 int          const masterPortNum, 
+NotifyMasterDone(const char * const masterHostName,
+                 int          const masterPortNum,
                  int          const childNum,
-                 unsigned int const seconds, 
+                 unsigned int const seconds,
                  boolean *    const moreWorkToDoP,
                  int *        const nextFrameStartP,
                  int *        const nextFrameEndP) {
@@ -2098,11 +2099,11 @@ NotifyMasterDone(const char * const masterHostName,
     time_t tempTimeStart, tempTimeEnd;
     const char * error;
 
-    machineDebug("CHILD: NOTIFYING MASTER Machine %d assignment complete", 
+    machineDebug("CHILD: NOTIFYING MASTER Machine %d assignment complete",
                  childNum);
 
     time(&tempTimeStart);
-    
+
     ConnectToSocket(masterHostName, masterPortNum, &hostEntry,
                     &clientSocket, &error);
     if (error)
@@ -2132,9 +2133,9 @@ NotifyMasterDone(const char * const masterHostName,
 
 
 void
-DecodeServer(int          const numInputFiles, 
-             const char * const decodeFileName, 
-             const char * const masterHostName, 
+DecodeServer(int          const numInputFiles,
+             const char * const decodeFileName,
+             const char * const masterHostName,
              int          const masterPortNum) {
 /*----------------------------------------------------------------------------
    Execute the decode server.
@@ -2220,7 +2221,7 @@ DecodeServer(int          const numInputFiles,
             }
         } else {
             frameDone[frameReady] = TRUE;
-            
+
             machineDebug("DECODE SERVER:  FRAME %d READY", frameReady);
 
             if ( waitMachine[frameReady] ) {
@@ -2233,7 +2234,7 @@ DecodeServer(int          const numInputFiles,
                                     &clientSocket, &error);
                     if (error)
                         errorExit("DECODE SERVER: "
-                                  "Can't connect to child machine.  %s", 
+                                  "Can't connect to child machine.  %s",
                                   error);
                     close(clientSocket);
                     waitPtr = waitList[waitPtr]-1;
@@ -2243,7 +2244,7 @@ DecodeServer(int          const numInputFiles,
 
         close(otherSock);
     }
-    
+
     machineDebug("DECODE SERVER:  Shutting down");
 
     /* tell Master server we are done */
diff --git a/converter/ppm/ppmtompeg/param.c b/converter/ppm/ppmtompeg/param.c
index ce2cadf1..9499b4ea 100644
--- a/converter/ppm/ppmtompeg/param.c
+++ b/converter/ppm/ppmtompeg/param.c
@@ -1,8 +1,8 @@
 /*===========================================================================*
- * param.c              
- *                      
- *  Procedures to read in parameter file  
- *                                    
+ * param.c
+ *
+ *  Procedures to read in parameter file
+ *
  *===========================================================================*/
 
 /* COPYRIGHT INFORMATION IS AT THE END OF THIS FILE */
@@ -10,9 +10,9 @@
 #define _DEFAULT_SOURCE 1
     /* New name for SVID & BSD source defines */
 #define _XOPEN_SOURCE 500
-    /* This makes sure popen() is in stdio.h.  In GNU libc 2.1.3, 
+    /* This makes sure popen() is in stdio.h.  In GNU libc 2.1.3,
      _POSIX_C_SOURCE = 2 is sufficient, but on AIX 4.3, the higher level
-     _XOPEN_SOURCE is required.  2000.09.09 
+     _XOPEN_SOURCE is required.  2000.09.09
 
      This also makes sure strdup() is in string.h.
     */
@@ -125,11 +125,6 @@ int mult_seq_headers = 0;  /* 0 for none, N for header/N GOPs */
 
 extern char currentPath[MAXPATHLEN];
 
-static const char * const optionText[LAST_OPTION+1] = { 
-    "GOP_SIZE", "PATTERN", "PIXEL", "PQSCALE",
-    "OUTPUT", "RANGE", "PSEARCH_ALG", "IQSCALE", "INPUT_DIR",
-    "INPUT_CONVERT", "INPUT", "BQSCALE", "BASE_FILE_FORMAT",
-    "SLICES_PER_FRAME", "BSEARCH_ALG", "REFERENCE_FRAME"};
 static bool optionSeen[NUM_OPTIONS+1];
     /* optionSeen[x] means we have seen option x in the parameter file we've
        been reading.
@@ -250,7 +245,7 @@ ReadMachineNames(FILE * const fpointer)
  *
  * GetFrameRate
  *
- * take a character string with the input frame rate 
+ * take a character string with the input frame rate
  * and return the correct frame rate code for use in the Sequence header
  *
  * RETURNS: frame rate code as per MPEG-I spec
@@ -292,7 +287,7 @@ mergeInputSource(struct inputSource *       const baseSourceP,
     unsigned int i;
 
     baseSourceP->ifArraySize += addedSourceP->numInputFileEntries;
-    REALLOCARRAY_NOFAIL(baseSourceP->inputFileEntries, 
+    REALLOCARRAY_NOFAIL(baseSourceP->inputFileEntries,
                         baseSourceP->ifArraySize);
     for (i = 0; i < addedSourceP->numInputFileEntries; ++i)
         baseSourceP->inputFileEntries[baseSourceP->numInputFileEntries++] =
@@ -303,7 +298,7 @@ mergeInputSource(struct inputSource *       const baseSourceP,
 
 /* Forward declaration for recursively called function */
 static void
-ReadInputFileNames(FILE *               const fpointer, 
+ReadInputFileNames(FILE *               const fpointer,
                    const char *         const endInput,
                    struct inputSource * const inputSourceP);
 
@@ -355,11 +350,11 @@ expandBackTickLine(const char *         const input,
 
 
 static void
-ReadInputFileNames(FILE *               const fpointer, 
+ReadInputFileNames(FILE *               const fpointer,
                    const char *         const endInput,
                    struct inputSource * const inputSourceP) {
 /*----------------------------------------------------------------------------
-   Read a list of input file names from the parameter file.  Add 
+   Read a list of input file names from the parameter file.  Add
    the information to *inputSourceP.
 
    If inputSourceP == NULL, read off the list, but ignore it.
@@ -384,7 +379,7 @@ ReadInputFileNames(FILE *               const fpointer,
         else {
             if (strncmp(input, endInput, strlen(endInput)) == 0)
                 endStatementRead = TRUE;
-            else if ((input[0] == '#') || (input[0] == '\n')) { 
+            else if ((input[0] == '#') || (input[0] == '\n')) {
                 /* It's a comment or blank line.  Ignore it */
             } else if (input[0] == '`' ) {
                 expandBackTickLine(input, inputSourceP);
@@ -405,7 +400,7 @@ static void
 initOptionSeen(void) {
 
     unsigned int index;
-    
+
     for (index = FIRST_OPTION; index < NUM_OPTIONS; ++index)
         optionSeen[index] = FALSE;
 }
@@ -477,7 +472,7 @@ verifyNoMissingCombineFramesOption(void) {
 static void
 verifyNoMissingOption(int  const function) {
 /*----------------------------------------------------------------------------
-  Verify that the parameter file contains every option it is supposed to. 
+  Verify that the parameter file contains every option it is supposed to.
   Abort program if not.
 -----------------------------------------------------------------------------*/
     switch(function) {
@@ -515,7 +510,7 @@ processIqtable(FILE * const fpointer) {
                         &qtable[row*8+2],  &qtable[row*8+3],
                         &qtable[row*8+4],  &qtable[row*8+5],
                         &qtable[row*8+6],  &qtable[row*8+7])) {
-            pm_error("Line %d of IQTABLE doesn't have 8 elements!", 
+            pm_error("Line %d of IQTABLE doesn't have 8 elements!",
                      row);
         }
         for (col = 0; col < 8; ++col) {
@@ -528,7 +523,7 @@ processIqtable(FILE * const fpointer) {
             }
         }
     }
-            
+
     if (qtable[0] != 8) {
         pm_message("Warning:  IQTable Element 1,1 reset to 8, "
                    "since it must be 8.");
@@ -593,15 +588,15 @@ removeTrailingWhite(const char *  const rawLine,
         pm_error("Unable to get memory to process parameter file");
 
     p = buffer + strlen(buffer) - 1;  /* Point to last character */
-    
+
     /* Position p to just before the trailing white space (might be one
        character before beginning of string!)
     */
     while (p >= buffer && isspace(*p))
         --p;
-    
+
     ++p;  /* Move to first trailing whitespace character */
-    
+
     *p = '\0';  /* Chop off all the trailing whitespace */
 
     *editedLineP = buffer;
@@ -622,7 +617,7 @@ readNiqTable(FILE * const fpointer) {
                         &niqtable[row*8+2],  &niqtable[row*8+3],
                         &niqtable[row*8+4],  &niqtable[row*8+5],
                         &niqtable[row*8+6],  &niqtable[row*8+7])) {
-            pm_error("Line %d of NIQTABLE doesn't have 8 elements!", 
+            pm_error("Line %d of NIQTABLE doesn't have 8 elements!",
                      row);
         }
         for ( col = 0; col < 8; col++ ) {
@@ -675,7 +670,7 @@ processParamLine(char const input[],
             optionSeen[OPTION_ASPECT_RATIO] = TRUE;
         }
         break;
-        
+
     case 'B':
         if (strneq(input, "BQSCALE", 7)) {
             SetBQScale(atoi(SkipSpacesTabs(&input[7])));
@@ -694,7 +689,7 @@ processParamLine(char const input[],
             optionSeen[OPTION_BIT_RATE] = TRUE;
         } else if (strneq(input, "BUFFER_SIZE", 11)) {
             setBufferSize(SkipSpacesTabs(&input[11]));
-            optionSeen[OPTION_BUFFER_SIZE] = TRUE;                  
+            optionSeen[OPTION_BUFFER_SIZE] = TRUE;
         }
         break;
 
@@ -717,8 +712,8 @@ processParamLine(char const input[],
 
             strcpy(currentFramePath, arg);
         } else if (strneq(input, "FRAME_INPUT", 11)) {
-            ReadInputFileNames(fpointer, "FRAME_END_INPUT", 
-                               frameInputSourceP->stdinUsed ? 
+            ReadInputFileNames(fpointer, "FRAME_END_INPUT",
+                               frameInputSourceP->stdinUsed ?
                                NULL : frameInputSourceP);
             optionSeen[OPTION_FRAME_INPUT] = TRUE;
         } else if (strneq(input, "FORCE_I_ALIGN", 13)) {
@@ -726,7 +721,7 @@ processParamLine(char const input[],
         } else if (strneq(input, "FORCE_ENCODE_LAST_FRAME", 23)) {
             /* NO-OP.  We used to drop trailing B frames by default and you
                needed this option to change the last frame to I so you could
-               encode all the frames.  Now we just do that all the time.  
+               encode all the frames.  Now we just do that all the time.
                Why wouldn't we?
             */
         } else if (strneq(input, "FRAME_RATE", 10)) {
@@ -737,7 +732,7 @@ processParamLine(char const input[],
             optionSeen[OPTION_FRAME_RATE] = TRUE;
         }
         break;
-        
+
     case 'G':
         if (strneq(input, "GOP_SIZE", 8)) {
             SetGOPSize(atoi(SkipSpacesTabs(&input[8])));
@@ -749,8 +744,8 @@ processParamLine(char const input[],
 
             strcpy(currentGOPPath, arg);
         } else if (strneq(input, "GOP_INPUT", 9)) {
-            ReadInputFileNames(fpointer, "GOP_END_INPUT", 
-                               gopInputSourceP->stdinUsed ? 
+            ReadInputFileNames(fpointer, "GOP_END_INPUT",
+                               gopInputSourceP->stdinUsed ?
                                NULL : gopInputSourceP);
             optionSeen[OPTION_GOP_INPUT] = TRUE;
         } else if (strneq(input, "GAMMA", 5)) {
@@ -759,7 +754,7 @@ processParamLine(char const input[],
             optionSeen[OPTION_GAMMA] = TRUE;
         }
         break;
-        
+
     case 'I':
         if (strneq(input, "IQSCALE", 7)) {
             SetIQScale(atoi(SkipSpacesTabs(&input[7])));
@@ -774,7 +769,7 @@ processParamLine(char const input[],
             strcpy(inputConversion, SkipSpacesTabs(&input[13]));
             optionSeen[OPTION_INPUT_CONVERT] = TRUE;
         } else if (streq(input, "INPUT")) {
-            ReadInputFileNames(fpointer, "END_INPUT", 
+            ReadInputFileNames(fpointer, "END_INPUT",
                                inputSourceP->stdinUsed ?
                                NULL : inputSourceP);
             optionSeen[OPTION_INPUT] = TRUE;
@@ -792,7 +787,7 @@ processParamLine(char const input[],
         if (strneq(input, "KEEP_TEMP_FILES", 15))
             keepTempFiles = TRUE;
         break;
-        
+
     case 'N':
       if (strneq(input, "NIQTABLE", 8)) {
           readNiqTable(fpointer);
@@ -808,11 +803,11 @@ processParamLine(char const input[],
                 strcpy(outputFileName, arg);
             else
                 sprintf(outputFileName, "%s.gop.%d", arg, whichGOP);
-            
+
             optionSeen[OPTION_OUTPUT] = TRUE;
         }
         break;
-        
+
     case 'P':
         if (strneq(input, "PATTERN", 7)) {
             SetFramePattern(SkipSpacesTabs(&input[7]));
@@ -842,7 +837,7 @@ processParamLine(char const input[],
             optionSeen[OPTION_PARALLEL] = TRUE;
         }
         break;
-        
+
     case 'R':
         if (strneq(input, "RANGE", 5)) {
             processRanges(SkipSpacesTabs(&input[5]));
@@ -900,14 +895,14 @@ processParamLine(char const input[],
             optionSeen[OPTION_USER_DATA] = TRUE;
         }
         break;
-        
+
     case 'W':
         if (strneq(input, "WARN_UNDERFLOW", 14))
             paramP->warnUnderflow = TRUE;
         if (strneq(input, "WARN_OVERFLOW", 13))
             paramP->warnOverflow = TRUE;
         break;
-        
+
     case 'Y':
         if (strneq(input, "YUV_SIZE", 8)) {
             const char * const arg = SkipSpacesTabs(&input[8]);
@@ -934,7 +929,7 @@ processParamLine(char const input[],
 
 
 void
-ReadParamFile(const char *         const fileName, 
+ReadParamFile(const char *         const fileName,
               majorProgramFunction const function,
               struct params *      const paramP) {
 /*----------------------------------------------------------------------------
@@ -1014,7 +1009,7 @@ ReadParamFile(const char *         const fileName,
   if (yuvUsed) {
       if (!optionSeen[OPTION_YUV_SIZE])
           pm_error("YUV format used but YUV_SIZE not given");
-      
+
       if (!optionSeen[OPTION_YUV_FORMAT]) {
           strcpy (yuvConversion, "EYUV");
           pm_message("WARNING:  YUV format not specified; "
@@ -1031,7 +1026,7 @@ ReadParamFile(const char *         const fileName,
   if (optionSeen[OPTION_IO_CONVERT] != optionSeen[OPTION_SLAVE_CONVERT])
       pm_error("Must have either both IO_SERVER_CONVERT and SLAVE_CONVERT "
                "or neither");
-      
+
   if (optionSeen[OPTION_DEFS_SPECIFICS] && !optionSeen[OPTION_SPECIFICS])
       pm_error("Does not make sense to define Specifics file options, "
                "but no specifics file!");
diff --git a/converter/ppm/ppmtompeg/parse_huff.pl b/converter/ppm/ppmtompeg/parse_huff.pl
index 1fc6466c..633e5877 100644
--- a/converter/ppm/ppmtompeg/parse_huff.pl
+++ b/converter/ppm/ppmtompeg/parse_huff.pl
@@ -51,7 +51,7 @@
 #    composed of 1, 0, space, and 's'.  Spaces are ignored, and
 #    s corresponds to the sign bit.  In the output of this program,
 #    We'll completely right-shift the data, with a 0 for the sign
-#    bit.  The encoder will make appropriate changes before outputing.
+#    bit.  The encoder will make appropriate changes before outputting.
 
 
 open(HUFFC, "> huff.c") || die "Can't write huff.c: $!\n";
diff --git a/converter/ppm/ppmtompeg/psearch.c b/converter/ppm/ppmtompeg/psearch.c
index 3cca1241..e350137e 100644
--- a/converter/ppm/ppmtompeg/psearch.c
+++ b/converter/ppm/ppmtompeg/psearch.c
@@ -58,7 +58,7 @@ int psearchAlg;
  *
  * PRECONDITIONS:   The relevant block in 'current' is valid (it has not
  *          been dct'd).  Thus, the data in 'current' can be
- *          accesed through y_blocks, cr_blocks, and cb_blocks.
+ *          accessed through y_blocks, cr_blocks, and cb_blocks.
  *          This is not the case for the blocks in 'prev.'
  *          Therefore, references into 'prev' should be done
  *          through the struct items ref_y, ref_cr, ref_cb
diff --git a/converter/ppm/ppmtompeg/psocket.c b/converter/ppm/ppmtompeg/psocket.c
index 6a50dc27..aac61022 100644
--- a/converter/ppm/ppmtompeg/psocket.c
+++ b/converter/ppm/ppmtompeg/psocket.c
@@ -10,15 +10,15 @@
 ============================================================================*/
 
 #define _XOPEN_SOURCE 500 /* Make sure stdio.h contains pclose() */
-/* _ALL_SOURCE is needed on AIX to make the C library include the 
-   socket services (e.g. define struct sockaddr) 
+/* _ALL_SOURCE is needed on AIX to make the C library include the
+   socket services (e.g. define struct sockaddr)
 
    Note that AIX standards.h actually sets feature declaration macros such
    as _XOPEN_SOURCE, unless they are already set.
 */
 #define _ALL_SOURCE
 #define __EXTENSIONS__
-  /* __EXTENSIONS__ is for a broken Sun C library (uname SunOS kosh 5.8 
+  /* __EXTENSIONS__ is for a broken Sun C library (uname SunOS kosh 5.8
      generic_108528-16 sun4u sparc).  When you define _XOPEN_SOURCE,
      it's vnode.h and resource.h fail to define some data types that they
      need (e.g. timestruct_t).  But with __EXTENSIONS__, they declare the
@@ -126,8 +126,8 @@ unmarshallInt(unsigned char const buffer[],
 
 
 static void
-safeRead(int             const fd, 
-         unsigned char * const buf, 
+safeRead(int             const fd,
+         unsigned char * const buf,
          unsigned int    const nbyte) {
 /*----------------------------------------------------------------------------
     Safely read from file 'fd'.  Keep reading until we get
@@ -144,7 +144,7 @@ safeRead(int             const fd,
             errorExit("read (of %u bytes (total %u) ) returned "
                       "errno %d (%s)",
                       nbyte-numRead, nbyte, errno, strerror(errno));
-        else 
+        else
             numRead += result;
     }
 }
@@ -203,8 +203,8 @@ marshallInt(int              const value,
 
 
 static void
-safeWrite(int             const fd, 
-          unsigned char * const buf, 
+safeWrite(int             const fd,
+          unsigned char * const buf,
           unsigned int    const nbyte) {
 /*----------------------------------------------------------------------------
   Safely write to file 'fd'.  Keep writing until we write 'nbyte'
@@ -217,7 +217,7 @@ safeWrite(int             const fd,
     while (numWritten < nbyte) {
         int const result = write(fd, &buf[numWritten], nbyte-numWritten);
 
-        if (result == -1) 
+        if (result == -1)
             errorExit("write (of %u bytes (total %u) ) returned "
                       "errno %d (%s)",
                       nbyte-numWritten, nbyte, errno, strerror(errno));
@@ -251,8 +251,8 @@ WriteInt(int const socketFd,
 
 
 void
-ConnectToSocket(const char *      const machineName, 
-                int               const portNum, 
+ConnectToSocket(const char *      const machineName,
+                int               const portNum,
                 struct hostent ** const hostEnt,
                 int *             const socketFdP,
                 const char **     const errorP) {
@@ -266,7 +266,7 @@ ConnectToSocket(const char *      const machineName,
    **hostEnt.
 -----------------------------------------------------------------------------*/
     int rc;
-    
+
     *errorP = NULL;  /* initial value */
 
     if ((*hostEnt) == NULL) {
@@ -277,15 +277,15 @@ ConnectToSocket(const char *      const machineName,
     if (!*errorP) {
         rc = socket(AF_INET, SOCK_STREAM, 0);
         if (rc < 0)
-            pm_asprintf(errorP, "socket() failed with errno %d (%s)", 
+            pm_asprintf(errorP, "socket() failed with errno %d (%s)",
                         errno, strerror(errno));
         else {
             int const socketFd = rc;
-            
+
             int rc;
             unsigned short tempShort;
             struct sockaddr_in  nameEntry;
-            
+
             nameEntry.sin_family = AF_INET;
             memset((void *) nameEntry.sin_zero, 0, 8);
             memcpy((void *) &(nameEntry.sin_addr.s_addr),
@@ -293,12 +293,12 @@ ConnectToSocket(const char *      const machineName,
                    (size_t) (*hostEnt)->h_length);
             tempShort = portNum;
             nameEntry.sin_port = htons(tempShort);
-            
+
             rc = connect(socketFd, (struct sockaddr *) &nameEntry,
                          sizeof(struct sockaddr));
-            
+
             if (rc != 0)
-                pm_asprintf(errorP, 
+                pm_asprintf(errorP,
                             "connect() to host '%s', port %d failed with "
                             "errno %d (%s)",
                             machineName, portNum, errno, strerror(errno));
@@ -317,7 +317,7 @@ ConnectToSocket(const char *      const machineName,
 static bool
 portInUseErrno(int const testErrno) {
 /*----------------------------------------------------------------------------
-   Return TRUE iff 'testErrno' is what a bind() would return if one requestd
+   Return TRUE iff 'testErrno' is what a bind() would return if one requested
    a port number that is unavailable (but other port numbers might be).
 -----------------------------------------------------------------------------*/
     bool retval;
@@ -340,19 +340,19 @@ static void
 bindToUnusedPort(int              const socketFd,
                  unsigned short * const portNumP,
                  const char **    const errorP) {
-    
+
     bool foundPort;
     unsigned short trialPortNum;
 
     *errorP = NULL;  /* initial value */
 
-    for (foundPort = FALSE, trialPortNum = 2048; 
-         !foundPort && trialPortNum < 16384 && !*errorP; 
+    for (foundPort = FALSE, trialPortNum = 2048;
+         !foundPort && trialPortNum < 16384 && !*errorP;
          ++trialPortNum) {
-        
+
         struct sockaddr_in nameEntry;
         int rc;
-        
+
         memset((char *) &nameEntry, 0, sizeof(nameEntry));
         nameEntry.sin_family = AF_INET;
         nameEntry.sin_port   = htons(trialPortNum);
@@ -365,10 +365,10 @@ bindToUnusedPort(int              const socketFd,
             *portNumP = trialPortNum;
         } else if (!portInUseErrno(errno))
             pm_asprintf(errorP, "bind() of TCP port number %hu failed "
-                        "with errno %d (%s)", 
+                        "with errno %d (%s)",
                         trialPortNum, errno, strerror(errno));
     }
-    
+
     if (!*errorP && !foundPort)
         pm_asprintf(errorP, "Unable to find a free port.  Every TCP port "
                     "in the range 2048-16383 is in use");
@@ -389,7 +389,7 @@ CreateListeningSocket(int *         const socketP,
    partner can connect).
 -----------------------------------------------------------------------------*/
     int rc;
-    
+
     rc = socket(AF_INET, SOCK_STREAM, 0);
     if (rc < 0)
         pm_asprintf(errorP,
@@ -415,7 +415,7 @@ CreateListeningSocket(int *         const socketP,
             rc = listen(socketFd, SOMAXCONN);
             if (rc != 0)
                 pm_asprintf(errorP, "Unable to listen on TCP socket.  "
-                            "listen() fails with errno %d (%s)", 
+                            "listen() fails with errno %d (%s)",
                             errno, strerror(errno));
         }
         if (*errorP)
@@ -433,11 +433,11 @@ AcceptConnection(int           const listenSocketFd,
     struct sockaddr otherSocket;
     socklenx_t      otherSize;
         /* This is an ugly dual-meaning variable.  As input to accept(),
-           it is the storage size of 'otherSocket'.  As output, it is the 
+           it is the storage size of 'otherSocket'.  As output, it is the
            data length of 'otherSocket'.
         */
     int             rc;
-    
+
     otherSize = sizeof(otherSocket);
 
     rc = accept(listenSocketFd, &otherSocket, &otherSize);
@@ -450,3 +450,6 @@ AcceptConnection(int           const listenSocketFd,
         *errorP = NULL;
     }
 }
+
+
+
diff --git a/converter/ppm/ppmtompeg/rate.c b/converter/ppm/ppmtompeg/rate.c
index 6ec330cf..3fa41102 100644
--- a/converter/ppm/ppmtompeg/rate.c
+++ b/converter/ppm/ppmtompeg/rate.c
@@ -1,6 +1,6 @@
 /*============================================================================*
  * rate.c								      *
- *									      * 
+ *									      *
  *	Procedures concerned with rate control                                *
  *									      *
  * EXPORTED PROCEDURES:							      *
@@ -75,7 +75,7 @@
 
 #define MAX_BIT_RATE 104857600		/* 18 digit number in units of 400 */
 #define MAX_BUFFER_SIZE 16760832        /* 10 digit number in units of 16k */
-#define DEFAULT_BUFFER_SIZE 327680      /* maximun for "constrained" bitstream */
+#define DEFAULT_BUFFER_SIZE 327680      /* maximum for "constrained" bitstream */
 #define DEFAULT_VBV_FULLNESS 3          /* wait till 1/3 full */
 #define DEFAULT_PICT_RATE_CODE 5        /* code for 30 Frames/sec */
 #define DEFAULT_PICT_RATE 30            /* 30 frames per second */
@@ -92,7 +92,7 @@ static bool wantVbvUnderflowWarning;
 static bool wantVbvOverflowWarning;
 
 /*   Variables for the VBV buffer defined in MPEG specs */
-static unsigned int VBV_remainingDelay; 
+static unsigned int VBV_remainingDelay;
     /* delay in units of 1/90000 seconds */
 static int32 VBV_buffer = 0;	  /* fullness of the theoretical VBV buffer */
 static int32 bufferFillRate = 0;    /* constant rate at which buffer filled */
@@ -104,7 +104,7 @@ static int Xi, Xp, Xb;  /*  Global complexity measure  */
 static int Si, Sp, Sb;  /*  Total # bits for last pict of type (Overhead?) */
 
 static float Qi, Qp, Qb; /* avg quantizaton for last picture of type  */
-     
+
 /*  Target bit allocations for each type of picture*/
 int Ti, Tp, Tb;
 
@@ -175,24 +175,6 @@ static int Qscale;	       /* Clipped, truncated quantization value */
 static FILE *RC_FILE;
 #endif
 
-static const char * const Frame_header1 = 
-"  Fm         #     Bit      GOP                    V                ";
-static const char * const Frame_header2 = 
-"   #  type   MBs   Alloc    left  Ni Np Nb  N_act  buff   Q_rc Qscale";
-static const char * const Frame_header3 = 
-"----     -  ----  ------ -------  -- -- --  -----  ------ ----   ----";
-static const char * const Frame_trailer1 = 
-"                      avg          virt     %    GOP      %     VBV";
-static const char * const Frame_trailer2 = 
-"    Sx    Qx      Xx  act N_act  buffer alloc    left  left     buf  delay";
-static const char * const Frame_trailer3 = 
-"------ --.-- -------  --- --.-- -------   --- -------   --- ------- ------";
-
-static const char * const MB_header1 = 
-"MB#  #bits  Q mqt     Dj  Q_j   actj  N_act  totbits b/MB %alloc %done";
-static const char * const MB_header2 = 
-"---  ----- -- --- ------  ---  -----  --.--   ------ ----    ---   ---";
-
 static char rc_buffer[101];
 
 /*	EXTERNAL Variables  */
@@ -211,8 +193,8 @@ void checkSpatialActivity (Block blk0, Block blk1, Block blk2, Block blk3);
 void incNumBlocks (int num);
 void calculateVBVDelay (int num);
 int BlockExperiments  (int16 *OrigBlock, int16 *NewBlock, int control);
-     
-     
+
+
 
 static void
 analyzePattern(const char *  const framePattern,
@@ -226,10 +208,10 @@ analyzePattern(const char *  const framePattern,
     unsigned int i;
 
     /*  Initialize Pattern info */
-    *gop_xP = framePatternLen;    
+    *gop_xP = framePatternLen;
 
     for (i = 0, *gop_iP = 0, *gop_pP = 0, *gop_bP = 0, *errorP = NULL;
-         i < framePatternLen && !*errorP; 
+         i < framePatternLen && !*errorP;
          ++i) {
         switch(framePattern[i]) {
         case 'i': ++*gop_iP; break;
@@ -241,7 +223,7 @@ analyzePattern(const char *  const framePattern,
     }
     assert(*gop_xP == *gop_iP + *gop_pP + *gop_bP);
 }
-  
+
 
 
 /*===========================================================================*
@@ -252,7 +234,7 @@ analyzePattern(const char *  const framePattern,
  *
  * RETURNS:	nothing
  *
- * SIDE EFFECTS:   many global variables 
+ * SIDE EFFECTS:   many global variables
  *
  * NOTES:  Get rid of the redundant pattern stuff!!
  *===========================================================================*/
@@ -266,7 +248,7 @@ initRateControl(bool const wantUnderflowWarning,
     wantVbvOverflowWarning  = wantOverflowWarning;
 
     DBG_PRINT(("Initializing Allocation Data\n"));
-  
+
 #ifdef RC_STATS_FILE
     RC_FILE = fopen("RC_STATS_FILE", "w");
     if ( RC_FILE  == NULL) {
@@ -278,7 +260,7 @@ initRateControl(bool const wantUnderflowWarning,
 #endif
 
     VBV_remainingDelay = 0;
-  
+
     analyzePattern(framePattern, framePatternLen,
                    &GOP_X, &GOP_I, &GOP_P, &GOP_B, &error);
 
@@ -291,46 +273,46 @@ initRateControl(bool const wantUnderflowWarning,
     }
 
 
-    /* Initializing GOP bit allocation */	
+    /* Initializing GOP bit allocation */
     rc_R = 0;
     rc_G = (bit_rate * GOP_X/frameRateRounded);
-  
+
     /*   Initialize the "global complexity measures" */
     Xi = (160 * bit_rate/115);
     Xp = (60 * bit_rate/115);
     Xb = (42 * bit_rate/115);
-  
+
     /*   Initialize MB counters */
     rc_totalMBBits= rc_bitsThisMB= rc_totalFrameBits=rc_totalOverheadBits = 0;
     rc_numBlocks = rc_totalQuant = 0;
-  
+
     /*   init virtual buffers  */
     reactionParameter = (2 * bit_rate / frameRateRounded);
     d0_i = (10 * reactionParameter / 31);
     d0_p = (Kp * d0_i);
     d0_b = (Kb * d0_i);
-  
+
     lastFrameVirtBuf = d0_i;	/*  start with I Frame */
     rc_Q = lastFrameVirtBuf  * 31 / reactionParameter;
-  
+
     /*   init spatial activity measures */
     avg_act = 400;		/* Suggested initial value */
     N_act = 1;
-  
+
     mquant = rc_Q * N_act;
-  
+
     frameDelayIncrement = (90000 / frameRateRounded);
         /* num of "delay" units per frame */
-    bufferFillRate = bit_rate / frameRateRounded; 
+    bufferFillRate = bit_rate / frameRateRounded;
         /* VBV buf fills at constant rate */
     VBV_buffer = buffer_size;
     DBG_PRINT(("VBV- delay: %d, fill rate: %d, delay/Frame: %d units, "
                "buffer size: %d\n",
-               VBV_remainginDelay, bufferFillRate, frameDelayIncrement, 
+               VBV_remainginDelay, bufferFillRate, frameDelayIncrement,
                buffer_size));
-  
+
     result = initGOPRateControl();
-  
+
     return result;
 }
 
@@ -343,21 +325,21 @@ initRateControl(bool const wantUnderflowWarning,
  *
  * RETURNS:	nothing
  *
- * SIDE EFFECTS:   many global variables 
+ * SIDE EFFECTS:   many global variables
  *
  *===========================================================================*/
 int
 initGOPRateControl()
 {
     DBG_PRINT(("Initializing new GOP\n"));
-  
+
     Nx = GOP_X;
     Ni = GOP_I;
     Np = GOP_P;
     Nb = GOP_B;
-  
+
     rc_R += rc_G;
-  
+
     DBG_PRINT(("bufsize: %d, bitrate: %d, pictrate: %d, GOP bits: %d\n",
                buffer_size, bit_rate, frameRateRounded, rc_R));
     DBG_PRINT(("Xi: %d, Xp: %d, Xb: %d Nx: %d, Ni: %d, Np: %d, Nb: %d\n",
@@ -389,20 +371,20 @@ targetRateControl(MpegFrame * const frame) {
     float tempX, tempY, tempZ;
     int result;
     int frameType;
-  
+
     minimumBits = (bit_rate / (8 * frameRateRounded));
-  
+
     /*   Check if new GOP */
     if (Nx == 0) {
         initGOPRateControl();
     }
-  
+
     if (MB_cnt < 0) {MB_cnt = determineMBCount();}
-  
+
     switch (frame->type) {
     case TYPE_IFRAME:
         frameType = 'I';
-    
+
         tempX = ( (Np * Ki * Xp) / (Xi * Kp) );
         tempY = ( (Nb * Ki * Xb) / (Xi*Kb) );
         tempZ = Ni + tempX + tempY;
@@ -411,7 +393,7 @@ targetRateControl(MpegFrame * const frame) {
         current_Tx = Ti = result;
         lastFrameVirtBuf = d0_i;
         break;
-    
+
     case TYPE_PFRAME:
         frameType = 'P';
         tempX =  ( (Ni * Kp * Xi) / (Ki * Xp) );
@@ -422,7 +404,7 @@ targetRateControl(MpegFrame * const frame) {
         current_Tx = Tp = result;
         lastFrameVirtBuf = d0_p;
         break;
-    
+
     case TYPE_BFRAME:
         frameType = 'B';
         tempX =  ( (Ni * Kb * Xi) / (Ki * Xb) );
@@ -433,17 +415,17 @@ targetRateControl(MpegFrame * const frame) {
         current_Tx = Tb = result;
         lastFrameVirtBuf = d0_b;
         break;
-    
+
     default:
         frameType = 'X';
     }
-  
+
     N_act = 1;
     rc_Q = lastFrameVirtBuf  * 31 / reactionParameter;
     mquant = rc_Q * N_act;
     Qscale = (mquant > 31 ? 31 : mquant);
     Qscale = (Qscale < 1 ? 1 : Qscale);
-  
+
 #ifdef HEINOUS_DEBUG_MODE
     {
         const char * strPtr;
@@ -459,15 +441,15 @@ targetRateControl(MpegFrame * const frame) {
     /*   Print Frame info */
     sprintf(rc_buffer, "%4d     %1c  %4d  %6d %7d  "
             "%2d %2d %2d   %2.2f  %6d %4d    %3d",
-            frame->id,frameType,MB_cnt,current_Tx,rc_R,Ni,Np,Nb, 
+            frame->id,frameType,MB_cnt,current_Tx,rc_R,Ni,Np,Nb,
             N_act, lastFrameVirtBuf, rc_Q, Qscale);
-  
+
 #ifdef RC_STATS_FILE
     fprintf(RC_FILE,"%s\n", rc_buffer);
     fflush(RC_FILE);
 #endif
     DBG_PRINT(("%s\n",rc_buffer));
-  
+
     /*  Print headers for Macroblock info */
     if (RC_MB_SAMPLE_RATE) {
 #ifdef HEINOUS_DEBUG_MODE
@@ -483,7 +465,7 @@ targetRateControl(MpegFrame * const frame) {
 
 
 
-static void 
+static void
 updateVBVBuffer(int const frameBits) {
 /*----------------------------------------------------------------------------
   Update the VBV buffer after each frame.  This theoretical buffer is
@@ -532,11 +514,11 @@ updateRateControl(int const type) {
     pctAllocUsed = (totalBits *100 / current_Tx);
     rc_R -= totalBits;
     pctGOPUsed = (rc_R *100/ rc_G);
-  
+
     avg_act = (total_act_j / MB_cnt);
-  
+
     updateVBVBuffer(totalBits);
-  
+
     switch (type) {
     case TYPE_IFRAME:
         Ti = current_Tx;
@@ -563,9 +545,9 @@ updateRateControl(int const type) {
         Xb = frameComplexity;
         break;
     }
-  
+
 #ifdef HEINOUS_DEBUG_MODE
-    {  
+    {
         /*  Print Frame info */
         const char * strPtr;
         strPtr = Frame_trailer1;
@@ -575,26 +557,26 @@ updateRateControl(int const type) {
         strPtr = Frame_trailer3;
         DBG_PRINT(("%s\n",strPtr));
     }
-#endif  
+#endif
     sprintf(rc_buffer, "%6d  %2.2f  %6d  %3d  %2.2f %7d   "
             "%3d %7d   %3d  %6d %6d",
-            totalBits, avgQuant, frameComplexity, avg_act, N_act, 
-            currentVirtBuf, pctAllocUsed, rc_R, pctGOPUsed, 
+            totalBits, avgQuant, frameComplexity, avg_act, N_act,
+            currentVirtBuf, pctAllocUsed, rc_R, pctGOPUsed,
             VBV_buffer, VBV_remainingDelay);
 #ifdef RC_STATS_FILE
     fprintf(RC_FILE,"%s\n", rc_buffer);
     fflush(RC_FILE);
 #endif
     DBG_PRINT(("%s\n",rc_buffer));
-  
+
     Nx--;
     rc_totalMBBits= rc_bitsThisMB= rc_totalFrameBits=rc_totalOverheadBits = 0;
     rc_numBlocks = rc_totalQuant = total_act_j = currentVirtBuf = 0;
-  
+
     DBG_PRINT(("GOP now has %d bits remaining (%3d%%) for %d frames .. , "
-               "Ni= %d, Np= %d, Nb= %d\n", 
+               "Ni= %d, Np= %d, Nb= %d\n",
                rc_R, (rc_R*100/rc_G), (Ni+Np+Nb), Ni, Np, Nb));
-  
+
 }
 
 
@@ -622,21 +604,21 @@ int type;
   int pctUsed, pctDone;
   int bitsThisMB;
   int bitsPerMB;
-  
+
   bitsThisMB = rc_bitsThisMB;
   totalBits = rc_totalFrameBits;
-  bitsPerMB = (totalBits / rc_numBlocks); 
-  pctDone = (rc_numBlocks * 100/ MB_cnt); 
+  bitsPerMB = (totalBits / rc_numBlocks);
+  pctDone = (rc_numBlocks * 100/ MB_cnt);
   pctUsed = (totalBits *100/current_Tx);
-  
+
   sprintf(rc_buffer, "%3d  %5d %2d %3d %6d  %3d %6d   %2.2f   %6d %4d    %3d   %3d\n",
-	  (rc_numBlocks - 1), bitsThisMB, Qscale, mquant, currentVirtBuf, 
+	  (rc_numBlocks - 1), bitsThisMB, Qscale, mquant, currentVirtBuf,
 	  rc_Q, act_j, N_act, totalBits, bitsPerMB, pctUsed, pctDone);
 #ifdef RC_STATS_FILE
   fprintf(RC_FILE, "%s", rc_buffer);
   fflush(RC_FILE);
 #endif
-  
+
   if ( (RC_MB_SAMPLE_RATE) && ((rc_numBlocks -1) % RC_MB_SAMPLE_RATE)) {
     DBG_PRINT(("%s\n", rc_buffer));
   } else {
@@ -695,7 +677,7 @@ void incMacroBlockBits(num)
  *
  * RETURNS:     new Qscale
  *
- * SIDE EFFECTS:   
+ * SIDE EFFECTS:
  *
  *===========================================================================*/
 int needQScaleChange(oldQScale, blk0, blk1, blk2, blk3)
@@ -705,19 +687,19 @@ int needQScaleChange(oldQScale, blk0, blk1, blk2, blk3)
      Block blk2;
      Block blk3;
 {
-  
+
   /*   One more MacroBlock seen */
   rc_numBlocks++;		/* this notes each block num in MB */
-  
+
   checkBufferFullness(oldQScale);
-  
+
   checkSpatialActivity(blk0, blk1, blk2, blk3);
-  
+
   mquant = rc_Q * N_act;
   Qscale = (mquant > 31 ? 31 : mquant);
   Qscale = (Qscale < 1 ? 1 : Qscale);
   rc_totalQuant += Qscale;
-  
+
   if (oldQScale == Qscale)
     return -1;
   else
@@ -727,7 +709,7 @@ int needQScaleChange(oldQScale, blk0, blk1, blk2, blk3)
 
 /*===========================================================================*
  *
- * determineMBCount() 
+ * determineMBCount()
  *
  *      Determines number of Macro Blocks in frame from the frame sizes
  *	passed.
@@ -741,7 +723,7 @@ int
   determineMBCount ()
 {
   int y,x;
-  
+
   x = (Fsize_x +15)/16;
   y = (Fsize_y +15)/16;
   return  (x * y);
@@ -769,11 +751,11 @@ void checkBufferFullness (oldQScale)
      int oldQScale;
 {
   int temp;
-  
+
   temp = lastFrameVirtBuf + rc_totalFrameBits;
   temp -=  (current_Tx * rc_numBlocks / MB_cnt);
   currentVirtBuf = temp;
-  
+
   rc_Q = (currentVirtBuf * 31 / reactionParameter);
   return;
 }
@@ -783,8 +765,8 @@ void checkBufferFullness (oldQScale)
  *
  * void checkSpatialActivity()
  *
- *      Calcualtes the spatial activity for the four luminance blocks of the
- *	macroblock.  Along with the normalized reference quantization parameter 
+ *      Calculates the spatial activity for the four luminance blocks of the
+ *	macroblock.  Along with the normalized reference quantization parameter
  *  (rc_Q) , it determines the quantization factor for the next macroblock.
  *
  * RETURNS:     nothing
@@ -801,19 +783,19 @@ void checkSpatialActivity(blk0, blk1, blk2, blk3)
      Block blk3;
 {
   int temp;
-  int16 *blkArray[4]; 
+  int16 *blkArray[4];
   int16 *curBlock;
   int16 *blk_ptr;
   int var[4];
   int i, j;
-  
-  
+
+
   blkArray[0] = (int16 *) blk0;
   blkArray[1] = (int16 *) blk1;
   blkArray[2] = (int16 *) blk2;
   blkArray[3] = (int16 *) blk3;
-  
-  
+
+
   for (i =0; i < 4; i++) {	/* Compute the activity in each block */
     curBlock = blkArray[i];
     blk_ptr = curBlock;
@@ -821,14 +803,14 @@ void checkSpatialActivity(blk0, blk1, blk2, blk3)
     /*  Find the mean pixel value */
     for (j=0; j < DCTSIZE_SQ; j ++) {
       P_mean += *(blk_ptr++);
-      /*			P_mean += curBlock[j]; 
+      /*			P_mean += curBlock[j];
 				if (curBlock[j] != *(blk_ptr++)) {
 				printf("ARRAY ERROR: block %d\n", j);
 				}
 				*/
     }
     P_mean /= DCTSIZE_SQ;
-    
+
     /*  Now find the variance  */
     curBlock = blkArray[i];
     blk_ptr = curBlock;
@@ -839,25 +821,25 @@ void checkSpatialActivity(blk0, blk1, blk2, blk3)
 	printf("ARRAY ERROR: block %d\n", j);
       }
       temp = curBlock[j] - P_mean;
-#endif      
+#endif
       temp = *(blk_ptr++) - P_mean;
       var[i] += (temp * temp);
     }
     var[i] /= DCTSIZE_SQ;
   }
-  
+
   /*  Choose the minimum variance from the 4 blocks and use as the activity */
   var_sblk  = var[0];
   for (i=1; i < 4; i++) {
     var_sblk = (var_sblk < var[i] ? var_sblk : var[i]);
   }
-  
-  
+
+
   act_j = 1 + var_sblk;
   total_act_j += act_j;
   temp = (2 * act_j + avg_act);
   N_act = ( (float) temp / (float) (act_j + 2*avg_act) );
-  
+
   return;
 }
 
@@ -900,7 +882,7 @@ int getRateMode()
 void setBitRate (const char * const charPtr)
 {
   int rate, rnd;
-  
+
   rate = atoi(charPtr);
   if (rate > 0) {
     RateControlMode = FIXED_RATE;
@@ -915,7 +897,7 @@ void setBitRate (const char * const charPtr)
   rate = (rate > MAX_BIT_RATE ? MAX_BIT_RATE : rate);
   bit_rate = rate;
   DBG_PRINT(("Bit rate is: %d\n", bit_rate));
-} 
+}
 
 
 
@@ -957,7 +939,7 @@ int getBitRate ()
 void setBufferSize (const char * const charPtr)
 {
   int size;
-  
+
   size = atoi(charPtr);
   size = (size > MAX_BUFFER_SIZE ? MAX_BUFFER_SIZE : size);
   if (size > 0) {
diff --git a/converter/ppm/ppmtompeg/readframe.c b/converter/ppm/ppmtompeg/readframe.c
index 2a359b2f..dcc02052 100644
--- a/converter/ppm/ppmtompeg/readframe.c
+++ b/converter/ppm/ppmtompeg/readframe.c
@@ -1,13 +1,13 @@
 /*===========================================================================*
- * readframe.c                    
- *                                
- *  procedures to read in frames  
- *                                
- * EXPORTED PROCEDURES:           
- *  ReadFrame                     
- *  SetFileType                   
- *  SetFileFormat                 
- *                                
+ * readframe.c
+ *
+ *  procedures to read in frames
+ *
+ * EXPORTED PROCEDURES:
+ *  ReadFrame
+ *  SetFileType
+ *  SetFileFormat
+ *
  *===========================================================================*/
 
 /* COPYRIGHT INFORMATION IS AT THE END OF THIS FILE */
@@ -62,7 +62,7 @@ struct YuvLine {
 #ifdef __OS2__
   #define popen _popen
 #endif
-   
+
 
 /*==================*
  * Global VARIABLES *
@@ -100,7 +100,7 @@ static void DoKillDim (MpegFrame *mf, int w, int h);
 
 
 
-void    
+void
 SetResize(bool const set) {
     resizeFrame = set;
 }
@@ -134,7 +134,7 @@ ReadPNM(MpegFrame * const mpegFrameP,
 static void
 openFile(struct inputSource * const inputSourceP,
          unsigned int         const frameNumber,
-         const char *         const conversion, 
+         const char *         const conversion,
          FILE **              const ifPP) {
 
     if (inputSourceP->stdinUsed) {
@@ -145,24 +145,24 @@ openFile(struct inputSource * const inputSourceP,
                 "INPUT_CONVERTER * in the parameter file or supply the "
                 "frames in files by specifying a directory with "
                 "INPUT_DIRECTORY in the parameter file.");
-        
+
         *ifPP = stdin;
     } else {
         const char * fileName;
         const char * fullFileName;
-        
+
         GetNthInputFileName(inputSourceP, frameNumber, &fileName);
-        
+
         pm_asprintf(&fullFileName, "%s/%s", currentPath, fileName);
-        
+
         CurrFile = fullFileName;
-        
+
         if (fileType == ANY_FILE_TYPE) {
             char command[1024];
             const char * convertPtr;
             char * commandPtr;
             const char * charPtr;
-            
+
             /* replace every occurrence of '*' with fullFileName */
             convertPtr = conversion;
             commandPtr = command;
@@ -172,7 +172,7 @@ openFile(struct inputSource * const inputSourceP,
                     ++commandPtr;
                     ++convertPtr;
                 }
-                
+
                 if (*convertPtr == '*') {
                     /* copy fullFileName */
                     charPtr = fullFileName;
@@ -185,7 +185,7 @@ openFile(struct inputSource * const inputSourceP,
                 }
             }
             *commandPtr = '\0';
-            
+
             *ifPP = popen(command, "r");
             if (*ifPP == NULL) {
                 pm_message(
@@ -201,7 +201,7 @@ openFile(struct inputSource * const inputSourceP,
             *ifPP = fopen(fullFileName, "rb");
             if (*ifPP == NULL)
                 pm_error("Couldn't open input file '%s'", fullFileName);
-            
+
             if (baseFormat == JMOVIE_FILE_TYPE)
                 unlink(fullFileName);
         }
@@ -238,7 +238,7 @@ fileIsAtEnd(FILE * const ifP) {
 
     c = getc(ifP);
     if (c == EOF) {
-        if (feof(ifP)) 
+        if (feof(ifP))
             eof = TRUE;
         else
             pm_error("File error on getc() to position to image");
@@ -248,7 +248,7 @@ fileIsAtEnd(FILE * const ifP) {
         eof = FALSE;
 
         rc = ungetc(c, ifP);
-        if (rc == EOF) 
+        if (rc == EOF)
             pm_error("File error doing ungetc() to position to image.");
     }
     return eof;
@@ -262,14 +262,11 @@ ReadFrameFile(MpegFrame *  const frameP,
               const char * const conversion,
               bool *       const eofP) {
 /*----------------------------------------------------------------------------
-   Read a frame from the file 'ifP'.
+   Read a frame from the file 'ifP', doing adjustments as indicated.
 
    Return *eofP == TRUE iff we encounter EOF before we can get the
    frame.
 -----------------------------------------------------------------------------*/
-    MpegFrame   tempFrame;
-    MpegFrame * framePtr;
-
     /* To make this code fit Netpbm properly, we should remove handling
        of all types except PNM and use pm_nextimage() to handle sensing
        of end of stream.
@@ -278,53 +275,59 @@ ReadFrameFile(MpegFrame *  const frameP,
     if (fileIsAtEnd(ifP))
         *eofP = TRUE;
     else {
+        MpegFrame   preResizeFrame;
+            /* The frame object that holds the frame before resizing */
+        MpegFrame * rawFrameP;
+            /* The frame object with which we read in the raw frame */
+
         *eofP = FALSE;
 
         if (resizeFrame) {
-            tempFrame.inUse = FALSE;
-            tempFrame.orig_y = NULL;
-            tempFrame.y_blocks = NULL;
-            tempFrame.decoded_y = NULL;
-            tempFrame.halfX = NULL;
-            framePtr = &tempFrame;
+            preResizeFrame.inUse = FALSE;
+            preResizeFrame.orig_y = NULL;
+            preResizeFrame.y_blocks = NULL;
+            preResizeFrame.decoded_y = NULL;
+            preResizeFrame.halfX = NULL;
+            rawFrameP = &preResizeFrame;
         } else
-            framePtr = frameP;
+            rawFrameP = frameP;
 
         switch(baseFormat) {
         case YUV_FILE_TYPE:
 
             /* Encoder YUV */
             if ((strncmp (yuvConversion, "EYUV", 4) == 0) ||
-                (strncmp (yuvConversion, "UCB", 3) == 0)) 
+                (strncmp (yuvConversion, "UCB", 3) == 0))
 
-                ReadEYUV(framePtr, ifP, realWidth, realHeight);
+                ReadEYUV(rawFrameP, ifP, realWidth, realHeight);
 
             else
                 /* Abekas-type (interlaced) YUV */
-                ReadAYUV(framePtr, ifP, realWidth, realHeight);
+                ReadAYUV(rawFrameP, ifP, realWidth, realHeight);
 
             break;
         case Y_FILE_TYPE:
-            ReadY(framePtr, ifP, realWidth, realHeight);
+            ReadY(rawFrameP, ifP, realWidth, realHeight);
             break;
         case PNM_FILE_TYPE:
-            ReadPNM(framePtr, ifP);
+            ReadPNM(rawFrameP, ifP);
             break;
         case SUB4_FILE_TYPE:
-            ReadSub4(framePtr, ifP, yuvWidth, yuvHeight);
+            ReadSub4(rawFrameP, ifP, yuvWidth, yuvHeight);
             break;
         case JPEG_FILE_TYPE:
         case JMOVIE_FILE_TYPE:
-            ReadJPEG(framePtr, ifP);
+            ReadJPEG(rawFrameP, ifP);
             break;
         default:
             break;
         }
 
-        if (resizeFrame)
-            Frame_Resize(frameP, &tempFrame, Fsize_x, Fsize_y, 
+        if (resizeFrame) {
+            assert(rawFrameP == &preResizeFrame);
+            Frame_Resize(frameP, &preResizeFrame, Fsize_x, Fsize_y,
                          outputWidth, outputHeight);
-    
+        }
         if (GammaCorrection)
             DoGamma(frameP, Fsize_x, Fsize_y);
 
@@ -338,7 +341,7 @@ ReadFrameFile(MpegFrame *  const frameP,
 
 
 void
-ReadFrame(MpegFrame *          const frameP, 
+ReadFrame(MpegFrame *          const frameP,
           struct inputSource * const inputSourceP,
           unsigned int         const frameNumber,
           const char *         const conversion,
@@ -693,7 +696,7 @@ SeparateLine(fpointer, lineptr, width)
         fprintf(stderr, "       or any even-length string consisting of the letters U, V, and Y.\n");
             exit(1);
         }
-    
+
     }
 
 }
@@ -738,7 +741,7 @@ ReadY(mf, fpointer, width, height)
     for (y = Fsize_y; y < height; y++) {
     safe_fread(junk, 1, width, fpointer);
     }
-    
+
     for (y = 0 ; y < (Fsize_y >> 1); y++) {
       memset(mf->orig_cb[y], 128, (Fsize_x>>1));
       memset(mf->orig_cr[y], 128, (Fsize_x>>1));
@@ -830,7 +833,7 @@ int w,h;
   int i,j;
 
   if (!init_done) {
-    for(i=0; i<256; i++) 
+    for(i=0; i<256; i++)
       GammaVal[i]=(unsigned char) (pow(((double) i)/255.0,GammaValue)*255.0+0.5);
     init_done=TRUE;
   }
@@ -871,7 +874,7 @@ int w,h;
                         ^ kill_dim_break
                              ^kill_dim_end
               kill_dim_slope gives the slope (y = kill_dim_slope * x +0)
-              from 0 to kill_dim_break                      
+              from 0 to kill_dim_break
  *
  *===========================================================================*/
 
@@ -930,7 +933,7 @@ int w,h;
  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  */
 
-/*  
+/*
  *  $Header: /n/picasso/project/mpeg/mpeg_dist/mpeg_encode/RCS/readframe.c,v 1.27 1995/08/14 22:31:40 smoot Exp $
  *  $Log: readframe.c,v $
  *  Revision 1.27  1995/08/14 22:31:40  smoot
diff --git a/converter/ppm/ppmtompeg/specifics.c b/converter/ppm/ppmtompeg/specifics.c
index a8a48af3..bd74e805 100644
--- a/converter/ppm/ppmtompeg/specifics.c
+++ b/converter/ppm/ppmtompeg/specifics.c
@@ -41,6 +41,7 @@
 
 #include "netpbm/mallocvar.h"
 #include "netpbm/nstring.h"
+#include "netpbm/pm_system.h"
 
 #include "all.h"
 #include "mtypes.h"
@@ -67,7 +68,7 @@ void Parse_Specifics_File_v1 (FILE *fp);
 void Parse_Specifics_File_v2 (FILE *fp);
 FrameSpecList *MakeFslEntry (void);
 void AddSlc (FrameSpecList *c,int snum, int qs);
-Block_Specifics *AddBs (FrameSpecList *c,int bnum, 
+Block_Specifics *AddBs (FrameSpecList *c,int bnum,
 				    boolean rel, int qs);
 FrameSpecList *MakeFslEntry (void);
 #define my_upper(c) (((c>='a') && (c<='z')) ? (c-'a'+'A') : c)
@@ -144,7 +145,7 @@ static char version = -1;
  *   Cpp's and reads in the specifics file.  Creates fsl data structure.
  *
  *   Returns: nothing
- * 
+ *
  *   Modifies: fsl, file specificsFile".cpp"
  *
  *================================================================
@@ -152,38 +153,37 @@ static char version = -1;
 void
 Specifics_Init() {
 
-    FILE *specificsFP;
-  
-    {
-        const char * command;
-        pm_asprintf(&command, "rm -f %s.cpp", specificsFile);
-        system(command);
-        pm_strfree(command);
-    }
+    /* 'specificsFile' is a global variable whose value is the name of the
+       specifics file, given by the parameter file.
+    */
+
+    FILE *       specificsFP;
+    const char * preprocessedFileNm;
+
+    pm_message("Specifics file: %s", specificsFile);
+
+    pm_asprintf(&preprocessedFileNm, "%s.cpp", specificsFile);
+
+    pm_system_lp("rm", NULL, NULL, NULL, NULL, "-f", preprocessedFileNm);
+
     {
         const char * command;
-        pm_asprintf(&command, "cpp -P %s %s %s.cpp",
-                    specificsDefines, specificsFile, specificsFile);
-        system(command);
+        pm_asprintf(&command, "cpp -P %s '%s' -o '%s'",
+                    specificsDefines, specificsFile, preprocessedFileNm);
+        pm_system(NULL, NULL, NULL, NULL, command);
         pm_strfree(command);
     }
-    strcat(specificsFile, ".cpp");
-    if ((specificsFP = fopen(specificsFile, "r")) == NULL) {
-        fprintf(stderr, "Error with specifics file, cannot open %s\n",
-                specificsFile);
-        exit(1);
-    }
-    printf("Specifics file: %s\n", specificsFile);
+
+    specificsFP = pm_openr(preprocessedFileNm);
+
+    pm_system_lp("rm", NULL, NULL, NULL, NULL, "-f", preprocessedFileNm);
 
     Parse_Specifics_File(specificsFP);
-    {
-        const char * command;
-        pm_asprintf(&command, "rm -f %s.cpp", specificsFile);
-        system(command);
-        pm_strfree(command);
-    }
-}
 
+    pm_close(specificsFP);
+
+    pm_strfree(preprocessedFileNm);
+}
 
 
 
@@ -244,7 +244,7 @@ FILE *fp;
       fprintf(stderr, "Specifics file: What? *%s*\n", line);
       break;
     }}
-  
+
 }
 
 /* Version 1 */
@@ -253,7 +253,7 @@ FILE *fp;
 {
   char line[1024],*lp;
   FrameSpecList *current, *new;
-  char typ; 
+  char typ;
   int fnum,snum, bnum, qs, newqs;
 
   fsl = MakeFslEntry();
@@ -301,7 +301,7 @@ FILE *fp;
       fprintf(stderr," What? *%s*\n", line);
       break;
     }}
-  
+
 }
 
 
@@ -382,7 +382,7 @@ Parse_Specifics_File_v2(FILE * const fP) {
                 } else {
                     numScanned =
                         2 + sscanf(lp, "%s %d %d %d %d",
-                                   kind, &fx, &fy, &sx, &sy); 
+                                   kind, &fx, &fy, &sx, &sy);
                 }
 
                 qs = newqs;
@@ -573,7 +573,7 @@ int start_qs;
   FrameSpecList *tmp;
   boolean found_it;
   static int leftovers = 0;  /* Used in case of forced movement into 1..31 range */
-  
+
   *info = (BlockMV * )NULL;
   if (last == (FrameSpecList *) NULL){
     /* No cache, try to find number fn */
@@ -590,7 +590,7 @@ int start_qs;
   } else {
     if (last->framenum != fn) { /* cache miss! */
       /* first check if it is next */
-      if ((last->next != (FrameSpecList *) NULL) && 
+      if ((last->next != (FrameSpecList *) NULL) &&
 	  (last->next->framenum == fn)) {
 	last = last->next;
       } else {
@@ -617,13 +617,13 @@ int start_qs;
     fprintf(stderr, "PROGRAMMER ERROR: last has wrong number!\n");
     return -1; /* no data on it */
   }
-  
+
   switch(typ) {
   case 0: /* Frame: num is ignored */
     leftovers = 0;
 #ifdef BLEAH
     printf("QSchange frame %d to %d\n", fn, last->qscale);
-#endif 
+#endif
     return last->qscale;
     break;
 
@@ -683,8 +683,8 @@ int start_qs;
   /* no luck */
   return -1;
 }
-     
-    
+
+
 /*================================================================
  *
  *  SpecTypeLookup
diff --git a/converter/ppm/ppmtopcx.c b/converter/ppm/ppmtopcx.c
index fa68edc5..5b7e1003 100644
--- a/converter/ppm/ppmtopcx.c
+++ b/converter/ppm/ppmtopcx.c
@@ -12,7 +12,7 @@
 **
 ** 11/Dec/94: first version
 ** 12/Dec/94: added handling of "packed" format (16 colors or less)
-** 
+**
 ** ZSoft PCX File Format Technical Reference Manual
 ** http://bespin.org/~qz/pc-gpe/pcx.txt
 ** http://web.archive.org/web/20100206055706/http://www.qzx.com/pc-gpe/pcx.txt
@@ -31,13 +31,13 @@
 #define PCX_MAXVAL      (pixval)255
 
 
-struct cmdlineInfo {
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
-    const char *inputFilespec;  /* '-' if stdin */
+    const char * inputFilespec;  /* '-' if stdin */
     unsigned int truecolor;   /* -24bit option */
-    unsigned int use_8_bit; /* -8bit option */
+    unsigned int use8Bit; /* -8bit option */
     unsigned int planes;    /* zero means minimum */
     unsigned int packed;
     unsigned int verbose;
@@ -49,16 +49,16 @@ struct cmdlineInfo {
 
 
 
-struct pcxCmapEntry {
+struct PcxCmapEntry {
     unsigned char r;
     unsigned char g;
     unsigned char b;
 };
 
-static struct pcxCmapEntry
+static struct PcxCmapEntry
 pcxCmapEntryFromPixel(pixel const colorPixel) {
 
-    struct pcxCmapEntry retval;
+    struct PcxCmapEntry retval;
 
     retval.r = PPM_GETR(colorPixel);
     retval.g = PPM_GETG(colorPixel);
@@ -70,11 +70,11 @@ pcxCmapEntryFromPixel(pixel const colorPixel) {
 
 
 static void
-parseCommandLine(int argc, char ** argv,
-                 struct cmdlineInfo * const cmdlineP) {
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -82,7 +82,7 @@ parseCommandLine(int argc, char ** argv,
    Note that the strings we return are stored in the storage that
    was passed to us as the argv array.  We also trash *argv.
 -----------------------------------------------------------------------------*/
-    optEntry *option_def;
+    optEntry * option_def;
         /* Instructions to pm_optParseOptions3 on how to parse our options.
          */
     optStruct3 opt;
@@ -94,15 +94,15 @@ parseCommandLine(int argc, char ** argv,
     MALLOCARRAY(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0, "24bit",     OPT_FLAG,   NULL,                  
+    OPTENT3(0, "24bit",     OPT_FLAG,   NULL,
             &cmdlineP->truecolor,    0);
-    OPTENT3(0, "8bit",      OPT_FLAG,   NULL,    
-            &cmdlineP->use_8_bit,    0);
-    OPTENT3(0, "planes",    OPT_UINT,   &cmdlineP->planes, 
+    OPTENT3(0, "8bit",      OPT_FLAG,   NULL,
+            &cmdlineP->use8Bit,    0);
+    OPTENT3(0, "planes",    OPT_UINT,   &cmdlineP->planes,
             &planesSpec,             0);
-    OPTENT3(0, "packed",    OPT_FLAG,   NULL,                  
+    OPTENT3(0, "packed",    OPT_FLAG,   NULL,
             &cmdlineP->packed,       0);
-    OPTENT3(0, "verbose",   OPT_FLAG,   NULL,                  
+    OPTENT3(0, "verbose",   OPT_FLAG,   NULL,
             &cmdlineP->verbose,      0);
     OPTENT3(0, "stdpalette", OPT_FLAG,  NULL,
             &cmdlineP->stdpalette,   0);
@@ -115,7 +115,7 @@ parseCommandLine(int argc, char ** argv,
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3( &argc, argv, opt, sizeof(opt), 0 );
+    pm_optParseOptions3( &argc, (char **)argv, opt, sizeof(opt), 0 );
         /* Uses and sets argc, argv, and some of *cmdline_p and others. */
 
     if (!xposSpec)
@@ -141,17 +141,17 @@ parseCommandLine(int argc, char ** argv,
             pm_error("-planes is meaningless with -packed.");
         if (cmdlineP->truecolor)
             pm_error("-planes is meaningless with -24bit");
-        if (cmdlineP->use_8_bit)
+        if (cmdlineP->use8Bit)
             pm_error("-planes is meaningless with -8bit");
     }
-    
+
     if (paletteSpec && cmdlineP->stdpalette)
         pm_error("You can't specify both -palette and -stdpalette");
 
     if (!paletteSpec)
         cmdlineP->palette = NULL;
 
-    if (cmdlineP->use_8_bit && cmdlineP->truecolor) 
+    if (cmdlineP->use8Bit && cmdlineP->truecolor)
         pm_error("You cannot specify both -8bit and -truecolor");
 
     if (argc-1 < 1)
@@ -172,11 +172,11 @@ parseCommandLine(int argc, char ** argv,
  * Write out a two-byte little-endian word to the PCX file
  */
 static void
-Putword(int    const w, 
-        FILE * const fp) {
+putword(unsigned int const w,
+        FILE *       const fp) {
 
     int rc;
-    
+
     rc = pm_writelittleshort(fp, w);
 
     if (rc != 0)
@@ -189,26 +189,24 @@ Putword(int    const w,
  * Write out a byte to the PCX file
  */
 static void
-Putbyte(int    const b, 
-        FILE * const fp) {
+putbyte(unsigned int const b,
+        FILE *       const ofP) {
 
     int rc;
 
-    rc = fputc(b & 0xff, fp);
+    rc = fputc(b & 0xff, ofP);
+
     if (rc == EOF)
         pm_error("Error writing byte to output file.");
 }
 
 
 
-static const unsigned char bitmask[] = {1, 2, 4, 8, 16, 32, 64, 128};
-
-
 static void
-extractPlane(unsigned char * const rawrow, 
-             int             const cols, 
-             unsigned char * const buf, 
-             int             const plane) {
+extractPlane(unsigned char * const rawrow,
+             unsigned int    const cols,
+             unsigned char * const buf,
+             unsigned int    const plane) {
 /*----------------------------------------------------------------------------
    From the image row 'rawrow', which is an array of 'cols' palette indices
    (as unsigned 8 bit integers), extract plane number 'plane' and return
@@ -223,12 +221,10 @@ extractPlane(unsigned char * const rawrow,
     int cbit;  /* Significance of bit representing current column in output */
     unsigned char *cp;  /* Ptr to next output byte to fill */
     unsigned char byteUnderConstruction;
-    
+
     cp = buf;  /* initial value */
 
-    cbit = 7;
-    byteUnderConstruction = 0x00;
-    for (col = 0; col < cols; ++col) {
+    for (col = 0, cbit = 7, byteUnderConstruction = 0x00; col < cols; ++col) {
         if (rawrow[col] & planeMask)
             byteUnderConstruction |= (1 << cbit);
 
@@ -250,14 +246,17 @@ extractPlane(unsigned char * const rawrow,
 
 
 static void
-PackBits(unsigned char * const rawrow, 
-         int             const width, 
-         unsigned char * const buf, 
-         int             const bits) {
+packBits(unsigned char * const rawrow,
+         unsigned int    const width,
+         unsigned char * const buf,
+         unsigned int    const bits) {
 
-    int x, i, shift;
+    unsigned int x;
+    int i;
+    int shift;
 
-    shift = i = -1;
+    shift = -1;
+    i = -1;
 
     for (x = 0; x < width; ++x) {
         if (shift < 0) {
@@ -273,71 +272,73 @@ PackBits(unsigned char * const rawrow,
 
 
 static void
-write_header(FILE *              const fp, 
-             int                 const cols, 
-             int                 const rows, 
-             int                 const BitsPerPixel, 
-             int                 const Planes, 
-             struct pcxCmapEntry const cmap16[],
-             unsigned int        const xPos, 
-             unsigned int        const yPos) {
-
-    int i, BytesPerLine;
-
-    Putbyte(PCX_MAGIC, fp);        /* .PCX magic number            */
-    Putbyte(0x05, fp);             /* PC Paintbrush version        */
-    Putbyte(0x01, fp);             /* .PCX run length encoding     */
-    Putbyte(BitsPerPixel, fp);     /* bits per pixel               */
-    
-    Putword(xPos, fp);             /* x1   - image left            */
-    Putword(yPos, fp);             /* y1   - image top             */
-    Putword(xPos+cols-1, fp);      /* x2   - image right           */
-    Putword(yPos+rows-1, fp);      /* y2   - image bottom          */
-
-    Putword(cols, fp);             /* horizontal resolution        */
-    Putword(rows, fp);             /* vertical resolution          */
+writeHeader(FILE *              const ofP,
+            unsigned int        const cols,
+            unsigned int        const rows,
+            unsigned int        const bitsPerPixel,
+            unsigned int        const planes,
+            struct PcxCmapEntry const cmap16[],
+            unsigned int        const xPos,
+            unsigned int        const yPos) {
+
+    unsigned int bytesPerLine;
+
+    putbyte(PCX_MAGIC, ofP);        /* .PCX magic number            */
+    putbyte(0x05, ofP);             /* PC Paintbrush version        */
+    putbyte(0x01, ofP);             /* .PCX run length encoding     */
+    putbyte(bitsPerPixel, ofP);     /* bits per pixel               */
+
+    putword(xPos, ofP);             /* x1   - image left            */
+    putword(yPos, ofP);             /* y1   - image top             */
+    putword(xPos+cols-1, ofP);      /* x2   - image right           */
+    putword(yPos+rows-1, ofP);      /* y2   - image bottom          */
+
+    putword(cols, ofP);             /* horizontal resolution        */
+    putword(rows, ofP);             /* vertical resolution          */
 
     /* Write out the Color Map for images with 16 colors or less */
-    if (cmap16)
+    if (cmap16) {
+        unsigned int i;
         for (i = 0; i < 16; ++i) {
-            Putbyte(cmap16[i].r, fp);
-            Putbyte(cmap16[i].g, fp);
-            Putbyte(cmap16[i].b, fp);
+            putbyte(cmap16[i].r, ofP);
+            putbyte(cmap16[i].g, ofP);
+            putbyte(cmap16[i].b, ofP);
         }
-    else {
+    } else {
         unsigned int i;
         for (i = 0; i < 16; ++i) {
-            Putbyte(0, fp);
-            Putbyte(0, fp);
-            Putbyte(0, fp);
+            putbyte(0, ofP);
+            putbyte(0, ofP);
+            putbyte(0, ofP);
         }
     }
-    Putbyte(0, fp);                /* reserved byte                */
-    Putbyte(Planes, fp);           /* number of color planes       */
+    putbyte(0, ofP);                /* reserved byte                */
+    putbyte(planes, ofP);           /* number of color planes       */
 
-    BytesPerLine = ((cols * BitsPerPixel) + 7) / 8;
-    Putword(BytesPerLine, fp);    /* number of bytes per scanline */
+    bytesPerLine = ((cols * bitsPerPixel) + 7) / 8;
+    putword(bytesPerLine, ofP);    /* number of bytes per scanline */
 
-    Putword(1, fp);                /* palette info                 */
+    putword(1, ofP);                /* palette info                 */
 
     {
         unsigned int i;
         for (i = 0; i < 58; ++i)        /* fill to end of header        */
-            Putbyte(0, fp);
+            putbyte(0, ofP);
     }
 }
 
 
 
 static void
-PCXEncode(FILE *                const fp, 
-          const unsigned char * const buf, 
-          int                   const Size) {
+pcxEncode(FILE *                const ofP,
+          const unsigned char * const buf,
+          unsigned int          const size) {
 
-    const unsigned char * const end = buf + Size;
+    const unsigned char * const end = buf + size;
 
     const unsigned char * currentP;
-    int previous, count;
+    unsigned int          previous;
+    unsigned int          count;
 
     currentP = buf;
     previous = *currentP++;
@@ -350,19 +351,19 @@ PCXEncode(FILE *                const fp,
         else {
             if (count > 1 || (previous & 0xc0) == 0xc0) {
                 count |= 0xc0;
-                Putbyte ( count , fp );
+                putbyte ( count , ofP );
             }
-            Putbyte(previous, fp);
+            putbyte(previous, ofP);
             previous = c;
-            count   = 1;
+            count = 1;
         }
     }
 
     if (count > 1 || (previous & 0xc0) == 0xc0) {
         count |= 0xc0;
-        Putbyte ( count , fp );
+        putbyte(count, ofP);
     }
-    Putbyte(previous, fp);
+    putbyte(previous, ofP);
 }
 
 
@@ -377,10 +378,10 @@ indexOfColor(colorhash_table const cht,
 -----------------------------------------------------------------------------*/
 
     int const rc = ppm_lookupcolor(cht, &color);
-            
+
     if (rc < 0)
         pm_error("Image contains color which is not "
-                 "in the palette: %u/%u/%u", 
+                 "in the palette: %u/%u/%u",
                  PPM_GETR(color), PPM_GETG(color), PPM_GETB(color));
 
     return rc;
@@ -389,61 +390,46 @@ indexOfColor(colorhash_table const cht,
 
 
 static void
-ppmTo16ColorPcx(pixel **            const pixels, 
-                int                 const cols, 
-                int                 const rows, 
-                struct pcxCmapEntry const pcxcmap[], 
-                int                 const colors, 
-                colorhash_table     const cht, 
-                bool                const packbits,
-                unsigned int        const planesRequested,
-                unsigned int        const xPos,
-                unsigned int        const yPos) {
+writeRaster16Color(FILE * const ofP,
+                   pixel **            const pixels,
+                   unsigned int        const cols,
+                   unsigned int        const rows,
+                   unsigned int        const planes,
+                   colorhash_table     const cht,
+                   bool                const packbits,
+                   unsigned int        const bitsPerPixel) {
+
+    unsigned int const bytesPerLine = ((cols * bitsPerPixel) + 7) / 8;
+
+    unsigned char * indexRow;  /* malloc'ed */
+    /* indexRow[x] is the palette index of the pixel at column x of
+       the row currently being processed
+    */
+    unsigned char * planesrow; /* malloc'ed */
+    /* This is the input for a single row to the compressor */
 
-    int Planes, BytesPerLine, BitsPerPixel;
-    unsigned char *indexRow;  /* malloc'ed */
-        /* indexRow[x] is the palette index of the pixel at column x of
-           the row currently being processed
-        */
-    unsigned char *planesrow; /* malloc'ed */
-        /* This is the input for a single row to the compressor */
-    int row;
+    unsigned int row;
 
-    if (packbits) {
-        Planes = 1;
-        if (colors > 4)        BitsPerPixel = 4;
-        else if (colors > 2)   BitsPerPixel = 2;
-        else                   BitsPerPixel = 1;
-    } else {
-        BitsPerPixel = 1;
-        if (planesRequested)
-            Planes = planesRequested;
-        else {
-            if (colors > 8)        Planes = 4;
-            else if (colors > 4)   Planes = 3;
-            else if (colors > 2)   Planes = 2;
-            else                   Planes = 1;
-        }
-    }
-    BytesPerLine = ((cols * BitsPerPixel) + 7) / 8;
     MALLOCARRAY_NOFAIL(indexRow, cols);
-    MALLOCARRAY_NOFAIL(planesrow, BytesPerLine);
+    MALLOCARRAY(planesrow, bytesPerLine);
+
+    if (!planesrow)
+        pm_error("Failed to allocate buffer for a line of %u bytes",
+                 bytesPerLine);
 
-    write_header(stdout, cols, rows, BitsPerPixel, Planes, pcxcmap, 
-                 xPos, yPos);
     for (row = 0; row < rows; ++row) {
-        int col;
+        unsigned int col;
         for (col = 0; col < cols; ++col)
             indexRow[col] = indexOfColor(cht, pixels[row][col]);
 
         if (packbits) {
-            PackBits(indexRow, cols, planesrow, BitsPerPixel);
-            PCXEncode(stdout, planesrow, BytesPerLine);
+            packBits(indexRow, cols, planesrow, bitsPerPixel);
+            pcxEncode(ofP, planesrow, bytesPerLine);
         } else {
             unsigned int plane;
-            for (plane = 0; plane < Planes; ++plane) {
+            for (plane = 0; plane < planes; ++plane) {
                 extractPlane(indexRow, cols, planesrow, plane);
-                PCXEncode(stdout, planesrow, BytesPerLine);
+                pcxEncode(stdout, planesrow, bytesPerLine);
             }
         }
     }
@@ -454,83 +440,142 @@ ppmTo16ColorPcx(pixel **            const pixels,
 
 
 static void
-ppmTo256ColorPcx(pixel **            const pixels, 
-                 int                 const cols, 
-                 int                 const rows, 
-                 struct pcxCmapEntry const pcxcmap[], 
-                 int                 const colors, 
+ppmTo16ColorPcx(pixel **            const pixels,
+                unsigned int        const cols,
+                unsigned int        const rows,
+                struct PcxCmapEntry const pcxcmap[],
+                unsigned int        const colorCt,
+                colorhash_table     const cht,
+                bool                const packbits,
+                unsigned int        const planesRequested,
+                unsigned int        const xPos,
+                unsigned int        const yPos) {
+
+    unsigned int planes;
+    unsigned int bitsPerPixel;
+
+    if (packbits) {
+        planes = 1;
+        if (colorCt > 4)        bitsPerPixel = 4;
+        else if (colorCt > 2)   bitsPerPixel = 2;
+        else                    bitsPerPixel = 1;
+    } else {
+        bitsPerPixel = 1;
+        if (planesRequested)
+            planes = planesRequested;
+        else {
+            if (colorCt > 8)        planes = 4;
+            else if (colorCt > 4)   planes = 3;
+            else if (colorCt > 2)   planes = 2;
+            else                   planes = 1;
+        }
+    }
+
+    writeHeader(stdout, cols, rows, bitsPerPixel, planes, pcxcmap,
+                xPos, yPos);
+
+    writeRaster16Color(stdout, pixels, cols, rows, planes, cht, packbits,
+                       bitsPerPixel);
+}
+
+
+
+static void
+ppmTo256ColorPcx(pixel **            const pixels,
+                 unsigned int        const cols,
+                 unsigned int        const rows,
+                 struct PcxCmapEntry const pcxcmap[],
+                 unsigned int        const colorCt,
                  colorhash_table     const cht,
-                 unsigned int        const xPos, 
+                 unsigned int        const xPos,
                  unsigned int        const yPos) {
 
-    int row;
-    unsigned int i;
-    unsigned char *rawrow;
+    unsigned char * rawrow;
+    unsigned int    row;
+
+    MALLOCARRAY(rawrow, cols);
 
-    rawrow = (unsigned char *)pm_allocrow(cols, sizeof(unsigned char));
+    if (!rawrow)
+        pm_error("Failed to allocate a buffer for %u columns", cols);
 
     /* 8 bits per pixel, 1 plane */
-    write_header(stdout, cols, rows, 8, 1, NULL, xPos, yPos);
+    writeHeader(stdout, cols, rows, 8, 1, NULL, xPos, yPos);
     for (row = 0; row < rows; ++row) {
-        int col;
+        unsigned int col;
         for (col = 0; col < cols; ++col)
             rawrow[col] = indexOfColor(cht, pixels[row][col]);
-        PCXEncode(stdout, rawrow, cols);
+        pcxEncode(stdout, rawrow, cols);
+
     }
-    Putbyte(PCX_256_COLORS, stdout);
-    for (i = 0; i < MAXCOLORS; ++i) {
-        Putbyte(pcxcmap[i].r, stdout);
-        Putbyte(pcxcmap[i].g, stdout);
-        Putbyte(pcxcmap[i].b, stdout);
+    putbyte(PCX_256_COLORS, stdout);
+
+    {
+        unsigned int i;
+
+        for (i = 0; i < MAXCOLORS; ++i) {
+            putbyte(pcxcmap[i].r, stdout);
+            putbyte(pcxcmap[i].g, stdout);
+            putbyte(pcxcmap[i].b, stdout);
+        }
     }
-    pm_freerow((void*)rawrow);
+    free(rawrow);
 }
 
 
 
 static void
-ppmToTruecolorPcx(pixel **     const pixels, 
-                  int          const cols, 
-                  int          const rows, 
+ppmToTruecolorPcx(pixel **     const pixels,
+                  unsigned int const cols,
+                  unsigned int const rows,
                   pixval       const maxval,
-                  unsigned int const xPos, 
+                  unsigned int const xPos,
                   unsigned int const yPos) {
 
-    unsigned char *redrow, *greenrow, *bluerow;
-    int col, row;
+    unsigned char * redrow;
+    unsigned char * grnrow;
+    unsigned char * blurow;
+    unsigned int    row;
+
+    MALLOCARRAY(redrow, cols);
+    MALLOCARRAY(grnrow, cols);
+    MALLOCARRAY(blurow, cols);
 
-    redrow   = (unsigned char *)pm_allocrow(cols, sizeof(unsigned char));
-    greenrow = (unsigned char *)pm_allocrow(cols, sizeof(unsigned char));
-    bluerow  = (unsigned char *)pm_allocrow(cols, sizeof(unsigned char));
+    if (!redrow || !grnrow || !blurow)
+        pm_error("Unable to allocate buffer for a row of %u pixels", cols);
 
     /* 8 bits per pixel, 3 planes */
-    write_header(stdout, cols, rows, 8, 3, NULL, xPos, yPos);
-    for( row = 0; row < rows; row++ ) {
-        register pixel *pP = pixels[row];
-        for( col = 0; col < cols; col++, pP++ ) {
-            if( maxval != PCX_MAXVAL ) {
-                redrow[col]   = (long)PPM_GETR(*pP) * PCX_MAXVAL / maxval;
-                greenrow[col] = (long)PPM_GETG(*pP) * PCX_MAXVAL / maxval;
-                bluerow[col]  = (long)PPM_GETB(*pP) * PCX_MAXVAL / maxval;
-            }
-            else {
-                redrow[col]   = PPM_GETR(*pP);
-                greenrow[col] = PPM_GETG(*pP);
-                bluerow[col]  = PPM_GETB(*pP);
+    writeHeader(stdout, cols, rows, 8, 3, NULL, xPos, yPos);
+
+    for (row = 0; row < rows; ++row) {
+        pixel * const pixrow = pixels[row];
+
+        unsigned int col;
+
+        for (col = 0; col < cols; ++col) {
+            pixel const pix = pixrow[col];
+
+            if (maxval != PCX_MAXVAL) {
+                redrow[col] = (long)PPM_GETR(pix) * PCX_MAXVAL / maxval;
+                grnrow[col] = (long)PPM_GETG(pix) * PCX_MAXVAL / maxval;
+                blurow[col] = (long)PPM_GETB(pix) * PCX_MAXVAL / maxval;
+            } else {
+                redrow[col] = PPM_GETR(pix);
+                grnrow[col] = PPM_GETG(pix);
+                blurow[col] = PPM_GETB(pix);
             }
         }
-        PCXEncode(stdout, redrow, cols);
-        PCXEncode(stdout, greenrow, cols);
-        PCXEncode(stdout, bluerow, cols);
+        pcxEncode(stdout, redrow, cols);
+        pcxEncode(stdout, grnrow, cols);
+        pcxEncode(stdout, blurow, cols);
     }
-    pm_freerow((void*)bluerow);
-    pm_freerow((void*)greenrow);
-    pm_freerow((void*)redrow);
+    free(blurow);
+    free(grnrow);
+    free(redrow);
 }
 
 
 
-static const struct pcxCmapEntry 
+static const struct PcxCmapEntry
 stdPalette[] = {
     {   0,   0,   0 },
     {   0,   0, 170 },
@@ -565,7 +610,7 @@ putPcxColorInHash(colorhash_table const cht,
     int rc;
 
     PPM_DEPTH(ppmColor, newPcxColor, PCX_MAXVAL, maxval);
-        
+
     rc = ppm_lookupcolor(cht, &ppmColor);
 
     if (rc == -1)
@@ -577,8 +622,8 @@ putPcxColorInHash(colorhash_table const cht,
            'maxval' is less than PCX_MAXVAL), and two distinct
            colors in the standard palette are indistinguishable at
            subject image color resolution.
-           
-           So we have to figure out wether color 'newPcxColor' or
+
+           So we have to figure out whether color 'newPcxColor' or
            'existingPcxColor' is a better match for 'ppmColor'.
         */
 
@@ -588,8 +633,8 @@ putPcxColorInHash(colorhash_table const cht,
         pixel existingPcxColor;
 
         PPM_DEPTH(idealPcxColor, ppmColor, maxval, PCX_MAXVAL);
-        
-        PPM_ASSIGN(existingPcxColor, 
+
+        PPM_ASSIGN(existingPcxColor,
                    stdPalette[existingColorIndex].r,
                    stdPalette[existingColorIndex].g,
                    stdPalette[existingColorIndex].b);
@@ -608,19 +653,18 @@ putPcxColorInHash(colorhash_table const cht,
 
 
 static void
-generateStandardPalette(struct pcxCmapEntry ** const pcxcmapP,
+generateStandardPalette(struct PcxCmapEntry ** const pcxcmapP,
                         pixval                 const maxval,
                         colorhash_table *      const chtP,
-                        int *                  const colorsP) {
+                        unsigned int *         const colorsP) {
 
     unsigned int const stdPaletteSize = 16;
-    unsigned int colorIndex;
-    struct pcxCmapEntry * pcxcmap;
-    colorhash_table cht;
+
+    unsigned int          colorIndex;
+    struct PcxCmapEntry * pcxcmap;
+    colorhash_table       cht;
 
     MALLOCARRAY_NOFAIL(pcxcmap, MAXCOLORS);
-    
-    *pcxcmapP = pcxcmap;
 
     cht = ppm_alloccolorhash();
 
@@ -629,8 +673,8 @@ generateStandardPalette(struct pcxCmapEntry ** const pcxcmapP,
             /* The color of this colormap entry, in PCX resolution */
 
         pcxcmap[colorIndex] = stdPalette[colorIndex];
-        
-        PPM_ASSIGN(pcxColor, 
+
+        PPM_ASSIGN(pcxColor,
                    stdPalette[colorIndex].r,
                    stdPalette[colorIndex].g,
                    stdPalette[colorIndex].b);
@@ -648,65 +692,65 @@ generateStandardPalette(struct pcxCmapEntry ** const pcxcmapP,
         pcxcmap[colorIndex].b = 0;
     }
 
+    *pcxcmapP = pcxcmap;
     *chtP = cht;
     *colorsP = stdPaletteSize;
 }
-    
+
 
 
 static void
 readPpmPalette(const char *   const paletteFileName,
-               pixel       (* const ppmPaletteP)[], 
+               pixel       (* const ppmPaletteP)[],
                unsigned int * const paletteSizeP) {
 
     FILE * pfP;
     pixel ** pixels;
     int cols, rows;
     pixval maxval;
-    
+
     pfP = pm_openr(paletteFileName);
 
     pixels = ppm_readppm(pfP, &cols, &rows, &maxval);
 
     pm_close(pfP);
-    
+
     *paletteSizeP = rows * cols;
-    if (*paletteSizeP > MAXCOLORS) 
+    if (*paletteSizeP > MAXCOLORS)
         pm_error("ordered palette image contains %d pixels.  Maximum is %d",
                  *paletteSizeP, MAXCOLORS);
 
     {
-        int j;
-        int row;
-        j = 0;  /* initial value */
-        for (row = 0; row < rows; ++row) {
-            int col;
-            for (col = 0; col < cols; ++col) 
+        unsigned int j;
+        unsigned int row;
+        for (row = 0, j = 0; row < rows; ++row) {
+            unsigned int col;
+            for (col = 0; col < cols; ++col)
                 (*ppmPaletteP)[j++] = pixels[row][col];
         }
     }
     ppm_freearray(pixels, rows);
-}        
+}
 
 
 
 static void
-readPaletteFromFile(struct pcxCmapEntry ** const pcxcmapP,
+readPaletteFromFile(struct PcxCmapEntry ** const pcxcmapP,
                     const char *           const paletteFileName,
                     pixval                 const maxval,
                     colorhash_table *      const chtP,
-                    int *                  const colorsP) {
+                    unsigned int *         const colorsP) {
 
     unsigned int colorIndex;
     pixel ppmPalette[MAXCOLORS];
     unsigned int paletteSize;
-    struct pcxCmapEntry * pcxcmap;
+    struct PcxCmapEntry * pcxcmap;
     colorhash_table cht;
 
     readPpmPalette(paletteFileName, &ppmPalette, &paletteSize);
 
     MALLOCARRAY_NOFAIL(pcxcmap, MAXCOLORS);
-    
+
     *pcxcmapP = pcxcmap;
 
     cht = ppm_alloccolorhash();
@@ -716,8 +760,8 @@ readPaletteFromFile(struct pcxCmapEntry ** const pcxcmapP,
             /* The color of this colormap entry, in PCX resolution */
 
         pcxcmap[colorIndex] = pcxCmapEntryFromPixel(ppmPalette[colorIndex]);
-        
-        PPM_ASSIGN(pcxColor, 
+
+        PPM_ASSIGN(pcxColor,
                    ppmPalette[colorIndex].r,
                    ppmPalette[colorIndex].g,
                    ppmPalette[colorIndex].b);
@@ -728,12 +772,12 @@ readPaletteFromFile(struct pcxCmapEntry ** const pcxcmapP,
     *chtP = cht;
     *colorsP = paletteSize;
 }
-    
+
 
 
 static void
 moveBlackToIndex0(colorhist_vector const chv,
-                  int              const colors) {
+                  unsigned int     const colorCt) {
 /*----------------------------------------------------------------------------
    If black is in the palette, make it at Index 0.
 -----------------------------------------------------------------------------*/
@@ -745,19 +789,20 @@ moveBlackToIndex0(colorhist_vector const chv,
 
     blackPresent = FALSE;  /* initial assumption */
 
-    for (i = 0; i < colors; ++i)
+    for (i = 0; i < colorCt; ++i)
         if (PPM_EQUAL(chv[i].color, blackPixel))
             blackPresent = TRUE;
-            
+
     if (blackPresent) {
         /* We use a trick here.  ppm_addtocolorhist() always adds to the
            beginning of the table and if the color is already elsewhere in
            the table, removes it.
         */
-        int colors2;
-        colors2 = colors;
-        ppm_addtocolorhist(chv, &colors2, MAXCOLORS, &blackPixel, 0, 0);
-        assert(colors2 == colors);
+        int colorCt2;
+
+        colorCt2 = colorCt;
+        ppm_addtocolorhist(chv, &colorCt2, MAXCOLORS, &blackPixel, 0, 0);
+        assert(colorCt2 == colorCt);
     }
 }
 
@@ -765,12 +810,12 @@ moveBlackToIndex0(colorhist_vector const chv,
 
 static void
 makePcxColormapFromImage(pixel **               const pixels,
-                         int                    const cols,
-                         int                    const rows,
+                         unsigned int           const cols,
+                         unsigned int           const rows,
                          pixval                 const maxval,
-                         struct pcxCmapEntry ** const pcxcmapP,
+                         struct PcxCmapEntry ** const pcxcmapP,
                          colorhash_table *      const chtP,
-                         int *                  const colorsP,
+                         unsigned int *         const colorCtP,
                          bool *                 const tooManyColorsP) {
 /*----------------------------------------------------------------------------
    Make a colormap (palette) for the PCX header that can be used
@@ -780,35 +825,35 @@ makePcxColormapFromImage(pixel **               const pixels,
    *pcxcmapP.
 
    Also return a lookup hash to relate a color in the image to the
-   appropriate index in *pcxcmapP.  Return that in newly malloc'ed 
+   appropriate index in *pcxcmapP.  Return that in newly malloc'ed
    storage as *chtP.
 
-   Iff there are too many colors to do that (i.e. more than 256), 
+   Iff there are too many colors to do that (i.e. more than 256),
    return *tooManyColorsP == TRUE.
 -----------------------------------------------------------------------------*/
-    int colors;
+    int colorCt;
     colorhist_vector chv;
 
     pm_message("computing colormap...");
 
-    chv = ppm_computecolorhist(pixels, cols, rows, MAXCOLORS, &colors);
+    chv = ppm_computecolorhist(pixels, cols, rows, MAXCOLORS, &colorCt);
     if (chv == NULL)
         *tooManyColorsP = TRUE;
     else {
-        int i;
-        struct pcxCmapEntry * pcxcmap;
+        unsigned int i;
+        struct PcxCmapEntry * pcxcmap;
 
         *tooManyColorsP = FALSE;
 
-        pm_message("%d colors found", colors);
-        
-        moveBlackToIndex0(chv, colors);
+        pm_message("%d colors found", colorCt);
+
+        moveBlackToIndex0(chv, colorCt);
 
         MALLOCARRAY_NOFAIL(pcxcmap, MAXCOLORS);
 
         *pcxcmapP = pcxcmap;
 
-        for (i = 0; i < colors; ++i) {
+        for (i = 0; i < colorCt; ++i) {
             pixel p;
 
             PPM_DEPTH(p, chv[i].color, maxval, PCX_MAXVAL);
@@ -825,9 +870,9 @@ makePcxColormapFromImage(pixel **               const pixels,
             pcxcmap[i].b = 0;
         }
 
-        *chtP = ppm_colorhisttocolorhash(chv, colors);
+        *chtP = ppm_colorhisttocolorhash(chv, colorCt);
 
-        *colorsP = colors;
+        *colorCtP = colorCt;
 
         ppm_freecolorhist(chv);
     }
@@ -835,45 +880,45 @@ makePcxColormapFromImage(pixel **               const pixels,
 
 
 
-static void 
-ppmToPalettePcx(pixel **            const pixels, 
-                int                 const cols, 
-                int                 const rows,
+static void
+ppmToPalettePcx(pixel **            const pixels,
+                unsigned int        const cols,
+                unsigned int        const rows,
                 pixval              const maxval,
-                unsigned int        const xPos, 
+                unsigned int        const xPos,
                 unsigned int        const yPos,
-                struct pcxCmapEntry const pcxcmap[],
+                struct PcxCmapEntry const pcxcmap[],
                 colorhash_table     const cht,
-                int                 const colors,
+                unsigned int        const colorCt,
                 bool                const packbits,
                 unsigned int        const planes,
-                bool                const use_8_bit) {
-    
+                bool                const use8Bit) {
+
     /* convert image */
-    if( colors <= 16 && !use_8_bit )
-        ppmTo16ColorPcx(pixels, cols, rows, pcxcmap, colors, cht, 
+    if (colorCt <= 16 && !use8Bit )
+        ppmTo16ColorPcx(pixels, cols, rows, pcxcmap, colorCt, cht,
                         packbits, planes, xPos, yPos);
     else
-        ppmTo256ColorPcx(pixels, cols, rows, pcxcmap, colors, cht,
+        ppmTo256ColorPcx(pixels, cols, rows, pcxcmap, colorCt, cht,
                          xPos, yPos);
 }
 
 
 
 int
-main(int argc, char *argv[]) {
+main(int argc, const char *argv[]) {
 
-    struct cmdlineInfo cmdline;
-    FILE* ifP;
+    struct CmdlineInfo cmdline;
+    FILE * ifP;
     int rows, cols;
     pixval maxval;
     pixel **pixels;
-    struct pcxCmapEntry * pcxcmap;
+    struct PcxCmapEntry * pcxcmap;
     colorhash_table cht;
     bool truecolor;
-    int colors;
+    unsigned int colorCt;
 
-    ppm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
@@ -886,17 +931,17 @@ main(int argc, char *argv[]) {
     else {
         if (cmdline.stdpalette) {
             truecolor = FALSE;
-            generateStandardPalette(&pcxcmap, maxval, &cht, &colors);
+            generateStandardPalette(&pcxcmap, maxval, &cht, &colorCt);
         } else if (cmdline.palette) {
             truecolor = FALSE;
-            readPaletteFromFile(&pcxcmap, cmdline.palette, maxval, 
-                                &cht, &colors);
+            readPaletteFromFile(&pcxcmap, cmdline.palette, maxval,
+                                &cht, &colorCt);
         } else {
             bool tooManyColors;
             makePcxColormapFromImage(pixels, cols, rows, maxval,
-                                     &pcxcmap, &cht, &colors,
+                                     &pcxcmap, &cht, &colorCt,
                                      &tooManyColors);
-            
+
             if (tooManyColors) {
                 pm_message("too many colors - writing a 24bit PCX file");
                 pm_message("if you want a non-24bit file, "
@@ -908,16 +953,19 @@ main(int argc, char *argv[]) {
     }
 
     if (truecolor)
-        ppmToTruecolorPcx(pixels, cols, rows, maxval, 
+        ppmToTruecolorPcx(pixels, cols, rows, maxval,
                           cmdline.xpos, cmdline.ypos);
     else {
-        ppmToPalettePcx(pixels, cols, rows, maxval, 
+        ppmToPalettePcx(pixels, cols, rows, maxval,
                         cmdline.xpos, cmdline.ypos,
-                        pcxcmap, cht, colors, cmdline.packed, 
-                        cmdline.planes, cmdline.use_8_bit);
-        
+                        pcxcmap, cht, colorCt, cmdline.packed,
+                        cmdline.planes, cmdline.use8Bit);
+
         ppm_freecolorhash(cht);
         free(pcxcmap);
     }
     return 0;
 }
+
+
+
diff --git a/converter/ppm/ppmtospu.c b/converter/ppm/ppmtospu.c
index b558c1fe..a6acbaa0 100644
--- a/converter/ppm/ppmtospu.c
+++ b/converter/ppm/ppmtospu.c
@@ -292,7 +292,7 @@ computePalette(struct PixelType * const pixelType) {
 
     /* Uses popularity algorithm */
 
-    /* Count the occurences of each color */
+    /* Count the occurrences of each color */
 
     for (i = 0; i < 512; ++i)
         hist[i] = 0;
diff --git a/converter/ppm/sldtoppm.c b/converter/ppm/sldtoppm.c
index 2dc049f8..2fef0233 100644
--- a/converter/ppm/sldtoppm.c
+++ b/converter/ppm/sldtoppm.c
@@ -600,7 +600,7 @@ slider(slvecfn   slvec,
             curcolor = cw & 0xFF;
             break;
 
-        default:              /*  Co-ordinates  */
+        default:              /*  Coordinates  */
             lx = vec.f.x = cw;
             ly = vec.f.y = sli();
             vec.t.x = sli();
diff --git a/converter/ppm/xim.h b/converter/ppm/xim.h
index 70a9a761..116312bb 100644
--- a/converter/ppm/xim.h
+++ b/converter/ppm/xim.h
@@ -6,7 +6,7 @@
 ** Taken from the X.V11R4 version of XimHeader.h:
 **
 ** Author: Philip R. Thompson
-** Address:  phils@athena.mit.edu, 9-526 
+** Address:  phils@athena.mit.edu, 9-526
 ** Note:  size of header should be 1024 (1K) bytes.
 ** $Header: /mit/phils/X/RCS/XimHeader.h,v 1.7 89/11/09 17:26:54 phils Exp Locker: phils $
 ** $Date: 89/11/09 17:26:54 $
@@ -24,7 +24,7 @@ typedef struct ImageHeader {
     char file_version[8];   /* header version */
     char header_size[8];    /* Size of file header in bytes  */
     char image_width[8];    /* Width of the raster image */
-    char image_height[8];   /* Height of the raster imgage */
+    char image_height[8];   /* Height of the raster image */
     char num_colors[8];     /* Actual number of entries in c_map */
     char num_channels[3];   /* 0 or 1 = pixmap, 3 = RG&B buffers */
     char bytes_per_line[5]; /* bytes per scanline */
@@ -63,9 +63,9 @@ typedef struct XimImage {
     short tpics, npics;    /* number of images, total & left in file */
     short ncolors;         /*   "    "  colors in the color table */
     Color* colors;         /* colortable, one byte per r/g/b & pixel */
-    const char* author;    /* author credit, copyright, etc */
-    const char* date;      /* date image was made, grabbed, etc. */
-    const char* program;   /* program used to make this */
+    const char* author;         /* author credit, copyright, etc */
+    const char* date;           /* date image was made, grabbed, etc. */
+    const char* program;        /* program used to make this */
     short ncomments;       /* number of comments strings */
     char** comments;      /* pointers to null terminated strings */
     char* offset;         /* original offset in machine memory */
@@ -81,7 +81,7 @@ typedef struct XimImage {
 typedef struct XimAsciiHeader {
     char file_version[4];   /* header version */
     char header_size[8];    /* Size of file header (fixed part only) */
-    char image_height[8];   /* Height of the raster imgage in pixels */
+    char image_height[8];   /* Height of the raster image in pixels */
     char image_width[8];    /* Width of the raster image in pixels */
     char bytes_line[8];     /* Actual # of bytes separating scanlines */
     char bits_channel[4];   /* Bits per channel (usually 1 or 8) */
@@ -111,7 +111,7 @@ typedef struct XimAsciiHeader {
 
 /* Note:
 * - All data is in char's in order to maintain easily portability
-*   across machines, and some human readibility.
+*   across machines, and some human readability.
 * - Images may be stored as pixmaps (8 bits/pixel) or as separate
 *   red, green, blue channel data (24+ bits/pixel).
 * - An alpha channel is optional and is found after every num_channels
diff --git a/converter/ppm/ximtoppm.c b/converter/ppm/ximtoppm.c
index 92b123f6..d839e770 100644
--- a/converter/ppm/ximtoppm.c
+++ b/converter/ppm/ximtoppm.c
@@ -22,7 +22,9 @@
 #include "shhopt.h"
 #include "nstring.h"
 
-struct cmdlineInfo {
+
+
+struct CmdlineInfo {
     /* All the information the user supplied in the command line,
        in a form easy for the program to use.
     */
@@ -34,8 +36,8 @@ struct cmdlineInfo {
 
 
 static void
-parseCommandLine(int argc, char ** argv,
-                 struct cmdlineInfo *cmdlineP) {
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo *cmdlineP) {
 /*----------------------------------------------------------------------------
    Note that many of the strings that this function returns in the
    *cmdlineP structure are actually in the supplied argv array.  And
@@ -50,14 +52,14 @@ parseCommandLine(int argc, char ** argv,
     unsigned int alphaoutSpec;
 
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0,   "alphaout",   OPT_STRING, 
+    OPTENT3(0,   "alphaout",   OPT_STRING,
             &cmdlineP->alpha_filename, &alphaoutSpec, 0);
 
     opt.opt_table = option_def;
     opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
     opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
 
-    pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
+    pm_optParseOptions3(&argc, (char**)argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and all of *cmdlineP. */
 
     if (!alphaoutSpec)
@@ -67,21 +69,21 @@ parseCommandLine(int argc, char ** argv,
         cmdlineP->input_filename = "-";  /* he wants stdin */
     else if (argc - 1 == 1)
         cmdlineP->input_filename = strdup(argv[1]);
-    else 
+    else
         pm_error("Too many arguments.  The only argument accepted "
                  "is the input file specification");
 
-    if (cmdlineP->alpha_filename && 
+    if (cmdlineP->alpha_filename &&
         streq(cmdlineP->alpha_filename, "-"))
         cmdlineP->alpha_stdout = TRUE;
-    else 
+    else
         cmdlineP->alpha_stdout = FALSE;
 }
 
 
 
 /* The subroutines are excerpted and slightly modified from the
-   X.V11R4 version of xim_io.c. 
+   X.V11R4 version of xim_io.c.
 */
 
 static int
@@ -100,6 +102,11 @@ ReadXimHeader(FILE *     const in_fp,
         pm_message("ReadXimHeader: unable to read file header" );
         return(0);
     }
+    /* Force broken ASCIIZ strings to at least be valid ASCIIZ */
+    a_head.author [sizeof(a_head.author)  - 1] = '\0';
+    a_head.date   [sizeof(a_head.date)    - 1] = '\0';
+    a_head.program[sizeof(a_head.program) - 1] = '\0';
+
     if (atoi(a_head.header_size) != sizeof(ImageHeader)) {
         pm_message("ReadXimHeader: header size mismatch" );
         return(0);
@@ -113,14 +120,16 @@ ReadXimHeader(FILE *     const in_fp,
     header->ncolors = atoi(a_head.num_colors);
     header->nchannels = atoi(a_head.num_channels);
     header->bytes_per_line = atoi(a_head.bytes_per_line);
-/*    header->npics = atoi(a_head.num_pictures);
-*/
+#if 0
+    header->npics = atoi(a_head.num_pictures);
+#endif
     header->bits_channel = atoi(a_head.bits_per_channel);
     header->alpha_flag = atoi(a_head.alpha_channel);
     header->author = pm_strdup(a_head.author);
     header->date = pm_strdup(a_head.date);
     header->program = pm_strdup(a_head.program);
-    /* Do double checking for bakwards compatibility */
+
+    /* Do double checking for backwards compatibility */
     if (header->npics == 0)
         header->npics = 1;
     if (header->bits_channel == 0)
@@ -130,7 +139,7 @@ ReadXimHeader(FILE *     const in_fp,
         header->bits_channel = 8;
     }
     if ((int)header->bytes_per_line == 0)
-        header->bytes_per_line = 
+        header->bytes_per_line =
             (header->bits_channel == 1 && header->nchannels == 1) ?
                 (header->width + 7) / 8 :
                 header->width;
@@ -186,9 +195,10 @@ ReadImageChannel(FILE *         const infp,
             }
             marker += i;
         }
-        /* return to the beginning of the next image's bufffer */
+        /* return to the beginning of the next image's buffer */
         if (fseek(infp, marker, 0) == -1) {
-            pm_message("ReadImageChannel: can't fseek to location in image buffer" );
+            pm_message("ReadImageChannel: can't fseek to location "
+                       "in image buffer");
             return(0);
         }
         free((char *)line);
@@ -271,7 +281,7 @@ ReadXimImage(FILE *     const in_fp,
 *  Author: Philip Thompson
 *  $Date: 89/11/01 10:14:23 $
 *  $Revision: 1.14 $
-*  Purpose: General xim libray of utililities
+*  Purpose: General xim library of utililities
 *  Copyright (c) 1988  Philip R. Thompson
 *                Computer Resource Laboratory (CRL)
 *                Dept. of Architecture and Planning
@@ -297,28 +307,26 @@ ReadXimImage(FILE *     const in_fp,
 ***********************************************************************/
 
 static int
-ReadXim(in_fp, xim)
-    FILE *in_fp;
-    XimImage *xim;
-{
+ReadXim(FILE *     const in_fp,
+        XimImage * const xim) {
+
     if (!ReadXimHeader(in_fp, xim)) {
         pm_message("can't read xim header" );
-    return(0);
-    }
-    if (!ReadXimImage(in_fp, xim)) {
+        return 0;
+    } else if (!ReadXimImage(in_fp, xim)) {
         pm_message("can't read xim data" );
-    return(0);
-    }
-    return(1);
+        return 0;
+    } else
+        return 1;
 }
 
 
 
 int
-main(int argc,
-     char *argv[]) {
+main(int          argc,
+     const char **argv) {
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     FILE *ifP, *imageout_file, *alpha_file;
     XimImage xim;
     pixel *pixelrow, colormap[256];
@@ -330,24 +338,24 @@ main(int argc,
     pixval maxval;
     bool success;
 
-    ppm_init(&argc, argv);
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
-    
+
     ifP = pm_openr(cmdline.input_filename);
-    
+
     if (cmdline.alpha_stdout)
         alpha_file = stdout;
-    else if (cmdline.alpha_filename == NULL) 
+    else if (cmdline.alpha_filename == NULL)
         alpha_file = NULL;
     else
         alpha_file = pm_openw(cmdline.alpha_filename);
-    
-    if (cmdline.alpha_stdout) 
+
+    if (cmdline.alpha_stdout)
         imageout_file = NULL;
     else
         imageout_file = stdout;
-    
+
     success = ReadXim(ifP, &xim);
     if (!success)
         pm_error("can't read Xim file");
@@ -374,7 +382,7 @@ main(int argc,
             "unknown Xim file type, nchannels == %d, bits_channel == %d",
             xim.nchannels, xim.bits_channel);
 
-    if (imageout_file) 
+    if (imageout_file)
         ppm_writeppminit(imageout_file, cols, rows, maxval, 0);
     if (alpha_file)
         pgm_writepgminit(alpha_file, cols, rows, maxval, 0);
@@ -386,8 +394,8 @@ main(int argc,
         if (mapped) {
             byte * const ximrow = xim.data + row * xim.bytes_per_line;
             unsigned int col;
-            
-            for (col = 0; col < cols; ++col) 
+
+            for (col = 0; col < cols; ++col)
                 pixelrow[col] = colormap[ximrow[col]];
             alpharow[col] = 0;
         } else {
@@ -403,11 +411,11 @@ main(int argc,
                            redrow[col], grnrow[col], blurow[col]);
                 if (xim.nchannels > 3)
                     alpharow[col] = othrow[col];
-                else 
+                else
                     alpharow[col] = 0;
             }
         }
-        if (imageout_file) 
+        if (imageout_file)
             ppm_writeppmrow(imageout_file, pixelrow, cols, maxval, 0);
         if (alpha_file)
             pgm_writepgmrow(alpha_file, alpharow, cols, maxval, 0);
@@ -420,3 +428,6 @@ main(int argc,
 
     return 0;
 }
+
+
+
diff --git a/converter/ppm/xpmtoppm.README b/converter/ppm/xpmtoppm.README
index b5e254fa..0a32113c 100644
--- a/converter/ppm/xpmtoppm.README
+++ b/converter/ppm/xpmtoppm.README
@@ -49,7 +49,7 @@ xpmtoppm.c:
   - Now understands multword X11 color names
   
   - Now reads multiple color keys. Takes the color
-    of the hightest available key. Lines no longer need
+    of the highest available key. Lines no longer need
     to begin with key 'c'.
     
   - expanded line buffer to from 500 to 2048 for bigger files
diff --git a/converter/ppm/xpmtoppm.c b/converter/ppm/xpmtoppm.c
index 46101a09..c97b9fdc 100644
--- a/converter/ppm/xpmtoppm.c
+++ b/converter/ppm/xpmtoppm.c
@@ -544,7 +544,7 @@ interpretXpm3ColorTableLine(char               const line[],
                     addToColorMap(hashP, colorName, curbuf, isTransparent);
                     highkey = curkey;
                 }
-                /* intialize state to process this new key */
+                /* initialize state to process this new key */
                 curkey = key;
                 curbuf[0] = '\0';
                 isTransparent = FALSE;
@@ -606,7 +606,7 @@ readXpm3Header(FILE *             const ifP,
                ColorNameHash **   const colorNameHashPP) {
 /*----------------------------------------------------------------------------
   Read the header of the XPM file on stream *ifP.  Assume the
-  getLine() stream is presently positioned to the beginning of the
+  getLine() stream is currently positioned to the beginning of the
   file and it is a Version 3 XPM file.  Leave the stream positioned
   after the header.
 
@@ -721,7 +721,7 @@ readXpm1Header(FILE *           const ifP,
                ColorNameHash ** const colorNameHashPP) {
 /*----------------------------------------------------------------------------
   Read the header of the XPM file on stream *ifP.  Assume the
-  getLine() stream is presently positioned to the beginning of the
+  getLine() stream is currently positioned to the beginning of the
   file and it is a Version 1 XPM file.  Leave the stream positioned
   after the header.
 
@@ -1074,7 +1074,7 @@ main(int argc, char *argv[]) {
 **  - Now understands multiword X11 color names
 **
 **  - Now reads multiple color keys. Takes the color
-**    of the hightest available key. Lines no longer need
+**    of the highest available key. Lines no longer need
 **    to begin with key 'c'.
 **
 **  - expanded line buffer to from 500 to 2048 for bigger files