about summary refs log tree commit diff
path: root/converter/other/bmptopnm.c
diff options
context:
space:
mode:
Diffstat (limited to 'converter/other/bmptopnm.c')
-rw-r--r--converter/other/bmptopnm.c827
1 files changed, 482 insertions, 345 deletions
diff --git a/converter/other/bmptopnm.c b/converter/other/bmptopnm.c
index bf4d10f8..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,
@@ -80,6 +80,19 @@ struct pixelformat {
         */
 };
 
+typedef struct {
+    /* These are all encodings of floating point */
+    unsigned long x;
+    unsigned long y;
+    unsigned long z;
+} cieXyz;
+
+typedef struct {
+    cieXyz red;
+    cieXyz grn;
+    cieXyz blu;
+} cieXyzTriple;
+
 struct bmpInfoHeader {
     enum rowOrder rowOrder;
     unsigned int cols;
@@ -92,17 +105,18 @@ 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;
+    cieXyzTriple endPoints;
 };
 
 
@@ -137,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 */
@@ -145,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 "
@@ -208,27 +222,74 @@ GetLong(FILE * const fp) {
 
 
 
-typedef struct {
-    long dummy[12];
-} cieXyzTriple;
+static cieXyz
+GetCieXyz(FILE * const ifP) {
+
+    cieXyz retval;
+
+    retval.x = GetLong(ifP);
+    retval.y = GetLong(ifP);
+    retval.z = GetLong(ifP);
+
+    return retval;
+}
+
+
 
 static cieXyzTriple
-GetCieXyzTriple(FILE * const fp) {
+GetCieXyzTriple(FILE *         const ifP) {
 
-    cieXyzTriple v;
-    unsigned int i;
+    cieXyzTriple retval;
 
-    for (i = 0; i < 12; ++i) 
-        if (pm_readlittlelong(fp, &v.dummy[i]) == -1)
-            pm_error(er_read, ifname);
+    retval.red = GetCieXyz(ifP);
+    retval.grn = GetCieXyz(ifP);
+    retval.blu = GetCieXyz(ifP);
 
-    return v;
+    return retval;
 }
 
 
 
 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;
+}
 
 
 
@@ -238,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);
@@ -250,15 +311,11 @@ 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 short    xHotSpot;
-    unsigned short    yHotSpot;
     unsigned long     offBits;
-    unsigned long int fileSize;
-
 
     if (GetByte(ifP) != 'B')
         pm_error("'%s' is not a BMP file.  (It doesn't start with 'BM')",
@@ -268,33 +325,47 @@ bmpReadfileheader(FILE *         const ifP,
                  ifname);
 
 
-    fileSize = GetLong(ifP);  /* This is not always reliable. */
-    xHotSpot = GetShort(ifP);
-    yHotSpot = GetShort(ifP);
+    /* fileSize = */ GetLong(ifP);  /* This is not always reliable. */
+    /* xHotSpot = */ GetShort(ifP);
+    /* yHotSpot = */ GetShort(ifP);
     offBits  = GetLong(ifP);
 
     *offBitsP = offBits;
 
+    assert(BMPlenfileheader() == 14);
+
     *bytesReadP = 14;
 }
 
 
 
 static void
-readOs2InfoHeader(FILE *                 const ifP,
-                  struct bmpInfoHeader * const headerP) {
+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;
 
-    headerP->class = C_OS2;
-
     pm_readlittleshortu(ifP, &colsField);
     if (colsField == 0)
         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");
@@ -313,22 +384,19 @@ readOs2InfoHeader(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;
-    
-    pm_message("OS/2 BMP, %dx%dx%d",
-               headerP->cols, headerP->rows, headerP->cBitCount);
 }
 
 
@@ -337,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",
@@ -373,13 +441,10 @@ readWindowsBasic40ByteInfoHeader(FILE *                 const ifP,
 
    Return the information from the info header as *headerP.
 -----------------------------------------------------------------------------*/
-    int colorsimportant;   /* ColorsImportant value from header */
     int colorsused;        /* ColorsUsed value from header */
     unsigned short planesField, bitCountField;
     int32_t colsField;
 
-    headerP->class = C_WIN;
-
     pm_readlittlelong2(ifP, &colsField);
 
     if (colsField == 0)
@@ -388,6 +453,7 @@ readWindowsBasic40ByteInfoHeader(FILE *                 const ifP,
         pm_error("Invalid BMP file: says width is negative (%d)", colsField);
     else
         headerP->cols = (unsigned int)colsField;
+
     {
         long const cy = GetLong(ifP);
 
@@ -413,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 */
@@ -421,24 +487,30 @@ 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 */
+    /* colorsimportant = */ GetLong(ifP);  /* ColorsImportant */
 
     if (headerP->cBitCount <= 8) {
         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);
@@ -451,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;
 
@@ -512,52 +584,17 @@ 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,
+                          struct bmpInfoHeader * const headerP,
+                          unsigned int *         const bytesReadP) {
 
+    unsigned long redMsk, grnMsk, bluMsk, trnMsk;
 
-static void
-readV4InfoHeaderExtension(FILE *                 const ifP, 
-                          struct bmpInfoHeader * const headerP) {
+    redMsk = GetLong(ifP);
+    grnMsk = GetLong(ifP);
+    bluMsk = GetLong(ifP);
+    trnMsk = GetLong(ifP);
 
     if (headerP->bitFields) {
         /* A document from Microsoft says on Windows 95 there is no
@@ -565,21 +602,40 @@ readV4InfoHeaderExtension(FILE *                 const ifP,
            (5,5,5) or (5,6,5) for 16 bit and (8,8,8) for 32 bit.
            It calls these RGB555, RGB565, RGB888.
         */
-        headerP->pixelformat.red = bitPositionFromMask(GetLong(ifP));
-        headerP->pixelformat.grn = bitPositionFromMask(GetLong(ifP));
-        headerP->pixelformat.blu = bitPositionFromMask(GetLong(ifP));
-        headerP->pixelformat.trn = bitPositionFromMask(GetLong(ifP));
+        headerP->pixelformat.red = bitPositionFromMask(redMsk);
+        headerP->pixelformat.grn = bitPositionFromMask(grnMsk);
+        headerP->pixelformat.blu = bitPositionFromMask(bluMsk);
+        headerP->pixelformat.trn = bitPositionFromMask(trnMsk);
 
         computeConventionalBgr(&headerP->pixelformat, headerP->cBitCount);
     } else
         headerP->pixelformat = defaultPixelformat(headerP->cBitCount);
 
     GetLong(ifP);  /* Color space */
-    GetCieXyzTriple(ifP);  /* Endpoints */
+
+    headerP->endPoints = GetCieXyzTriple(ifP);  /* 36 bytes */
+
     GetLong(ifP);  /* GammaRed */
     GetLong(ifP);  /* GammaGreen */
     GetLong(ifP);  /* GammaBlue */
-} 
+
+    *bytesReadP = 68;
+}
+
+
+
+static void
+readV5InfoHeaderExtension(FILE *                 const ifP,
+                          struct bmpInfoHeader * const headerP,
+                          unsigned int *         const bytesReadP) {
+
+    GetLong(ifP);  /* Intent */
+    GetLong(ifP);  /* ProfileData */
+    GetLong(ifP);  /* ProfileSize */
+    GetLong(ifP);  /* Reserved */
+
+    *bytesReadP = 16;
+}
 
 
 
@@ -593,117 +649,157 @@ defaultV4InfoHeaderExtension(struct bmpInfoHeader * const headerP) {
 
 
 static void
-readWindowsInfoHeader(FILE *                 const ifP, 
-                      unsigned int           const cInfoHeaderSize,
-                      struct bmpInfoHeader * const headerP) {
-
+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
        new with Windows 95 and NT 4.0.  The "V5 header" is 124 bytes
        and was new with Windows 98 and Windows 2000.
     */
+    unsigned int bytesRead;
+
     readWindowsBasic40ByteInfoHeader(ifP, headerP);
 
-    if (cInfoHeaderSize >= 108) 
-        readV4InfoHeaderExtension(ifP, headerP);
-    else 
+    bytesRead = 40;
+
+    if (cInfoHeaderSize >= BMP_HDRLEN_WIN_V4) {
+        unsigned int v4BytesRead;
+        readV4InfoHeaderExtension(ifP, headerP, &v4BytesRead);
+        bytesRead += v4BytesRead;
+
+        assert(bytesRead == BMP_HDRLEN_WIN_V4);
+    } else
         defaultV4InfoHeaderExtension(headerP);
 
-    if (cInfoHeaderSize >= 124) {
-        /* Read off the V5 info header extension. */
-        GetLong(ifP);  /* Intent */
-        GetLong(ifP);  /* ProfileData */
-        GetLong(ifP);  /* ProfileSize */
-        GetLong(ifP);  /* Reserved */
+    if (cInfoHeaderSize >= BMP_HDRLEN_WIN_V5) {
+        unsigned int v5BytesRead;
+        readV5InfoHeaderExtension(ifP, headerP, &v5BytesRead);
+        bytesRead += v5BytesRead;
+        assert(bytesRead == BMP_HDRLEN_WIN_V5);
     }
 
-    pm_message("Windows BMP, %dx%dx%d",
-               headerP->cols, headerP->rows, headerP->cBitCount);
+    for (; bytesRead < cInfoHeaderSize;) {
+        GetByte(ifP);
+        ++bytesRead;
+    }
+
+    assert(bytesRead == cInfoHeaderSize);
 }
 
 
 
 static void
-bmpReadinfoheader(FILE *                 const ifP, 
+bmpReadinfoheader(FILE *                 const ifP,
                   unsigned int *         const bytesReadP,
-                  struct bmpInfoHeader * const headerP) {
+                  struct bmpInfoHeader * const headerP,
+                  const char **          const errorP) {
 
     unsigned int const cInfoHeaderSize = GetLong(ifP);
 
-    switch (cInfoHeaderSize) {
-    case 12:
-        readOs2InfoHeader(ifP, headerP);
-        break;
-    case 40: 
-        readWindowsInfoHeader(ifP, cInfoHeaderSize, headerP);
-        break;
-    case 108:
-        pm_error("This is a Version 4 Windows BMP; "
-                 "this program knows only Version 1");
-        break;
-    case 124:
-        pm_error("This is a Version 5 Windows BMP; "
-                 "this program knows only Version 1");
-        break;
-    default:
-        pm_error("%s: unknown Info Header size: %u bytes", 
-                 ifname, cInfoHeaderSize);
-        break;
+    const char * error;
+
+    BMPdetermineclass(cInfoHeaderSize, &headerP->class, &error);
+
+    if (error) {
+        pm_asprintf(errorP, "Cannot determine the class of BMP from the "
+                    "info header size %u.  %s", cInfoHeaderSize, error);
+        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:
+            readWindowsInfoHeaderRest(ifP, cInfoHeaderSize, headerP);
+            break;
+        case BMP_C_OS2_1x:
+        case BMP_C_OS2_2x:
+            readOs2InfoHeaderRest(ifP, headerP);
+            break;
+        }
+        *errorP = NULL;
+        *bytesReadP = cInfoHeaderSize;
     }
-    *bytesReadP = cInfoHeaderSize;
+    /* Part of our anti-arithmetic overflow strategy is to make sure height
+       and width always fit in 16 bits, so they can be multiplied together.
+       This shouldn't be a problem, since they come from 16 bit fields in
+       the BMP info header.
+    */
+    assert(headerP->cols < (1<<16));
+    assert(headerP->rows < (1<<16));
 }
 
 
 
 static void
-bmpReadColormap(FILE *         const ifP, 
-                int            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));
 
     unsigned int i;
-
-    xel * colormap;
     unsigned int bytesRead;
 
-    colormap = pnm_allocrow(MAX(1,cmapsize));
-    
-    bytesRead = 0;  /* initial value */
-
-    for (i = 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:
         */
-        unsigned int r, g, b;
-        
-        b = GetByte(ifP);
-        g = GetByte(ifP);
-        r = GetByte(ifP);
+        unsigned int const b = GetByte(ifP);
+        unsigned int const g = GetByte(ifP);
+        unsigned int const r = GetByte(ifP);
+
+        unsigned int j;
 
         PNM_ASSIGN(colormap[i], r, g, b);
 
         bytesRead += 3;
 
-        if (class == C_WIN) {
+        for (j = 3; j < BMPlenrgb(class); ++j) {
             GetByte(ifP);
             bytesRead += 1;
         }
     }
-    *colormapP = colormap;
+
+    *colormapP  = colormap;
     *bytesReadP = bytesRead;
 }
 
@@ -718,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 ?
@@ -735,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;
-}        
+}
 
 
 
@@ -758,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;
     }
 }
@@ -770,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,
@@ -780,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;
@@ -791,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;
     }
-} 
+}
 
 
 
@@ -810,7 +906,7 @@ convertRow32(unsigned char      const bmprow[],
              xel                      xelrow[],
              int                const cols,
              struct pixelformat const pixelformat) {
-    
+
     /* It's truecolor */
 
     unsigned int col;
@@ -826,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[].
@@ -871,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;
@@ -894,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 {
@@ -911,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;
@@ -932,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;
@@ -950,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
@@ -1000,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;
@@ -1034,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.
     */
 
@@ -1052,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;
 
@@ -1061,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 */
@@ -1086,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 ||
@@ -1132,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);
         }
@@ -1150,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
@@ -1179,37 +1293,40 @@ bmpReadraster(FILE *            const ifP,
         */
     unsigned char ** bmpRaster;
 
+    assert(cols < (1<<16));
+    assert(bytesPerRow < (1<<16));
+
     bmpRaster = allocBmpRaster(rows, bytesPerRow);
 
     *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.");
@@ -1226,36 +1343,51 @@ bmpReadraster(FILE *            const ifP,
 
 static void
 reportHeader(struct bmpInfoHeader const header,
-             unsigned int         const offBits) {
-             
-    pm_message("BMP image header says:");
-    pm_message("  Class of BMP: %s", 
-               header.class == C_WIN ? "Windows" : 
-               header.class == C_OS2 ? "OS/2" :
-               "???");
-    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", 
-               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);
-}        
+             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",
+                   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);
+    } else {
+        pm_message("%s BMP, %ux%ux%u",
+                   BMPClassName(header.class),
+                   header.cols,
+                   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;
@@ -1264,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)
@@ -1281,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), "
@@ -1290,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));
     }
 }
 
@@ -1305,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;
 }
@@ -1316,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;
@@ -1350,16 +1482,16 @@ isValidBmpBpp(unsigned int const cBitCount) {
 
 
 static void
-readBmp(FILE *               const ifP, 
-        unsigned char ***    const bmpRasterP, 
-        int *                const colsP, 
-        int *                const rowsP,
-        bool *               const grayPresentP, 
+readBmp(FILE *               const ifP,
+        unsigned char ***    const bmpRasterP,
+        unsigned int *       const colsP,
+        unsigned int *       const rowsP,
+        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 */
@@ -1367,33 +1499,39 @@ 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;
     }
     {
         unsigned int bytesRead;
-        bmpReadinfoheader(ifP, &bytesRead, &bmpHeader);
+        const char * error;
+        bmpReadinfoheader(ifP, &bytesRead, &bmpHeader, &error);
+        if (error)
+            pm_error("Failed to read the BMP info header.  Image may "
+                     "not be a valid BMP.  %s", error);
+
         if (verbose)
             pm_message("Read %u bytes of header", bytesRead);
         pos += bytesRead;
     }
 
-    if (verbose) 
-        reportHeader(bmpHeader, offBits);
+    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);
@@ -1404,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",
@@ -1416,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,
-               int                const cols, 
-               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
@@ -1440,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;
@@ -1450,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);
@@ -1460,12 +1598,12 @@ writeRasterGen(unsigned char **   const bmpRaster,
 
 static void
 writeRasterPbm(unsigned char ** const bmpRaster,
-               int              const cols, 
-               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
@@ -1475,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 colChars = pbm_packed_bytes(cols);
-    
-    int row;
+    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]; 
+
+    for (row = 0; row < rows; ++row){
+        unsigned char * const bitrow = bmpRaster[row];
 
         if (colorformat == BlackWhite) {
             unsigned int i;
-            for (i = 0; i < colChars; ++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);
@@ -1517,8 +1655,8 @@ main(int argc, const char ** argv) {
            black and white and whether it has colors other than black, white,
            and gray.
         */
-    int cols, rows;
-    unsigned char **bmpRaster;
+    unsigned int cols, rows;
+    unsigned char ** bmpRaster;
         /* The raster part of the BMP image, as a row x column array, with
            each element being a raw byte from the BMP raster.  Note that
            bmpRaster[0] is really Row 0 -- the top row of the image, even
@@ -1532,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);
 
@@ -1547,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);
 
@@ -1565,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);