about summary refs log tree commit diff
path: root/converter/other
diff options
context:
space:
mode:
Diffstat (limited to 'converter/other')
-rw-r--r--converter/other/Makefile26
-rw-r--r--converter/other/bmptopnm.c572
-rw-r--r--converter/other/gemtopnm.c200
-rw-r--r--converter/other/jbig/jbigtopnm.c394
-rw-r--r--converter/other/jbig/libjbig/jbig.c196
-rw-r--r--converter/other/jpeg2000/jpeg2ktopam.c107
-rw-r--r--converter/other/jpeg2000/libjasper/jpc/jpc_util.c26
-rw-r--r--converter/other/jpeg2000/pamtojpeg2k.c82
-rw-r--r--converter/other/pamtotga.c349
-rw-r--r--converter/other/pamtotiff.c62
10 files changed, 1104 insertions, 910 deletions
diff --git a/converter/other/Makefile b/converter/other/Makefile
index b01f66ae..2be88781 100644
--- a/converter/other/Makefile
+++ b/converter/other/Makefile
@@ -166,6 +166,8 @@ endif
 OBJECTS = $(BINARIES:%=%.o) $(EXTRA_OBJECTS)
 MERGE_OBJECTS = $(MERGEBINARIES:%=%.o2) $(EXTRA_OBJECTS)
 
+HAVE_MERGE_COMPAT=YES
+
 pnmtops.o pnmtops.o2: CFLAGS_TARGET=$(PNMTOPS_NOFLATE_OPT)
 
 SCRIPTS = anytopnm pnmtoplainpnm
@@ -248,7 +250,7 @@ bmptopnm.o bmptopnm.o2: bmp.h
 
 pamtotga.o pamtotga.o2: tga.h
 
-install.bin: install.bin.local
+install.bin install.merge: install.bin.local
 .PHONY: install.bin.local
 install.bin.local: $(PKGDIR)/bin
 # Remember that $(SYMLINK) might just be a copy command.
@@ -296,3 +298,25 @@ ifeq ($(HAVE_PNGLIB),Y)
 	cd $(PKGDIR)/bin ; \
 	$(SYMLINK) pamtopng$(EXE) pamrgbatopng$(EXE)
 endif
+
+mergecomptrylist:
+	cat /dev/null >$@
+	echo "TRY(\"bmptoppm\",     main_bmptopnm);"     >>$@
+	echo "TRY(\"gemtopbm\",     main_gemtopnm);"     >>$@
+ifneq ($(JPEGLIB),NONE)
+	echo "TRY(\"ppmtojpeg\",    main_pnmtojpeg);"    >>$@
+endif
+	echo "TRY(\"ppmtouil\",     main_pamtouil);"     >>$@
+	echo "TRY(\"ppmtotga\",     main_pamtotga);"     >>$@
+	echo "TRY(\"pnmtopnm\",     main_pamtopnm);"     >>$@
+	echo "TRY(\"pnmtofits\",    main_pamtofits);"    >>$@
+ifneq ($(TIFF_PREREQ_MISSING),Y)
+	echo "TRY(\"pnmtotiff\",    main_pamtotiff);"    >>$@
+endif
+ifeq ($(HAVE_PNGLIB),Y)
+	echo "TRY(\"pngtopnm\",     main_pngtopam);"     >>$@
+endif
+	echo "TRY(\"icontopbm\",    main_sunicontopnm);" >>$@
+ifeq ($(HAVE_PNGLIB),Y)
+	echo "TRY(\"pamrgbatopng\", main_pamtopng);"     >>$@
+endif
diff --git a/converter/other/bmptopnm.c b/converter/other/bmptopnm.c
index 787b9020..3f66634b 100644
--- a/converter/other/bmptopnm.c
+++ b/converter/other/bmptopnm.c
@@ -1,7 +1,7 @@
 /*****************************************************************************
                                     bmptopnm.c
 ******************************************************************************
- 
+
  Bmptopnm - Converts from a Microsoft Windows or OS/2 .BMP file to a
  PBM, PGM, or PPM file.
 
@@ -9,7 +9,7 @@
  The name was changed in March 2002.
 
  Copyright (C) 1992 by David W. Sanderson.
- 
+
  Permission to use, copy, modify, and distribute this software and its
  documentation for any purpose and without fee is hereby granted,
  provided that the above copyright notice appear in all copies and
@@ -62,14 +62,14 @@ struct bitPosition {
 };
 
 struct pixelformat {
-    /* The format of a pixel representation from the raster.  i.e. which 
-       bits apply to red, green, blue, and transparency 
+    /* The format of a pixel representation from the raster.  i.e. which
+       bits apply to red, green, blue, and transparency
     */
     struct bitPosition red;
     struct bitPosition blu;
     struct bitPosition grn;
     struct bitPosition trn;
-    
+
     bool conventionalBgr;
         /* This means that the above bit positions are just the conventional
            BGR format -- one byte Blue, one byte Green, one byte Red,
@@ -83,7 +83,7 @@ struct pixelformat {
 typedef struct {
     /* These are all encodings of floating point */
     unsigned long x;
-    unsigned long y; 
+    unsigned long y;
     unsigned long z;
 } cieXyz;
 
@@ -105,14 +105,14 @@ struct bmpInfoHeader {
            described by the "mask" values in the header, rather than
            fixed formats.
         */
-    unsigned int cmapsize;
+    unsigned int cmapSize;
         /* Size in bytes of the colormap (palette) in the BMP file.
 
            Zero means there is no colormap.
         */
     unsigned int imageSize;
-        /* Size in bytes of the image data.  We only reference this 
-           when the image is compressed. */    
+        /* Size in bytes of the image data.  We only reference this
+           when the image is compressed. */
     unsigned short cPlanes;
     BMPCompType compression;
     struct pixelformat pixelformat;
@@ -151,7 +151,7 @@ parseCommandLine(int argc, const char ** argv,
 
     option_def_index = 0;   /* incremented by OPTENT3 */
     OPTENT3(0,   "verbose",     OPT_FLAG,   NULL, &cmdlineP->verbose,   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 */
@@ -159,7 +159,7 @@ parseCommandLine(int argc, const char ** argv,
     pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
         /* Uses and sets argc, argv, and some of *cmdlineP and others. */
 
-    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 "
@@ -251,7 +251,45 @@ GetCieXyzTriple(FILE *         const ifP) {
 
 
 static struct pixelformat
-defaultPixelformat(unsigned int const bitCount);
+defaultPixelformat(unsigned int const bitCount) {
+
+    struct pixelformat retval;
+
+    switch (bitCount) {
+    case 16:
+        /* This layout is sometimes called "RGB555".  A document from
+           Microsoft says this is the default (when the "compression"
+           field of the header says COMP_BITFIELDS).
+        */
+        retval.conventionalBgr = FALSE;
+        retval.red.shift = 10;
+        retval.grn.shift = 5;
+        retval.blu.shift = 0;
+        retval.trn.shift = 0;
+        retval.red.mask = 0x1f;  /* 5 bits */
+        retval.grn.mask = 0x1f;  /* 5 bits */
+        retval.blu.mask = 0x1f;  /* 5 bits */
+        retval.trn.mask = 0;
+        break;
+    case 24:
+    case 32:
+        retval.conventionalBgr = TRUE;
+        retval.red.shift = 16;
+        retval.grn.shift = 8;
+        retval.blu.shift = 0;
+        retval.trn.shift = 0;
+        retval.red.mask = 0xff;  /* 8 bits */
+        retval.grn.mask = 0xff;  /* 8 bits */
+        retval.blu.mask = 0xff;  /* 8 bits */
+        retval.trn.mask = 0;
+        break;
+    default:
+        /* colormapped - masks are undefined */
+        break;
+    }
+
+    return retval;
+}
 
 
 
@@ -261,7 +299,7 @@ readOffBytes(FILE * const fp, unsigned int const nbytes) {
    Read 'nbytes' from file 'fp'.  Abort program if read error.
 -----------------------------------------------------------------------------*/
     int i;
-    
+
     for(i = 0; i < nbytes; ++i) {
         int rc;
         rc = getc(fp);
@@ -273,8 +311,8 @@ readOffBytes(FILE * const fp, unsigned int const nbytes) {
 
 
 static void
-bmpReadfileheader(FILE *         const ifP, 
-                  unsigned int * const bytesReadP, 
+bmpReadfileheader(FILE *         const ifP,
+                  unsigned int * const bytesReadP,
                   unsigned int * const offBitsP) {
 
     unsigned long     offBits;
@@ -304,7 +342,21 @@ bmpReadfileheader(FILE *         const ifP,
 static void
 readOs2InfoHeaderRest(FILE *                 const ifP,
                       struct bmpInfoHeader * const headerP) {
+/*----------------------------------------------------------------------------
+   Read the rest of the info header, after its size field, of an OS2 BMP from
+   *ifP.
+
+   Add the information from it to *headerP, in particular these members:
 
+     cols
+     rows
+     rowOrder
+     cPlanes
+     cBitCount
+     cmapSize
+     pixelformat
+     compression
+-----------------------------------------------------------------------------*/
     unsigned short colsField, rowsField;
     unsigned short planesField, bitCountField;
 
@@ -313,7 +365,7 @@ readOs2InfoHeaderRest(FILE *                 const ifP,
         pm_error("Invalid BMP file: says width is zero");
     else
         headerP->cols = colsField;
-    
+
     pm_readlittleshortu(ifP, &rowsField);
     if (rowsField == 0)
         pm_error("Invalid BMP file: says height is zero");
@@ -332,16 +384,16 @@ readOs2InfoHeaderRest(FILE *                 const ifP,
        same as for Windows.
     */
     if (headerP->cBitCount <= 8)
-        headerP->cmapsize = 1 << headerP->cBitCount;
+        headerP->cmapSize = 1 << headerP->cBitCount;
     else if (headerP->cBitCount == 24)
-        headerP->cmapsize = 0;
+        headerP->cmapSize = 0;
     /* There is a 16 bit truecolor format, but we don't know how the
        bits are divided among red, green, and blue, so we can't handle it.
     */
     else
         pm_error("Unrecognized bits per pixel in OS/2 BMP file header: %d",
                  headerP->cBitCount);
-                 
+
     headerP->pixelformat = defaultPixelformat(headerP->cBitCount);
 
     headerP->compression = BMPCOMP_RGB;
@@ -353,24 +405,24 @@ static void
 validateCompression(unsigned long const compression,
                     enum rowOrder const rowOrder,
                     unsigned int  const cBitCount) {
-    
+
     if (compression != BMPCOMP_RGB && compression != BMPCOMP_BITFIELDS &&
-        compression != BMPCOMP_RLE4 && compression != BMPCOMP_RLE8) 
+        compression != BMPCOMP_RLE4 && compression != BMPCOMP_RLE8)
         pm_error("Input has unknown encoding.  "
                  "Compression type code = %ld.  The only ones we know "
                  "are RGB (%u), BITFIELDS (%u), "
                  "RLE4 (%u), and RLE8 (%u)",
                  compression, BMPCOMP_RGB, BMPCOMP_BITFIELDS,
                  BMPCOMP_RLE4, BMPCOMP_RLE8);
-                     
+
     if ((compression == BMPCOMP_RLE4 || compression == BMPCOMP_RLE8) &&
-        rowOrder == TOPDOWN )                        
+        rowOrder == TOPDOWN )
         pm_error("Invalid BMP header.  Claims image is top-down and also "
                  "compressed, which is an impossible combination.");
 
     if ((compression == BMPCOMP_RLE4 && cBitCount !=4 ) ||
-        (compression == BMPCOMP_RLE8 && cBitCount !=8 )) 
-        pm_error("Invalid BMP header.  " 
+        (compression == BMPCOMP_RLE8 && cBitCount !=8 ))
+        pm_error("Invalid BMP header.  "
                  "Compression type (%s) disagrees with "
                  "number of bits per pixel (%u).",
                  compression == BMPCOMP_RLE4 ? "RLE4" : "RLE8",
@@ -427,7 +479,7 @@ readWindowsBasic40ByteInfoHeader(FILE *                 const ifP,
 
         headerP->bitFields = (compression == BMPCOMP_BITFIELDS);
 
-        headerP->compression = compression;             
+        headerP->compression = compression;
     }
     /* And read the rest of the junk in the 40 byte header */
     headerP->imageSize = GetLong(ifP);   /* ImageSize */
@@ -435,7 +487,7 @@ readWindowsBasic40ByteInfoHeader(FILE *                 const ifP,
     GetLong(ifP);   /* YpixelsPerMeter */
     colorsused = GetLong(ifP);   /* ColorsUsed */
     /* See comments in bmp.h for info about the definition of the following
-       word and its relationship to the color map size (headerP->cmapsize).
+       word and its relationship to the color map size (headerP->cmapSize).
     */
     /* colorsimportant = */ GetLong(ifP);  /* ColorsImportant */
 
@@ -443,16 +495,22 @@ readWindowsBasic40ByteInfoHeader(FILE *                 const ifP,
         if (colorsused != 0) {
             if (colorsused > 1 << headerP->cBitCount)
                 pm_error("Invalid BMP header.  Says %u bits per pixel, "
-                         "but %d colors used", 
+                         "but %d colors used",
                          headerP->cBitCount, colorsused);
+            else if (colorsused == 1 && headerP->cBitCount == 1) {
+                pm_message("Abnormal BMP header.  Says 1 bit per pixel. "
+                           "Should have 2 colors, but says only 1 color used. "
+                    );
+                headerP->cmapSize = colorsused;
+        }
             else
-                headerP->cmapsize = colorsused;
-        } else 
-            headerP->cmapsize = 1 << headerP->cBitCount;
-    } else if (headerP->cBitCount == 24 || 
-               headerP->cBitCount == 16 || 
+                headerP->cmapSize = colorsused;
+        } else
+            headerP->cmapSize = 1 << headerP->cBitCount;
+    } else if (headerP->cBitCount == 24 ||
+               headerP->cBitCount == 16 ||
                headerP->cBitCount == 32)
-        headerP->cmapsize = 0;
+        headerP->cmapSize = 0;
     else
         pm_error("Unrecognized bits per pixel in Windows BMP file header: %d",
                  headerP->cBitCount);
@@ -465,18 +523,18 @@ lsbZeroCount(unsigned int const mask)
 /*----------------------------------------------------------------------------
    Return the number of consecutive zeroes in the mask 'mask', starting with
    the least significant bit and going up.  E.g. for 0x20, it would be 5.
-   
+
    Use GCC built-in when available.
 -----------------------------------------------------------------------------*/
 
-#if HAVE_GCC_BITCOUNT 
+#if HAVE_GCC_BITCOUNT
 {
       return ( mask==0 ? sizeof(mask)*8 : __builtin_ctz(mask) );
 }
 #else
 {
       unsigned int i=0;
-    
+
       while (((mask >> i) & 0x1) == 0 && i < sizeof(mask)*8)
         ++i;
 
@@ -526,51 +584,8 @@ computeConventionalBgr(struct pixelformat * const fP,
 
 
 
-static struct pixelformat
-defaultPixelformat(unsigned int const bitCount) {
-
-    struct pixelformat retval;
-
-    switch (bitCount) {
-    case 16:
-        /* This layout is sometimes called "RGB555".  A document from
-           Microsoft says this is the default (when the "compression"
-           field of the header says COMP_BITFIELDS).
-        */
-        retval.conventionalBgr = FALSE;
-        retval.red.shift = 10;
-        retval.grn.shift = 5;
-        retval.blu.shift = 0;
-        retval.trn.shift = 0;
-        retval.red.mask = 0x1f;  /* 5 bits */
-        retval.grn.mask = 0x1f;  /* 5 bits */
-        retval.blu.mask = 0x1f;  /* 5 bits */
-        retval.trn.mask = 0;
-        break;
-    case 24:
-    case 32:
-        retval.conventionalBgr = TRUE;
-        retval.red.shift = 16;
-        retval.grn.shift = 8;
-        retval.blu.shift = 0;
-        retval.trn.shift = 0;
-        retval.red.mask = 0xff;  /* 8 bits */
-        retval.grn.mask = 0xff;  /* 8 bits */
-        retval.blu.mask = 0xff;  /* 8 bits */
-        retval.trn.mask = 0;
-        break;
-    default:
-        /* colormapped - masks are undefined */
-        break;
-    }
-
-    return retval;
-}
-
-
-
 static void
-readV4InfoHeaderExtension(FILE *                 const ifP, 
+readV4InfoHeaderExtension(FILE *                 const ifP,
                           struct bmpInfoHeader * const headerP,
                           unsigned int *         const bytesReadP) {
 
@@ -605,12 +620,12 @@ readV4InfoHeaderExtension(FILE *                 const ifP,
     GetLong(ifP);  /* GammaBlue */
 
     *bytesReadP = 68;
-} 
+}
 
 
 
 static void
-readV5InfoHeaderExtension(FILE *                 const ifP, 
+readV5InfoHeaderExtension(FILE *                 const ifP,
                           struct bmpInfoHeader * const headerP,
                           unsigned int *         const bytesReadP) {
 
@@ -634,10 +649,31 @@ defaultV4InfoHeaderExtension(struct bmpInfoHeader * const headerP) {
 
 
 static void
-readWindowsInfoHeaderRest(FILE *                 const ifP, 
+readWindowsInfoHeaderRest(FILE *                 const ifP,
                           unsigned int           const cInfoHeaderSize,
                           struct bmpInfoHeader * const headerP) {
-
+/*----------------------------------------------------------------------------
+   Read the rest of the info header, after the length field, of a Windows BMP
+   from *ifP.
+
+   'cInfoHeaderSize' is the size of the info header, not counting its size
+   field.  Note that besides telling us how much data to read, this also
+   implies which of the three major formats the data is in.
+
+   Add the information from it to *headerP, in particular these members:
+
+     cols
+     rows
+     rowOrder
+     cPlanes
+     cBitCount
+     bitFields
+     compression
+     imageSize
+     cmapSize
+     pixelformat
+     endPoints
+-----------------------------------------------------------------------------*/
     /* There are 3 major formats of Windows
        BMP, identified by the 3 info header lengths.  The original
        one is 40 bytes.  The "V4 header" is 108 bytes and was
@@ -656,7 +692,7 @@ readWindowsInfoHeaderRest(FILE *                 const ifP,
         bytesRead += v4BytesRead;
 
         assert(bytesRead == BMP_HDRLEN_WIN_V4);
-    } else 
+    } else
         defaultV4InfoHeaderExtension(headerP);
 
     if (cInfoHeaderSize >= BMP_HDRLEN_WIN_V5) {
@@ -670,14 +706,14 @@ readWindowsInfoHeaderRest(FILE *                 const ifP,
         GetByte(ifP);
         ++bytesRead;
     }
-    
+
     assert(bytesRead == cInfoHeaderSize);
 }
 
 
 
 static void
-bmpReadinfoheader(FILE *                 const ifP, 
+bmpReadinfoheader(FILE *                 const ifP,
                   unsigned int *         const bytesReadP,
                   struct bmpInfoHeader * const headerP,
                   const char **          const errorP) {
@@ -694,11 +730,11 @@ bmpReadinfoheader(FILE *                 const ifP,
         pm_strfree(error);
     } else {
         switch (headerP->class) {
-        case BMP_C_WIN_V1: 
-        case BMP_C_WIN_V2: 
-        case BMP_C_WIN_V3: 
-        case BMP_C_WIN_V4: 
-        case BMP_C_WIN_V5: 
+        case BMP_C_WIN_V1:
+        case BMP_C_WIN_V2:
+        case BMP_C_WIN_V3:
+        case BMP_C_WIN_V4:
+        case BMP_C_WIN_V5:
             readWindowsInfoHeaderRest(ifP, cInfoHeaderSize, headerP);
             break;
         case BMP_C_OS2_1x:
@@ -721,29 +757,29 @@ bmpReadinfoheader(FILE *                 const ifP,
 
 
 static void
-bmpReadColormap(FILE *         const ifP, 
-                enum bmpClass  const class, 
-                xel **         const colormapP, 
-                unsigned int   const cmapsize,
+bmpReadColormap(FILE *         const ifP,
+                enum bmpClass  const class,
+                xel **         const colormapP,
+                unsigned int   const cmapSize,
                 unsigned int * const bytesReadP) {
 /*----------------------------------------------------------------------------
    Read the color map from the present position in the input BMP file
    *ifP.
 
-   The map has 'cmapsize' entries in it.  cmapsize == 0 means there is
+   The map has 'cmapSize' entries in it.  cmapSize == 0 means there is
    no color map.
 
    We return a color map as *colormapP.  If there is no color map in the
    BMP, this is just an arbitrary color map.
- 
+
    'class' is the class of BMP image - Windows or OS/2.
 -----------------------------------------------------------------------------*/
-    xel * const colormap = pnm_allocrow(MAX(1, cmapsize));
-    
+    xel * const colormap = pnm_allocrow(MAX(1, cmapSize));
+
     unsigned int i;
     unsigned int bytesRead;
 
-    for (i = 0, bytesRead = 0; i < cmapsize; ++i) {
+    for (i = 0, bytesRead = 0; i < cmapSize; ++i) {
         /* There is a document that says the bytes are ordered R,G,B,Z,
            but in practice it appears to be the following instead:
         */
@@ -778,13 +814,13 @@ extractBitFields(unsigned int       const rasterval,
                  pixval *           const bP,
                  pixval *           const aP) {
 
-    unsigned int const rbits = 
+    unsigned int const rbits =
         (rasterval >> pixelformat.red.shift) & pixelformat.red.mask;
-    unsigned int const gbits = 
+    unsigned int const gbits =
         (rasterval >> pixelformat.grn.shift) & pixelformat.grn.mask;
-    unsigned int const bbits = 
+    unsigned int const bbits =
         (rasterval >> pixelformat.blu.shift) & pixelformat.blu.mask;
-    unsigned int const abits = 
+    unsigned int const abits =
         (rasterval >> pixelformat.trn.shift) & pixelformat.trn.mask;
 
     *rP = pixelformat.red.mask > 0 ?
@@ -795,7 +831,7 @@ extractBitFields(unsigned int       const rasterval,
         (unsigned int) bbits * maxval / pixelformat.blu.mask : 0;
     *aP = pixelformat.trn.mask > 0 ?
         (unsigned int) abits * maxval / pixelformat.trn.mask : 0;
-}        
+}
 
 
 
@@ -818,7 +854,7 @@ convertRow16(unsigned char      const bmprow[],
         extractBitFields(rasterval, pixelformat, 255, &r, &g, &b, &a);
 
         PNM_ASSIGN(xelrow[col], r, g, b);
-        
+
         cursor += 2;
     }
 }
@@ -830,7 +866,7 @@ convertRow24(unsigned char      const bmprow[],
              xel                      xelrow[],
              int                const cols,
              struct pixelformat const pixelformat) {
-    
+
     /* It's truecolor */
     /* There is a document that gives a much different format for
        24 bit BMPs.  But this seems to be the de facto standard, and is,
@@ -840,7 +876,7 @@ convertRow24(unsigned char      const bmprow[],
 
     unsigned int col;
     unsigned int cursor;
-    
+
     cursor = 0;
     for (col = 0; col < cols; ++col) {
         pixval r, g, b, a;
@@ -851,17 +887,17 @@ convertRow24(unsigned char      const bmprow[],
             b = bmprow[cursor+0];
             a = 0;
         } else {
-            unsigned int const rasterval = 
+            unsigned int const rasterval =
                 (bmprow[cursor+0] << 16) +
                 (bmprow[cursor+1] << 8) +
                 (bmprow[cursor+2] << 0);
-            
+
             extractBitFields(rasterval, pixelformat, 255, &r, &g, &b, &a);
         }
         PNM_ASSIGN(xelrow[col], r, g, b);
         cursor += 3;
     }
-} 
+}
 
 
 
@@ -870,7 +906,7 @@ convertRow32(unsigned char      const bmprow[],
              xel                      xelrow[],
              int                const cols,
              struct pixelformat const pixelformat) {
-    
+
     /* It's truecolor */
 
     unsigned int col;
@@ -886,40 +922,40 @@ convertRow32(unsigned char      const bmprow[],
             b = bmprow[cursor+0];
             a = 0;
         } else {
-            unsigned int const rasterval = 
+            unsigned int const rasterval =
                 (bmprow[cursor+0] << 24) +
                 (bmprow[cursor+1] << 16) +
                 (bmprow[cursor+2] << 8) +
                 (bmprow[cursor+3] << 0);
-            
+
             extractBitFields(rasterval, pixelformat, 255, &r, &g, &b, &a);
         }
 
-        PNM_ASSIGN(xelrow[col], 
+        PNM_ASSIGN(xelrow[col],
                    bmprow[cursor+2], bmprow[cursor+1], bmprow[cursor+0]);
         cursor += 4;
     }
-} 
+}
 
 
 static void
 validateIndex(unsigned int const index,
-	      unsigned int const cmapsize ) {
+              unsigned int const cmapSize ) {
 
-    if (index >= cmapsize)
+    if (index >= cmapSize)
         pm_error("Error: invalid index to color palette.");
 }
 
 
 
 static void
-convertRow(unsigned char      const bmprow[], 
+convertRow(unsigned char      const bmprow[],
            xel                      xelrow[],
-           int                const cols, 
-           unsigned int       const cBitCount, 
+           int                const cols,
+           unsigned int       const cBitCount,
            struct pixelformat const pixelformat,
            xel                const colormap[],
-           unsigned int       const cmapsize
+           unsigned int       const cmapSize
            ) {
 /*----------------------------------------------------------------------------
    Convert a row in raw BMP raster format bmprow[] to a row of xels xelrow[].
@@ -931,20 +967,20 @@ convertRow(unsigned char      const bmprow[],
    If the image is colormapped, colormap[] is the colormap
    (colormap[i] is the color with color index i).
 -----------------------------------------------------------------------------*/
-    if (cBitCount == 24) 
+    if (cBitCount == 24)
         convertRow24(bmprow, xelrow, cols, pixelformat);
-    else if (cBitCount == 16) 
+    else if (cBitCount == 16)
         convertRow16(bmprow, xelrow, cols, pixelformat);
-    else if (cBitCount == 32) 
+    else if (cBitCount == 32)
         convertRow32(bmprow, xelrow, cols, pixelformat);
-    else if (cBitCount == 8) {            
+    else if (cBitCount == 8) {
         /* It's a whole byte colormap index */
-        unsigned int col; 
+        unsigned int col;
         for (col = 0; col < cols; ++col) {
             unsigned int const index = bmprow[col];
-            validateIndex(index, cmapsize);
+            validateIndex(index, cmapSize);
             xelrow[col] = colormap[index];
-	}
+    }
     } else if (cBitCount == 1 || cBitCount == 2 || cBitCount == 4) {
         /* It's a bit field color index */
         unsigned char const mask = ( 1 << cBitCount ) - 1;
@@ -954,9 +990,9 @@ convertRow(unsigned char      const bmprow[],
         for (col = 0; col < cols; ++col) {
             unsigned int const cursor = (col*cBitCount)/8;
             unsigned int const shift = 8 - ((col*cBitCount) % 8) - cBitCount;
-            unsigned int const index = 
+            unsigned int const index =
                 (bmprow[cursor] & (mask << shift)) >> shift;
-            validateIndex(index, cmapsize);
+            validateIndex(index, cmapSize);
             xelrow[col] = colormap[index];
         }
     } else {
@@ -971,8 +1007,8 @@ static unsigned char **
 allocBmpRaster(unsigned int const rows,
                unsigned int const bytesPerRow) {
 
-    unsigned int const storageSize = 
-        rows * sizeof(unsigned char *) + rows * bytesPerRow;        
+    unsigned int const storageSize =
+        rows * sizeof(unsigned char *) + rows * bytesPerRow;
     unsigned char ** bmpRaster;
     unsigned int row;
     unsigned char * startOfRows;
@@ -992,7 +1028,7 @@ allocBmpRaster(unsigned int const rows,
 
     startOfRows = (unsigned char *)(bmpRaster + rows);
 
-    for (row = 0; row < rows; ++row) 
+    for (row = 0; row < rows; ++row)
         bmpRaster[row] = startOfRows + row * bytesPerRow;
 
     return bmpRaster;
@@ -1010,47 +1046,51 @@ readrow(FILE *           const ifP,
     size_t bytesRead;
 
     assert(bytesPerRow > 0);
-    
+
     bytesRead = fread(bmpRaster[row], 1, bytesPerRow, ifP);
 
     if (bytesRead < bytesPerRow) {
         if (feof(ifP))
             pm_error("End of file reading row %u of BMP raster.", row);
-        else 
+        else
             pm_error("Error reading BMP raster.  Errno=%d (%s)",
                      errno, strerror(errno));
     }
     *bytesReadP += bytesRead;
 }
- 
+
 
 
 static void
-nibbleAlign(unsigned char * const ptr,
-            unsigned int    const nibbles){
+nybbleAlign(unsigned char * const bytes,
+            unsigned int    const nybbleCt){
 /*----------------------------------------------------------------------------
-  Shift data pointed by ptr one half byte toward the MSB (to the left).
- 
+  Shift the 'nybbleCt' nybbles of bytes[], after the first byte, one nybble
+  toward the left, with the first of those nybble shifting into the right half
+  of the first byte.  Leave the left half of the first byte alone.
+
   Example:
- 
-  (Numbers in hex, 8 nibbles)
-            5F 13 7E 89 A1
+
+  (Numbers in hex, 8 nybbles)
+            5? 13 7E 89 A1
    becomes  51 37 E8 9A 10
 -----------------------------------------------------------------------------*/
-    unsigned int const fullByteCount = (nibbles-1) / 2;
+    unsigned int const fullByteCt = (nybbleCt + 1) / 2;
     unsigned int i;
-              
-    ptr[0] = ptr[0] & ptr[1] >> 4;
-                                    
-    for (i = 0; i < fullByteCount; ++i)
-        ptr[i+1] = ptr[i+1] << 4 & ptr[i+2] >> 4;
-    
-    if (nibbles % 2 == 1)   /* if there is a final odd nibble */
-        ptr[fullByteCount+1] <<= 4; /* shift it a half byte */
+
+    bytes[0] >>= 4;
+
+    for (i = 0; i < fullByteCt; ++i)
+        bytes[i] = bytes[i] << 4 | bytes[i+1] >> 4;
+
+    if (nybbleCt % 2 == 0) {
+        /* There is a final right nybble.  Shift it. */
+        bytes[fullByteCt] <<= 4;
+    }
 }
 
 
-           
+
 enum rleStatus { ABS_MODE, ENC_MODE, END_OF_ROW, END_OF_BMP, DELTA };
 
 static enum rleStatus
@@ -1060,9 +1100,9 @@ readRLEcode(FILE *          const ifP,
 
     unsigned short s;
     enum rleStatus retval;
-    
+
     s = GetBigShort(ifP);
-    
+
     if      (s == 0) retval = END_OF_ROW;
     else if (s == 1) retval = END_OF_BMP;
     else if (s == 2) retval = DELTA;
@@ -1094,16 +1134,18 @@ readrowRLE(FILE *           const ifP,
     bool const rle4 = (compression == BMPCOMP_RLE4);
     int  const pixelsPerRowMargin = rle4 ? cols % 2 : 0;
 
-    char const err_decode[] = 
+    char const err_decode[] =
         "Error while decoding compressed BMP image.  "
-        "%s.  Row: %u  Pixel: %u" ; 
-     
+        "%s.  Row: %u  Pixel: %u" ;
+
     unsigned int totalBytesRead;
     unsigned int pixelsRead;
 
-    /* There are RLE4 images with rows coded up the byte boundary, resulting
-       in each row one pixel larger than the column length stated in the
-       BMP info header (header.cols) when the column length is odd.
+    /* There are RLE4 images with rows coded up to the byte boundary,
+       resulting in each row one pixel larger than the column length
+       stated in the BMP info header (header.cols) when the column length
+       is odd.
+
        pixelsPerRowMargin is a "wart" to provide for this case.
     */
 
@@ -1112,7 +1154,7 @@ readrowRLE(FILE *           const ifP,
 
     while (true) {
         unsigned int n;
-            /* decompressed bytes already read; current write point */ 
+            /* decompressed bytes already read; current write point */
         unsigned int cnt;
         unsigned char code;
 
@@ -1121,23 +1163,23 @@ readrowRLE(FILE *           const ifP,
         switch (readRLEcode(ifP, &cnt, &code)) {
         case ENC_MODE: {
             unsigned int const byteCnt = rle4 ? (cnt + 1) /2 : cnt;
-            unsigned int i; 
+            unsigned int i;
 
             if (pixelsRead + cnt > cols + pixelsPerRowMargin)
                 pm_error(err_decode,  "Too many pixels in encoded mode",
-                         row, pixelsRead ); 
-                 
+                         row, pixelsRead );
+
             for (i = 0; i < byteCnt; ++i)
                 bmpRaster[row][n+i] = code;
-                 
+
             if (rle4 && pixelsRead % 2 == 1)
                 /* previous read ended odd */
-                nibbleAlign(&bmpRaster[row][n-1], cnt); 
-            
+                nybbleAlign(&bmpRaster[row][n-1], cnt);
+
             pixelsRead += cnt;
             totalBytesRead += 2;
         } break;
-        
+
         case ABS_MODE: {
             unsigned int cmpBytesRead; /* compressed bytes read */
             /* align read-end to 16 bit boundary */
@@ -1146,43 +1188,43 @@ readrowRLE(FILE *           const ifP,
 
             if (pixelsRead + cnt > cols + pixelsPerRowMargin)
                 pm_error(err_decode,  "Too many pixels in absolute mode",
-                         row, pixelsRead); 
+                         row, pixelsRead);
 
-            cmpBytesRead = fread(&bmpRaster[row][n], 
+            cmpBytesRead = fread(&bmpRaster[row][n],
                                  sizeof(char), bytesToRead, ifP);
 
             if (cmpBytesRead < bytesToRead) {
                 if (feof(ifP))
                     pm_error("End of file reading row %u "
                              "of compressed BMP raster.", row);
-                else 
+                else
                     pm_error("Error reading BMP raster.  Errno=%d (%s)",
                              errno, strerror(errno));
             }
             if (rle4 && pixelsRead % 2 == 1) /* previous read ended odd */
-                nibbleAlign(&bmpRaster[row][n-1], cnt); 
-    
+                nybbleAlign(&bmpRaster[row][n-1], cnt);
+
             pixelsRead += cnt;
             totalBytesRead += cmpBytesRead + 2;
         } break;
-            
+
         case END_OF_ROW: {
             if (cols == pixelsRead ||
                 cols + pixelsPerRowMargin == pixelsRead) {
                 if (!lastrow) {
                     *bytesReadP += totalBytesRead + 2;
                     return;
-                } else if (readRLEcode(ifP, NULL, NULL) == END_OF_BMP) { 
+                } else if (readRLEcode(ifP, NULL, NULL) == END_OF_BMP) {
                     *bytesReadP += totalBytesRead +4;
                     return;
                 } else
                     /* lastrow and END_OF_BITMAP not detected */
                     pm_error(err_decode,  "End of bitmap not marked",
-                             row, pixelsRead ); 
+                             row, pixelsRead );
             } else
                 pm_error(err_decode,  "Premature end of row",
                          row, pixelsRead);
-        } break;  
+        } break;
 
         case END_OF_BMP: {
             if (lastrow && (cols == pixelsRead ||
@@ -1192,15 +1234,27 @@ readrowRLE(FILE *           const ifP,
             } else
                 pm_error(err_decode,  "Premature end of bitmap",
                          row, pixelsRead );
+            /* Windows programs do not reject premature end of bitmap.
+               Rather, they set the remaining pixels of the raster to
+               an arbitrary value.  In practice, images with incomplete
+               bitmaps are rare.
+            */
         } break;
 
         case DELTA: {
+            /* Delta means "move the point (col,row) by the amount given
+               in the next two bytes."  Like premature end of bitmap, the
+               official specs do not specify what value the skipped pixels
+               should be set to.  Judging from Windows utilities, there is
+               no consensus within Microsoft either.
+            */
             pm_error(err_decode,
                      "Delta code in compressed BMP image.  "
-                     "This program does not process deltas.",
+                     "This program does not process deltas",
                      row, pixelsRead);
+
         } break;
-         
+
         default:
             pm_error("Internal error processing RLE code in row %u", row);
         }
@@ -1210,13 +1264,13 @@ readrowRLE(FILE *           const ifP,
 
 
 static void
-bmpReadraster(FILE *            const ifP, 
-              unsigned int      const cols, 
-              unsigned int      const rows, 
+bmpReadraster(FILE *            const ifP,
+              unsigned int      const cols,
+              unsigned int      const rows,
               enum rowOrder     const rowOrder,
-              unsigned int      const cBitCount, 
+              unsigned int      const cBitCount,
               BMPCompType       const compression,
-              unsigned char *** const bmpRasterP, 
+              unsigned char *** const bmpRasterP,
               unsigned int *    const bytesReadP) {
 /*----------------------------------------------------------------------------
    Read the raster from the BMP file on *ifP (which is positioned to the
@@ -1246,33 +1300,33 @@ bmpReadraster(FILE *            const ifP,
 
     *bytesReadP = 0;
 
-    /* row order BOTTOMUP is by far the most common case - the bottom 
+    /* row order BOTTOMUP is by far the most common case - the bottom
        line is first in the file, the top line last.
-       
+
        We have never actually seen TOPDOWN, except in a Microsoft spec
     */
-    
+
     switch(compression){
     case BMPCOMP_RGB:
     case BMPCOMP_BITFIELDS: {
         unsigned int i;
         for (i = 0; i < rows; ++i)
-            readrow(ifP, rowOrder == TOPDOWN ? i : rows - i - 1, 
+            readrow(ifP, rowOrder == TOPDOWN ? i : rows - i - 1,
                     bytesPerRow, bmpRaster, bytesReadP);
     } break;
-    case BMPCOMP_RLE4: 
+    case BMPCOMP_RLE4:
     case BMPCOMP_RLE8: {
         unsigned int i;
         /* Read all rows except last */
         assert(rows >= 1);
         for (i = 0; i < rows - 1; ++i){
-            readrowRLE(ifP, rowOrder == TOPDOWN ? i : rows - i - 1, 
+            readrowRLE(ifP, rowOrder == TOPDOWN ? i : rows - i - 1,
                        cols, FALSE, compression, bmpRaster, bytesReadP);
         }
         /* Read last row */
-        readrowRLE(ifP, rowOrder == TOPDOWN ? i : rows - i - 1, 
+        readrowRLE(ifP, rowOrder == TOPDOWN ? i : rows - i - 1,
                    cols, TRUE,  compression, bmpRaster, bytesReadP);
-    } break;             
+    } break;
     case BMPCOMP_JPEG:
         pm_error("BMP file uses JPEG compression.  We don't know how to "
                  "interpret that.");
@@ -1291,19 +1345,19 @@ static void
 reportHeader(struct bmpInfoHeader const header,
              unsigned int         const offBits,
              bool                 const verbose) {
-             
+
     if (verbose) {
         pm_message("BMP image header says:");
         pm_message("  Class of BMP: %s", BMPClassName(header.class));
         pm_message("  Width: %d pixels", header.cols);
         pm_message("  Height: %d pixels", header.rows);
         pm_message("  Depth: %d planes", header.cPlanes);
-        pm_message("  Row order: %s", 
+        pm_message("  Row order: %s",
                    header.rowOrder == BOTTOMUP ? "bottom up" : "top down");
         pm_message("  Byte offset of raster within file: %u", offBits);
         pm_message("  Bits per pixel in raster: %u", header.cBitCount);
         pm_message("  Compression: %s", BMPCompTypeName(header.compression));
-        pm_message("  Colors in color map: %u", header.cmapsize);
+        pm_message("  Colors in color map: %u", header.cmapSize);
     } else {
         pm_message("%s BMP, %ux%ux%u",
                    BMPClassName(header.class),
@@ -1311,20 +1365,29 @@ reportHeader(struct bmpInfoHeader const header,
                    header.rows,
                    header.cBitCount);
     }
-}        
+}
+
+
+
+static void
+validateCPlanes(unsigned short const cPlanes) {
+
+    if (cPlanes != 1)
+        pm_error("Error: invalid planes value in BMP header.  Must be 1");
+}
 
 
 
 static void
 analyzeColors(xel          const colormap[],
-              unsigned int const cmapsize,
+              unsigned int const cmapSize,
               xelval       const maxval,
               bool *       const grayPresentP,
               bool *       const colorPresentP) {
-    
-    if (cmapsize == 0) {
+
+    if (cmapSize == 0) {
         /* No colormap, and we're not about to search the entire raster,
-           so we just assume it's full color 
+           so we just assume it's full color
         */
         *colorPresentP = TRUE;
         *grayPresentP = TRUE;
@@ -1333,7 +1396,7 @@ analyzeColors(xel          const colormap[],
 
         *colorPresentP = FALSE;  /* initial assumption */
         *grayPresentP = FALSE;   /* initial assumption */
-        for (i = 0; i < cmapsize; ++i) {
+        for (i = 0; i < cmapSize; ++i) {
             if (PPM_ISGRAY(colormap[i])) {
                 if (PPM_GETR(colormap[i]) != 0 &&
                     PPM_GETR(colormap[i]) != maxval)
@@ -1350,8 +1413,8 @@ static void
 warnIfOffBitsWrong(struct bmpInfoHeader const bmpHeader,
                    unsigned int         const offBits) {
 
-    if (offBits != BMPoffbits(bmpHeader.class, bmpHeader.cBitCount, 
-                              bmpHeader.cmapsize)) {
+    if (offBits != BMPoffbits(bmpHeader.class, bmpHeader.cBitCount,
+                              bmpHeader.cmapSize)) {
 
         pm_message("warning: the BMP header says the raster starts "
                    "at offset %u bytes into the file (offbits), "
@@ -1359,8 +1422,8 @@ warnIfOffBitsWrong(struct bmpInfoHeader const bmpHeader,
                    "the raster.  This inconsistency probably means the "
                    "input file is not a legal BMP file and is unusable.",
                    offBits,
-                   BMPoffbits(bmpHeader.class, bmpHeader.cBitCount, 
-                              bmpHeader.cmapsize));
+                   BMPoffbits(bmpHeader.class, bmpHeader.cBitCount,
+                              bmpHeader.cmapSize));
     }
 }
 
@@ -1374,8 +1437,8 @@ readColorMap(FILE *               const ifP,
 
     unsigned int bytesRead;
 
-    bmpReadColormap(ifP, bmpHeader.class, 
-                    colorMapP, bmpHeader.cmapsize, &bytesRead);
+    bmpReadColormap(ifP, bmpHeader.class,
+                    colorMapP, bmpHeader.cmapSize, &bytesRead);
 
     *posP += bytesRead;
 }
@@ -1385,7 +1448,7 @@ readColorMap(FILE *               const ifP,
 static void
 readRaster(FILE *               const ifP,
            struct bmpInfoHeader const bmpHeader,
-           unsigned char ***    const bmpRasterP, 
+           unsigned char ***    const bmpRasterP,
            unsigned int *       const posP) {
 
     unsigned int bytesRead;
@@ -1419,16 +1482,16 @@ isValidBmpBpp(unsigned int const cBitCount) {
 
 
 static void
-readBmp(FILE *               const ifP, 
-        unsigned char ***    const bmpRasterP, 
-        unsigned int *       const colsP, 
+readBmp(FILE *               const ifP,
+        unsigned char ***    const bmpRasterP,
+        unsigned int *       const colsP,
         unsigned int *       const rowsP,
-        bool *               const grayPresentP, 
+        bool *               const grayPresentP,
         bool *               const colorPresentP,
-        unsigned int *       const cBitCountP, 
+        unsigned int *       const cBitCountP,
         struct pixelformat * const pixelformatP,
         xel **               const colormapP,
-        unsigned int *       const cmapsizeP,
+        unsigned int *       const cmapSizeP,
         bool                 const verbose) {
 
     xel * colormap;  /* malloc'ed */
@@ -1436,13 +1499,13 @@ readBmp(FILE *               const ifP,
         /* Current byte position in the BMP file */
 
     /* The following are all information from the BMP headers */
-    
+
     unsigned int offBits;
         /* Byte offset into file of raster */
     struct bmpInfoHeader bmpHeader;
 
     pos = 0;  /* Starting at the beginning ... */
-    { 
+    {
         unsigned int bytesRead;
         bmpReadfileheader(ifP, &bytesRead, &offBits);
         pos += bytesRead;
@@ -1462,11 +1525,13 @@ readBmp(FILE *               const ifP,
 
     reportHeader(bmpHeader, offBits, verbose);
 
+    validateCPlanes(bmpHeader.cPlanes);
+
     warnIfOffBitsWrong(bmpHeader, offBits);
 
     readColorMap(ifP, bmpHeader, &colormap, &pos);
 
-    analyzeColors(colormap, bmpHeader.cmapsize, bmpMaxval, 
+    analyzeColors(colormap, bmpHeader.cmapSize, bmpMaxval,
                   grayPresentP, colorPresentP);
 
     readOffBytes(ifP, offBits - pos);
@@ -1477,7 +1542,7 @@ readBmp(FILE *               const ifP,
 
     if (fgetc(ifP) != EOF)
         pm_message("warning: some image data remains unread.");
-    
+
     if (!isValidBmpBpp(bmpHeader.cBitCount))
         pm_error("Invalid BMP image: 'cBitCount' field of header "
                  "(number of bits for each pixel in raster) is %u",
@@ -1489,23 +1554,23 @@ readBmp(FILE *               const ifP,
     *rowsP        = bmpHeader.rows;
     *pixelformatP = bmpHeader.pixelformat;
     *colormapP    = colormap;
-    *cmapsizeP    = bmpHeader.cmapsize;
+    *cmapSizeP    = bmpHeader.cmapSize;
 }
 
 
 
 static void
 writeRasterGen(unsigned char **   const bmpRaster,
-               unsigned int       const cols, 
-               unsigned int       const rows, 
+               unsigned int       const cols,
+               unsigned int       const rows,
                int                const format,
-               unsigned int       const cBitCount, 
+               unsigned int       const cBitCount,
                struct pixelformat const pixelformat,
                xel                const colormap[],
-               unsigned int       const cmapsize) {
+               unsigned int       const cmapSize) {
 /*----------------------------------------------------------------------------
   Write the PNM raster to Standard Output, corresponding to the raw BMP
-  raster bmpRaster.  Write the raster assuming the PNM image has 
+  raster bmpRaster.  Write the raster assuming the PNM image has
   dimensions 'cols' by 'rows' and format 'format', with maxval 255.
 
   The BMP image has 'cBitCount' bits per pixel, arranged in format
@@ -1513,7 +1578,7 @@ writeRasterGen(unsigned char **   const bmpRaster,
 
   If the image is colormapped, colormap[] is the colormap
   (colormap[i] is the color with color index i).
-  
+
   writeRasterPbm() is faster for a PBM image.
 -----------------------------------------------------------------------------*/
     xel * xelrow;
@@ -1523,7 +1588,7 @@ writeRasterGen(unsigned char **   const bmpRaster,
 
     for (row = 0; row < rows; ++row) {
         convertRow(bmpRaster[row], xelrow, cols, cBitCount, pixelformat,
-                   colormap, cmapsize);
+                   colormap, cmapSize);
         pnm_writepnmrow(stdout, xelrow, cols, bmpMaxval, format, FALSE);
     }
     pnm_freerow(xelrow);
@@ -1533,12 +1598,12 @@ writeRasterGen(unsigned char **   const bmpRaster,
 
 static void
 writeRasterPbm(unsigned char ** const bmpRaster,
-               unsigned int     const cols, 
-               unsigned int     const rows, 
+               unsigned int     const cols,
+               unsigned int     const rows,
                xel              const colormap[]) {
 /*----------------------------------------------------------------------------
   Write the PBM raster to Standard Output corresponding to the raw BMP
-  raster bmpRaster.  Write the raster assuming the PBM image has 
+  raster bmpRaster.  Write the raster assuming the PBM image has
   dimensions 'cols' by 'rows'.
 
   The BMP image has 'cBitCount' bits per pixel, arranged in format
@@ -1548,28 +1613,28 @@ writeRasterPbm(unsigned char ** const bmpRaster,
   (colormap[i] is the color with color index i).  We cannot handle the
   abnormal case in which colormap[0] and colormap[1] have the same
   value (i.e. both white or both black.)
-  
+
   We destroy *bmpRaster as a side effect.
 -----------------------------------------------------------------------------*/
     unsigned int const colCharCt = pbm_packed_bytes(cols);
-    
+
     unsigned int row;
     enum colorFormat {BlackWhite, WhiteBlack};
     enum colorFormat colorformat;
-                  
+
     if (PPM_GETR(colormap[0]) > 0)
         colorformat = WhiteBlack;
-    else                  
+    else
         colorformat = BlackWhite;
-        
+
     for (row = 0; row < rows; ++row){
-        unsigned char * const bitrow = bmpRaster[row]; 
+        unsigned char * const bitrow = bmpRaster[row];
 
         if (colorformat == BlackWhite) {
             unsigned int i;
-            for (i = 0; i < colCharCt; ++i) 
-                bitrow[i] = ~bitrow[i]; /* flip all pixels */ 
-        }   
+            for (i = 0; i < colCharCt; ++i)
+                bitrow[i] = ~bitrow[i]; /* flip all pixels */
+        }
 
         pbm_cleanrowend_packed(bitrow, cols);
         pbm_writepbmrow_packed(stdout, bitrow, cols, FALSE);
@@ -1605,13 +1670,12 @@ main(int argc, const char ** argv) {
         /* Malloc'ed colormap (palette) from the BMP.  Contents of map
            undefined if not a colormapped BMP.
          */
-    unsigned int cmapsize;
-        /* Number of colormap entries.  Described in the BMP header.
-           Note that a file may be 8 bits per pixel but have less than
-           256 colors.  In the 1 bit per pixel case, there should be
-           2 entries according to the official specification, but we
-           allow files with just 1.
-	 */
+    unsigned int cmapSize;
+        /* Number of colormap entries.  From BMP header.  Note that a file may
+           be 8 bits per pixel but have fewer than 256 colors.  In the 1 bit
+           per pixel case, there should be 2 entries according to the official
+           specification, but we allow files with just 1.
+        */
 
     pm_proginit(&argc, argv);
 
@@ -1620,11 +1684,11 @@ main(int argc, const char ** argv) {
     ifP = pm_openr(cmdline.inputFileName);
     if (streq(cmdline.inputFileName, "-"))
         ifname = "Standard Input";
-    else 
+    else
         ifname = cmdline.inputFileName;
 
-    readBmp(ifP, &bmpRaster, &cols, &rows, &grayPresent, &colorPresent, 
-            &cBitCount, &pixelformat, &colormap, &cmapsize,
+    readBmp(ifP, &bmpRaster, &cols, &rows, &grayPresent, &colorPresent,
+            &cBitCount, &pixelformat, &colormap, &cmapSize,
             cmdline.verbose);
     pm_close(ifP);
 
@@ -1638,14 +1702,14 @@ main(int argc, const char ** argv) {
         outputType = PBM_TYPE;
         pm_message("WRITING PBM IMAGE");
     }
-    
+
     if (outputType == PBM_TYPE  && cBitCount == 1){
         pbm_writepbminit(stdout, cols, rows, FALSE);
         writeRasterPbm(bmpRaster, cols, rows, colormap);
     } else {
         pnm_writepnminit(stdout, cols, rows, bmpMaxval, outputType, FALSE);
         writeRasterGen(bmpRaster, cols, rows, outputType, cBitCount,
-                       pixelformat, colormap, cmapsize); 
+                       pixelformat, colormap, cmapSize);
     }
     free(colormap);
     free(bmpRaster);
diff --git a/converter/other/gemtopnm.c b/converter/other/gemtopnm.c
index aac74793..d862213f 100644
--- a/converter/other/gemtopnm.c
+++ b/converter/other/gemtopnm.c
@@ -36,7 +36,7 @@
  * read 4-plane color IMG files.  Therefore changed from PBM to PPM.
  * Bryan changed it further to use the PNM facilities so it outputs
  * both PBM and PPM in the Netpbm tradition.  Name changed from
- * gemtopbm to gemtopnm.  
+ * gemtopbm to gemtopnm.
  */
 
 #include <assert.h>
@@ -50,106 +50,106 @@
 char pattern[8];
 
 static void getinit ARGS ((FILE *file, int *colsP, int *rowsP, int *padrightP,
-			   int *patlenP, int *planesP));
+               int *patlenP, int *planesP));
 
 int
 main(argc, argv)
-	int             argc;
-	char           *argv[];
+    int             argc;
+    char           *argv[];
 {
-	int     debug = 0;
-	FILE    *f;
+    int     debug = 0;
+    FILE    *f;
     int     row;
-	int     rows, cols, padright, patlen, planes;
+    int     rows, cols, padright, patlen, planes;
       /* attributes of input image */
     int type;  /* The format type (PBM/PPM) of the output image */
-	bit	*bitrow[4];
+    bit *bitrow[4];
       /* One row of input, one or four planes.  (If one, only [0] is defined)*/
     xel * xelrow;  /* One row of output */
-	const char * const usage = "[-debug] [gem IMG file]";
-	int argn;
+    const char * const usage = "[-debug] [gem IMG file]";
+    int argn;
 
 /* Process multiple planes by maintaining a separate row of bits for each
- * plane. In a single-plane image, all we have to do is write out the 
+ * plane. In a single-plane image, all we have to do is write out the
  * first plane; in a multiple-plane image, we combine them just before writing
  * out the row.
  */
-	pnm_init( &argc, argv );
-    
+    pnm_init( &argc, argv );
+
     argn = 1;
 
-	while (argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0')
-	  {
-	    if (pm_keymatch(argv[1], "-debug", 2))
-	      debug = 1;
-	    else
-	      pm_usage (usage);
-	    ++argn;
-	  }
+    while (argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0')
+      {
+        if (pm_keymatch(argv[1], "-debug", 2))
+          debug = 1;
+        else
+          pm_usage (usage);
+        ++argn;
+      }
 
-	if (argc == argn)
-		f = stdin;
-	else {
-		f = pm_openr (argv[argn]);
-		++argn;
-	}
+    if (argc == argn)
+        f = stdin;
+    else {
+        f = pm_openr (argv[argn]);
+        ++argn;
+    }
 
-	if (argn != argc)
-	  pm_usage (usage);
+    if (argn != argc)
+      pm_usage (usage);
 
-	getinit (f, &cols, &rows, &padright, &patlen, &planes);
+    getinit (f, &cols, &rows, &padright, &patlen, &planes);
 
-    if (planes == 1) 
+    if (planes == 1)
         type = PBM_TYPE;
-    else 
+    else
         type = PPM_TYPE;
 
-	pnm_writepnminit( stdout, cols, rows, MAXVAL, type, 0 );
+    pnm_writepnminit( stdout, cols, rows, MAXVAL, type, 0 );
 
-    { 
+    {
         /* allocate input row data structure */
         int plane;
-        for (plane = 0; plane < planes; plane++) 
+        for (plane = 0; plane < planes; plane++)
             bitrow[plane] = malloc (cols + padright);
     }
     xelrow = pnm_allocrow(cols+padright);   /* Output row */
 
-	for (row = 0; row < rows; ) {
+    for (row = 0; row < rows; ) {
       int linerep;
       int plane;
 
-	  linerep = 1;
-	  for (plane = 0; plane < planes; plane++) {
+      linerep = 1;
+      for (plane = 0; plane < planes; plane++) {
         int col;
-		col = 0;
-		while (col < cols) {
+        col = 0;
+        while (col < cols) {
             int c;
-			switch (c = getc(f)) {
-			case 0x80:	/* Bit String */
+            switch (c = getc(f)) {
+            case 0x80:  /* Bit String */
             {
                 int j;
-				c = getc(f);	/* Byte count */
-				if (debug)
+                c = getc(f);    /* Byte count */
+                if (debug)
                   pm_message("bit string of %d bytes", c);
-				
-				if (col + c * 8 > cols + padright)
-				  pm_error ("bad byte count");
-				for (j = 0; j < c; ++j) {
+
+                if (col + c * 8 > cols + padright)
+                  pm_error ("bad byte count");
+                for (j = 0; j < c; ++j) {
                     int cc, k;
-					cc = getc(f);
-					for (k = 0x80; k; k >>= 1) {
-						bitrow[plane][col] = (k & cc) ? 0 : 1;
-						++col;
-					}
-				}
+                    cc = getc(f);
+                    for (k = 0x80; k; k >>= 1) {
+                        bitrow[plane][col] = (k & cc) ? 0 : 1;
+                        ++col;
+                    }
+                }
             }
             break;
-			case 0:		/* Pattern run */
+            case 0:     /* Pattern run */
             {
                 int j, l;
-				c = getc(f);	/* Repeat count */
-				if (debug)
-					pm_message("pattern run of %d repetitions",	c);
+                c = getc(f);    /* Repeat count */
+                if (debug)
+                    pm_message("pattern run of %d repetitions", c);
                 /* line repeat */
                 if (c == 0) {
                     c = getc(f);
@@ -158,25 +158,25 @@ main(argc, argv)
                     linerep = getc(f);
                     break;
                 }
-				fread (pattern, 1, patlen, f);
-				if (col + c * patlen * 8 > cols + padright)
-				  pm_error ("bad pattern repeat count");
-				for (j = 0; j < c; ++j)
-					for (l = 0; l < patlen; ++l) {
+                fread (pattern, 1, patlen, f);
+                if (col + c * patlen * 8 > cols + padright)
+                  pm_error ("bad pattern repeat count");
+                for (j = 0; j < c; ++j)
+                    for (l = 0; l < patlen; ++l) {
                         int k;
-						for (k = 0x80; k; k >>= 1) {
-							bitrow[plane][col] = (k & pattern[l]) ? 0 : 1;
-							++col;
-						}
+                        for (k = 0x80; k; k >>= 1) {
+                            bitrow[plane][col] = (k & pattern[l]) ? 0 : 1;
+                            ++col;
+                        }
                     }
             }
             break;
 
-			default:	/* Solid run */
+            default:    /* Solid run */
             {
                 int l, j;
-				if (debug)
-					pm_message("solid run of %d bytes %s", c & 0x7f,
+                if (debug)
+                    pm_message("solid run of %d bytes %s", c & 0x7f,
                                c & 0x80 ? "on" : "off" );
                 /* each byte had eight bits DSB */
                 l = (c & 0x80) ? 0: 1;
@@ -185,23 +185,23 @@ main(argc, argv)
                     pm_error ("bad solid run repeat count");
                 for (j = 0; j < c; ++j) {
                     bitrow[plane][col] = l;
-					++col;
+                    ++col;
                 }
             }
-				break;
+                break;
 
-			case EOF:	/* End of file */
-				pm_error( "end of file reached" );
+            case EOF:   /* End of file */
+                pm_error( "end of file reached" );
 
-			}
-		}
+            }
+        }
                 if ( debug )
                         pm_message( "EOL plane %d row %d", plane, row );
                 if (col != cols + padright)
                         pm_error( "EOL beyond edge" );
-	  }
+      }
 
-	  if (planes == 4) {
+      if (planes == 4) {
           /* Construct a pixel from the 4 planes of bits for this row */
           int col;
           for (col = 0; col < cols; col++) {
@@ -212,21 +212,21 @@ main(argc, argv)
             const int b_bit = !bitrow[2][col];
             i = bitrow[3][col];
 
-			/* Deal with weird GEM palette - white/black/gray are
-               encoded oddly 
+            /* Deal with weird GEM palette - white/black/gray are
+               encoded oddly
             */
-			if (r_bit == g_bit && g_bit == b_bit) {
+            if (r_bit == g_bit && g_bit == b_bit) {
                 /* It's black, white, or gray */
-				if (r_bit && i) r = LIGHT;
-				else if (r_bit) r = BLACK;
-				else if (i) r = MAXVAL;
-				else r = DARK;
-				g = b = r;	
-			} else {
+                if (r_bit && i) r = LIGHT;
+                else if (r_bit) r = BLACK;
+                else if (i) r = MAXVAL;
+                else r = DARK;
+                g = b = r;
+            } else {
                 /* It's one of the twelve colored colors */
                 if (!i) {
                     /* Low intensity */
-                    r = r_bit * LIGHT; 
+                    r = r_bit * LIGHT;
                     g = g_bit * LIGHT;
                     b = b_bit * LIGHT;
                 } else {
@@ -237,21 +237,21 @@ main(argc, argv)
                 }
             }
             PPM_ASSIGN(xelrow[col], r, g, b);
-		}
-	  } else {
+        }
+      } else {
           int col;
-          for (col = 0; col < cols; col++) 
+          for (col = 0; col < cols; col++)
               PNM_ASSIGN1(xelrow[col], bitrow[0][col]);
       }
-	  while (linerep--) {
-		pnm_writepnmrow( stdout, xelrow, cols, MAXVAL, type, 0 );
-		++row;
-	  }
-	}
+      while (linerep--) {
+        pnm_writepnmrow( stdout, xelrow, cols, MAXVAL, type, 0 );
+        ++row;
+      }
+    }
     pnm_freerow(xelrow);
-	pm_close( f );
-	pm_close( stdout );
-	exit(0);
+    pm_close( f );
+    pm_close( stdout );
+    exit(0);
 }
 
 
@@ -303,3 +303,5 @@ getinit (file, colsP, rowsP, padrightP, patlenP, planesP)
     }
 }
 
+
+
diff --git a/converter/other/jbig/jbigtopnm.c b/converter/other/jbig/jbigtopnm.c
index 733ba227..0d55ccc1 100644
--- a/converter/other/jbig/jbigtopnm.c
+++ b/converter/other/jbig/jbigtopnm.c
@@ -1,22 +1,93 @@
 /*
     jbigtopnm - JBIG to PNM converter
-  
+
     This program was derived from jbgtopbm.c in Markus Kuhn's
     JBIG-KIT package by Bryan Henderson on 2000.05.11
 
     The main difference is that this version uses the Netpbm libraries.
-  
+
  */
 
+#include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <ctype.h>
+#include <limits.h>
+
 #include <jbig.h>
+
 #include "pnm.h"
+#include "shhopt.h"
+#include "mallocvar.h"
 
 #define BUFSIZE 8192
 
 
+
+typedef struct {
+    /* All the information the user supplied in the command line,
+       in a form easy for the program to use.
+    */
+    const char * inputFileName;
+    const char * outputFileName;
+    unsigned long xmax;
+    unsigned long ymax;
+    unsigned int binary;
+    unsigned int diagnose;
+    unsigned int planeSpec;
+    unsigned int plane;
+} CmdlineInfo;
+
+
+
+static void
+parseCommandLine(int                 argc,
+                 const char ** const argv,
+                 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;
+
+    optStruct3 opt;
+
+    unsigned int xmaxSpec, ymaxSpec;
+
+    unsigned int option_def_index;
+
+    MALLOCARRAY_NOFAIL(option_def, 100);
+
+    option_def_index = 0;   /* incremented by OPTENT3 */
+    OPTENT3(0, "binary",   OPT_FLAG, NULL,             &cmdlineP->binary,   0);
+    OPTENT3(0, "diagnose", OPT_FLAG, NULL,             &cmdlineP->diagnose, 0);
+    OPTENT3(0, "plane",    OPT_UINT, &cmdlineP->plane, &cmdlineP->planeSpec,0);
+    OPTENT3(0, "xmax",     OPT_UINT, &cmdlineP->xmax,  &xmaxSpec,           0);
+    OPTENT3(0, "ymax",     OPT_UINT, &cmdlineP->ymax,  &ymaxSpec,           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 (!xmaxSpec)
+        cmdlineP->xmax = UINT_MAX;
+    if (!ymaxSpec)
+        cmdlineP->ymax = UINT_MAX;
+
+    cmdlineP->inputFileName  = (argc-1 >= 1) ? argv[1] : "-";
+    cmdlineP->outputFileName = (argc-1 >= 2) ? argv[2] : "-";
+
+    if (argc-1 > 2)
+        pm_error("Too  many arguments: %u.  The only possible "
+                 "non-option arguments are input file name and "
+                 "output file name", argc-1);
+}
+
+
+
 static void
 collect_image (unsigned char *data, size_t len, void *image) {
     static int cursor = 0;
@@ -29,7 +100,7 @@ collect_image (unsigned char *data, size_t len, void *image) {
 
 
 
-static void 
+static void
 write_pnm (FILE *fout, const unsigned char * const image, const int bpp,
            const int rows, const int cols, const int maxval,
            const int format) {
@@ -46,22 +117,22 @@ write_pnm (FILE *fout, const unsigned char * const image, const int bpp,
         for (col = 0; col < cols; col++) {
             int j;
             for (j = 0; j < bpp; j++)
-                PNM_ASSIGN1(pnm_row[col], 
+                PNM_ASSIGN1(pnm_row[col],
                             image[(((row*cols)+col) * bpp) + j]);
         }
         pnm_writepnmrow(fout, pnm_row, cols, maxval, format, 0);
     }
-    
+
     pnm_freerow(pnm_row);
 }
 
 
 
 static void
-write_raw_pbm(FILE * const fout, 
+write_raw_pbm(FILE * const fout,
               const unsigned char * const binary_image,
               int                   const cols,
-              int                   const rows) { 
+              int                   const rows) {
 
     unsigned int const bytes_per_row = pbm_packed_bytes(cols);
 
@@ -70,7 +141,7 @@ write_raw_pbm(FILE * const fout,
     pbm_writepbminit(fout, cols, rows, 0);
 
     for (row = 0; row < rows; ++row)
-        pbm_writepbmrow_packed(fout, &binary_image[row*bytes_per_row], cols, 
+        pbm_writepbmrow_packed(fout, &binary_image[row*bytes_per_row], cols,
                                0);
 }
 
@@ -79,7 +150,7 @@ write_raw_pbm(FILE * const fout,
 /*
  *
  */
-static void 
+static void
 diagnose_bie(FILE *f)
 {
   unsigned char bih[20];
@@ -89,198 +160,153 @@ diagnose_bie(FILE *f)
   len = fread(bih, 1, 20, f);
   if (len < 20) {
     printf("Input file is %d < 20 bytes long and does therefore not "
-	   "contain an intact BIE header!\n", len);
+       "contain an intact BIE header!\n", len);
     return;
   }
 
   printf("Decomposition of BIH:\n\n  DL = %d\n  D  = %d\n  P  = %d\n"
-	 "  -  = %d\n  XD = %lu\n  YD = %lu\n  L0 = %lu\n  MX = %d\n"
-	 "  MY = %d\n",
-	 bih[0], bih[1], bih[2], bih[3],
-	 xd = ((unsigned long) bih[ 4] << 24) | ((unsigned long)bih[ 5] << 16)|
-	 ((unsigned long) bih[ 6] <<  8) | ((unsigned long) bih[ 7]),
-	 yd = ((unsigned long) bih[ 8] << 24) | ((unsigned long)bih[ 9] << 16)|
-	 ((unsigned long) bih[10] <<  8) | ((unsigned long) bih[11]),
-	 l0 = ((unsigned long) bih[12] << 24) | ((unsigned long)bih[13] << 16)|
-	 ((unsigned long) bih[14] <<  8) | ((unsigned long) bih[15]),
-	 bih[16], bih[17]);
+     "  -  = %d\n  XD = %lu\n  YD = %lu\n  L0 = %lu\n  MX = %d\n"
+     "  MY = %d\n",
+     bih[0], bih[1], bih[2], bih[3],
+     xd = ((unsigned long) bih[ 4] << 24) | ((unsigned long)bih[ 5] << 16)|
+     ((unsigned long) bih[ 6] <<  8) | ((unsigned long) bih[ 7]),
+     yd = ((unsigned long) bih[ 8] << 24) | ((unsigned long)bih[ 9] << 16)|
+     ((unsigned long) bih[10] <<  8) | ((unsigned long) bih[11]),
+     l0 = ((unsigned long) bih[12] << 24) | ((unsigned long)bih[13] << 16)|
+     ((unsigned long) bih[14] <<  8) | ((unsigned long) bih[15]),
+     bih[16], bih[17]);
   printf("  order   = %d %s%s%s%s%s\n", bih[18],
-	 bih[18] & JBG_HITOLO ? " HITOLO" : "",
-	 bih[18] & JBG_SEQ ? " SEQ" : "",
-	 bih[18] & JBG_ILEAVE ? " ILEAVE" : "",
-	 bih[18] & JBG_SMID ? " SMID" : "",
-	 bih[18] & 0xf0 ? " other" : "");
+     bih[18] & JBG_HITOLO ? " HITOLO" : "",
+     bih[18] & JBG_SEQ ? " SEQ" : "",
+     bih[18] & JBG_ILEAVE ? " ILEAVE" : "",
+     bih[18] & JBG_SMID ? " SMID" : "",
+     bih[18] & 0xf0 ? " other" : "");
   printf("  options = %d %s%s%s%s%s%s%s%s\n", bih[19],
-	 bih[19] & JBG_LRLTWO ? " LRLTWO" : "",
-	 bih[19] & JBG_VLENGTH ? " VLENGTH" : "",
-	 bih[19] & JBG_TPDON ? " TPDON" : "",
-	 bih[19] & JBG_TPBON ? " TPBON" : "",
-	 bih[19] & JBG_DPON ? " DPON" : "",
-	 bih[19] & JBG_DPPRIV ? " DPPRIV" : "",
-	 bih[19] & JBG_DPLAST ? " DPLAST" : "",
-	 bih[19] & 0x80 ? " other" : "");
+     bih[19] & JBG_LRLTWO ? " LRLTWO" : "",
+     bih[19] & JBG_VLENGTH ? " VLENGTH" : "",
+     bih[19] & JBG_TPDON ? " TPDON" : "",
+     bih[19] & JBG_TPBON ? " TPBON" : "",
+     bih[19] & JBG_DPON ? " DPON" : "",
+     bih[19] & JBG_DPPRIV ? " DPPRIV" : "",
+     bih[19] & JBG_DPLAST ? " DPLAST" : "",
+     bih[19] & 0x80 ? " other" : "");
   printf("\n  %lu stripes, %d layers, %d planes\n\n",
-	 ((yd >> bih[1]) +  ((((1UL << bih[1]) - 1) & xd) != 0) + l0 - 1) / l0,
-	 bih[1] - bih[0], bih[2]);
+     ((yd >> bih[1]) +  ((((1UL << bih[1]) - 1) & xd) != 0) + l0 - 1) / l0,
+     bih[1] - bih[0], bih[2]);
 
   return;
 }
 
 
-int main (int argc, char **argv)
+int main (int argc, const char **argv)
 {
-    FILE *fin = stdin, *fout = stdout;
-    const char *fnin = "<stdin>", *fnout = "<stdout>";
-    int i, j, result;
-    int all_args = 0, files = 0;
-    struct jbg_dec_state s;
-    char *buffer;
-    unsigned char *p;
-    size_t len, cnt;
-    unsigned long xmax = 4294967295UL, ymax = 4294967295UL;
-    int plane = -1, use_graycode = 1, diagnose = 0;
-
-    pnm_init(&argc, argv);
-
-    buffer = malloc(BUFSIZE);
-    if (!buffer)
-        pm_error("Sorry, not enough memory available!");
-
-    /* parse command line arguments */
-    for (i = 1; i < argc; i++) {
-        if (!all_args && argv[i][0] == '-') {
-            if (argv[i][1] == '\0' && files == 0)
-                ++files;
-            else {
-                for (j = 1; j > 0 && argv[i][j]; j++) {
-                    switch(tolower(argv[i][j])) {
-                    case '-' :
-                        all_args = 1;
-                        break;
-                    case 'b':
-                        use_graycode = 0;
-                        break;
-                    case 'd':
-                        diagnose = 1;
-                        break;
-                    case 'x':
-                        if (++i >= argc)
-                            pm_error("-x needs a value");
-                        xmax = atol(argv[i]);
-                        j = -1;
-                        break;
-                    case 'y':
-                        if (++i >= argc)
-                            pm_error("-y needs a value");
-                        ymax = atol(argv[i]);
-                        j = -1;
-                        break;
-                    case 'p':
-                        if (++i >= argc)
-                            pm_error("-p needs a value");
-                        plane = atoi(argv[i]);
-                        j = -1;
-                        break;
-                    default:
-                        pm_error("Unrecognized option: %c", argv[i][j]);
-                    }
-                }
-            }
-        } else {
-            switch (files++) {
-            case 0:
-                if (argv[i][0] != '-' || argv[i][1] != '\0') {
-                    fnin = argv[i];
-                    fin = fopen(fnin, "rb");
-                    if (!fin)
-                        pm_error("Can't open input file '%s'", fnin);
-                }
-                if (diagnose) {
-                    diagnose_bie(fin);
-                    exit(0);
-                }
-                break;
-            case 1:
-                fnout = argv[i];
-                fout = fopen(fnout, "wb");
-                if (!fout)
-                    pm_error("Can't open output file '%s'", fnout);
+    CmdlineInfo cmdline;
+    FILE * ifP;
+    FILE * ofP;
+
+    pm_proginit(&argc, argv);
+
+    parseCommandLine(argc, argv, &cmdline);
+
+    ifP = pm_openr(cmdline.inputFileName);
+    ofP = pm_openw(cmdline.outputFileName);
+
+    if (cmdline.diagnose)
+        diagnose_bie(ifP);
+    else {
+        struct jbg_dec_state s;
+        unsigned char * buffer;
+        int result;
+
+        MALLOCARRAY(buffer, BUFSIZE);
+        if (!buffer)
+            pm_error("Failed to get %u bytes of memory for buffer", BUFSIZE);
+
+        /* send input file to decoder */
+        jbg_dec_init(&s);
+        jbg_dec_maxsize(&s, cmdline.xmax, cmdline.ymax);
+        result = JBG_EAGAIN;
+        do {
+            size_t len;
+            size_t cnt;
+            unsigned char * p;
+
+            len = fread(buffer, 1, BUFSIZE, ifP);
+            if (len == 0)
                 break;
-            default:
-                pm_error("Too many non-option arguments");
+            cnt = 0;
+            p = &buffer[0];
+            while (len > 0 && (result == JBG_EAGAIN || result == JBG_EOK)) {
+                result = jbg_dec_in(&s, p, len, &cnt);
+                p += cnt;
+                len -= cnt;
+            }
+        } while (result == JBG_EAGAIN || result == JBG_EOK);
+        if (ferror(ifP))
+            pm_error("Error reading input file");
+        if (result != JBG_EOK && result != JBG_EOK_INTR)
+            pm_error("Invalid contents of input file.  %s",
+                     jbg_strerror(result));
+        if (cmdline.planeSpec && jbg_dec_getplanes(&s) <= cmdline.plane)
+            pm_error("Image has only %u planes", jbg_dec_getplanes(&s));
+
+        {
+            /* Write it out */
+
+            int rows, cols;
+            int maxval;
+            int bpp;
+            bool justOnePlane;
+            unsigned int plane_to_write;
+
+            cols = jbg_dec_getwidth(&s);
+            rows = jbg_dec_getheight(&s);
+            maxval = pm_bitstomaxval(jbg_dec_getplanes(&s));
+            bpp = (jbg_dec_getplanes(&s)+7)/8;
+
+            if (jbg_dec_getplanes(&s) == 1) {
+                justOnePlane = true;
+                plane_to_write = 0;
+            } else {
+                if (cmdline.planeSpec) {
+                    justOnePlane = true;
+                    plane_to_write = cmdline.plane;
+                } else
+                    justOnePlane = false;
             }
-        }
-    }
 
-    /* send input file to decoder */
-    jbg_dec_init(&s);
-    jbg_dec_maxsize(&s, xmax, ymax);
-    result = JBG_EAGAIN;
-    do {
-        len = fread(buffer, 1, BUFSIZE, fin);
-        if (!len) break;
-        cnt = 0;
-        p = (unsigned char *) buffer;
-        while (len > 0 && (result == JBG_EAGAIN || result == JBG_EOK)) {
-            result = jbg_dec_in(&s, p, len, &cnt);
-            p += cnt;
-            len -= cnt;
-        }
-    } while (result == JBG_EAGAIN || result == JBG_EOK);
-    if (ferror(fin)) 
-        pm_error("Problem while reading input file '%s", fnin);
-    if (result != JBG_EOK && result != JBG_EOK_INTR) 
-        pm_error("Problem with input file '%s': %s\n", 
-                 fnin, jbg_strerror(result));
-    if (plane >= 0 && jbg_dec_getplanes(&s) <= plane) 
-        pm_error("Image has only %d planes!\n", jbg_dec_getplanes(&s));
-
-    {
-        /* Write it out */
-
-        int rows, cols;
-        int maxval;
-        int bpp;
-        int plane_to_write;
-
-        cols = jbg_dec_getwidth(&s);
-        rows = jbg_dec_getheight(&s);
-        maxval = pm_bitstomaxval(jbg_dec_getplanes(&s));
-        bpp = (jbg_dec_getplanes(&s)+7)/8;
-
-        if (jbg_dec_getplanes(&s) == 1) 
-            plane_to_write = 0;
-        else 
-            plane_to_write = plane;
-
-        if (plane_to_write >= 0) {
-            /* Write just one plane */
-            unsigned char * binary_image;
-
-            pm_message("WRITING PBM FILE");
-
-            binary_image=jbg_dec_getimage(&s, plane_to_write);
-            write_raw_pbm(fout, binary_image, cols, rows);
-        } else {
-            unsigned char *image;
-            pm_message("WRITING PGM FILE");
-
-            /* Write out all the planes */
-            /* What jbig.doc doesn't tell you is that jbg_dec_merge_planes
-               delivers the image in chunks, in consecutive calls to 
-               the data-out callback function.  And a row can span two
-               chunks.
-            */
-            image = malloc(cols*rows*bpp);
-            jbg_dec_merge_planes(&s, use_graycode, collect_image, image);
-            write_pnm(fout, image, bpp, rows, cols, maxval, PGM_TYPE);
-            free(image);
+            if (justOnePlane) {
+                unsigned char * binary_image;
+
+                pm_message("WRITING PBM FILE");
+
+                binary_image=jbg_dec_getimage(&s, plane_to_write);
+                write_raw_pbm(ofP, binary_image, cols, rows);
+            } else {
+                unsigned char *image;
+                pm_message("WRITING PGM FILE");
+
+                /* Write out all the planes */
+                /* What jbig.doc doesn't tell you is that jbg_dec_merge_planes
+                   delivers the image in chunks, in consecutive calls to
+                   the data-out callback function.  And a row can span two
+                   chunks.
+                */
+                image = malloc(cols*rows*bpp);
+                jbg_dec_merge_planes(&s, !cmdline.binary, collect_image,
+                                     image);
+                write_pnm(ofP, image, bpp, rows, cols, maxval, PGM_TYPE);
+                free(image);
+            }
+            jbg_dec_free(&s);
         }
-    }
-  
-    pm_close(fout);
-
-    jbg_dec_free(&s);
 
+        pm_close(ofP);
+        pm_close(ifP);
+        free(buffer);
+    }
     return 0;
 }
+
+
+
diff --git a/converter/other/jbig/libjbig/jbig.c b/converter/other/jbig/libjbig/jbig.c
index ba9c6452..e8141070 100644
--- a/converter/other/jbig/libjbig/jbig.c
+++ b/converter/other/jbig/libjbig/jbig.c
@@ -22,7 +22,7 @@
  *  You should have received a copy of the GNU General Public License
  *  along with this program; if not, write to the Free Software
  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- * 
+ *
  *  If you want to use this program under different license conditions,
  *  then contact the author for an arrangement.
  */
@@ -66,7 +66,7 @@
 
 /* object code version id */
 
-const char jbg_version[] = 
+const char jbg_version[] =
   "JBIG-KIT " JBG_VERSION " -- (c) 1995-2014 Markus Kuhn -- "
   "Licence: " JBG_LICENCE "\n";
 
@@ -115,7 +115,7 @@ static const char *errmsg[] = {
  * then simply add the necessary semaphores or mutex primitives below.
  * In contrast to C's malloc() and realloc(), but like C's calloc(),
  * these functions take two parameters nmemb and size that are multiplied
- * before being passed on to the corresponding C function. 
+ * before being passed on to the corresponding C function.
  * This we can catch all overflows during a size_t multiplication a
  * a single place.
  */
@@ -135,7 +135,7 @@ static void *checked_malloc(size_t nmemb, size_t size)
   /* assert that nmemb * size <= SIZE_MAX */
   if (size > SIZE_MAX / nmemb)
     abort();
-  
+
   p = malloc(nmemb * size);
 
   if (!p)
@@ -161,7 +161,7 @@ static void *checked_realloc(void *ptr, size_t nmemb, size_t size)
   /* assert that nmemb * size <= SIZE_MAX */
   if (size > SIZE_MAX / nmemb)
     abort();
-  
+
   p = realloc(ptr, nmemb * size);
 
   if (!p)
@@ -210,7 +210,7 @@ static void checked_free(void *ptr)
 static struct jbg_buf *jbg_buf_init(struct jbg_buf **free_list)
 {
   struct jbg_buf *new_block;
-  
+
   /* Test whether a block from the free list is available */
   if (*free_list) {
     new_block = *free_list;
@@ -236,13 +236,13 @@ static struct jbg_buf *jbg_buf_init(struct jbg_buf **free_list)
 static void jbg_buf_free(struct jbg_buf **free_list)
 {
   struct jbg_buf *tmp;
-  
+
   while (*free_list) {
     tmp = (*free_list)->next;
     checked_free(*free_list);
     *free_list = tmp;
   }
-  
+
   return;
 }
 
@@ -306,7 +306,7 @@ static void jbg_buf_remove_zeros(struct jbg_buf *head)
    */
   if (head->last->len && head->last->d[head->last->len - 1] == MARKER_ESC)
     jbg_buf_write(MARKER_STUFF, head);
- 
+
   return;
 }
 
@@ -322,7 +322,7 @@ static void jbg_buf_prefix(struct jbg_buf *new_prefix, struct jbg_buf **start)
   new_prefix->last->next->previous = new_prefix->last;
   new_prefix->last = new_prefix->last->next->last;
   *start = new_prefix;
-  
+
   return;
 }
 
@@ -339,7 +339,7 @@ static void jbg_buf_output(struct jbg_buf **head,
 			void *file)
 {
   struct jbg_buf *tmp;
-  
+
   while (*head) {
     data_out((*head)->d, (*head)->len, file);
     tmp = (*head)->next;
@@ -347,7 +347,7 @@ static void jbg_buf_output(struct jbg_buf **head,
     *(*head)->free_list = *head;
     *head = tmp;
   }
-  
+
   return;
 }
 
@@ -362,7 +362,7 @@ static void jbg_buf_output(struct jbg_buf **head,
 unsigned long jbg_ceil_half(unsigned long x, int n)
 {
   unsigned long mask;
-  
+
   assert(n >= 0 && n < 32);
   mask = (1UL << n) - 1;     /* the lowest n bits are 1 here */
   return (x >> n) + ((mask & x) != 0);
@@ -794,7 +794,7 @@ void jbg_enc_init(struct jbg_enc_state *s, unsigned long x, unsigned long y,
   s->comment = NULL;
   s->dppriv = jbg_dptable;
   s->res_tab = jbg_resred;
-  
+
   s->highres = (int *) checked_malloc(planes, sizeof(int));
   s->lhp[0] = p;
   s->lhp[1] = (unsigned char **)
@@ -804,9 +804,9 @@ void jbg_enc_init(struct jbg_enc_state *s, unsigned long x, unsigned long y,
     s->lhp[1][i] = (unsigned char *)
       checked_malloc(jbg_ceil_half(y, 1), jbg_ceil_half(x, 1+3));
   }
-  
+
   s->free_list = NULL;
-  s->s = (struct jbg_arenc_state *) 
+  s->s = (struct jbg_arenc_state *)
     checked_malloc(s->planes, sizeof(struct jbg_arenc_state));
   s->tx = (int *) checked_malloc(s->planes, sizeof(int));
   lx = jbg_ceil_half(x, 1);
@@ -828,9 +828,9 @@ void jbg_enc_init(struct jbg_enc_state *s, unsigned long x, unsigned long y,
  * l0 (height of one stripe in the lowest resolution layer) is
  * selected, which obeys the recommended limitations for l0 in annex A
  * and C of the JBIG standard. The selected number of resolution layers
- * is returned. 
+ * is returned.
  */
-int jbg_enc_lrlmax(struct jbg_enc_state *s, unsigned long x, 
+int jbg_enc_lrlmax(struct jbg_enc_state *s, unsigned long x,
 		   unsigned long y)
 {
   for (s->d = 0; s->d < 6; s->d++)
@@ -844,8 +844,8 @@ int jbg_enc_lrlmax(struct jbg_enc_state *s, unsigned long x,
 
 
 /*
- * As an alternative to jbg_enc_lrlmax(), the following function allows
- * to specify the number of layers directly. The stripe height and layer
+ * As an alternative to jbg_enc_lrlmax(), the following function allows the
+ * user to specify the number of layers directly. The stripe height and layer
  * range is also adjusted automatically here.
  */
 void jbg_enc_layers(struct jbg_enc_state *s, int d)
@@ -877,9 +877,9 @@ int jbg_enc_lrange(struct jbg_enc_state *s, int dl, int dh)
 
 
 /*
- * The following function allows to specify the bits describing the
- * options of the format as well as the maximum AT movement window and
- * the number of layer 0 lines per stripes.
+ * The following function allows the user to specify the bits describing the
+ * options of the format as well as the maximum AT movement window and the
+ * number of layer 0 lines per stripes.
  */
 void jbg_enc_options(struct jbg_enc_state *s, int order, int options,
 		     unsigned long l0, int mx, int my)
@@ -955,7 +955,7 @@ static void encode_sde(struct jbg_enc_state *s,
   hp = s->lhp[s->highres[plane]][plane] + stripe * hl * hbpl;
   lp2 = s->lhp[1 - s->highres[plane]][plane] + stripe * ll * lbpl;
   lp1 = lp2 + lbpl;
-  
+
   /* check whether we can refer to any state of a previous stripe */
   reset = (stripe == 0) || (s->options & JBG_SDRST);
 
@@ -1033,7 +1033,7 @@ static void encode_sde(struct jbg_enc_state *s,
 	at_determined = 1;
       }
       assert(s->tx[plane] >= 0); /* i.e., tx can safely be cast to unsigned */
-      
+
       /* typical prediction */
       if (s->options & JBG_TPBON) {
 	ltp = 1;
@@ -1064,11 +1064,11 @@ static void encode_sde(struct jbg_enc_state *s,
        *          76543210765432107654321076543210     line_h2
        *  76543210765432107654321X76543210             line_h1
        */
-      
+
       line_h1 = line_h2 = line_h3 = 0;
       if (i > 0 || !reset) line_h2 = (long)*(hp - hbpl) << 8;
       if (i > 1 || !reset) line_h3 = (long)*(hp - hbpl - hbpl) << 8;
-      
+
       /* encode line */
       for (j = 0; j < hx; hp++) {
 	line_h1 |= *hp;
@@ -1175,7 +1175,7 @@ static void encode_sde(struct jbg_enc_state *s,
     /*
      *  Encode differential layer
      */
-    
+
     for (i = 0; i < hl && y < hy; i++, y++) {
 
       /* check whether it is worth to perform an ATMOVE */
@@ -1211,7 +1211,7 @@ static void encode_sde(struct jbg_enc_state *s,
 	}
 	at_determined = 1;
       }
-      
+
       if ((i >> 1) >= ll - 1 || (y >> 1) >= ly - 1)
 	lp1 = lp2;
 
@@ -1297,7 +1297,7 @@ static void encode_sde(struct jbg_enc_state *s,
        *            76543210 7654321Y 76543210 76543210     line_l2
        *            76543210 76543210 76543210 76543210     line_l1
        */
-      
+
 
       line_h1 = line_h2 = line_h3 = line_l1 = line_l2 = line_l3 = 0;
       if (i > 0 || !reset) line_h2 = (long)*(hp - hbpl) << 8;
@@ -1307,7 +1307,7 @@ static void encode_sde(struct jbg_enc_state *s,
       }
       line_l2 = (long)*lp2 << 8;
       line_l1 = (long)*lp1 << 8;
-      
+
       /* encode line */
       for (j = 0; j < hx; lp1++, lp2++) {
 	if ((j >> 1) < lbpl * 8 - 8) {
@@ -1401,8 +1401,8 @@ static void encode_sde(struct jbg_enc_state *s,
 #endif
 			continue;
 		      }
-		    }	
-		  }	
+		    }
+		  }
 		}
 
 		/* determine context */
@@ -1435,7 +1435,7 @@ static void encode_sde(struct jbg_enc_state *s,
 #ifdef DEBUG
 		encoded_pixels++;
 #endif
-		
+
 		/* statistics for adaptive template changes */
 		if (!at_determined && j >= s->mx) {
 		  c[0] += !(((line_h2 >> 6) ^ line_h1) & 0x100);
@@ -1443,7 +1443,7 @@ static void encode_sde(struct jbg_enc_state *s,
 		    c[t] += !(((line_h1 >> t) ^ line_h1) & 0x100);
 		  ++c_all;
 		}
-		
+
 	      } while (++j & 1 && j < hx);
 	  } while (j & 7 && j < hx);
 	  hp++;
@@ -1455,10 +1455,10 @@ static void encode_sde(struct jbg_enc_state *s,
 	lp1 -= lbpl;
 	lp2 -= lbpl;
       }
-      
+
     } /* for (i = ...) */
   }
-  
+
   arith_encode_flush(se);
   jbg_buf_remove_zeros(s->sde[stripe][layer][plane]);
   jbg_buf_write(MARKER_ESC, s->sde[stripe][layer][plane]);
@@ -1539,7 +1539,7 @@ static void resolution_reduction(struct jbg_enc_state *s, int plane,
   hp1 = hp2 + hbpl;
   hp3 = hp2 - hbpl;
   lp = s->lhp[1 - s->highres[plane]][plane];
-  
+
 #ifdef DEBUG
   fprintf(stderr, "resolution_reduction: plane = %d, higher_layer = %d\n",
 	  plane, higher_layer);
@@ -1606,7 +1606,7 @@ static void resolution_reduction(struct jbg_enc_state *s, int plane,
   {
     FILE *f;
     char fn[50];
-    
+
     sprintf(fn, "dbg_d=%02d.pbm", higher_layer - 1);
     f = fopen(fn, "wb");
     fprintf(f, "P4\n%lu %lu\n", lx, ly);
@@ -1619,7 +1619,7 @@ static void resolution_reduction(struct jbg_enc_state *s, int plane,
 }
 
 
-/* 
+/*
  * This function is called inside the three loops of jbg_enc_out() in
  * order to write the next SDE. It has first to generate the required
  * SDE and all SDEs which have to be encoded before this SDE can be
@@ -1640,7 +1640,7 @@ static void output_sde(struct jbg_enc_state *s,
   int lfcl;     /* lowest fully coded layer */
   long i;
   unsigned long u;
-  
+
   assert(s->sde[stripe][layer][plane] != SDE_DONE);
 
   if (s->sde[stripe][layer][plane] != SDE_TODO) {
@@ -1677,7 +1677,7 @@ static void output_sde(struct jbg_enc_state *s,
     if (lfcl > 1)
       resolution_reduction(s, plane, lfcl - 1);
   }
-  
+
   encode_sde(s, stripe, layer, plane);
 
 #ifdef DEBUG
@@ -1685,14 +1685,14 @@ static void output_sde(struct jbg_enc_state *s,
 #endif
   jbg_buf_output(&s->sde[stripe][layer][plane], s->data_out, s->file);
   s->sde[stripe][layer][plane] = SDE_DONE;
-  
+
   if (stripe == s->stripes - 1 && layer > 0 &&
       s->sde[0][layer-1][plane] == SDE_TODO) {
     s->highres[plane] ^= 1;
     if (layer > 1)
       resolution_reduction(s, plane, layer - 1);
   }
-  
+
   return;
 }
 
@@ -1727,7 +1727,7 @@ void jbg_int2dppriv(unsigned char *dptable, const char *internal)
   int trans1[ 9] = { 1, 0, 3, 2, 8, 7, 6, 5, 4 };
   int trans2[11] = { 1, 0, 3, 2, 10, 9, 8, 7, 6, 5, 4 };
   int trans3[12] = { 1, 0, 3, 2, 11, 10, 9, 8, 7, 6, 5, 4 };
-  
+
   for (i = 0; i < 1728; dptable[i++] = 0) ;
 
 #define FILL_TABLE1(offset, len, trans) \
@@ -1760,7 +1760,7 @@ void jbg_dppriv2int(char *internal, const unsigned char *dptable)
   int trans1[ 9] = { 1, 0, 3, 2, 8, 7, 6, 5, 4 };
   int trans2[11] = { 1, 0, 3, 2, 10, 9, 8, 7, 6, 5, 4 };
   int trans3[12] = { 1, 0, 3, 2, 11, 10, 9, 8, 7, 6, 5, 4 };
-  
+
 #define FILL_TABLE2(offset, len, trans) \
   for (i = 0; i < len; i++) { \
     k = 0; \
@@ -1788,7 +1788,7 @@ void jbg_enc_out(struct jbg_enc_state *s)
   unsigned long bpl;
   unsigned char buf[20];
   unsigned long xd, yd, y;
-  long ii[3], is[3], ie[3];    /* generic variables for the 3 nested loops */ 
+  long ii[3], is[3], ie[3];    /* generic variables for the 3 nested loops */
   unsigned long stripe;
   int layer, plane;
   int order;
@@ -1916,7 +1916,7 @@ void jbg_enc_out(struct jbg_enc_state *s)
   for (ii[0] = is[0]; ii[0] <= ie[0]; ii[0]++)
     for (ii[1] = is[1]; ii[1] <= ie[1]; ii[1]++)
       for (ii[2] = is[2]; ii[2] <= ie[2]; ii[2]++) {
-	
+
 	stripe = ii[iindex[order][STRIPE]];
 	if (s->order & JBG_HITOLO)
 	  layer = s->dh - (ii[iindex[order][LAYER]] - s->dl);
@@ -1947,7 +1947,7 @@ void jbg_enc_out(struct jbg_enc_state *s)
 	 */
 	if (s->yd1 > s->yd &&
 	    (stripe == s->stripes - 1 ||
-	     (stripe == s->stripes - 2 && 
+	     (stripe == s->stripes - 2 &&
 	      (s->dl != s->dh || s->planes > 1)))) {
 	  s->yd1 = s->yd;
 	  yd = jbg_ceil_half(s->yd, s->d - s->dh);
@@ -2015,10 +2015,10 @@ void jbg_enc_free(struct jbg_enc_state *s)
       checked_free(s->lhp[1][plane]);
     checked_free(s->lhp[1]);
   }
-  
+
   /* clear buffer for index of highres image in lhp */
   checked_free(s->highres);
-  
+
   return;
 }
 
@@ -2037,7 +2037,7 @@ const char *jbg_strerror(int errnum)
 
 
 /*
- * The constructor for a decoder 
+ * The constructor for a decoder
  */
 void jbg_dec_init(struct jbg_dec_state *s)
 {
@@ -2075,7 +2075,7 @@ void jbg_dec_maxsize(struct jbg_dec_state *s, unsigned long xmax,
 /*
  * Decode the new len PSDC bytes to which data points and add them to
  * the current stripe. Return the number of bytes which have actually
- * been read (this will be less than len if a marker segment was 
+ * been read (this will be less than len if a marker segment was
  * part of the data or if the final byte was 0xff, in which case
  * this code cannot determine whether we have a marker segment).
  */
@@ -2104,7 +2104,7 @@ static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data,
   se = s->s[plane] + layer - s->dl;
   se->pscd_ptr = data;
   se->pscd_end = data + len;
-  
+
   /* number of lines per stripe in highres image */
   hl = s->l0 << layer;
   /* number of lines per stripe in lowres image */
@@ -2192,7 +2192,7 @@ static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data,
 	/* this line is 'not typical' and has to be coded completely */
       }
       s->pseudo = 0;
-      
+
       /*
        * Layout of the variables line_h1, line_h2, line_h3, which contain
        * as bits the neighbour pixels of the currently decoded pixel X:
@@ -2201,7 +2201,7 @@ static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data,
        *                     76543210 76543210 76543210 76543210     line_h2
        *   76543210 76543210 76543210 76543210 X                     line_h1
        */
-      
+
       if (x == 0) {
 	line_h1 = line_h2 = line_h3 = 0;
 	if (s->i > 0 || (y > 0 && !s->reset[plane][layer - s->dl]))
@@ -2209,7 +2209,7 @@ static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data,
 	if (s->i > 1 || (y > 1 && !s->reset[plane][layer - s->dl]))
 	  line_h3 = (long)*(hp - hbpl - hbpl) << 8;
       }
-      
+
       /*
        * Another tiny JBIG standard bug:
        *
@@ -2313,7 +2313,7 @@ static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data,
 				      (line_h1 & 0x003)));
 	    if (pix < 0)
 	      goto leave;
-	    
+
 	    line_h1 = (line_h1 << 1) | pix;
 	    line_h2 <<= 1;
 	    line_h3 <<= 1;
@@ -2325,7 +2325,7 @@ static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data,
       x = 0;
       s->pseudo = 1;
     } /* for (i = ...) */
-    
+
   } else {
 
     /*
@@ -2376,7 +2376,7 @@ static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data,
        *                     76543210 76543210 Y6543210 76543210     line_l2
        *                     76543210 76543210 76543210 76543210     line_l1
        */
-      
+
 
       if (x == 0) {
 	line_h1 = line_h2 = line_h3 = line_l1 = line_l2 = line_l3 = 0;
@@ -2390,14 +2390,14 @@ static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data,
 	line_l2 = (long)*lp2 << 8;
 	line_l1 = (long)*lp1 << 8;
       }
-      
+
       /* decode line */
       while (x < hx) {
 	if ((x & 15) == 0)
 	  if ((x >> 1) < lbpl * 8 - 8) {
 	    line_l1 |= *(lp1 + 1);
 	    line_l2 |= *(lp2 + 1);
-	    if (s->i > 1 || 
+	    if (s->i > 1 ||
 		(y > 1 && !s->reset[plane][layer - s->dl]))
 	      line_l3 |= *(lp2 - lbpl + 1);
 	  }
@@ -2428,13 +2428,13 @@ static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data,
 		line_h1 = (line_h1 << 1) | (cx & 1);
 	      } while ((++x & 1) && x < hx);
 	      line_h2 <<= 2;  line_h3 <<= 2;
-	    } else 
+	    } else
 	      do {
-		
+
 		/* deterministic prediction */
 		if (s->options & JBG_DPON)
 		  if ((y & 1) == 0)
-		    if ((x & 1) == 0) 
+		    if ((x & 1) == 0)
 		      /* phase 0 */
 		      pix = s->dppriv[((line_l3 >> 15) & 0x003) |
 				      ((line_l2 >> 13) & 0x00c) |
@@ -2490,7 +2490,7 @@ static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data,
 		line_h1 = (line_h1 << 1) | pix;
 		line_h2 <<= 1;
 		line_h3 <<= 1;
-		
+
 	      } while ((++x & 1) && x < hx);
 	    line_l1 <<= 1; line_l2 <<= 1;  line_l3 <<= 1;
 	  } while ((x & 7) && x < hx);
@@ -2500,7 +2500,7 @@ static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data,
 	++lp2;
       } /* while */
       x = 0;
-      
+
       *(hp - 1) <<= hbpl * 8 - hx;
       if ((s->i & 1) == 0) {
 	/* low resolution pixels are used twice */
@@ -2508,9 +2508,9 @@ static size_t decode_pscd(struct jbg_dec_state *s, unsigned char *data,
 	lp2 -= lbpl;
       } else
 	s->pseudo = 1;
-      
+
     } /* for (i = ...) */
-    
+
   }
 
  leave:
@@ -2579,7 +2579,7 @@ int jbg_dec_in(struct jbg_dec_state *s, unsigned char *data, size_t len,
   if (s->bie_len < 20) {
     while (s->bie_len < 20 && *cnt < len)
       s->buffer[s->bie_len++] = data[(*cnt)++];
-    if (s->bie_len < 20) 
+    if (s->bie_len < 20)
       return JBG_EAGAIN;
     /* test whether this looks like a valid JBIG header at all */
     if (s->buffer[1] < s->buffer[0])
@@ -2640,7 +2640,7 @@ int jbg_dec_in(struct jbg_dec_state *s, unsigned char *data, size_t len,
 
     /* calculate number of stripes that will be required */
     s->stripes = jbg_stripes(s->l0, s->yd, s->d);
-    
+
     /* some initialization */
     s->ii[iindex[s->order & 7][STRIPE]] = 0;
     s->ii[iindex[s->order & 7][LAYER]] = s->dl;
@@ -2703,7 +2703,7 @@ int jbg_dec_in(struct jbg_dec_state *s, unsigned char *data, size_t len,
   }
 
   /* read in DPTABLE */
-  if (s->bie_len < 20 + 1728 && 
+  if (s->bie_len < 20 + 1728 &&
       (s->options & (JBG_DPON | JBG_DPPRIV | JBG_DPLAST)) ==
       (JBG_DPON | JBG_DPPRIV)) {
     assert(s->bie_len >= 20);
@@ -2711,7 +2711,7 @@ int jbg_dec_in(struct jbg_dec_state *s, unsigned char *data, size_t len,
       s->dppriv = (char *) checked_malloc(1728, sizeof(char));
     while (s->bie_len < 20 + 1728 && *cnt < len)
       s->dppriv[s->bie_len++ - 20] = data[(*cnt)++];
-    if (s->bie_len < 20 + 1728) 
+    if (s->bie_len < 20 + 1728)
       return JBG_EAGAIN;
     dppriv = (unsigned char *) s->dppriv;
     s->dppriv = (char *) checked_malloc(6912, sizeof(char));
@@ -2722,7 +2722,7 @@ int jbg_dec_in(struct jbg_dec_state *s, unsigned char *data, size_t len,
   /*
    * BID processing loop
    */
-  
+
   while (*cnt < len) {
 
     /* process floating marker segments */
@@ -2799,27 +2799,27 @@ int jbg_dec_in(struct jbg_dec_state *s, unsigned char *data, size_t len,
 	break;
       case MARKER_ABORT:
 	return JBG_EABORT;
-	
+
       case MARKER_SDNORM:
       case MARKER_SDRST:
 	/* decode final pixels based on trailing zero bytes */
 	decode_pscd(s, s->buffer, 2);
 
-	arith_decode_init(s->s[s->ii[iindex[s->order & 7][PLANE]]] + 
+	arith_decode_init(s->s[s->ii[iindex[s->order & 7][PLANE]]] +
 			  s->ii[iindex[s->order & 7][LAYER]] - s->dl,
 			  s->ii[iindex[s->order & 7][STRIPE]] != s->stripes - 1
 			  && s->buffer[1] != MARKER_SDRST);
-	
+
 	s->reset[s->ii[iindex[s->order & 7][PLANE]]]
 	  [s->ii[iindex[s->order & 7][LAYER]] - s->dl] =
 	    (s->buffer[1] == MARKER_SDRST);
-	
+
 	/* prepare for next SDE */
 	s->x = 0;
 	s->i = 0;
 	s->pseudo = 1;
 	s->at_moves = 0;
-	
+
 	/* increment layer/stripe/plane loop variables */
 	/* start and end value for each loop: */
 	is[iindex[s->order & 7][STRIPE]] = 0;
@@ -2840,7 +2840,7 @@ int jbg_dec_in(struct jbg_dec_state *s, unsigned char *data, size_t len,
 	} while (--i >= 0 && j);
 
 	s->buf_len = 0;
-	
+
 	/* check whether this have been all SDEs */
 	if (j) {
 #ifdef DEBUG
@@ -2885,7 +2885,7 @@ int jbg_dec_in(struct jbg_dec_state *s, unsigned char *data, size_t len,
 #endif
 	return JBG_EINVAL | 14;
       }
-      
+
     }
   }  /* of BID processing loop 'while (*cnt < len) ...' */
 
@@ -2928,7 +2928,7 @@ unsigned long jbg_dec_getheight(const struct jbg_dec_state *s)
     else
       return jbg_ceil_half(s->yd, s->d - (s->ii[0] - 1));
   }
-  
+
   return s->yd;
 }
 
@@ -2948,7 +2948,7 @@ unsigned char *jbg_dec_getimage(const struct jbg_dec_state *s, int plane)
     else
       return s->lhp[(s->ii[0] - 1) & 1][plane];
   }
-  
+
   return s->lhp[s->d & 1][plane];
 }
 
@@ -2966,11 +2966,11 @@ unsigned long jbg_dec_getsize(const struct jbg_dec_state *s)
     if (s->ii[0] < 1)
       return 0;
     else
-      return 
+      return
 	jbg_ceil_half(s->xd, s->d - (s->ii[0] - 1) + 3) * /* overflow risk? */
 	jbg_ceil_half(s->yd, s->d - (s->ii[0] - 1));
   }
-  
+
   return jbg_ceil_half(s->xd, 3) * s->yd;
 }
 
@@ -2988,17 +2988,17 @@ unsigned long jbg_dec_getsize_merged(const struct jbg_dec_state *s)
     if (s->ii[0] < 1)
       return 0;
     else
-      return 
+      return
 	jbg_ceil_half(s->xd, s->d - (s->ii[0] - 1)) * /* overflow risk? */
 	jbg_ceil_half(s->yd, s->d - (s->ii[0] - 1)) *
 	((s->planes + 7) / 8);
   }
-  
+
   return s->xd * s->yd * ((s->planes + 7) / 8);
 }
 
 
-/* 
+/*
  * The destructor function which releases any resources obtained by the
  * other decoder functions.
  */
@@ -3019,7 +3019,7 @@ void jbg_dec_free(struct jbg_dec_state *s)
     checked_free(s->lhp[0][i]);
     checked_free(s->lhp[1][i]);
   }
-  
+
   checked_free(s->s);
   checked_free(s->tx);
   checked_free(s->ty);
@@ -3061,10 +3061,10 @@ void jbg_split_planes(unsigned long x, unsigned long y, int has_planes,
   if (encode_planes > has_planes)
     encode_planes = has_planes;
   use_graycode = use_graycode != 0 && encode_planes > 1;
-  
+
   for (p = 0; p < encode_planes; p++)
     memset(dest[p], 0, bpl * y);
-  
+
   for (line = 0; line < y; line++) {                 /* lines loop */
     for (i = 0; i * 8 < x; i++) {                    /* dest bytes loop */
       for (k = 0; k < 8 && i * 8 + k < x; k++) {     /* pixel loop */
@@ -3096,11 +3096,11 @@ void jbg_split_planes(unsigned long x, unsigned long y, int has_planes,
     for (p = 0; p < encode_planes; p++)              /* right padding loop */
       dest[p][bpl * (line + 1) - 1] <<= 8 - k;
   }
-  
+
   return;
 }
 
-/* 
+/*
  * Merge the separate bit planes decoded by the JBIG decoder into an
  * integer pixel field. This is essentially the counterpart to
  * jbg_split_planes().
@@ -3121,7 +3121,7 @@ void jbg_dec_merge_planes(const struct jbg_dec_state *s, int use_graycode,
 
   /* sanity check */
   use_graycode = use_graycode != 0;
-  
+
   x = jbg_dec_getwidth(s);
   y = jbg_dec_getheight(s);
   if (x == 0 || y == 0)
@@ -3135,7 +3135,7 @@ void jbg_dec_merge_planes(const struct jbg_dec_state *s, int use_graycode,
       src = s->lhp[(s->ii[0] - 1) & 1];
   else
     src = s->lhp[s->d & 1];
-  
+
   for (line = 0; line < y; line++) {                    /* lines loop */
     for (i = 0; i * 8 < x; i++) {                       /* src bytes loop */
       for (k = 0; k < 8 && i * 8 + k < x; k++) {        /* pixel loop */
@@ -3155,10 +3155,10 @@ void jbg_dec_merge_planes(const struct jbg_dec_state *s, int use_graycode,
       }
     }
   }
-  
+
   if (bp - buf > 0)
     data_out(buf, bp - buf, file);
-  
+
   return;
 }
 
@@ -3173,7 +3173,7 @@ void jbg_dec_merge_planes(const struct jbg_dec_state *s, int use_graycode,
  *  - not enough bytes left for complete marker segment
  *  - no marker segment terminates the PSCD
  *  - unknown marker code encountered
- *  
+ *
  */
 static unsigned char *jbg_next_pscdms(unsigned char *p, size_t len)
 {
diff --git a/converter/other/jpeg2000/jpeg2ktopam.c b/converter/other/jpeg2000/jpeg2ktopam.c
index b7276241..b507f56e 100644
--- a/converter/other/jpeg2000/jpeg2ktopam.c
+++ b/converter/other/jpeg2000/jpeg2ktopam.c
@@ -62,7 +62,7 @@ parseCommandLine(int argc, char ** argv,
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENTRY */
-    OPTENT3(0, "verbose",      OPT_FLAG,   NULL, 
+    OPTENT3(0, "verbose",      OPT_FLAG,   NULL,
             &cmdlineP->verbose,   0);
     OPTENT3(0, "debuglevel",   OPT_UINT,   &cmdlineP->debuglevel,
             &debuglevelSpec,      0);
@@ -80,7 +80,7 @@ parseCommandLine(int argc, char ** 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\n"
                  "is the input file specification");
 
@@ -107,11 +107,11 @@ validateJ2k(jas_stream_t * const instreamP) {
     }
 }
 
-        
+
 
 
 static void
-readJ2k(const char *   const inputFilename, 
+readJ2k(const char *   const inputFilename,
         jas_image_t ** const jasperPP) {
 
     jas_image_t * jasperP;
@@ -127,7 +127,7 @@ readJ2k(const char *   const inputFilename,
         instreamP = jas_stream_fopen(inputFilename, "rb");
         if (instreamP == NULL )
             pm_error("cannot open input image file '%s'", inputFilename);
-    } 
+    }
 
     validateJ2k(instreamP);
 
@@ -139,7 +139,7 @@ readJ2k(const char *   const inputFilename,
         pm_error("Unable to interpret JPEG-2000 input.  "
                  "The Jasper library jas_image_decode() subroutine failed.");
 
-	jas_stream_close(instreamP);
+    jas_stream_close(instreamP);
 
     *jasperPP = jasperP;
 }
@@ -150,7 +150,7 @@ static void
 getRgbComponents(int jasperCmpnt[], jas_image_t * const jasperP) {
 
     {
-        int const rc = 
+        int const rc =
             jas_image_getcmptbytype(jasperP,
                                     JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_RGB_R));
         if (rc < 0)
@@ -159,12 +159,12 @@ getRgbComponents(int jasperCmpnt[], jas_image_t * const jasperP) {
         else
             jasperCmpnt[PAM_RED_PLANE] = rc;
 
-        if (jas_image_cmptsgnd(jasperP, rc)) 
+        if (jas_image_cmptsgnd(jasperP, rc))
             pm_error("Input image says it is RGB, but has signed values "
                      "for what should be the red intensities.");
     }
     {
-        int const rc = 
+        int const rc =
             jas_image_getcmptbytype(jasperP,
                                     JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_RGB_G));
         if (rc < 0)
@@ -173,12 +173,12 @@ getRgbComponents(int jasperCmpnt[], jas_image_t * const jasperP) {
         else
             jasperCmpnt[PAM_GRN_PLANE] = rc;
 
-        if (jas_image_cmptsgnd(jasperP, rc)) 
+        if (jas_image_cmptsgnd(jasperP, rc))
             pm_error("Input image says it is RGB, but has signed values "
                      "for what should be the green intensities.");
     }
     {
-        int const rc = 
+        int const rc =
             jas_image_getcmptbytype(jasperP,
                                     JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_RGB_B));
         if (rc < 0)
@@ -187,18 +187,18 @@ getRgbComponents(int jasperCmpnt[], jas_image_t * const jasperP) {
         else
             jasperCmpnt[PAM_BLU_PLANE] = rc;
 
-        if (jas_image_cmptsgnd(jasperP, rc)) 
+        if (jas_image_cmptsgnd(jasperP, rc))
             pm_error("Input image says it is RGB, but has signed values "
                      "for what should be the blue intensities.");
     }
-}            
+}
 
 
 
 static void
 getGrayComponent(int * jasperCmptP, jas_image_t * const jasperP) {
 
-    int const rc = 
+    int const rc =
         jas_image_getcmptbytype(jasperP,
                                 JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_GRAY_Y));
     if (rc < 0)
@@ -206,7 +206,7 @@ getGrayComponent(int * jasperCmptP, jas_image_t * const jasperP) {
                  "no gray intensity component");
     else
         *jasperCmptP = rc;
-    if (jas_image_cmptsgnd(jasperP, 0)) 
+    if (jas_image_cmptsgnd(jasperP, 0))
         pm_error("Input image says it is grayscale, but has signed values "
                  "for what should be the gray levels.");
 }
@@ -221,13 +221,13 @@ validateComponentsAlike(jas_image_t * const jasperP) {
    all the channels are the same, and abort the program if not.
 -----------------------------------------------------------------------------*/
     int cmptNo;
-    
+
     for (cmptNo = 0; cmptNo < jas_image_numcmpts(jasperP); ++cmptNo) {
-        if (jas_image_cmptwidth(jasperP, cmptNo) != 
+        if (jas_image_cmptwidth(jasperP, cmptNo) !=
             jas_image_cmptwidth(jasperP, 0))
             pm_message("Input image does not have components all the same "
                        "width.");
-        if (jas_image_cmptheight(jasperP, cmptNo) != 
+        if (jas_image_cmptheight(jasperP, cmptNo) !=
             jas_image_cmptheight(jasperP, 0))
             pm_message("Input image does not have components all the same "
                        "height.");
@@ -241,7 +241,7 @@ maxJasperComponentPrecision(jas_image_t * const jasperP) {
 
     int cmptNo;
     unsigned int max;
-    
+
     max = 1;
 
     for (cmptNo = 0; cmptNo < jas_image_numcmpts(jasperP); ++cmptNo)
@@ -262,8 +262,8 @@ computeOutputParm(jas_image_t * const jasperP,
           with the Jasper library that corresponds to Plane P of the PAM.
        */
 
-	switch (jas_clrspc_fam(jas_image_clrspc(jasperP))) {
-	case JAS_CLRSPC_FAM_GRAY:
+    switch (jas_clrspc_fam(jas_image_clrspc(jasperP))) {
+    case JAS_CLRSPC_FAM_GRAY:
         outpamP->depth = 1;
         MALLOCARRAY_NOFAIL(jasperCmptNo, 1);
         getGrayComponent(&jasperCmptNo[0], jasperP);
@@ -275,7 +275,7 @@ computeOutputParm(jas_image_t * const jasperP,
             strcpy(outpamP->tuple_type, PAM_PGM_TUPLETYPE);
         }
         break;
-	case JAS_CLRSPC_FAM_RGB:
+    case JAS_CLRSPC_FAM_RGB:
         outpamP->depth = 3;
         MALLOCARRAY_NOFAIL(jasperCmptNo, 3);
         getRgbComponents(jasperCmptNo, jasperP);
@@ -293,15 +293,15 @@ computeOutputParm(jas_image_t * const jasperP,
                 jasperCmptNo[plane] = plane;
         }
         strcpy(outpamP->tuple_type, "");
-        if (jas_image_cmptsgnd(jasperP, 0)) 
+        if (jas_image_cmptsgnd(jasperP, 0))
             pm_message("Warning: Input image has signed sample values.  "
                        "They will be represented in the PAM output in "
                        "two's complement.");
     }
     outpamP->plainformat = FALSE;
 
-	outpamP->width = jas_image_cmptwidth(jasperP, 0);
-	outpamP->height = jas_image_cmptheight(jasperP, 0);
+    outpamP->width = jas_image_cmptwidth(jasperP, 0);
+    outpamP->height = jas_image_cmptheight(jasperP, 0);
 
     validateComponentsAlike(jasperP);
 
@@ -309,7 +309,7 @@ computeOutputParm(jas_image_t * const jasperP,
         unsigned int const maxPrecision = maxJasperComponentPrecision(jasperP);
 
         outpamP->maxval = pm_bitstomaxval(maxPrecision);
-        
+
         outpamP->bytes_per_sample = (maxPrecision + 7)/8;
     }
     *jasperCmptNoP = jasperCmptNo;
@@ -320,7 +320,7 @@ computeOutputParm(jas_image_t * const jasperP,
 static void
 createMatrices(struct pam * const outpamP, jas_matrix_t *** matrixP) {
 
-    jas_matrix_t ** matrix; 
+    jas_matrix_t ** matrix;
     unsigned int plane;
 
     MALLOCARRAY_NOFAIL(matrix, outpamP->depth);
@@ -331,14 +331,14 @@ createMatrices(struct pam * const outpamP, jas_matrix_t *** matrixP) {
         if (matrix[plane] == NULL)
             pm_error("Unable to create matrix for plane %u.  "
                      "jas_matrix_create() failed.", plane);
-    }   
+    }
     *matrixP = matrix;
 }
 
 
 
 static void
-destroyMatrices(struct pam *    const outpamP, 
+destroyMatrices(struct pam *    const outpamP,
                 jas_matrix_t ** const matrix ) {
 
     unsigned int plane;
@@ -346,7 +346,7 @@ destroyMatrices(struct pam *    const outpamP,
     for (plane = 0; plane < outpamP->depth; ++plane)
         jas_matrix_destroy(matrix[plane]);
     free(matrix);
-}    
+}
 
 
 
@@ -356,7 +356,7 @@ computeComponentMaxval(struct pam *  const outpamP,
                        int           const jasperCmpt[],
                        sample **     const jasperMaxvalP,
                        bool *        const singleMaxvalP) {
-    
+
     sample * jasperMaxval;
     unsigned int plane;
 
@@ -364,7 +364,7 @@ computeComponentMaxval(struct pam *  const outpamP,
 
     *singleMaxvalP = TRUE;  /* initial assumption */
     for (plane = 0; plane < outpamP->depth; ++plane) {
-        jasperMaxval[plane] = 
+        jasperMaxval[plane] =
             pm_bitstomaxval(jas_image_cmptprec(jasperP, jasperCmpt[plane]));
         if (jasperMaxval[plane] != jasperMaxval[0])
             *singleMaxvalP = FALSE;
@@ -372,7 +372,7 @@ computeComponentMaxval(struct pam *  const outpamP,
     *jasperMaxvalP = jasperMaxval;
 }
 
-                       
+
 
 static void
 copyRowSingleMaxval(jas_seqent_t ** const jasperRow,
@@ -387,10 +387,10 @@ copyRowSingleMaxval(jas_seqent_t ** const jasperRow,
    This is significantly faster than copyRowAnyMaxval().
 -----------------------------------------------------------------------------*/
     unsigned int col;
-    
+
     for (col = 0; col < outpamP->width; ++col) {
         unsigned int plane;
-        for (plane = 0; plane < outpamP->depth; ++plane) 
+        for (plane = 0; plane < outpamP->depth; ++plane)
             tuplerow[col][plane] = jasperRow[plane][col];
     }
 }
@@ -411,12 +411,12 @@ copyRowAnyMaxval(jas_seqent_t ** const jasperRow,
    This is significantly slower than copyRowSingleMaxval().
 -----------------------------------------------------------------------------*/
     unsigned int col;
-            
+
     for (col = 0; col < outpamP->width; ++col) {
         unsigned int plane;
-        for (plane = 0; plane < outpamP->depth; ++plane) 
-            tuplerow[col][plane] = 
-                jasperRow[plane][col] * 
+        for (plane = 0; plane < outpamP->depth; ++plane)
+            tuplerow[col][plane] =
+                jasperRow[plane][col] *
                 outpamP->maxval / jasperMaxval[plane];
     }
 }
@@ -461,11 +461,11 @@ convertToPamPnm(struct pam *  const outpamP,
                                     matrix[plane]);
             if (rc != 0)
                 pm_error("jas_image_readcmpt() of row %u plane %u "
-                         "failed.", 
+                         "failed.",
                          row, plane);
             jasperRow[plane] = jas_matrix_getref(matrix[plane], 0, 0);
         }
-        if (singleMaxval) 
+        if (singleMaxval)
             copyRowSingleMaxval(jasperRow, tuplerow, outpamP);
         else
             copyRowAnyMaxval(jasperRow, tuplerow, outpamP, jasperMaxval);
@@ -489,25 +489,25 @@ main(int argc, char **argv)
     struct pam outpam;
     int * jasperCmpt;  /* malloc'ed */
        /* jaspercmpt[P] is the component number for use with the
-          Jasper library that corresponds to Plane P of the PAM.  
+          Jasper library that corresponds to Plane P of the PAM.
        */
     jas_image_t * jasperP;
 
     pnm_init(&argc, argv);
-    
+
     parseCommandLine(argc, argv, &cmdline);
-    
-    { 
+
+    {
         int rc;
-        
+
         rc = jas_init();
         if ( rc != 0 )
             pm_error("Failed to initialize Jasper library.  "
                      "jas_init() returns rc %d", rc );
     }
-    
+
     jas_setdbglevel(cmdline.debuglevel);
-    
+
     readJ2k(cmdline.inputFilename, &jasperP);
 
     outpam.file = stdout;
@@ -517,13 +517,16 @@ main(int argc, char **argv)
     computeOutputParm(jasperP, &outpam, &jasperCmpt);
 
     pnm_writepaminit(&outpam);
-    
+
     convertToPamPnm(&outpam, jasperP, jasperCmpt);
-    
+
     free(jasperCmpt);
-	jas_image_destroy(jasperP);
+    jas_image_destroy(jasperP);
 
     pm_close(stdout);
-    
+
     return 0;
 }
+
+
+
diff --git a/converter/other/jpeg2000/libjasper/jpc/jpc_util.c b/converter/other/jpeg2000/libjasper/jpc/jpc_util.c
index ecc4b914..fede2bef 100644
--- a/converter/other/jpeg2000/libjasper/jpc/jpc_util.c
+++ b/converter/other/jpeg2000/libjasper/jpc/jpc_util.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__
  */
 
diff --git a/converter/other/jpeg2000/pamtojpeg2k.c b/converter/other/jpeg2000/pamtojpeg2k.c
index 1272a422..4d73316a 100644
--- a/converter/other/jpeg2000/pamtojpeg2k.c
+++ b/converter/other/jpeg2000/pamtojpeg2k.c
@@ -98,7 +98,7 @@ parseCommandLine(int argc, char ** argv,
     char * modeOpt;
 
     unsigned int option_def_index;
-    
+
     MALLOCARRAY_NOFAIL(option_def, 100);
 
     option_def_index = 0;   /* incremented by OPTENTRY */
@@ -134,25 +134,25 @@ parseCommandLine(int argc, char ** argv,
             &numrlvlsSpec,       0);
     OPTENT3(0, "numgbits",     OPT_UINT,   &cmdlineP->numgbits,
             &numgbitsSpec,       0);
-    OPTENT3(0, "nomct",        OPT_FLAG,   NULL, 
+    OPTENT3(0, "nomct",        OPT_FLAG,   NULL,
             &cmdlineP->nomct,    0);
-    OPTENT3(0, "sop",          OPT_FLAG,   NULL, 
+    OPTENT3(0, "sop",          OPT_FLAG,   NULL,
             &cmdlineP->sop,      0);
-    OPTENT3(0, "eph",          OPT_FLAG,   NULL, 
+    OPTENT3(0, "eph",          OPT_FLAG,   NULL,
             &cmdlineP->eph,      0);
-    OPTENT3(0, "lazy",         OPT_FLAG,   NULL, 
+    OPTENT3(0, "lazy",         OPT_FLAG,   NULL,
             &cmdlineP->lazy,     0);
-    OPTENT3(0, "termall",      OPT_FLAG,   NULL, 
+    OPTENT3(0, "termall",      OPT_FLAG,   NULL,
             &cmdlineP->termall,  0);
-    OPTENT3(0, "segsym",       OPT_FLAG,   NULL, 
+    OPTENT3(0, "segsym",       OPT_FLAG,   NULL,
             &cmdlineP->segsym,    0);
-    OPTENT3(0, "vcausal",      OPT_FLAG,   NULL, 
+    OPTENT3(0, "vcausal",      OPT_FLAG,   NULL,
             &cmdlineP->vcausal,   0);
-    OPTENT3(0, "pterm",        OPT_FLAG,   NULL, 
+    OPTENT3(0, "pterm",        OPT_FLAG,   NULL,
             &cmdlineP->pterm,     0);
-    OPTENT3(0, "resetprob",    OPT_FLAG,   NULL, 
+    OPTENT3(0, "resetprob",    OPT_FLAG,   NULL,
             &cmdlineP->resetprob, 0);
-    OPTENT3(0, "verbose",      OPT_FLAG,   NULL, 
+    OPTENT3(0, "verbose",      OPT_FLAG,   NULL,
             &cmdlineP->verbose,   0);
     OPTENT3(0, "debuglevel",   OPT_UINT,   &cmdlineP->debuglevel,
             &debuglevelSpec,      0);
@@ -223,7 +223,7 @@ parseCommandLine(int argc, char ** 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\n"
                  "is the input file specification");
 
@@ -232,7 +232,7 @@ parseCommandLine(int argc, char ** argv,
 
 
 static void
-createJasperRaster(struct pam *  const inpamP, 
+createJasperRaster(struct pam *  const inpamP,
                    jas_image_t * const jasperP) {
 /*----------------------------------------------------------------------------
    Create the raster in the *jasperP object, reading the raster from the
@@ -254,7 +254,7 @@ createJasperRaster(struct pam *  const inpamP,
         if (matrix[plane] == NULL)
             pm_error("Unable to create matrix for plane %u.  "
                      "jas_matrix_create() failed.", plane);
-    }   
+    }
     tuplerow = pnm_allocpamrow(inpamP);
 
     jasperMaxval = pm_bitstomaxval(pm_maxvaltobits(inpamP->maxval));
@@ -271,7 +271,7 @@ createJasperRaster(struct pam *  const inpamP,
                 unsigned int jasperSample;
 
                 if (oddMaxval)
-                    jasperSample = tuplerow[col][plane] * 
+                    jasperSample = tuplerow[col][plane] *
                         jasperMaxval / inpamP->maxval;
                 else
                     jasperSample = tuplerow[col][plane];
@@ -279,16 +279,16 @@ createJasperRaster(struct pam *  const inpamP,
                 jas_matrix_set(matrix[plane], 0, col, jasperSample);
             }
         }
-        { 
+        {
             unsigned int plane;
 
             for (plane = 0; plane < inpamP->depth; ++plane) {
                 int rc;
-                rc = jas_image_writecmpt(jasperP, plane, 0, row, 
+                rc = jas_image_writecmpt(jasperP, plane, 0, row,
                                          inpamP->width, 1,
                                          matrix[plane]);
                 if (rc != 0)
-                    pm_error("jas_image_writecmpt() of plane %u failed.", 
+                    pm_error("jas_image_writecmpt() of plane %u failed.",
                              plane);
             }
         }
@@ -297,14 +297,14 @@ createJasperRaster(struct pam *  const inpamP,
     pnm_freepamrow(tuplerow);
     for (plane = 0; plane < inpamP->depth; ++plane)
         jas_matrix_destroy(matrix[plane]);
-    
+
     free(matrix);
 }
 
 
 
 static void
-createJasperImage(struct pam *   const inpamP, 
+createJasperImage(struct pam *   const inpamP,
                   jas_image_t ** const jasperPP) {
 
 	jas_image_cmptparm_t * cmptparms;
@@ -322,7 +322,7 @@ createJasperImage(struct pam *   const inpamP,
         cmptparms[plane].prec = pm_maxvaltobits(inpamP->maxval);
         cmptparms[plane].sgnd = 0;
     }
-    *jasperPP = 
+    *jasperPP =
         jas_image_create(inpamP->depth, cmptparms, JAS_CLRSPC_UNKNOWN);
     if (*jasperPP == NULL)
         pm_error("Unable to create jasper image structure.  "
@@ -371,7 +371,7 @@ convertToJasperImage(struct pam *   const inpamP,
 
 
 static void
-writeJpc(jas_image_t *      const jasperP, 
+writeJpc(jas_image_t *      const jasperP,
          struct cmdlineInfo const cmdline,
          FILE *             const ofP) {
 
@@ -383,8 +383,8 @@ writeJpc(jas_image_t *      const jasperP,
 
     /* Note: ilyrrates is a hack because we're too lazy to properly parse
        command line options to get the information and then compose
-       a proper input to Jasper.  So the user can screw things up by 
-       specifying garbage for the -ilyrrates option 
+       a proper input to Jasper.  So the user can screw things up by
+       specifying garbage for the -ilyrrates option
     */
     if (strlen(cmdline.ilyrrates) > 0)
         pm_asprintf(&ilyrratesOpt, "ilyrrates=%s", cmdline.ilyrrates);
@@ -410,7 +410,7 @@ writeJpc(jas_image_t *      const jasperP,
         */
         rateOpt[0] = '\0';
     }
-    pm_asprintf(&options, 
+    pm_asprintf(&options,
                 "imgareatlx=%u "
                 "imgareatly=%u "
                 "tilegrdtlx=%u "
@@ -428,7 +428,7 @@ writeJpc(jas_image_t *      const jasperP,
                 "numrlvls=%u "
                 "numgbits=%u "
                 "%s %s %s %s %s %s %s %s %s",
-                
+
                 cmdline.imgareatlx,
                 cmdline.imgareatly,
                 cmdline.tilegrdtlx,
@@ -471,8 +471,8 @@ writeJpc(jas_image_t *      const jasperP,
             pm_message("Using Jasper to encode to 'jpc' format with options "
                        "'%s'", options);
 
-        rc = jas_image_encode(jasperP, outStreamP, 
-                              jas_image_strtofmt((char*)"jpc"), 
+        rc = jas_image_encode(jasperP, outStreamP,
+                              jas_image_strtofmt((char*)"jpc"),
                               (char *)options);
         if (rc != 0)
             pm_error("jas_image_encode() failed to encode the JPEG 2000 "
@@ -484,11 +484,11 @@ writeJpc(jas_image_t *      const jasperP,
         int rc;
 
         rc = jas_stream_close(outStreamP);
-            
+
         if (rc != 0)
             pm_error("Failed to close output stream, "
                      "jas_stream_close() rc = %d", rc);
-    }                     
+    }
 
 	jas_image_clearfmts();
 
@@ -506,33 +506,33 @@ main(int argc, char **argv)
     jas_image_t * jasperP;
 
     pnm_init(&argc, argv);
-    
+
     parseCommandLine(argc, argv, &cmdline);
-    
-    { 
+
+    {
         int rc;
-        
+
         rc = jas_init();
         if ( rc != 0 )
             pm_error("Failed to initialize Jasper library.  "
                      "jas_init() returns rc %d", rc );
     }
-    
+
     jas_setdbglevel(cmdline.debuglevel);
-    
+
     ifP = pm_openr(cmdline.inputFilename);
-    
+
     pnm_readpaminit(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));
-    
+
     convertToJasperImage(&inpam, &jasperP);
-    
+
     writeJpc(jasperP, cmdline, stdout);
-    
+
 	jas_image_destroy(jasperP);
 
     pm_close(ifP);
 
     pm_close(stdout);
-    
+
     return 0;
 }
diff --git a/converter/other/pamtotga.c b/converter/other/pamtotga.c
index 27974dd3..1daa1e25 100644
--- a/converter/other/pamtotga.c
+++ b/converter/other/pamtotga.c
@@ -14,6 +14,7 @@
 #define _BSD_SOURCE  /* Make sure string.h contains strdup() */
 #define _XOPEN_SOURCE 500  /* Make sure strdup() is in string.h */
 
+#include <assert.h>
 #include <string.h>
 
 #include "pm_c_util.h"
@@ -27,22 +28,24 @@
 /* Max number of colors allowed for colormapped output. */
 #define MAXCOLORS 256
 
-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;  /* Filespec of input file */
-    char *outName;
+    const char *          inputFileName;
+    const char *          outName;
     enum TGAbaseImageType imgType;
-    bool defaultFormat;
-    unsigned int norle;
+    enum TGAmapType       mapType;
+    bool                  defaultFormat;
+    unsigned int          norle;
+    unsigned int          verbose;
 };
 
 
 
 static void
-parseCommandLine(int argc, char ** argv,
-                 struct cmdlineInfo * const cmdlineP) {
+parseCommandLine(int argc, const char ** argv,
+                 struct CmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    Parse the program arguments (given by argc and argv) into a form
    the program can deal with more easily -- a cmdline_info structure.
@@ -57,38 +60,47 @@ parseCommandLine(int argc, char ** argv,
     unsigned int option_def_index;
 
     unsigned int outNameSpec;
-    unsigned int cmap, mono, rgb;
+    unsigned int cmap, cmap16, mono, rgb;
 
     option_def_index = 0;   /* incremented by OPTENT3 */
-    OPTENT3(0,   "name",       OPT_STRING, 
+    OPTENT3(0,   "name",       OPT_STRING,
             &cmdlineP->outName, &outNameSpec, 0);
-    OPTENT3(0,   "cmap",       OPT_FLAG, 
+    OPTENT3(0,   "cmap",       OPT_FLAG,
             NULL, &cmap, 0);
-    OPTENT3(0,   "mono",       OPT_FLAG, 
+    OPTENT3(0,   "cmap16",     OPT_FLAG,
+            NULL, &cmap16, 0);
+    OPTENT3(0,   "mono",       OPT_FLAG,
             NULL, &mono, 0);
-    OPTENT3(0,   "rgb",        OPT_FLAG, 
+    OPTENT3(0,   "rgb",        OPT_FLAG,
             NULL, &rgb, 0);
-    OPTENT3(0,   "norle",      OPT_FLAG, 
+    OPTENT3(0,   "norle",      OPT_FLAG,
             NULL, &cmdlineP->norle, 0);
-    
+    OPTENT3(0,   "verbose",    OPT_FLAG,
+            NULL, &cmdlineP->verbose, 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 some of *cmdline_p and others. */
 
-    if (cmap + mono + rgb > 1)
-        pm_error("You may specify only one of -cmap, -mono, and -rgb.");
+    if (cmap + cmap16 + mono + rgb > 1)
+        pm_error("You may specify only one of -cmap, -cmap16, "
+                 "-mono, and -rgb.");
 
-    if (cmap + mono + rgb == 0)
+    if (cmap + cmap16 + mono + rgb == 0)
         cmdlineP->defaultFormat = TRUE;
     else {
         cmdlineP->defaultFormat = FALSE;
-    
-        if (cmap)
+
+        if (cmap) {
             cmdlineP->imgType = TGA_MAP_TYPE;
-        else if (mono)
+            cmdlineP->mapType = TGA_MAPTYPE_LONG;
+        } else if (cmap16) {
+            cmdlineP->imgType = TGA_MAP_TYPE;
+            cmdlineP->mapType = TGA_MAPTYPE_SHORT;
+        } else if (mono)
             cmdlineP->imgType = TGA_MONO_TYPE;
         else if (rgb)
             cmdlineP->imgType = TGA_RGB_TYPE;
@@ -96,56 +108,22 @@ parseCommandLine(int argc, char ** argv,
 
     if (!outNameSpec)
         cmdlineP->outName = NULL;
-    
-    if (argc-1 == 0) 
-        cmdlineP->inputFilespec = "-";
+
+    if (argc-1 == 0)
+        cmdlineP->inputFileName = "-";
     else if (argc-1 != 1)
         pm_error("Program takes zero or one argument (filename).  You "
                  "specified %d", argc-1);
     else
-        cmdlineP->inputFilespec = argv[1];
-
-}
-
-
-static void
-writeTgaHeader(struct ImageHeader const tgaHeader) {
-
-    unsigned char flags;
-
-    putchar(tgaHeader.IdLength);
-    putchar(tgaHeader.CoMapType);
-    putchar(tgaHeader.ImgType);
-    putchar(tgaHeader.Index_lo);
-    putchar(tgaHeader.Index_hi);
-    putchar(tgaHeader.Length_lo);
-    putchar(tgaHeader.Length_hi);
-    putchar(tgaHeader.CoSize);
-    putchar(tgaHeader.X_org_lo);
-    putchar(tgaHeader.X_org_hi);
-    putchar(tgaHeader.Y_org_lo);
-    putchar(tgaHeader.Y_org_hi);
-    putchar(tgaHeader.Width_lo);
-    putchar(tgaHeader.Width_hi);
-    putchar(tgaHeader.Height_lo);
-    putchar(tgaHeader.Height_hi);
-    putchar(tgaHeader.PixelSize);
-    flags = (tgaHeader.AttBits & 0xf) | 
-        ((tgaHeader.Rsrvd & 0x1) << 4) |
-        ((tgaHeader.OrgBit & 0x1) << 5) | 
-        ((tgaHeader.OrgBit & 0x3) << 6);
-    putchar(flags);
+        cmdlineP->inputFileName = argv[1];
 
-    if (tgaHeader.IdLength > 0)
-        fwrite(tgaHeader.Id, 1, (int) tgaHeader.IdLength, stdout);
 }
-    
 
 
 static void
 putPixel(struct pam *          const pamP,
-         tuple                 const tuple, 
-         enum TGAbaseImageType const imgType, 
+         tuple                 const tuple,
+         enum TGAbaseImageType const imgType,
          bool                  const withAlpha,
          tuplehash             const cht) {
 /*----------------------------------------------------------------------------
@@ -167,22 +145,22 @@ putPixel(struct pam *          const pamP,
         if (imgType == TGA_RGB_TYPE && pamP->depth < 3) {
             /* Make RGB pixel out of a single input plane */
             unsigned int plane;
-            
-            for (plane = 0; plane < 3; ++plane) 
-                putchar(pnm_scalesample(tuple[0], 
+
+            for (plane = 0; plane < 3; ++plane)
+                putchar(pnm_scalesample(tuple[0],
                                         pamP->maxval, TGA_MAXVAL));
         } else if (imgType == TGA_MONO_TYPE)
-            putchar(pnm_scalesample(tuple[0], 
+            putchar(pnm_scalesample(tuple[0],
                                     pamP->maxval, TGA_MAXVAL));
         else {
-            putchar(pnm_scalesample(tuple[PAM_BLU_PLANE], 
+            putchar(pnm_scalesample(tuple[PAM_BLU_PLANE],
                                     pamP->maxval, TGA_MAXVAL));
-            putchar(pnm_scalesample(tuple[PAM_GRN_PLANE], 
+            putchar(pnm_scalesample(tuple[PAM_GRN_PLANE],
                                     pamP->maxval, TGA_MAXVAL));
-            putchar(pnm_scalesample(tuple[PAM_RED_PLANE], 
+            putchar(pnm_scalesample(tuple[PAM_RED_PLANE],
                                     pamP->maxval, TGA_MAXVAL));
             if (withAlpha)
-                putchar(pnm_scalesample(tuple[PAM_TRN_PLANE], 
+                putchar(pnm_scalesample(tuple[PAM_TRN_PLANE],
                                         pamP->maxval, TGA_MAXVAL));
         }
     }
@@ -191,39 +169,47 @@ putPixel(struct pam *          const pamP,
 
 
 static void
-putMapEntry(struct pam * const pamP, 
-            tuple        const value, 
+putMapEntry(struct pam * const pamP,
+            tuple        const value,
             int          const size) {
 
-    if (size == 15 || size == 16) {
-        /* 5 bits each of red, green, and blue.  Watch for byte order */
-
+    if (size == 8)
+        putchar(pnm_scalesample(value[0],
+                                pamP->maxval, TGA_MAXVAL));
+    else if (size == 15 || size == 16) {
         tuple const tuple31 = pnm_allocpamtuple(pamP);
 
+        assert(pamP->depth >= 3);
+
         pnm_scaletuple(pamP, tuple31, value, 31);
         {
-            int const mapentry = 
+            unsigned int const trn =
+                size == 16 && tuple31[PAM_TRN_PLANE] > 0 ? 1 : 0;
+
+            unsigned int const mapentry =
                 tuple31[PAM_BLU_PLANE] << 0 |
                 tuple31[PAM_GRN_PLANE] << 5 |
-                tuple31[PAM_RED_PLANE] << 10;
-            
+                tuple31[PAM_RED_PLANE] << 10 |
+                trn                    << 15;
+
+            /* Note little-endian byte swapping */
             putchar(mapentry % 256);
             putchar(mapentry / 256);
         }
         pnm_freepamtuple(tuple31);
-    } else if (size == 8)
-        putchar(pnm_scalesample(value[0], 
-                                pamP->maxval, TGA_MAXVAL));
-    else {
-        /* Must be 24 or 32 */
-        putchar(pnm_scalesample(value[PAM_BLU_PLANE], 
+    } else {
+        assert(size == 24 || size == 32);
+
+        assert(pamP->depth >= 3);
+
+        putchar(pnm_scalesample(value[PAM_BLU_PLANE],
                                 pamP->maxval, TGA_MAXVAL));
-        putchar(pnm_scalesample(value[PAM_GRN_PLANE], 
+        putchar(pnm_scalesample(value[PAM_GRN_PLANE],
                                 pamP->maxval, TGA_MAXVAL));
-        putchar(pnm_scalesample(value[PAM_RED_PLANE], 
+        putchar(pnm_scalesample(value[PAM_RED_PLANE],
                                     pamP->maxval, TGA_MAXVAL));
         if (size == 32)
-            putchar(pnm_scalesample(value[PAM_TRN_PLANE], 
+            putchar(pnm_scalesample(value[PAM_TRN_PLANE],
                                     pamP->maxval, TGA_MAXVAL));
     }
 }
@@ -231,8 +217,8 @@ putMapEntry(struct pam * const pamP,
 
 
 static void
-computeRunlengths(struct pam * const pamP, 
-                   tuple *      const tuplerow, 
+computeRunlengths(struct pam * const pamP,
+                   tuple *      const tuplerow,
                    int *        const runlength) {
 
     int col, start;
@@ -240,7 +226,7 @@ computeRunlengths(struct pam * const pamP,
     /* Initialize all run lengths to 0.  (This is just an error check.) */
     for (col = 0; col < pamP->width; ++col)
         runlength[col] = 0;
-    
+
     /* Find runs of identical pixels. */
     for ( col = 0; col < pamP->width; ) {
         start = col;
@@ -251,7 +237,7 @@ computeRunlengths(struct pam * const pamP,
                   pnm_tupleequal(pamP, tuplerow[col], tuplerow[start]));
         runlength[start] = col - start;
     }
-    
+
     /* Now look for runs of length-1 runs, and turn them into negative runs. */
     for (col = 0; col < pamP->width; ) {
         if (runlength[col] == 1) {
@@ -271,23 +257,23 @@ computeRunlengths(struct pam * const pamP,
 
 
 static void
-computeOutName(struct cmdlineInfo const cmdline, 
+computeOutName(struct CmdlineInfo const cmdline,
                const char **      const outNameP) {
-    
+
     char * workarea;
 
     if (cmdline.outName)
         workarea = strdup(cmdline.outName);
-    else if (streq(cmdline.inputFilespec, "-"))
+    else if (streq(cmdline.inputFileName, "-"))
         workarea = NULL;
     else {
         char * cp;
-        workarea = strdup(cmdline.inputFilespec);
+        workarea = strdup(cmdline.inputFileName);
         cp = strchr(workarea, '.');
         if (cp != NULL)
         	*cp = '\0';	/* remove extension */
     }
-    
+
     if (workarea == NULL)
         *outNameP = NULL;
     else {
@@ -306,16 +292,16 @@ validateTupleType(struct pam * const pamP) {
     if (streq(pamP->tuple_type, "RGB_ALPHA")) {
         if (pamP->depth < 4)
             pm_error("Invalid depth for tuple type RGB_ALPHA.  "
-                     "Should have at least 4 planes, but has %d.", 
+                     "Should have at least 4 planes, but has %d.",
                      pamP->depth);
     } else if (streq(pamP->tuple_type, "RGB")) {
         if (pamP->depth < 3)
             pm_error("Invalid depth for tuple type RGB.  "
-                     "Should have at least 3 planes, but has %d.", 
+                     "Should have at least 3 planes, but has %d.",
                      pamP->depth);
     } else if (streq(pamP->tuple_type, "GRAYSCALE")) {
     } else if (streq(pamP->tuple_type, "BLACKANDWHITE")) {
-    } else 
+    } else
         pm_error("Invalid type of input.  PAM tuple type is '%s'.  "
                  "This programs understands only RGB_ALPHA, RGB, GRAYSCALE, "
                  "and BLACKANDWHITE.", pamP->tuple_type);
@@ -325,69 +311,76 @@ validateTupleType(struct pam * const pamP) {
 
 static void
 computeImageType_cht(struct pam *            const pamP,
-                     struct cmdlineInfo      const cmdline, 
+                     struct CmdlineInfo      const cmdline,
                      tuple **                const tuples,
                      enum TGAbaseImageType * const baseImgTypeP,
+                     enum TGAmapType *       const mapTypeP,
                      bool *                  const withAlphaP,
                      tupletable *            const chvP,
-                     tuplehash *             const chtP, 
+                     tuplehash *             const chtP,
                      int *                   const ncolorsP) {
 
-    unsigned int ncolors;
+    unsigned int          ncolors;
     enum TGAbaseImageType baseImgType;
-    bool withAlpha;
+    enum TGAmapType       mapType;
+    bool                  withAlpha;
 
     validateTupleType(pamP);
 
-    withAlpha = (streq(pamP->tuple_type, "RGB_ALPHA"));
-
     if (cmdline.defaultFormat) {
         /* default the image type */
-        if (withAlpha) {
+        if (streq(pamP->tuple_type, "RGB_ALPHA")) {
             baseImgType = TGA_RGB_TYPE;
             *chvP = NULL;
-        } else if (pamP->depth > 1) {
+            withAlpha = true;
+        } else if (streq(pamP->tuple_type, "RGB")) {
             pm_message("computing colormap...");
-            *chvP = 
+            *chvP =
                 pnm_computetuplefreqtable(pamP, tuples, MAXCOLORS, &ncolors);
             if (*chvP == NULL) {
                 pm_message("Too many colors for colormapped TGA.  Doing RGB.");
                 baseImgType = TGA_RGB_TYPE;
-            } else 
+            } else {
                 baseImgType = TGA_MAP_TYPE;
+                mapType = TGA_MAPTYPE_LONG;
+            }
+            withAlpha = false;
         } else {
             baseImgType = TGA_MONO_TYPE;
             *chvP = NULL;
+            withAlpha = false;
         }
     } else {
+        withAlpha = (streq(pamP->tuple_type, "RGB_ALPHA"));
+
         baseImgType = cmdline.imgType;
 
         if (baseImgType == TGA_MAP_TYPE) {
+            mapType = cmdline.mapType;
+
             if (withAlpha)
                 pm_error("Can't do a colormap because image has transparency "
                          "information");
             pm_message("computing colormap...");
-            *chvP = 
+            *chvP =
                 pnm_computetuplefreqtable(pamP, tuples, MAXCOLORS, &ncolors);
-            if (*chvP == NULL) 
+            if (*chvP == NULL)
                 pm_error("Too many colors for colormapped TGA.  "
-                         "Use 'pnmquant %d' to reduce the number of colors.", 
+                         "Use 'pnmquant %d' to reduce the number of colors.",
                          MAXCOLORS);
         } else
             *chvP = NULL;
-        if (baseImgType == TGA_MONO_TYPE && pamP->depth > 1)
-            pm_error("For Mono TGA output, input must be "
-                     "GRAYSCALE or BLACKANDWHITE PAM or PBM or PGM");
     }
-    
+
     if (baseImgType == TGA_MAP_TYPE) {
-        pm_message("%d colors found.", ncolors);
+        pm_message("%u colors found.", ncolors);
         /* Make a hash table for fast color lookup. */
         *chtP = pnm_computetupletablehash(pamP, *chvP, ncolors);
     } else
         *chtP = NULL;
 
     *baseImgTypeP = baseImgType;
+    *mapTypeP     = mapType;
     *withAlphaP   = withAlpha;
     *ncolorsP     = ncolors;
 }
@@ -397,8 +390,9 @@ computeImageType_cht(struct pam *            const pamP,
 static void
 computeTgaHeader(struct pam *          const pamP,
                  enum TGAbaseImageType const baseImgType,
+                 enum TGAmapType       const mapType,
                  bool                  const withAlpha,
-                 bool                  const rle, 
+                 bool                  const rle,
                  int                   const ncolors,
                  unsigned char         const orgBit,
                  const char *          const id,
@@ -417,7 +411,7 @@ computeTgaHeader(struct pam *          const pamP,
         case TGA_RGB_TYPE:  tgaHeaderP->ImgType = TGA_RGB;           break;
         }
     }
-    
+
     if (id) {
         tgaHeaderP->IdLength = strlen(id);
         tgaHeaderP->Id = strdup(id);
@@ -429,7 +423,18 @@ computeTgaHeader(struct pam *          const pamP,
         tgaHeaderP->CoMapType = 1;
         tgaHeaderP->Length_lo = ncolors % 256;
         tgaHeaderP->Length_hi = ncolors / 256;
-        tgaHeaderP->CoSize = 8 * pamP->depth;
+        if (pamP->depth < 3)
+            tgaHeaderP->CoSize = 8;
+        else {
+            switch (mapType) {
+            case TGA_MAPTYPE_SHORT:
+                tgaHeaderP->CoSize = withAlpha ? 16 : 15;
+                break;
+            case TGA_MAPTYPE_LONG:
+                tgaHeaderP->CoSize = withAlpha ? 32 : 24;
+                break;
+            }
+        }
     } else {
         tgaHeaderP->CoMapType = 0;
         tgaHeaderP->Length_lo = 0;
@@ -441,7 +446,7 @@ computeTgaHeader(struct pam *          const pamP,
         tgaHeaderP->PixelSize = 8;
         break;
     case TGA_RGB_TYPE:
-        tgaHeaderP->PixelSize = 8 * MAX((withAlpha ? 4: 3), pamP->depth);
+        tgaHeaderP->PixelSize = 8 * (withAlpha ? 4: 3);
         break;
     case TGA_MONO_TYPE:
         tgaHeaderP->PixelSize = 8;
@@ -461,6 +466,70 @@ computeTgaHeader(struct pam *          const pamP,
 
 
 static void
+reportTgaHeader(struct ImageHeader const tgaHeader) {
+
+    switch (tgaHeader.ImgType) {
+    case TGA_RLEMono:
+        pm_message("Generating monochrome, run-length encoded");
+        break;
+    case TGA_RLEMap:
+        pm_message("Generating colormapped, run-length encoded");
+        pm_message("%u bits per colormap entry", tgaHeader.CoSize);
+        break;
+    case TGA_RLERGB:
+        pm_message("Generating RGB truecolor, run-length encoded");
+        break;
+    case TGA_Mono:
+        pm_message("Generating monochrome, uncompressed");
+        break;
+    case TGA_Map:
+        pm_message("Generating colormapped, uncompressed");
+        pm_message("%u bits per colormap entry", tgaHeader.CoSize);
+        break;
+    case TGA_RGB:
+        pm_message("Generating RGB truecolor, uncompressed");
+        break;
+    }
+    pm_message("%u bits per pixel", tgaHeader.PixelSize);
+}
+
+
+
+static void
+writeTgaHeader(struct ImageHeader const tgaHeader) {
+
+    unsigned char flags;
+
+    putchar(tgaHeader.IdLength);
+    putchar(tgaHeader.CoMapType);
+    putchar(tgaHeader.ImgType);
+    putchar(tgaHeader.Index_lo);
+    putchar(tgaHeader.Index_hi);
+    putchar(tgaHeader.Length_lo);
+    putchar(tgaHeader.Length_hi);
+    putchar(tgaHeader.CoSize);
+    putchar(tgaHeader.X_org_lo);
+    putchar(tgaHeader.X_org_hi);
+    putchar(tgaHeader.Y_org_lo);
+    putchar(tgaHeader.Y_org_hi);
+    putchar(tgaHeader.Width_lo);
+    putchar(tgaHeader.Width_hi);
+    putchar(tgaHeader.Height_lo);
+    putchar(tgaHeader.Height_hi);
+    putchar(tgaHeader.PixelSize);
+    flags = (tgaHeader.AttBits & 0xf) |
+        ((tgaHeader.Rsrvd & 0x1) << 4) |
+        ((tgaHeader.OrgBit & 0x1) << 5) |
+        ((tgaHeader.OrgBit & 0x3) << 6);
+    putchar(flags);
+
+    if (tgaHeader.IdLength > 0)
+        fwrite(tgaHeader.Id, 1, (int) tgaHeader.IdLength, stdout);
+}
+
+
+
+static void
 releaseTgaHeader(struct ImageHeader const tgaHeader) {
 
     if (tgaHeader.IdLength > 0)
@@ -469,9 +538,9 @@ releaseTgaHeader(struct ImageHeader const tgaHeader) {
 
 
 
-static void 
+static void
 writeTgaRaster(struct pam *          const pamP,
-               tuple **              const tuples, 
+               tuple **              const tuples,
                tuplehash             const cht,
                enum TGAbaseImageType const imgType,
                bool                  const withAlpha,
@@ -500,7 +569,7 @@ writeTgaRaster(struct pam *          const pamP,
                     int i;
                     putchar(-runlength[col] - 1);
                     for (i = 0; i < -runlength[col]; ++i)
-                        putPixel(pamP, tuples[realrow][col+i], 
+                        putPixel(pamP, tuples[realrow][col+i],
                                  imgType, withAlpha, cht);
                     col += -runlength[col];
                 } else
@@ -519,47 +588,53 @@ writeTgaRaster(struct pam *          const pamP,
 
 
 int
-main(int argc, char *argv[]) {
+main(int argc, const char **argv) {
 
-    struct cmdlineInfo cmdline;
+    struct CmdlineInfo cmdline;
     FILE * ifP;
     tuple ** tuples;
     struct pam pam;
-    int ncolors;
+    int colorCt;
     tupletable chv;
     tuplehash cht;
     struct ImageHeader tgaHeader;
     enum TGAbaseImageType baseImgType;
+    enum TGAmapType mapType;
     bool withAlpha;
-    const char *outName;
+    const char * outName;
 
-    pnm_init( &argc, argv );
+    pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
 
-    ifP = pm_openr(cmdline.inputFilespec);
+    ifP = pm_openr(cmdline.inputFileName);
 
     computeOutName(cmdline, &outName);
 
     tuples = pnm_readpam(ifP, &pam, PAM_STRUCT_SIZE(tuple_type));
     pm_close(ifP);
 
-    computeImageType_cht(&pam, cmdline, tuples, 
-                         &baseImgType, &withAlpha, &chv, &cht, &ncolors);
+    computeImageType_cht(&pam, cmdline, tuples,
+                         &baseImgType, &mapType,
+                         &withAlpha, &chv, &cht, &colorCt);
 
     /* Do the Targa header */
-    computeTgaHeader(&pam, baseImgType, withAlpha, !cmdline.norle,
-                     ncolors, 0, outName, &tgaHeader);
+    computeTgaHeader(&pam, baseImgType, mapType, withAlpha, !cmdline.norle,
+                     colorCt, 0, outName, &tgaHeader);
+
+    if (cmdline.verbose)
+        reportTgaHeader(tgaHeader);
+
     writeTgaHeader(tgaHeader);
-    
+
     if (baseImgType == TGA_MAP_TYPE) {
         /* Write out the Targa colormap. */
-        int i;
-        for (i = 0; i < ncolors; ++i)
+        unsigned int i;
+        for (i = 0; i < colorCt; ++i)
             putMapEntry(&pam, chv[i]->tuple, tgaHeader.CoSize);
     }
 
-    writeTgaRaster(&pam, tuples, cht, baseImgType, withAlpha, 
+    writeTgaRaster(&pam, tuples, cht, baseImgType, withAlpha,
                    !cmdline.norle, 0);
 
     if (cht)
diff --git a/converter/other/pamtotiff.c b/converter/other/pamtotiff.c
index 72c7dc31..115b8b4a 100644
--- a/converter/other/pamtotiff.c
+++ b/converter/other/pamtotiff.c
@@ -142,30 +142,30 @@ parseIndexbits(bool          const indexbitsSpec,
         unsigned int i;
 
         /* Set initial values */
-        cmdlineP->indexsizeAllowed.b1 = FALSE;
-        cmdlineP->indexsizeAllowed.b2 = FALSE;
-        cmdlineP->indexsizeAllowed.b4 = FALSE;
-        cmdlineP->indexsizeAllowed.b8 = FALSE;
+        cmdlineP->indexsizeAllowed.b1 = false;
+        cmdlineP->indexsizeAllowed.b2 = false;
+        cmdlineP->indexsizeAllowed.b4 = false;
+        cmdlineP->indexsizeAllowed.b8 = false;
 
         for (i = 0; indexbits[i]; ++i) {
             const char * const thisItem = indexbits[i];
             if (streq(thisItem, "1"))
-                cmdlineP->indexsizeAllowed.b1 = TRUE;
+                cmdlineP->indexsizeAllowed.b1 = true;
             else if (streq(thisItem, "2"))
-                cmdlineP->indexsizeAllowed.b2 = TRUE;
+                cmdlineP->indexsizeAllowed.b2 = true;
             else if (streq(thisItem, "4"))
-                cmdlineP->indexsizeAllowed.b4 = TRUE;
+                cmdlineP->indexsizeAllowed.b4 = true;
             else if (streq(thisItem, "8"))
-                cmdlineP->indexsizeAllowed.b8 = TRUE;
+                cmdlineP->indexsizeAllowed.b8 = true;
             else
                 pm_error("Invalid item in -indexbits list: '%s'.  "
                          "We recognize only 1, 2, 4, and 8", thisItem);
-        }           
+        }
     } else {
-        cmdlineP->indexsizeAllowed.b1 = FALSE;
-        cmdlineP->indexsizeAllowed.b2 = FALSE;
-        cmdlineP->indexsizeAllowed.b4 = FALSE;
-        cmdlineP->indexsizeAllowed.b8 = TRUE;
+        cmdlineP->indexsizeAllowed.b1 = false;
+        cmdlineP->indexsizeAllowed.b2 = false;
+        cmdlineP->indexsizeAllowed.b4 = false;
+        cmdlineP->indexsizeAllowed.b8 = true;
     }
 }
 
@@ -233,8 +233,8 @@ parseCommandLine(int                 argc,
     OPTENT3(0, "tag",          OPT_NAMELIST, &cmdlineP->taglist, &tagSpec, 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 */
+    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. */
@@ -610,7 +610,7 @@ analyzeColorsInRgbInput(struct pam *   const pamP,
 -----------------------------------------------------------------------------*/
     if (cmdline.color && cmdline.truecolor) {
         *chvP = NULL;
-        *grayscaleP = FALSE;
+        *grayscaleP = false;
     } else {
         tupletable chv;
         bool grayscale;
@@ -620,15 +620,15 @@ analyzeColorsInRgbInput(struct pam *   const pamP,
                                          pamP->maxval,
                                          colorCtP);
         if (chv == NULL) {
-            grayscale = FALSE;
+            grayscale = false;
         } else {
             unsigned int i;
             pm_message("%u color%s found",
                        *colorCtP, *colorCtP == 1 ? "" : "s");
-            grayscale = TRUE;  /* initial assumption */
+            grayscale = true;  /* initial assumption */
             for (i = 0; i < *colorCtP && grayscale; ++i) {
                 if (!pnm_rgbtupleisgray(chv[i]->tuple))
-                    grayscale = FALSE;
+                    grayscale = false;
             }
         }
         *grayscaleP = grayscale;
@@ -686,7 +686,7 @@ analyzeColors(struct pam *   const pamP,
                                 chvP, colorCtP, grayscaleP);
     else {
         *chvP = NULL;
-        *grayscaleP = TRUE;
+        *grayscaleP = true;
     }
 }
 
@@ -727,7 +727,7 @@ computeRasterParm(struct pam *     const pamP,
    Compute the parameters of the raster portion of the TIFF image.
 
    'minisblack' and 'miniswhite' mean the user requests the corresponding
-   photometric.  Both FALSE means user has no explicit requirement.
+   photometric.  Both false means user has no explicit requirement.
 -----------------------------------------------------------------------------*/
     unsigned short defaultPhotometric;
     /* The photometric we use if the user specified no preference */
@@ -813,9 +813,9 @@ computeRasterParm(struct pam *     const pamP,
 /*----------------------------------------------------------------------------
   WRITE MODES
   -----------
-  
+
   The Tiff library does all output.  There are several issues:
-  
+
     1) The manner of output is opaque to the library client.  I.e.  we cannot
        see or control it.
 
@@ -826,22 +826,22 @@ computeRasterParm(struct pam *     const pamP,
 
     4) The Tiff library produces unhelpful error messages when the above
        conditions are not met.
-  
+
   We provide two modes for output:
-  
+
   1. Tmpfile mode (default)
-  
+
      We have the Tiff library direct output to an unnamed temporary file we
      create which is seekable and readable.  When output is complete, we copy
      the file's contents to Standard Output.
-  
+
   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
      rather than ask the Tiff library to use the file if it does not meet
      these requirements.
-  
+
      Direct mode is further divided into append and create.  They are the same
      except that in append mode, we insist that the file already exist,
      whereas with create mode, we create it if necessary.  In either case, if
@@ -1253,7 +1253,7 @@ main(int argc, const char *argv[]) {
     int ofd;
     int eof;
     unsigned int imageSeq;
-    
+
     pm_proginit(&argc, argv);
 
     parseCommandLine(argc, argv, &cmdline);
@@ -1277,7 +1277,7 @@ main(int argc, const char *argv[]) {
         break;
     }
 
-    eof = FALSE;  /* initial assumption */
+    eof = false;  /* initial assumption */
     imageSeq = 0;
 
     while (!eof) {