about summary refs log tree commit diff
path: root/converter
diff options
context:
space:
mode:
Diffstat (limited to 'converter')
-rw-r--r--converter/other/cameratopam/camera.c37
-rw-r--r--converter/other/fiasco/codec/decoder.c310
-rw-r--r--converter/other/jpeg2000/pamtojpeg2k.c6
-rw-r--r--converter/other/pamtotiff.c2
-rw-r--r--converter/other/pclxl.h14
-rw-r--r--converter/other/pngtopam.c5
-rw-r--r--converter/other/pngx.c36
-rw-r--r--converter/other/pngx.h6
-rw-r--r--converter/other/pnmtopalm/palmtopnm.c207
-rw-r--r--converter/other/pnmtopclxl.c126
-rw-r--r--converter/other/pstopnm.c281
-rw-r--r--converter/ppm/ilbmtoppm.c809
12 files changed, 981 insertions, 858 deletions
diff --git a/converter/other/cameratopam/camera.c b/converter/other/cameratopam/camera.c
index f6196777..439c9413 100644
--- a/converter/other/cameratopam/camera.c
+++ b/converter/other/cameratopam/camera.c
@@ -1,8 +1,6 @@
 #define _DEFAULT_SOURCE /* New name for SVID & BSD source defines */
-#define _BSD_SOURCE
-    /* Make sure strcasecmp is in string.h */
-#define _XOPEN_SOURCE
-    /* Make sure putenv is in stdlib.h */
+#define _XOPEN_SOURCE 500
+    /* Make sure putenv is in stdlib.h, strcaseeq is in nstring.h */
 
 #include <stdlib.h>
 #include <string.h>
@@ -17,6 +15,7 @@
 #include "pm.h"
 #include "mallocvar.h"
 #include "pm_c_util.h"
+#include "nstring.h"
 
 #include "global_variables.h"
 #include "cameratopam.h"
@@ -47,8 +46,8 @@
 #define FORC3 for (c=0; c < 3; c++)
 #define FORC4 for (c=0; c < colors; c++)
 
-static void 
-merror (const void *ptr, const char *where) 
+static void
+merror (const void *ptr, const char *where)
 {
     if (ptr == NULL)
         pm_error ("Out of memory in %s", where);
@@ -57,7 +56,7 @@ merror (const void *ptr, const char *where)
 
 
 
-static void  
+static void
 adobeCopyPixel(Image             const image,
                unsigned int      const row,
                unsigned int      const col,
@@ -307,7 +306,7 @@ minolta_z2()
 
 void
 nikon_e2100_load_raw(Image const image) {
-        
+
   unsigned char   data[3432], *dp;
   unsigned short pixel[2288], *pix;
   int row, col;
@@ -384,7 +383,7 @@ fuji_s3_load_raw(Image const image) {
   }
 }
 
-static void 
+static void
 fuji_common_load_raw(Image        const image,
                      unsigned int const ncol,
                      unsigned int const icol,
@@ -1044,7 +1043,7 @@ static void  sony_decrypt (unsigned *data, int len, int start, int key)
         u.bytes[1] = pad[p] >> 16;
         u.bytes[2] = pad[p] >>  8;
         u.bytes[3] = pad[p] >>  0;
-        
+
         pad[p] = u.word;
     }
   }
@@ -1154,9 +1153,9 @@ static void  ciff_block_1030()
 /*
    Parse a CIFF file, better known as Canon CRW format.
  */
-void 
-parse_ciff(FILE * const ifp, 
-           int    const offset, 
+void
+parse_ciff(FILE * const ifp,
+           int    const offset,
            int    const length)
 {
   int tboff, nrecs, i, type, len, roff, aoff, save, wbi=-1;
@@ -1309,7 +1308,7 @@ parse_rollei(FILE * const ifp)
 
 
 void
-parse_mos(FILE * const ifp, 
+parse_mos(FILE * const ifp,
           int    const offset)
 {
     char data[40];
@@ -1358,7 +1357,7 @@ static double getrat()
 
 
 
-static void 
+static void
 parse_makernote(FILE * const ifp)
 {
   unsigned base=0, offset=0, entries, tag, type, len, save;
@@ -1504,7 +1503,7 @@ get_timestamp(FILE * const ifp)
     timestamp = ts;
 }
 
-static void 
+static void
 parse_exif(FILE * const ifp, int base)
 {
   int entries, tag, len, val, save;
@@ -1529,7 +1528,7 @@ parse_exif(FILE * const ifp, int base)
   }
 }
 
-static int 
+static int
 parse_tiff_ifd(FILE * const ifp, int base, int level)
 {
   unsigned entries, tag, type, len, plen=16, save;
@@ -1690,7 +1689,7 @@ guess_cfa_pc:
       case 50723:           /* CameraCalibration1 */
       case 50724:           /* CameraCalibration2 */
     for (i=0; i < colors; i++)
-      FORC4 cc[i][c] = getrat();    
+      FORC4 cc[i][c] = getrat();
       case 50727:           /* AnalogBalance */
     FORC4 ab[c] = getrat();
     break;
@@ -1770,7 +1769,7 @@ parse_external_jpeg(const char * const ifname)
     strcpy (jname, ifname);
     jfile = jname + (file - ifname);
     jext  = jname + (ext  - ifname);
-    if (strcasecmp (ext, ".jpg")) {
+    if (!strcaseeq (ext, ".jpg")) {
         strcpy (jext, isupper(ext[1]) ? ".JPG":".jpg");
         memcpy (jfile, file+4, 4);
         memcpy (jfile+4, file, 4);
diff --git a/converter/other/fiasco/codec/decoder.c b/converter/other/fiasco/codec/decoder.c
index 8e2855ef..229996b6 100644
--- a/converter/other/fiasco/codec/decoder.c
+++ b/converter/other/fiasco/codec/decoder.c
@@ -3,11 +3,11 @@
  *
  *  Written by:     Ullrich Hafner
  *          Michael Unger
- *      
+ *
  *  This file is part of FIASCO (Fractal Image And Sequence COdec)
  *  Copyright (C) 1994-2000 Ullrich Hafner
  */
- 
+
 /*
  *  $Date: 2000/10/22 10:44:48 $
  *  $Author: hafner $
@@ -37,7 +37,7 @@
 /*****************************************************************************
 
                 prototypes
-  
+
 *****************************************************************************/
 
 static void
@@ -63,7 +63,7 @@ duplicate_state_image (const word_t *domain, unsigned offset, unsigned level);
 /*****************************************************************************
 
                 public code
-  
+
 *****************************************************************************/
 
 video_t *
@@ -78,7 +78,7 @@ alloc_video (bool_t store_wfa)
  */
 {
    video_t *video = Calloc (1, sizeof (video_t));
-   
+
    video->future_display = -1;
    video->display        = 0;
 
@@ -138,13 +138,13 @@ get_next_frame (bool_t store_wfa, int enlarge_factor,
  *  Get next frame of the WFA 'video' from stream 'input'.
  *  'orig_wfa' is the constant part of the WFA used by all frames.
  *  Depending on values of 'enlarge_factor' and 'smoothing' enlarge and
- *  smooth image, respectively. 
+ *  smooth image, respectively.
  *  If 'store_wfa' is TRUE, then store WFA structure of reference frames
  *  (used by analysis tool xwfa).
  *  If 'reference_frame' is not NULL, then load image 'reference_frame'
  *  from disk.
  *  'format' gives the color format to be used (either 4:2:0 or 4:4:4).
- *  If 'timer' is not NULL, then accumulate running time statistics. 
+ *  If 'timer' is not NULL, then accumulate running time statistics.
  *
  *  Return value:
  *  pointer to decoded frame
@@ -157,7 +157,7 @@ get_next_frame (bool_t store_wfa, int enlarge_factor,
    image_t *sframe            = NULL; /* current smoothed frame */
    bool_t   current_frame_is_future_frame = NO;
 
-   if (video->future_display == video->display)  
+   if (video->future_display == video->display)
    {
       /*
        *  Future frame is already computed since it has been used
@@ -189,7 +189,7 @@ get_next_frame (bool_t store_wfa, int enlarge_factor,
      clock_t       ptimer;
      unsigned int  stop_timer [3];
      wfa_t        *tmp_wfa = NULL;
-     
+
      if (!store_wfa)
         video->wfa = orig_wfa;
      else
@@ -198,7 +198,7 @@ get_next_frame (bool_t store_wfa, int enlarge_factor,
         copy_wfa (tmp_wfa, video->wfa);
         copy_wfa (video->wfa, orig_wfa);
      }
-   
+
      /*
       *  First step: read WFA from disk
       */
@@ -210,7 +210,7 @@ get_next_frame (bool_t store_wfa, int enlarge_factor,
         timer->input [video->wfa->frame_type] += stop_timer [0];
         timer->frames [video->wfa->frame_type]++;
      }
-      
+
      /*
       *  Read reference frame from disk if required
       *  (i.e., 1st frame is of type B or P)
@@ -225,7 +225,7 @@ get_next_frame (bool_t store_wfa, int enlarge_factor,
         video->frame  = read_image_file (reference_frame);
         video->sframe = NULL;
      }
-   
+
      /*
       *  Depending on current frame type update past and future frames
       */
@@ -313,7 +313,7 @@ get_next_frame (bool_t store_wfa, int enlarge_factor,
      }
      if (tmp_wfa)
         free_wfa (tmp_wfa);
-     
+
      current_frame_is_future_frame = NO;
      /*
       *  Second step: decode image
@@ -323,7 +323,7 @@ get_next_frame (bool_t store_wfa, int enlarge_factor,
         unsigned orig_width, orig_height;
 
         stop_timer [0] = stop_timer [1] = stop_timer [2] = 0;
-     
+
         enlarge_image (enlarge_factor, format,
                (video->wfa->wfainfo->color
                 && format == FORMAT_4_2_0)
@@ -332,10 +332,10 @@ get_next_frame (bool_t store_wfa, int enlarge_factor,
         if (enlarge_factor > 0)
         {
            orig_width  = video->wfa->wfainfo->width  << enlarge_factor;
-           orig_height = video->wfa->wfainfo->height << enlarge_factor; 
+           orig_height = video->wfa->wfainfo->height << enlarge_factor;
         }
         else
-        { 
+        {
            orig_width  = video->wfa->wfainfo->width  >> - enlarge_factor;
            orig_height = video->wfa->wfainfo->height >> - enlarge_factor;
            if (orig_width & 1)
@@ -343,7 +343,7 @@ get_next_frame (bool_t store_wfa, int enlarge_factor,
            if (orig_height & 1)
           orig_height++;
         }
-     
+
         frame = decode_image (orig_width, orig_height, format,
                   timer != NULL ? stop_timer : NULL,
                   video->wfa);
@@ -381,7 +381,7 @@ get_next_frame (bool_t store_wfa, int enlarge_factor,
      }
      else
         sframe = NULL;
-     
+
      stop_timer [0] = prg_timer (&ptimer, STOP);
      if (timer)
         timer->smooth [video->wfa->frame_type] += stop_timer [0];
@@ -399,7 +399,7 @@ get_next_frame (bool_t store_wfa, int enlarge_factor,
         video->future_display     = frame_number;
         current_frame_is_future_frame = YES;
      }
-      
+
      if (!store_wfa)
         remove_states (video->wfa->basis_states, video->wfa);
       } while (!video->frame);
@@ -407,7 +407,7 @@ get_next_frame (bool_t store_wfa, int enlarge_factor,
       if (!store_wfa)
      video->wfa = NULL;
    }
-   
+
    return video->sframe ? video->sframe : video->frame;
 }
 
@@ -418,8 +418,8 @@ decode_image (unsigned orig_width, unsigned orig_height, format_e format,
  *  Compute image which is represented by the given 'wfa'.
  *  'orig_width'x'orig_height' gives the resolution of the image at
  *  coding time. Use 4:2:0 subsampling or 4:4:4 'format' for color images.
- *  If 'dec_timer' is given, accumulate running time statistics. 
- *  
+ *  If 'dec_timer' is given, accumulate running time statistics.
+ *
  *  Return value:
  *  pointer to decoded image
  *
@@ -458,7 +458,7 @@ decode_image (unsigned orig_width, unsigned orig_height, format_e format,
    for (max_level = 0, state = wfa->basis_states; state < wfa->states; state++)
       if (isedge (wfa->into [state][0][0]) || isedge (wfa->into [state][1][0]))
      max_level = MAX(max_level, wfa->level_of_state [state]);
-   
+
 
    /*
     *  Allocate frame buffer for decoded image
@@ -468,7 +468,7 @@ decode_image (unsigned orig_width, unsigned orig_height, format_e format,
    width  = MAX(width, orig_width);
    height = MAX(height, orig_height);
    frame = alloc_image (width, height, wfa->wfainfo->color, format);
-   
+
    /*
     *  Allocate buffers for intermediate state images
     */
@@ -478,7 +478,7 @@ decode_image (unsigned orig_width, unsigned orig_height, format_e format,
       wfa->level_of_state [wfa->tree[wfa->root_state][0]] = 128;
       wfa->level_of_state [wfa->tree[wfa->root_state][1]] = 128;
    }
-   alloc_state_images (&images, &offsets, frame, root_state, 0, max_level, 
+   alloc_state_images (&images, &offsets, frame, root_state, 0, max_level,
                format, wfa);
 
    if (dec_timer)
@@ -498,20 +498,20 @@ decode_image (unsigned orig_width, unsigned orig_height, format_e format,
    prg_timer (&ptimer, START);
    free_state_images (max_level, frame->color, images, offsets, root_state, 0,
               format, wfa);
-   
+
    /*
     *  Crop decoded image if the image size differs.
     */
    if (orig_width != width || orig_height != height)
    {
-      frame->height = orig_height;  
-      frame->width  = orig_width;   
-      if (orig_width != width)      
+      frame->height = orig_height;
+      frame->width  = orig_width;
+      if (orig_width != width)
       {
      color_e   band;        /* current color band */
      word_t   *src, *dst;       /* source and destination pointers */
      unsigned  y;           /* current row */
-     
+
      for (band  = first_band (frame->color);
           band <= last_band (frame->color); band++)
      {
@@ -546,7 +546,7 @@ decode_state (unsigned state, unsigned level, wfa_t *wfa)
  *  pointer to decoded state image
  *
  *  Side effects:
- *  'wfa' states > 'state' are removed.  
+ *  'wfa' states > 'state' are removed.
  */
 {
    word_t  *domains [2];
@@ -571,7 +571,7 @@ decode_state (unsigned state, unsigned level, wfa_t *wfa)
    {
       word_t   *src, *dst;
       unsigned  y;
-        
+
       src = domains [0];
       dst = img->pixels [GRAY];
       for (y = img->height; y; y--)
@@ -603,73 +603,73 @@ decode_range (unsigned range_state, unsigned range_label, unsigned range_level,
  *  'wfa->level_of_state []' is changed
  */
 {
-   image_t   *state_image;      /* regenerated state image */
-   word_t   **images;           /* pointer to array of pointers
-                       to state images */
-   u_word_t  *offsets;          /* pointer to array of state image
-                       offsets */
-   word_t    *range;
-
-   enlarge_image (range_level - (wfa->level_of_state [range_state] - 1),
-          FORMAT_4_4_4, -1, wfa);
-   state_image    = alloc_image (width_of_level (range_level + 1),
-                 height_of_level (range_level + 1),
-                 NO, FORMAT_4_4_4);
-   alloc_state_images (&images, &offsets, state_image, NULL, range_state,
-               range_level + 1, NO, wfa);
-   compute_state_images (range_level + 1, images, offsets, wfa);
-
-   range = Calloc (size_of_level (range_level), sizeof (word_t));
-
-   if ((range_level & 1) == 0)      /* square image */
-   {
-      memcpy (range,
-          images [range_state + (range_level + 1) * wfa->states]
-          + range_label * size_of_level (range_level),
-          size_of_level (range_level) * sizeof (word_t));
-   }
-   else                 /* rectangle */
-   {
-      word_t   *src, *dst;
-      unsigned  y;
-      
-      src = images [range_state + (range_level + 1) * wfa->states]
-        + range_label * width_of_level (range_level);
-      dst = range;
-      for (y = height_of_level (range_level); y; y--)
-      {
-     memcpy (dst, src, width_of_level (range_level) * sizeof (word_t));
-     dst += width_of_level (range_level);
-     src += width_of_level (range_level + 1);
-      }
-   }
-
-   if (domain != NULL)          /* copy domain images */
-   {
-      int      s;           /* domain state */
-      unsigned edge;            /* counter */
-        
-      if (ischild (s = wfa->tree [range_state][range_label]))
-     *domain++ = duplicate_state_image (images [s + (range_level)
-                           * wfa->states],
-                        offsets [s + (range_level)
-                            * wfa->states],
-                        range_level);
-      for (edge = 0; isedge (s = wfa->into[range_state][range_label][edge]);
-       edge++)
-     *domain++ = duplicate_state_image (images [s + (range_level)
-                           * wfa->states],
-                        offsets [s + (range_level)
-                            * wfa->states],
-                        range_level);
-      *domain = NULL;
-   }
-   
-   free_state_images (range_level + 1, NO, images, offsets, NULL, range_state,
-              NO, wfa);
-   free_image (state_image);
-   
-   return range;
+    image_t   *state_image;      /* regenerated state image */
+    word_t   **images;           /* pointer to array of pointers
+                                    to state images */
+    u_word_t  *offsets;          /* pointer to array of state image
+                                    offsets */
+    word_t    *range;
+
+    enlarge_image (range_level - (wfa->level_of_state [range_state] - 1),
+                   FORMAT_4_4_4, -1, wfa);
+    state_image = alloc_image (width_of_level (range_level + 1),
+                               height_of_level (range_level + 1),
+                               NO, FORMAT_4_4_4);
+    alloc_state_images (&images, &offsets, state_image, NULL, range_state,
+                        range_level + 1, FORMAT_4_4_4, wfa);
+    compute_state_images (range_level + 1, images, offsets, wfa);
+
+    range = Calloc (size_of_level (range_level), sizeof (word_t));
+
+    if ((range_level & 1) == 0)      /* square image */
+    {
+        memcpy (range,
+                images [range_state + (range_level + 1) * wfa->states]
+                + range_label * size_of_level (range_level),
+                size_of_level (range_level) * sizeof (word_t));
+    }
+    else                 /* rectangle */
+    {
+        word_t   *src, *dst;
+        unsigned  y;
+
+        src = images [range_state + (range_level + 1) * wfa->states]
+            + range_label * width_of_level (range_level);
+        dst = range;
+        for (y = height_of_level (range_level); y; y--)
+        {
+            memcpy (dst, src, width_of_level (range_level) * sizeof (word_t));
+            dst += width_of_level (range_level);
+            src += width_of_level (range_level + 1);
+        }
+    }
+
+    if (domain != NULL)          /* copy domain images */
+    {
+        int      s;           /* domain state */
+        unsigned edge;            /* counter */
+
+        if (ischild (s = wfa->tree [range_state][range_label]))
+            *domain++ = duplicate_state_image (images [s + (range_level)
+                                                       * wfa->states],
+                                               offsets [s + (range_level)
+                                                        * wfa->states],
+                                               range_level);
+        for (edge = 0; isedge (s = wfa->into[range_state][range_label][edge]);
+             edge++)
+            *domain++ = duplicate_state_image (images [s + (range_level)
+                                                       * wfa->states],
+                                               offsets [s + (range_level)
+                                                        * wfa->states],
+                                               range_level);
+        *domain = NULL;
+    }
+
+    free_state_images (range_level + 1, NO, images, offsets, NULL, range_state,
+                       FORMAT_4_4_4, wfa);
+    free_image (state_image);
+
+    return range;
 }
 
 void
@@ -685,7 +685,7 @@ smooth_image (unsigned sf, const wfa_t *wfa, image_t *image)
  */
 {
    int      is, inegs;          /* integer factors of s and 1 - s*/
-   unsigned state;          
+   unsigned state;
    unsigned img_width  = image->width;
    unsigned img_height = image->height;
    real_t   s          = 1.0 - sf / 200.0;
@@ -695,7 +695,7 @@ smooth_image (unsigned sf, const wfa_t *wfa, image_t *image)
 
    is    = s * 512 + .5;        /* integer representation of s */
    inegs = (1 - s) * 512 + .5;      /* integer representation of 1 - s */
-   
+
    for (state = wfa->basis_states;
     state < (wfa->wfainfo->color
          ? wfa->tree [wfa->root_state][0]
@@ -706,10 +706,10 @@ smooth_image (unsigned sf, const wfa_t *wfa, image_t *image)
       unsigned  level  = wfa->level_of_state[state]; /* level of state image */
       unsigned  width  = width_of_level (level); /* size of state image */
       unsigned  height = height_of_level (level); /* size of state image */
-      
+
       if (wfa->y [state][1] >= img_height || wfa->x [state][1] >= img_width)
      continue;          /* outside visible area */
-     
+
       if (level % 2)            /* horizontal smoothing */
       {
      unsigned  i;           /* line counter */
@@ -719,12 +719,12 @@ smooth_image (unsigned sf, const wfa_t *wfa, image_t *image)
      img1 = bptr + (wfa->y [state][1] - 1) * img_width
         + wfa->x [state][1];
      img2 = bptr + wfa->y [state][1] * img_width + wfa->x [state][1];
-     
+
      for (i = MIN(width, img_width - wfa->x [state][1]); i;
           i--, img1++, img2++)
      {
         int tmp = *img1;
-        
+
 #ifdef HAVE_SIGNED_SHIFT
         *img1 = (((is * tmp) >> 10) << 1)
             + (((inegs * (int) *img2) >> 10) << 1);
@@ -746,12 +746,12 @@ smooth_image (unsigned sf, const wfa_t *wfa, image_t *image)
 
      img1 = bptr + wfa->y [state][1] * img_width + wfa->x [state][1] - 1;
      img2 = bptr + wfa->y [state][1] * img_width + wfa->x [state][1];
-     
+
      for (i = MIN(height, img_height - wfa->y [state][1]); i;
           i--, img1 += img_width, img2 += img_width)
      {
         int tmp = *img1;
-        
+
 #ifdef HAVE_SIGNED_SHIFT
         *img1 = (((is * tmp) >> 10) << 1)
             + (((inegs * (int) *img2) >> 10) << 1);
@@ -771,7 +771,7 @@ smooth_image (unsigned sf, const wfa_t *wfa, image_t *image)
 /*****************************************************************************
 
                 private code
-  
+
 *****************************************************************************/
 
 static void
@@ -789,7 +789,7 @@ enlarge_image (int enlarge_factor, format_e format, unsigned y_root,
  *  are modified.
  */
 {
-   
+
    if (enlarge_factor != 0 || format == FORMAT_4_2_0)
    {
       unsigned state;
@@ -801,11 +801,11 @@ enlarge_image (int enlarge_factor, format_e format, unsigned y_root,
       }
       else
      state = wfa->basis_states;
-      
+
       for (; state < wfa->states; state++)
       {
      unsigned label, n;
-     
+
      wfa->level_of_state [state]
         = MAX(wfa->level_of_state [state] + enlarge_factor * 2, 0);
 
@@ -855,12 +855,12 @@ compute_actual_size (unsigned luminance_root,
 {
    unsigned x = 0, y = 0;       /* maximum coordinates */
    unsigned state;          /* counter */
-   
+
    for (state = wfa->basis_states; state < wfa->states; state++)
       if (isedge (wfa->into [state][0][0]) || isedge (wfa->into [state][1][0]))
       {
           unsigned mult = state > luminance_root ? 2 : 1;
-          
+
           x = MAX((wfa->x [state][0]
                    + width_of_level (wfa->level_of_state [state])) * mult, x);
           y = MAX((wfa->y [state][0]
@@ -886,7 +886,7 @@ alloc_state_images (word_t ***images, u_word_t **offsets, const image_t *frame,
  *  'max_level' fives the max. level of a linear combination.
  *  Memory is allocated for every required state image.
  *  Use 4:2:0 subsampling or 4:4:4 'format' for color images.
- *  If 'range_state' > 0 then rather compute image of 'range_state' than 
+ *  If 'range_state' > 0 then rather compute image of 'range_state' than
  *  image of 'wfa->root_state'.
  *
  *  Return values:
@@ -900,7 +900,7 @@ alloc_state_images (word_t ***images, u_word_t **offsets, const image_t *frame,
    word_t   **simg;         /* ptr to list of state image ptr's */
    u_word_t  *offs;         /* ptr to list of offsets */
    unsigned   level;            /* counter */
-   
+
    simg = Calloc (wfa->states * (max_level + 1), sizeof (word_t *));
    offs = Calloc (wfa->states * (max_level + 1), sizeof (u_word_t));
 
@@ -938,7 +938,7 @@ alloc_state_images (word_t ***images, u_word_t **offsets, const image_t *frame,
         }
       }
    }
-   
+
    /*
     *  Generate list of state images which must be computed at each level
     */
@@ -946,9 +946,9 @@ alloc_state_images (word_t ***images, u_word_t **offsets, const image_t *frame,
    {
       int      child, domain;
       unsigned state, label, edge;
-      
+
       /*
-       *  Range approximation with child. 
+       *  Range approximation with child.
        */
       for (state = 1; state < (range_state > 0 ?
                    range_state + 1 : wfa->states); state++)
@@ -990,7 +990,7 @@ alloc_state_images (word_t ***images, u_word_t **offsets, const image_t *frame,
           }
            }
       /*
-       *  Range approximation with linear combination 
+       *  Range approximation with linear combination
        */
       for (state = 1; state < (range_state > 0 ?
                    range_state + 1 : wfa->states); state++)
@@ -1008,7 +1008,7 @@ alloc_state_images (word_t ***images, u_word_t **offsets, const image_t *frame,
             = width_of_level (level - 1);
           }
            }
-      
+
    }
 
    *images  = simg;
@@ -1039,7 +1039,7 @@ free_state_images (unsigned max_level, bool_t color, word_t **state_image,
    else
    {
       unsigned state;
-      
+
       /*
        *  Initialize state image array with states at 'max_level'
        */
@@ -1053,19 +1053,19 @@ free_state_images (unsigned max_level, bool_t color, word_t **state_image,
         level = max_level - 2;
      else
         level = max_level;
-      
+
      for (; state < wfa->states; state++)
         if (wfa->level_of_state [state] == level)
            state_image [state + level * wfa->states] = &marker;
       }
    }
-   
+
    for (level = max_level; level > 0; level--)
    {
       int      domain, child;
       unsigned state, label, edge;
       /*
-       *  Range approximation with child. 
+       *  Range approximation with child.
        */
       for (state = 1; state < (range_state > 0 ?
                    range_state + 1 : wfa->states); state++)
@@ -1080,7 +1080,7 @@ free_state_images (unsigned max_level, bool_t color, word_t **state_image,
           state_image [child + (level - 1) * wfa->states] = &marker;
            }
       /*
-       *  Range approximation with linear combination 
+       *  Range approximation with linear combination
        */
       for (state = 1; state < (range_state > 0 ?
                    range_state + 1 : wfa->states);
@@ -1089,7 +1089,7 @@ free_state_images (unsigned max_level, bool_t color, word_t **state_image,
         for (label = 0; label < MAXLABELS; label++)
            for (edge = 0; isedge (domain = wfa->into[state][label][edge]);
             edge++)
-          if (domain > 0    
+          if (domain > 0
               && (state_image [domain + (level - 1) * wfa->states]
               != NULL)
               && (state_image [domain + (level - 1) * wfa->states]
@@ -1112,7 +1112,7 @@ compute_state_images (unsigned max_level, word_t **simg,
  *  which are marked in the array 'simg' (offsets of state images
  *  are given by 'offset').
  *
- *  Warning: Several optimizations are used in this function making 
+ *  Warning: Several optimizations are used in this function making
  *  it difficult to understand.
  *
  *  No return value.
@@ -1123,7 +1123,7 @@ compute_state_images (unsigned max_level, word_t **simg,
  */
 {
    unsigned level, state;
-     
+
    /*
     *  Copy one-pixel images in case state_image pointer != &final distr.
     */
@@ -1138,17 +1138,17 @@ compute_state_images (unsigned max_level, word_t **simg,
     *  'weight' gives the weight in integer notation
     *  'src', 'dst', and 'idst' are pointers to the source and
     *  destination pixels (short or integer format), respectively.
-    *  Short format : one operation per register (16 bit mode). 
-    *  Integer format : two operations per register (32 bit mode). 
+    *  Short format : one operation per register (16 bit mode).
+    *  Integer format : two operations per register (32 bit mode).
     *  'src_offset', 'dst_offset', and 'dst_offset' give the number of
     *  pixels which have to be omitted when jumping to the next image row.
     */
-   for (level = 1; level <= max_level; level++) 
+   for (level = 1; level <= max_level; level++)
    {
       unsigned label;
       unsigned width  = width_of_level (level - 1);
       unsigned height = height_of_level (level - 1);
-      
+
       for (state = 1; state < wfa->states; state++)
      if (simg [state + level * wfa->states] != NULL)
         for (label = 0; label < MAXLABELS; label++)
@@ -1176,7 +1176,7 @@ compute_state_images (unsigned max_level, word_t **simg,
           }
 
           /*
-           *  Generate the state images by adding the corresponding 
+           *  Generate the state images by adding the corresponding
            *  weighted state images:
            *  subimage [label] =
            *       weight_1 * image_1 + ... + weight_n * image_n
@@ -1226,12 +1226,12 @@ compute_state_images (unsigned max_level, word_t **simg,
             src_offset = offset [domain + ((level - 1)
                                * wfa->states)] - width;
             weight     = wfa->int_weight [state][label][edge];
-            
+
             if (width == 1) /* can't add two-pixels in a row */
             {
                word_t   *dst;
                unsigned  dst_offset;
-               
+
                dst        = range;
                dst_offset = offset [state + level * wfa->states]
                     - width;
@@ -1240,7 +1240,7 @@ compute_state_images (unsigned max_level, word_t **simg,
 #else                   /* not HAVE_SIGNED_SHIFT */
                *dst++ = ((weight * (int) *src++) / 1024) * 2;
 #endif /* not HAVE_SIGNED_SHIFT */
-               if (height == 2) 
+               if (height == 2)
                {
                   src += src_offset;
                   dst += dst_offset;
@@ -1256,14 +1256,14 @@ compute_state_images (unsigned max_level, word_t **simg,
                unsigned  y;
                int      *idst;
                unsigned  idst_offset;
-               
+
                idst        = (int *) range;
                idst_offset = (offset [state + level * wfa->states]
                       - width) / 2;
                for (y = height; y; y--)
                {
                   int *comp_dst = idst + (width >> 1);
-                  
+
                   for (; idst != comp_dst; )
                   {
                  int tmp; /* temp. value of adjacent pixels */
@@ -1312,11 +1312,11 @@ compute_state_images (unsigned max_level, word_t **simg,
             {
                word_t   *dst;
                unsigned  dst_offset;
-               
+
                dst        = range;
                dst_offset = offset [state + level * wfa->states]
                     - width;
-               
+
                *dst++ = weight;
                if (height == 2)
                {
@@ -1329,7 +1329,7 @@ compute_state_images (unsigned max_level, word_t **simg,
                unsigned  x, y;
                int      *idst;
                unsigned  idst_offset;
-               
+
                weight      = (weight * 65536) | (weight & 0xffff);
                idst        = (int *) range;
                idst_offset = offset [state + level * wfa->states]
@@ -1351,7 +1351,7 @@ compute_state_images (unsigned max_level, word_t **simg,
           }
           else
              edge = 0;
-          
+
           /*
            *  Add remaining weighted domain images to current range
            */
@@ -1368,12 +1368,12 @@ compute_state_images (unsigned max_level, word_t **simg,
             src_offset = offset [domain + ((level - 1)
                                * wfa->states)] - width;
             weight     = wfa->int_weight [state][label][edge];
-            
+
             if (width == 1) /* can't add two-pixels in a row */
             {
                word_t   *dst;
                unsigned  dst_offset;
-               
+
                dst        = range;
                dst_offset = offset [state + level * wfa->states]
                     - width;
@@ -1383,7 +1383,7 @@ compute_state_images (unsigned max_level, word_t **simg,
 #else /* not HAVE_SIGNED_SHIFT */
                *dst++ += ((weight * (int) *src++) / 1024) * 2;
 #endif /* not HAVE_SIGNED_SHIFT */
-               if (height == 2) 
+               if (height == 2)
                {
                   src += src_offset;
                   dst += dst_offset;
@@ -1399,15 +1399,15 @@ compute_state_images (unsigned max_level, word_t **simg,
                int      *idst;
                unsigned  idst_offset;
                unsigned  y;
-               
+
                idst        = (int *) range;
                idst_offset = (offset [state + level * wfa->states]
                       - width) / 2;
-               
+
                for (y = height; y; y--)
                {
                   int *comp_dst = idst + (width >> 1);
-                  
+
                   for (; idst != comp_dst;)
                   {
                  int tmp; /* temp. value of adjacent pixels */
@@ -1457,11 +1457,11 @@ compute_state_images (unsigned max_level, word_t **simg,
             {
                word_t   *dst;
                unsigned  dst_offset;
-               
+
                dst        = range;
                dst_offset = offset [state + level * wfa->states]
                     - width;
-               
+
                *dst++ += weight;
                if (height == 2)
                {
@@ -1474,16 +1474,16 @@ compute_state_images (unsigned max_level, word_t **simg,
                int      *idst;
                unsigned  idst_offset;
                unsigned  y;
-               
+
                weight      = (weight * 65536) | (weight & 0xffff);
                idst        = (int *) range;
                idst_offset = (offset [state + level * wfa->states]
                       - width) /2;
-               
+
                for (y = height; y; y--)
                {
                   int *comp_dst = idst + (width >> 1);
-                  
+
                   for (; idst != comp_dst; )
                   {
                  *idst = (*idst + weight) & 0xfffefffe;
@@ -1494,14 +1494,14 @@ compute_state_images (unsigned max_level, word_t **simg,
             }
              }
           }
-           } 
+           }
    }
 }
 
 static word_t *
 duplicate_state_image (const word_t *domain, unsigned offset, unsigned level)
 /*
- *  Allocate new memory block 'pixels' and copy pixel values of 'domain' 
+ *  Allocate new memory block 'pixels' and copy pixel values of 'domain'
  *  (size and pixel offset are given by 'level' and 'offset')
  *  to the lock 'pixels'.
  *
diff --git a/converter/other/jpeg2000/pamtojpeg2k.c b/converter/other/jpeg2000/pamtojpeg2k.c
index 3d8a97af..1272a422 100644
--- a/converter/other/jpeg2000/pamtojpeg2k.c
+++ b/converter/other/jpeg2000/pamtojpeg2k.c
@@ -341,7 +341,7 @@ convertToJasperImage(struct pam *   const inpamP,
 
     createJasperImage(inpamP, &jasperP);
 
-    if (strncmp(inpamP->tuple_type, "RGB", 3) == 0) {
+    if (strneq(inpamP->tuple_type, "RGB", 3)) {
         if (inpamP->depth < 3)
             pm_error("Input tuple type is RGB*, but depth is only %d.  "
                      "It should be at least 3.", inpamP->depth);
@@ -355,8 +355,8 @@ convertToJasperImage(struct pam *   const inpamP,
                                   JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_RGB_B));
         }
     } else {
-        if (strncmp(inpamP->tuple_type, "GRAYSCALE", 9 == 0) ||
-            strncmp(inpamP->tuple_type, "BLACKANDWHITE", 13) == 0) {
+        if (strneq(inpamP->tuple_type, "GRAYSCALE", 9) ||
+            strneq(inpamP->tuple_type, "BLACKANDWHITE", 13)) {
             jas_image_setclrspc(jasperP, JAS_CLRSPC_GENGRAY);
             jas_image_setcmpttype(jasperP, 0,
                                   JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_GRAY_Y));
diff --git a/converter/other/pamtotiff.c b/converter/other/pamtotiff.c
index 139b1fd7..72c7dc31 100644
--- a/converter/other/pamtotiff.c
+++ b/converter/other/pamtotiff.c
@@ -21,9 +21,7 @@
 ** other special, indirect and consequential damages.
 */
 
-#define _DEFAULT_SOURCE  /* New name for SVID & BSD source defines */
 #define _XOPEN_SOURCE    /* Make sure stdio.h contains fileno() */
-#define _BSD_SOURCE      /* Make sure string.h contains strcasecmp() */
 
 #include <unistd.h>
 #include <stdio.h>
diff --git a/converter/other/pclxl.h b/converter/other/pclxl.h
index b1d1c043..5b3eae4b 100644
--- a/converter/other/pclxl.h
+++ b/converter/other/pclxl.h
@@ -48,7 +48,7 @@ enum DataOrg {
 };
 
 enum DataSource {
-    eDefault = 0
+    eDefaultDataSource = 0
 };
 
 enum DataType {
@@ -58,9 +58,9 @@ enum DataType {
     eSint16 = 3
 };
 
-enum DitherMatrix {  
+enum DitherMatrix {
     eDeviceBest = 0
-}; 
+};
 
 
 enum DuplexPageMode {
@@ -109,7 +109,7 @@ enum Measure {
 };
 
 enum MediaSource {
-    eDefaultSource = 0,
+    eDefaultMediaSource = 0,
     eAutoSelect = 1,
     eManualFeed = 2,
     eMultiPurposeTray = 3,
@@ -246,7 +246,7 @@ enum Attribute {
     aYSpacingData        = 176,
     aCharBoldValue       = 177
 };
-                                          
+
 enum Operator {
     oBeginSession        = 0x41,
     oEndSession          = 0x42,
@@ -317,7 +317,7 @@ enum Operator {
     oPiePath             = 0x9f,
     oRectangle           = 0xa0,
     oRectanglePath       = 0xa1,
-    oRoundRectangle      = 0xa2,  
+    oRoundRectangle      = 0xa2,
     oRoundRectanglePath  = 0xa3,
     oText                = 0xa8,
     oTextPath            = 0xa9,
@@ -384,7 +384,7 @@ struct sPaperFormat {
 enum {
     eSTART,
     eRLE,
-    eLIT 
+    eLIT
 } RLEstates;
 
 #endif
diff --git a/converter/other/pngtopam.c b/converter/other/pngtopam.c
index 01690520..1023c6c6 100644
--- a/converter/other/pngtopam.c
+++ b/converter/other/pngtopam.c
@@ -1238,9 +1238,8 @@ static void
 warnNonsquarePixels(struct pngx * const pngxP,
                     int *         const errorLevelP) {
 
-    if (pngx_chunkIsPresent(pngxP, PNG_INFO_pHYs)) {
-        float const r =
-            (float)pngx_xPixelsPerMeter(pngxP) / pngx_yPixelsPerMeter(pngxP);
+    if (pngx_pixelAspectRatioIsKnown(pngxP)) {
+        float const r = pngx_pixelAspectRatio(pngxP);
 
         if (r != 1.0) {
             const char * const baseMsg = "warning - non-square pixels";
diff --git a/converter/other/pngx.c b/converter/other/pngx.c
index a5171066..dfc74485 100644
--- a/converter/other/pngx.c
+++ b/converter/other/pngx.c
@@ -270,15 +270,39 @@ pngx_trns(struct pngx * const pngxP) {
 
 uint32_t
 pngx_xPixelsPerMeter(struct pngx * const pngxP) {
-
+/*----------------------------------------------------------------------------
+  Horizontal pixel density in pixel per meter; 0 if unknown.
+-----------------------------------------------------------------------------*/
     return png_get_x_pixels_per_meter(pngxP->png_ptr, pngxP->info_ptr);
 }
 
 
 
+float
+pngx_pixelAspectRatio(struct pngx * const pngxP) {
+/*----------------------------------------------------------------------------
+  Aspect ratio - y/x.  0.0 if unknown
+-----------------------------------------------------------------------------*/
+    return png_get_pixel_aspect_ratio(pngxP->png_ptr, pngxP->info_ptr);
+}
+
+
+
+bool
+pngx_pixelAspectRatioIsKnown(struct pngx * const pngxP) {
+/*----------------------------------------------------------------------------
+  There is pixel aspect ratio information in the PNG image.
+-----------------------------------------------------------------------------*/
+    return png_get_pixel_aspect_ratio(pngxP->png_ptr, pngxP->info_ptr) != 0.0;
+}
+
+
+
 uint32_t
 pngx_yPixelsPerMeter(struct pngx * const pngxP) {
-
+/*----------------------------------------------------------------------------
+  Vertical pixel density in pixel per meter; 0 if unknown.
+-----------------------------------------------------------------------------*/
     return png_get_y_pixels_per_meter(pngxP->png_ptr, pngxP->info_ptr);
 }
 
@@ -323,7 +347,7 @@ void
 pngx_setChrm(struct pngx *      const pngxP,
              struct pngx_chroma const chroma) {
 
-    png_set_cHRM(pngxP->png_ptr, pngxP->info_ptr, 
+    png_set_cHRM(pngxP->png_ptr, pngxP->info_ptr,
                  chroma.wx, chroma.wy,
                  chroma.rx, chroma.ry,
                  chroma.gx, chroma.gy,
@@ -460,7 +484,7 @@ void
 pngx_setPhys(struct pngx *    const pngxP,
              struct pngx_phys const phys) {
 
-    png_set_pHYs(pngxP->png_ptr, pngxP->info_ptr, 
+    png_set_pHYs(pngxP->png_ptr, pngxP->info_ptr,
                  phys.x, phys.y, phys.unit);
 }
 
@@ -664,7 +688,7 @@ pngx_readStart(struct pngx * const pngxP,
                FILE *        const ifP) {
 
     size_t sigByteCt;
-            
+
     verifyFileIsPng(ifP, &sigByteCt);
 
     /* Declare that we already read the signature bytes */
@@ -711,7 +735,7 @@ pngx_writeRow(struct pngx *    const pngxP,
 void
 pngx_readEnd(struct pngx * const pngxP) {
 
-    /* Note that some of info_ptr is not defined until png_read_end() 
+    /* Note that some of info_ptr is not defined until png_read_end()
        completes.  That's because it comes from chunks that are at the
        end of the stream.  In particular, text and time chunks may
        be at the end.  Furthermore, they may be in both places, in
diff --git a/converter/other/pngx.h b/converter/other/pngx.h
index 008081eb..be9b9558 100644
--- a/converter/other/pngx.h
+++ b/converter/other/pngx.h
@@ -116,6 +116,12 @@ pngx_xPixelsPerMeter(struct pngx * const pngxP);
 uint32_t
 pngx_yPixelsPerMeter(struct pngx * const pngxP);
 
+float
+pngx_pixelAspectRatio(struct pngx * const pngxP);
+
+bool
+pngx_pixelAspectRatioIsKnown(struct pngx * const pngxP);
+
 void
 pngx_removeChunk(struct pngx * const pngxP,
                  uint32_t      const chunkType);
diff --git a/converter/other/pnmtopalm/palmtopnm.c b/converter/other/pnmtopalm/palmtopnm.c
index b58c99bc..b3c0321a 100644
--- a/converter/other/pnmtopalm/palmtopnm.c
+++ b/converter/other/pnmtopalm/palmtopnm.c
@@ -26,8 +26,8 @@
 
 
 enum PalmCompressionType {
-    COMPRESSION_NONE, 
-    COMPRESSION_RLE, 
+    COMPRESSION_NONE,
+    COMPRESSION_RLE,
     COMPRESSION_SCANLINE,
     COMPRESSION_PACKBITS
 };
@@ -102,7 +102,7 @@ parseCommandLine(int argc, const char ** argv,
     unsigned int option_def_index;
 
     MALLOCARRAY_NOFAIL(option_def, 100);
-    
+
     option_def_index = 0;   /* incremented by OPTENTRY */
     OPTENT3(0, "verbose",     OPT_FLAG, NULL,
             &cmdlineP->verbose,  0);
@@ -110,7 +110,7 @@ parseCommandLine(int argc, const char ** argv,
             &cmdlineP->showhist, 0);
     OPTENT3(0, "transparent",    OPT_FLAG, NULL,
             &cmdlineP->transparent, 0);
-    OPTENT3(0, "rendition",  OPT_UINT, &cmdlineP->rendition, 
+    OPTENT3(0, "rendition",  OPT_UINT, &cmdlineP->rendition,
             &renditionSpec, 0);
 
     opt.opt_table = option_def;
@@ -124,9 +124,9 @@ parseCommandLine(int argc, const char ** argv,
     if (renditionSpec) {
         if (cmdlineP->rendition < 1)
             pm_error("The -rendition value must be at least 1");
-    } else 
+    } else
         cmdlineP->rendition = 1;
-    
+
     if (cmdlineP->transparent && cmdlineP->showhist)
         pm_error("You can't specify -showhist with -transparent");
 
@@ -144,7 +144,7 @@ parseCommandLine(int argc, const char ** argv,
 
 
 static xelval *
-createGraymap(unsigned int const ncolors, 
+createGraymap(unsigned int const ncolors,
               xelval       const maxval) {
     int i;
     xelval *map;
@@ -158,8 +158,8 @@ createGraymap(unsigned int const ncolors,
 
 
 
-static void 
-skipbytes(FILE *       const ifP, 
+static void
+skipbytes(FILE *       const ifP,
           unsigned int const nbytes) {
 
     unsigned char buf[256];
@@ -180,7 +180,7 @@ skipbytes(FILE *       const ifP,
                pm_error("Error reading Palm file.  Short read.");
             n = 0;
         }
-    }    
+    }
 }
 
 
@@ -188,7 +188,7 @@ skipbytes(FILE *       const ifP,
 static void
 interpretCompression(unsigned char              const compressionValue,
                      enum PalmCompressionType * const compressionTypeP) {
-    
+
     switch (compressionValue) {
     case PALM_COMPRESSION_RLE:
         *compressionTypeP = COMPRESSION_RLE;
@@ -224,17 +224,18 @@ readRestOfHeaderVersion3(FILE *           const ifP,
                          short *          const nextDepthOffsetP) {
 
     unsigned char unused;
-    
+
     pm_readcharu(ifP, sizeP);
     /* should be 0x18, but I can't see why we should really care */
     if (*sizeP != 0x18)
-        pm_message("Strange value for Palm bitmap header size: %hu", *sizeP);
+        pm_message("Strange value for Palm bitmap header size: %u",
+                   (unsigned)*sizeP);
 
     pm_readcharu(ifP, pixelFormatP);
     if (*pixelFormatP != PALM_FORMAT_INDEXED &&
         *pixelFormatP != PALM_FORMAT_565)
         pm_error("Unrecognized pixelformat type: %u", *pixelFormatP);
-    
+
     pm_readcharu(ifP, &unused);
 
 
@@ -248,15 +249,15 @@ readRestOfHeaderVersion3(FILE *           const ifP,
         *densityP != PALM_DENSITY_TRIPLE &&
         *densityP != PALM_DENSITY_QUADRUPLE)
         pm_error("Invalid value for -density: %d.", *densityP);
- 
+
     pm_readbiglong(ifP, transparentValueP);
     if (pixelSize < 16)
         *transparentIndexP = *transparentValueP;
     else
         *transparentIndexP = 0;
- 
+
     pm_readbiglong(ifP, nextBitmapOffsetP);
-    
+
     /* version < 3 specific */
     *nextDepthOffsetP = 0;
 }
@@ -273,18 +274,18 @@ readRestOfHeaderOld(FILE *           const ifP,
                     long *           const transparentValueP,
                     long *           const nextBitmapOffsetP,
                     short *          const nextDepthOffsetP) {
-    
+
     short pad;
     unsigned char transparentIndex;
-    
+
     pm_readbigshort(ifP, nextDepthOffsetP);
     pm_readcharu(ifP, &transparentIndex);
     *transparentIndexP = transparentIndex;
- 
+
     pm_readcharu(ifP,compressionTypeP);
-    
+
     pm_readbigshort(ifP, &pad); /* reserved by Palm as of 8/9/00 */
-    
+
     /* version 3 specific */
     *sizeP = 0;
     *pixelFormatP = 0;
@@ -310,7 +311,7 @@ interpretHeader(struct PalmHeader * const palmHeaderP,
                 long                const transparentValue,
                 unsigned int        const transparentIndex,
                 unsigned char       const compressionType) {
-    
+
     palmHeaderP->cols = cols;
     palmHeaderP->rows = rows;
     palmHeaderP->bytesPerRow = bytesPerRow;
@@ -333,11 +334,11 @@ interpretHeader(struct PalmHeader * const palmHeaderP,
         */
         pm_error("PALM_DIRECT_COLOR_FLAG is set but pixelFormat is not"
                  "PALM_FORMAT_565.");
-        
-    palmHeaderP->directColor = ((flags & PALM_DIRECT_COLOR_FLAG) || 
+
+    palmHeaderP->directColor = ((flags & PALM_DIRECT_COLOR_FLAG) ||
                                 palmHeaderP->pixelFormat == PALM_FORMAT_565);
-    
-    if (flags & PALM_IS_COMPRESSED_FLAG) 
+
+    if (flags & PALM_IS_COMPRESSED_FLAG)
         interpretCompression(compressionType,
                              &palmHeaderP->compressionType);
     else
@@ -362,7 +363,7 @@ readHeader(FILE *              const ifP,
     currentRendition = 1;
     while (!gotHeader) {
         short cols, rows, bytesPerRow, flags, nextDepthOffset, density;
-        unsigned char pixelSizeCode, version, compressionType, 
+        unsigned char pixelSizeCode, version, compressionType,
             size, pixelFormat;
         long transparentValue, nextBitmapOffset;
         unsigned int pixelSize, transparentIndex;
@@ -371,7 +372,7 @@ readHeader(FILE *              const ifP,
         pm_readbigshort(ifP, &rows);
         pm_readbigshort(ifP, &bytesPerRow);
         pm_readbigshort(ifP, &flags);
- 
+
         pm_readcharu(ifP, &pixelSizeCode);
         pixelSize = pixelSizeCode == 0 ? 1 : pixelSizeCode;
         if (pixelSizeCode != 0x00 &&
@@ -388,12 +389,12 @@ readHeader(FILE *              const ifP,
                      "bits per pixel.", bytesPerRow, cols, pixelSize);
 
         pm_readcharu(ifP, &version);
-        if (version > 3) 
+        if (version > 3)
             pm_error("Unknown encoding version type: %d", version);
         else if (version == 3)
             readRestOfHeaderVersion3(ifP, pixelSize,
                                      &size, &pixelFormat, &compressionType,
-                                     &density, &transparentIndex, 
+                                     &density, &transparentIndex,
                                      &transparentValue, &nextBitmapOffset,
                                      &nextDepthOffset);
         else
@@ -404,29 +405,29 @@ readHeader(FILE *              const ifP,
                                 &nextDepthOffset);
 
         if (currentRendition < requestedRendition) {
-             if (version < 3 && nextDepthOffset == 0 && pixelSizeCode != 0xFF) 
+             if (version < 3 && nextDepthOffset == 0 && pixelSizeCode != 0xFF)
                  pm_error("Not enough renditions in the input Palm Bitmap "
                           "to extract the %dth", requestedRendition);
-             if (version == 3 && nextBitmapOffset == 0) 
+             if (version == 3 && nextBitmapOffset == 0)
                  pm_error("Not enough renditions in the input Palm Bitmap "
                           "to extract the %dth", requestedRendition);
              /* nextDepthOffset is calculated in 4 byte words
-                from the beginning of this bitmap (so it equals its size) 
+                from the beginning of this bitmap (so it equals its size)
              */
              if (version < 3 && pixelSizeCode != 0xFF )
                  skipbytes(ifP, (nextDepthOffset*4)-16);
              else if (version == 3)
                  /* FIXME rewrite skipbytes to accept longs? */
-                 skipbytes(ifP, (short) nextBitmapOffset-24); 
+                 skipbytes(ifP, (short) nextBitmapOffset-24);
              if (pixelSizeCode != 0xFF)
                  ++currentRendition;
         } else if (pixelSizeCode != 0xFF) {
             gotHeader = TRUE;
-            
+
             interpretHeader(palmHeaderP,
                             cols, rows, bytesPerRow, flags, pixelSizeCode,
                             pixelSize, version, size, pixelFormat, density,
-                            transparentValue, transparentIndex, 
+                            transparentValue, transparentIndex,
                             compressionType);
         }
     }
@@ -466,9 +467,9 @@ reportPalmHeader(struct PalmHeader      const palmHeader,
     }
     pm_message("Dimensions: %hu columns x %hu rows",
                palmHeader.cols, palmHeader.rows);
-    pm_message("Row layout: %hu bytes per row, %hu bits per pixel",
+    pm_message("Row layout: %hu bytes per row, %u bits per pixel",
                palmHeader.bytesPerRow, palmHeader.pixelSize);
-    pm_message("Pixel Size code: %hu", palmHeader.pixelSizeCode);
+    pm_message("Pixel Size code: %u", (unsigned)palmHeader.pixelSizeCode);
     pm_message("Flags: 0x%04hx", palmHeader.flags);
     pm_message("  Direct Color: %s", yesno(palmHeader.directColor));
     pm_message("  Colormap:     %s", yesno(palmHeader.hasColormap));
@@ -478,9 +479,9 @@ reportPalmHeader(struct PalmHeader      const palmHeader,
         if (palmHeader.directColor) {
             /* Copied from doTransparent(...) */
             ColormapEntry const color = directColorInfo.transparentColor;
-            pm_message("Transparent value: #%02x%02x%02x", 
-                       (unsigned int)((color >> 16) & 0xFF), 
-                       (unsigned int)((color >>  8) & 0xFF), 
+            pm_message("Transparent value: #%02x%02x%02x",
+                       (unsigned int)((color >> 16) & 0xFF),
+                       (unsigned int)((color >>  8) & 0xFF),
                        (unsigned int)((color >>  0) & 0xFF));
         } else
             pm_message("Transparent index: %u", palmHeader.transparentIndex);
@@ -526,7 +527,7 @@ readRgbFormat(FILE *                     const ifP,
     pm_readcharu(ifP, &r);
     pm_readcharu(ifP, &g);
     pm_readcharu(ifP, &b);
-    
+
     if (r != 5 || g != 6 || b != 5)
         pm_error("This image has a direct color pixel format of "
                  "%u red, %u green, %u blue bits.  This program "
@@ -572,12 +573,12 @@ readDirectInfoType(FILE *                   const ifP,
     if ((palmHeader.directColor) && palmHeader.pixelSize != 16)
         pm_error("The image is of the direct color type, but has %u "
                  "bits per pixel.  The only kind of direct color images "
-                 "this program understands are 16 bit ones.", 
+                 "this program understands are 16 bit ones.",
                  palmHeader.pixelSize);
 
     if (palmHeader.version == 3) {
         /* All direct color info is in the header, because it'sversion
-           3 encoding.  No Direct Info Type section.  
+           3 encoding.  No Direct Info Type section.
         */
     } else {
         if (palmHeader.directColor) {
@@ -588,7 +589,7 @@ readDirectInfoType(FILE *                   const ifP,
             pm_readcharu(ifP, &padding);
             pm_readcharu(ifP, &padding);
 
-            readDirectTransparentColor(ifP, 
+            readDirectTransparentColor(ifP,
                                        &directInfoTypeP->transparentColor);
         } else {
             /* Not a direct color image; no Direct Info Type section. */
@@ -637,7 +638,7 @@ getColorInfo(struct PalmHeader        const palmHeader,
         directColorInfoP->pixelFormat.redbits   = 5;
         directColorInfoP->pixelFormat.greenbits = 6;
         directColorInfoP->pixelFormat.bluebits  = 5;
-        directColorInfoP->transparentColor = 
+        directColorInfoP->transparentColor =
             /* See convertRowToPnmDirect for this trick
 
                This will break once maxval isn't always set 255 for
@@ -657,7 +658,7 @@ getColorInfo(struct PalmHeader        const palmHeader,
     else if (palmHeader.pixelSize >= 8) {
         Colormap * const colormapP =
             palmcolor_build_default_8bit_colormap();
-        qsort(colormapP->color_entries, colormapP->ncolors, 
+        qsort(colormapP->color_entries, colormapP->ncolors,
               sizeof(ColormapEntry), palmcolor_compare_indices);
         *colormapPP = colormapP;
     } else
@@ -689,28 +690,28 @@ doTransparent(FILE *                 const ofP,
             ColormapEntry const searchTarget = transparentIndex << 24;
             ColormapEntry * const foundEntryP =
                 bsearch(&searchTarget,
-                        colormapP->color_entries, 
+                        colormapP->color_entries,
                         colormapP->ncolors,
-                        sizeof(searchTarget), 
+                        sizeof(searchTarget),
                         palmcolor_compare_indices);
             if (!foundEntryP)
                 pm_error("Invalid input; transparent index %u "
                          "is not among the %u colors in the image's colormap",
                          transparentIndex, colormapP->ncolors);
 
-            fprintf(ofP, "#%02x%02x%02x\n", 
+            fprintf(ofP, "#%02x%02x%02x\n",
                    (unsigned int) ((*foundEntryP >> 16) & 0xFF),
-                   (unsigned int) ((*foundEntryP >>  8) & 0xFF), 
+                   (unsigned int) ((*foundEntryP >>  8) & 0xFF),
                    (unsigned int) ((*foundEntryP >>  0) & 0xFF));
         } else if (directColor) {
             ColormapEntry const color = directColorInfo.transparentColor;
-            fprintf(ofP, "#%02x%02x%02x\n", 
-                   (unsigned int)((color >> 16) & 0xFF), 
-                   (unsigned int)((color >>  8) & 0xFF), 
+            fprintf(ofP, "#%02x%02x%02x\n",
+                   (unsigned int)((color >> 16) & 0xFF),
+                   (unsigned int)((color >>  8) & 0xFF),
                    (unsigned int)((color >>  0) & 0xFF));
         } else {
             unsigned int const maxval = pm_bitstomaxval(pixelSize);
-            unsigned int const grayval = 
+            unsigned int const grayval =
                 ((maxval - transparentIndex) * 256) / maxval;
             fprintf(ofP, "#%02x%02x%02x\n", grayval, grayval, grayval);
         }
@@ -728,10 +729,10 @@ createHistogram(unsigned int    const ncolors,
     MALLOCARRAY(seen, ncolors);
     if (!seen)
         pm_error("Can't allocate array for keeping track of "
-                 "how many pixels of each of %u colors are in the image.", 
+                 "how many pixels of each of %u colors are in the image.",
                  ncolors);
 
-    {    
+    {
         /* Initialize the counter for each color to zero */
         unsigned int i;
         for (i = 0; i < ncolors; ++i)
@@ -766,7 +767,7 @@ readScanlineRow(FILE *          const ifP,
 
         pm_readcharu(ifP, &diffmask);
         byteCount = MIN(bytesPerRow - j, 8);
-        
+
         for (k = 0; k < byteCount; ++k) {
             /* the first row cannot be compressed */
             if (firstRow || ((diffmask & (1 << (7 - k))) != 0)) {
@@ -805,7 +806,7 @@ readRleRow(FILE *          const ifP,
         memset(palmrow + j, inval, incount);
         j += incount;
     }
-} 
+}
 
 
 
@@ -815,7 +816,7 @@ readPackBitsRow16(FILE *          const ifP,
                   unsigned int    const bytesPerRow) {
 
     /*  From the Palm OS Programmer's API Reference:
-  
+
         Although the [...] spec is byte-oriented, the 16-bit algorithm is
         identical [to the 8-bit algorithm]: just substitute "word" for "byte".
     */
@@ -824,7 +825,7 @@ readPackBitsRow16(FILE *          const ifP,
     for (j = 0;  j < bytesPerRow; ) {
         char incount;
         pm_readchar(ifP, &incount);
-        if (incount < 0) { 
+        if (incount < 0) {
             /* How do we handle incount == -128 ? */
             unsigned int const runlength = (-incount + 1) * 2;
             unsigned int k;
@@ -846,13 +847,13 @@ readPackBitsRow16(FILE *          const ifP,
             }
             j += nonrunlength;
         }
-        if (j > bytesPerRow) 
+        if (j > bytesPerRow)
             pm_error("Bytes in PackBits compressed row exceed bytes per row.  "
                      "Bytes per row is %u.  "
                      "The bytes in this row were pushed up to %u bytes "
                      "(and then we gave up).", bytesPerRow, j);
     }
-} 
+}
 
 
 
@@ -866,7 +867,7 @@ readPackBitsRow(FILE *          const ifP,
     for (j = 0;  j < bytesPerRow; ) {
         char incount;
         pm_readchar(ifP, &incount);
-        if (incount < 0) { 
+        if (incount < 0) {
             /* How do we handle incount == -128 ? */
             unsigned int const runlength = -incount + 1;
             unsigned char inval;
@@ -884,13 +885,13 @@ readPackBitsRow(FILE *          const ifP,
             }
             j += nonrunlength;
         }
-        if (j > bytesPerRow) 
+        if (j > bytesPerRow)
             pm_error("Bytes in PackBits compressed row exceed bytes per row.  "
                      "Bytes per row is %u.  "
                      "The bytes in this row were pushed up to %u bytes "
                      "(and then we gave up).", bytesPerRow, j);
     }
-} 
+}
 
 
 
@@ -900,7 +901,7 @@ readUncompressedRow(FILE *          const ifP,
                     unsigned int    const bytesPerRow) {
 
     int bytesRead;
-    
+
     bytesRead = fread(palmrow, 1, bytesPerRow, ifP);
     if (bytesRead != bytesPerRow)
         pm_error("Error reading Palm file.  Short read.");
@@ -973,27 +974,27 @@ convertRowToPnmDirect(const unsigned char * const palmrow,
        blue=0x1F.  How do we promote those colors?  Simple
        shift would give us R=248,G=252,B=248; which is
        slightly green.  Hardly seems right.
-       
+
        So I've perverted the math a bit.  Each color value is
        multiplied by 255, then divided by either 31 (red or
        blue) or 63 (green).  That's the right way to do it
-       anyway.  
+       anyway.
     */
 
     const unsigned char *inbyte;
     unsigned int j;
-    
+
     for (inbyte = palmrow, j = 0;  j < cols;  ++j) {
         unsigned int inval;
         inval = *inbyte++ << 8;
         inval |= *inbyte++;
-        
+
         if (seen)
             ++seen[inval];
-        
-        PPM_ASSIGN(xelrow[j], 
-                   (((inval >> 11) & 0x1F) * maxval) / 0x1F, 
-                   (((inval >>  5) & 0x3F) * maxval) / 0x3F, 
+
+        PPM_ASSIGN(xelrow[j],
+                   (((inval >> 11) & 0x1F) * maxval) / 0x1F,
+                   (((inval >>  5) & 0x3F) * maxval) / 0x3F,
                    (((inval >>  0) & 0x1F) * maxval) / 0x1F
             );
     }
@@ -1017,21 +1018,21 @@ convertRowToPnmNotDirect(const unsigned char * const palmrow,
     unsigned int j;
 
     assert(pixelSize <= 8);
-    
+
     inbit = 8 - pixelSize;
     inbyteP = &palmrow[0];
     for (j = 0; j < cols; ++j) {
         short const color = (*inbyteP & (mask << inbit)) >> inbit;
         if (seen)
             ++seen[color];
-        
+
         if (colormapP) {
             ColormapEntry const searchTarget = color << 24;
             ColormapEntry * const foundEntryP =
                 bsearch(&searchTarget,
-                        colormapP->color_entries, 
+                        colormapP->color_entries,
                         colormapP->ncolors,
-                        sizeof(searchTarget), 
+                        sizeof(searchTarget),
                         palmcolor_compare_indices);
 
             if (!foundEntryP)
@@ -1040,13 +1041,13 @@ convertRowToPnmNotDirect(const unsigned char * const palmrow,
                          "in the colormap",
                          j, color, colormapP->ncolors);
 
-            PPM_ASSIGN(xelrow[j], 
-                       (*foundEntryP >> 16) & 0xFF, 
-                       (*foundEntryP >>  8) & 0xFF, 
+            PPM_ASSIGN(xelrow[j],
+                       (*foundEntryP >> 16) & 0xFF,
+                       (*foundEntryP >>  8) & 0xFF,
                        (*foundEntryP >>  0) & 0xFF);
         } else
             PNM_ASSIGN1(xelrow[j], graymap[color]);
-        
+
         if (!inbit) {
             ++inbyteP;
             inbit = 8 - pixelSize;
@@ -1076,22 +1077,22 @@ writePnm(FILE *            const ofP,
     xel *           xelrow;
     unsigned int *  seen;
     unsigned int    row;
-    
+
     pnm_writepnminit(ofP, cols, rows, maxval, format, 0);
     xelrow = pnm_allocrow(cols);
 
     /* Read the picture data, one row at a time */
     MALLOCARRAY_NOFAIL(palmrow, palmHeader.bytesPerRow);
-    MALLOCARRAY_NOFAIL(lastrow, palmHeader.bytesPerRow); 
-    
+    MALLOCARRAY_NOFAIL(lastrow, palmHeader.bytesPerRow);
+
     if (seenP) {
         createHistogram(nColors, &seen);
         *seenP = seen;
     } else
         seen = NULL;
 
-    /* We should actually use compressedDataSizeNN for checking the sanity 
-       of the data we're reading ... 
+    /* We should actually use compressedDataSizeNN for checking the sanity
+       of the data we're reading ...
     */
     if (palmHeader.compressionType != COMPRESSION_NONE) {
         if (palmHeader.version < 3) {
@@ -1104,8 +1105,8 @@ writePnm(FILE *            const ofP,
     }
 
     for (row = 0; row < rows; ++row) {
-        readDecompressedRow(ifP, palmrow, lastrow, 
-                            palmHeader.compressionType, 
+        readDecompressedRow(ifP, palmrow, lastrow,
+                            palmHeader.compressionType,
                             palmHeader.bytesPerRow,
                             palmHeader.pixelSize,
                             row == 0);
@@ -1133,18 +1134,18 @@ showHistogram(unsigned int * const seen,
               unsigned int   const ncolors) {
 
     unsigned int colorIndex;
-    
+
     for (colorIndex = 0;  colorIndex < ncolors; ++colorIndex) {
         if (!colormapP)
-            pm_message("%.3d -> %.3d:  %d", 
+            pm_message("%.3d -> %.3d:  %d",
                        colorIndex, graymap[colorIndex], seen[colorIndex]);
         else {
             ColormapEntry const searchTarget = colorIndex << 24;
             ColormapEntry * const foundEntryP =
                 bsearch(&searchTarget,
-                        colormapP->color_entries, 
+                        colormapP->color_entries,
                         colormapP->ncolors,
-                        sizeof(searchTarget), 
+                        sizeof(searchTarget),
                         palmcolor_compare_indices);
             if (foundEntryP)
                 pm_message("%.3d -> %ld,%ld,%ld:  %d", colorIndex,
@@ -1181,11 +1182,11 @@ main(int argc, const char **argv) {
     readHeader(ifP, cmdline.rendition, &palmHeader);
 
     readDirectInfoType(ifP, palmHeader, &directInfoType);
-   
+
     readColormap(ifP, palmHeader, &colormapFromImageP);
-    
+
     determineOutputFormat(palmHeader, &format, &maxval);
-    
+
     getColorInfo(palmHeader, directInfoType, colormapFromImageP,
                  &colormapP, &nColors, &directColorInfo);
 
@@ -1193,9 +1194,9 @@ main(int argc, const char **argv) {
         reportPalmHeader(palmHeader, directColorInfo);
 
     if (cmdline.transparent)
-        doTransparent(stdout, 
+        doTransparent(stdout,
                       palmHeader.hasTransparency, palmHeader.directColor,
-                      palmHeader.transparentIndex, 
+                      palmHeader.transparentIndex,
                       palmHeader.pixelSize, colormapP, directColorInfo);
     else {
         unsigned int * seen;
@@ -1204,12 +1205,12 @@ main(int argc, const char **argv) {
         graymap = createGraymap(nColors, maxval);
 
         writePnm(stdout,
-                 palmHeader, ifP, colormapP, graymap, nColors, format, maxval, 
+                 palmHeader, ifP, colormapP, graymap, nColors, format, maxval,
                  cmdline.showhist ? &seen : NULL);
-        
+
         if (cmdline.showhist)
             showHistogram(seen, colormapP, graymap, nColors);
-        
+
         free(graymap);
     }
     pm_close(ifP);
diff --git a/converter/other/pnmtopclxl.c b/converter/other/pnmtopclxl.c
index 8cabb614..f7db62ee 100644
--- a/converter/other/pnmtopclxl.c
+++ b/converter/other/pnmtopclxl.c
@@ -3,7 +3,7 @@
  *
  *  (C) 2002 Jochen Karrer, Linuxdata GbR
  *
- *      convert a pnm to PCL-XL image 
+ *      convert a pnm to PCL-XL image
  *
  * -------------------------------------------------------------
  */
@@ -44,7 +44,7 @@
 
 
 typedef struct InputSource {
-    const char *         name; 
+    const char *         name;
     struct InputSource * next;
 } InputSource;
 
@@ -82,7 +82,7 @@ parseCommandLine(int argc, char ** argv,
                  struct cmdlineInfo * const cmdlineP) {
 /*----------------------------------------------------------------------------
    parse program command line described in Unix standard form by argc
-   and argv.  Return the information in the options as *cmdlineP.  
+   and argv.  Return the information in the options as *cmdlineP.
 
    If command line is internally inconsistent (invalid options, etc.),
    issue error message to stderr and abort program.
@@ -104,25 +104,25 @@ parseCommandLine(int argc, char ** argv,
     option_def_index = 0;   /* incremented by OPTENT3 */
     OPTENT3(0, "dpi",       OPT_UINT,    &cmdlineP->dpi,
             &dpiSpec,         0);
-    OPTENT3(0, "xoffs",     OPT_FLOAT,   &cmdlineP->xoffs, 
+    OPTENT3(0, "xoffs",     OPT_FLOAT,   &cmdlineP->xoffs,
             &xoffsSpec,        0);
-    OPTENT3(0, "yoffs",     OPT_FLOAT,   &cmdlineP->yoffs, 
+    OPTENT3(0, "yoffs",     OPT_FLOAT,   &cmdlineP->yoffs,
             &yoffsSpec,        0);
-    OPTENT3(0, "format",    OPT_STRING,  &formatOpt, 
+    OPTENT3(0, "format",    OPT_STRING,  &formatOpt,
             &formatSpec,        0);
-    OPTENT3(0, "duplex",    OPT_STRING,  &duplexOpt, 
+    OPTENT3(0, "duplex",    OPT_STRING,  &duplexOpt,
             &cmdlineP->duplexSpec,        0);
     OPTENT3(0, "copies",    OPT_UINT,    &cmdlineP->copies,
             &cmdlineP->copiesSpec,        0);
-    OPTENT3(0, "colorok",   OPT_FLAG,    NULL,                  
+    OPTENT3(0, "colorok",   OPT_FLAG,    NULL,
             &cmdlineP->colorok, 0);
-    OPTENT3(0, "center",    OPT_FLAG,    NULL,                  
+    OPTENT3(0, "center",    OPT_FLAG,    NULL,
             &cmdlineP->center, 0 );
     OPTENT3(0, "feeder",    OPT_UINT,    &cmdlineP->feeder,
             &cmdlineP->feederSpec,        0);
     OPTENT3(0, "outtray",   OPT_UINT,    &cmdlineP->outtray,
             &cmdlineP->outtraySpec,       0);
-    OPTENT3(0, "verbose",   OPT_FLAG,    NULL,                  
+    OPTENT3(0, "verbose",   OPT_FLAG,    NULL,
             &cmdlineP->verbose, 0);
     OPTENT3(0, "jobsetup",  OPT_STRING,  &cmdlineP->jobsetup,
             &jobsetupSpec,      0);
@@ -216,7 +216,7 @@ parseCommandLine(int argc, char ** argv,
 
 static void
 freeSource(InputSource * const firstSourceP) {
-    
+
     InputSource * sourceP;
 
     sourceP = firstSourceP;
@@ -284,7 +284,7 @@ pnmToPcllinePackbits(pclGenerator * const pclGeneratorP,
     unsigned int col, padCt;
     unsigned int const padsize =
         pclGeneratorP->paddedLinelen - pclGeneratorP->linelen;
-        
+
     tuplerow = pnm_allocpamrow(pamP);
 
     pnm_readpamrow(pamP, tuplerow);
@@ -297,7 +297,7 @@ pnmToPcllinePackbits(pclGenerator * const pclGeneratorP,
         if (bitmask == 0) {
             pclGeneratorP->data[pclGeneratorP->cursor++] = accum;
             bitmask = 0x80; accum = 0x0;
-        } 
+        }
     }
     if (bitmask != 0x80)
         pclGeneratorP->data[pclGeneratorP->cursor++] = accum;
@@ -351,7 +351,7 @@ createPclGeneratorPackbits(struct pam *    const pamP,
 
     pclGeneratorP->data =
         malloc(pclDatabuffSize(pclGeneratorP->paddedLinelen));
-    
+
     if (pclGeneratorP->data == NULL)
         pm_error("Unable to allocate row buffer.");
 
@@ -378,7 +378,7 @@ pnmToPcllineWholebytes(pclGenerator * const pclGeneratorP,
     for (col = 0; col < pamP->width; ++col) {
         unsigned int plane;
         for (plane = 0; plane < pamP->depth; ++plane) {
-            pclGeneratorP->data[pclGeneratorP->cursor++] = 
+            pclGeneratorP->data[pclGeneratorP->cursor++] =
                 pnm_scalesample(tuplerow[col][plane], pamP->maxval, 255);
         }
     }
@@ -399,7 +399,7 @@ createPclGeneratorWholebytes(struct pam *    const pamP,
     pclGenerator * pclGenP;
 
     MALLOCVAR_NOFAIL(pclGenP);
-    
+
     if (pamP->depth <  3)
         pclGenP->colorSpace = eGray;
     else
@@ -418,7 +418,7 @@ createPclGeneratorWholebytes(struct pam *    const pamP,
         if (pclGenP->data == NULL)
             pm_error("Unable to allocate row buffer.");
     }
-    
+
     pclGenP->getnextrow = pnmToPcllineWholebytes;
 
     *pclGenPP = pclGenP;
@@ -436,7 +436,7 @@ destroyPclGenerator(pclGenerator * const pclGenP) {
 
 
 
-static void 
+static void
 createPclGenerator(struct pam *        const pamP,
                    pclGenerator **     const pclGeneratorPP,
                    bool                const colorok) {
@@ -448,16 +448,16 @@ createPclGenerator(struct pam *        const pamP,
                    "through Ppmtopgm.  To suppress this warning, use the "
                    "-colorok option.");
 
-    if (pamP->depth == 1 && pamP->maxval == 1) 
+    if (pamP->depth == 1 && pamP->maxval == 1)
         createPclGeneratorPackbits(pamP, pclGeneratorPP);
-    else 
+    else
         createPclGeneratorWholebytes(pamP, pclGeneratorPP);
 }
 
 
 
 
-struct tPrinter { 
+struct tPrinter {
     const char *name;
     float topmargin;
     float bottommargin;
@@ -478,7 +478,7 @@ out_ubyte(int           const fd,
 
 
 
-static int 
+static int
 XL_Operator(int           const fd,
             enum Operator const data)  {
 
@@ -514,7 +514,7 @@ static int
 out_sint16(int          const fd,
            signed short const sdata ) {
 
-    unsigned short const data= (unsigned short)sdata;    
+    unsigned short const data= (unsigned short)sdata;
 
     unsigned char c[2];
 
@@ -559,7 +559,7 @@ xl_ubyte_array(int                   const fd,
 
     unsigned int i;
     unsigned char head[4];
-    
+
     head[0] = 0xc8;
     head[1] = 0xc1;
     head[2] = len & 0xff;
@@ -671,7 +671,7 @@ convertAndWriteRleBlock(int                  const outFd,
     pm_rlenc_compressbyte(pclGeneratorP->data, outbuf, PM_RLE_PACKBITS,
                           pclGeneratorP->paddedLinelen * lineCt, &rlelen);
 
-    xl_dataLength(outFd, rlelen); 
+    xl_dataLength(outFd, rlelen);
     XY_Write(outFd, outbuf, rlelen);
 }
 
@@ -680,10 +680,10 @@ convertAndWriteRleBlock(int                  const outFd,
 /*
  * ------------------------------------------------------------
  * XL_WriteImage
- *  Write a PCL-XL image to the datastream 
+ *  Write a PCL-XL image to the datastream
  * ------------------------------------------------------------
  */
-static void 
+static void
 convertAndWriteImage(int            const outFd,
                      pclGenerator * const pclGenP,
                      struct pam *   const pamP) {
@@ -695,10 +695,10 @@ convertAndWriteImage(int            const outFd,
 
     xl_ubyte(outFd, eDirectPixel); xl_attr_ubyte(outFd, aColorMapping);
     xl_ubyte(outFd, pclGenP->colorDepth); xl_attr_ubyte(outFd, aColorDepth);
-    xl_uint16(outFd, pclGenP->width); xl_attr_ubyte(outFd, aSourceWidth);  
-    xl_uint16(outFd, pclGenP->height); xl_attr_ubyte(outFd, aSourceHeight);    
-    xl_uint16_xy(outFd, pclGenP->width*1, pclGenP->height*1); 
-    xl_attr_ubyte(outFd, aDestinationSize);   
+    xl_uint16(outFd, pclGenP->width); xl_attr_ubyte(outFd, aSourceWidth);
+    xl_uint16(outFd, pclGenP->height); xl_attr_ubyte(outFd, aSourceHeight);
+    xl_uint16_xy(outFd, pclGenP->width*1, pclGenP->height*1);
+    xl_attr_ubyte(outFd, aDestinationSize);
     XL_Operator(outFd, oBeginImage);
 
     pm_rlenc_allocoutbuf(&outbuf, inSize, PM_RLE_PACKBITS);
@@ -707,13 +707,13 @@ convertAndWriteImage(int            const outFd,
         unsigned int const blockHeight =
             MIN(20, pclGenP->height-blockStartLine);
 
-        xl_uint16(outFd, blockStartLine); xl_attr_ubyte(outFd, aStartLine); 
+        xl_uint16(outFd, blockStartLine); xl_attr_ubyte(outFd, aStartLine);
         xl_uint16(outFd, blockHeight); xl_attr_ubyte(outFd, aBlockHeight);
         xl_ubyte(outFd, eRLECompression); xl_attr_ubyte(outFd, aCompressMode);
         /* In modern PCL-XL, we could use a PadBytesMultiple attribute
            here to avoid having to pad the data to a multiple of 4
            bytes.  But PCL-XL 1.1 didn't have PadBytesMultiple.
-           xl_ubyte(outFd, 1); xl_attr_ubyte(outFd, aPadBytesMultiple); 
+           xl_ubyte(outFd, 1); xl_attr_ubyte(outFd, aPadBytesMultiple);
         */
         XL_Operator(outFd, oReadImage);
         convertAndWriteRleBlock(outFd, pclGenP, pamP,
@@ -735,16 +735,16 @@ printEmbeddedImage(int                 const outFd,
     struct pam pam;
     pclGenerator * pclGeneratorP;
 
-    openDataSource(outFd, eBinaryLowByteFirst, eDefaultSource);
+    openDataSource(outFd, eBinaryLowByteFirst, eDefaultDataSource);
 
     ifP = pm_openr(sourceP->name);
 
     pnm_readpaminit(ifP, &pam, PAM_STRUCT_SIZE(tuple_type));
-                
+
     createPclGenerator(&pam, &pclGeneratorP, colorok);
 
     convertAndWriteImage(outFd, pclGeneratorP, &pam);
-    
+
     destroyPclGenerator(pclGeneratorP);
 
     pm_close(ifP);
@@ -772,9 +772,9 @@ copyFile(const char * const sourceFileName,
         if (ferror(sourceFileP))
             pm_error("Read from file failed.  errno=%d (%s)",
                      errno, strerror(errno));
-        
+
         totalBytesWritten = 0;
-        
+
         while (totalBytesWritten < bytesRead) {
             ssize_t rc;
 
@@ -804,16 +804,16 @@ jobHead(int          const outFd,
    as opposed to e.g. Postscript.
 -----------------------------------------------------------------------------*/
     /* Reset */
-    XY_Puts(outFd,"\033%-12345X");  
+    XY_Puts(outFd,"\033%-12345X");
 
     if (userJobSetupFileName)
         copyFile(userJobSetupFileName, outFd);
 
     if (renderGray)
-        XY_Puts(outFd, "@PJL SET RENDERMODE=GRAYSCALE\n");  
+        XY_Puts(outFd, "@PJL SET RENDERMODE=GRAYSCALE\n");
 
-    XY_Puts(outFd, "@PJL ENTER LANGUAGE=PCLXL\n");  
-    XY_Puts(outFd, ") HP-PCL XL;1;1;Generated by Netpbm Pnmtopclxl\n");  
+    XY_Puts(outFd, "@PJL ENTER LANGUAGE=PCLXL\n");
+    XY_Puts(outFd, ") HP-PCL XL;1;1;Generated by Netpbm Pnmtopclxl\n");
 }
 
 
@@ -825,7 +825,7 @@ jobEnd(int const outFd) {
 
    Reset printer to quiescent mode.  Exit the printer language.
 -----------------------------------------------------------------------------*/
-    XY_Puts(outFd,"\033%-12345X");  
+    XY_Puts(outFd,"\033%-12345X");
 }
 
 
@@ -852,7 +852,7 @@ beginPage(int                 const outFd,
     }
 
     if (doMediaDestination) {
-        xl_ubyte(outFd, mediaDestination);  
+        xl_ubyte(outFd, mediaDestination);
         xl_attr_ubyte(outFd, aMediaDestination);
     }
 
@@ -898,11 +898,11 @@ setColorSpace(int                   const outFd,
    paletteDepth is not e8Bit.  Is each palette entry still a byte and only
    some of the byte gets used?  Or are there multiple entries per byte?
 -----------------------------------------------------------------------------*/
-    xl_ubyte(outFd, colorSpace); xl_attr_ubyte(outFd, aColorSpace);   
+    xl_ubyte(outFd, colorSpace); xl_attr_ubyte(outFd, aColorSpace);
     if (palette) {
-        xl_ubyte(outFd, paletteDepth); 
-        xl_attr_ubyte(outFd, aPaletteDepth);   
-        xl_ubyte_array(outFd, palette, paletteSize); 
+        xl_ubyte(outFd, paletteDepth);
+        xl_attr_ubyte(outFd, aPaletteDepth);
+        xl_ubyte_array(outFd, palette, paletteSize);
         xl_attr_ubyte(outFd, aPaletteData);
     }
     XL_Operator(outFd, oSetColorSpace);
@@ -925,8 +925,8 @@ positionCursor(int            const outFd,
     float xpos, ypos;
 
     if (center) {
-        float const width  = 1.0 * imageWidth/dpi;  
-        float const height = 1.0 * imageHeight/dpi;    
+        float const width  = 1.0 * imageWidth/dpi;
+        float const height = 1.0 * imageHeight/dpi;
         xpos = (PAPERWIDTH(format) - width)/2;
         ypos = (PAPERHEIGHT(format) - height)/2;
     } else {
@@ -985,11 +985,11 @@ convertAndPrintPage(int                  const outFd,
        an IllegalArraySize error from the printer on the SetColorSpace
        command.
 
-       So we don't use a palette at all now.  
+       So we don't use a palette at all now.
     */
     setColorSpace(outFd, pclGeneratorP->colorSpace, NULL, 0, 0);
 
-    positionCursor(outFd, center, xoffs, yoffs, 
+    positionCursor(outFd, center, xoffs, yoffs,
                    pclGeneratorP->width, pclGeneratorP->height, dpi, format);
 
     convertAndWriteImage(outFd, pclGeneratorP, pamP);
@@ -1007,7 +1007,7 @@ beginSession(int              const outFd,
              bool             const noReporting,
              enum ErrorReport const errorReport) {
 
-    xl_uint16_xy(outFd, xdpi, ydpi); xl_attr_ubyte(outFd, aUnitsPerMeasure); 
+    xl_uint16_xy(outFd, xdpi, ydpi); xl_attr_ubyte(outFd, aUnitsPerMeasure);
     xl_ubyte(outFd, measure);  xl_attr_ubyte(outFd, aMeasure);
     /* xl_ubyte(outFd,eNoReporting); xl_attr_ubyte(outFd,aErrorReport); */
     xl_ubyte(outFd,errorReport); xl_attr_ubyte(outFd,aErrorReport);
@@ -1015,8 +1015,8 @@ beginSession(int              const outFd,
 }
 
 
-             
-static void 
+
+static void
 endSession(int outFd) {
     XL_Operator(outFd,oEndSession);
 }
@@ -1046,9 +1046,9 @@ printPages(int                 const outFd,
     InputSource * sourceP;
     unsigned int sourceNum;
 
-    sourceP = firstSourceP;    
+    sourceP = firstSourceP;
 
-    openDataSource(outFd, eBinaryLowByteFirst, eDefaultSource);
+    openDataSource(outFd, eBinaryLowByteFirst, eDefaultDataSource);
 
     sourceNum = 0;   /* initial value */
 
@@ -1074,9 +1074,9 @@ printPages(int                 const outFd,
                 pm_message("Processing File %u, Page %u", sourceNum, pageNum);
 
                 pnm_readpaminit(ifP, &pam, PAM_STRUCT_SIZE(tuple_type));
-                
+
                 createPclGenerator(&pam, &pclGeneratorP, colorok);
-                
+
                 convertAndPrintPage(
                     outFd, pclGeneratorP, &pam,
                     format, dpi, center, xoffs, yoffs, doDuplex, duplex,
@@ -1087,7 +1087,7 @@ printPages(int                 const outFd,
             }
         }
         pm_close(ifP);
-        sourceP = sourceP->next; 
+        sourceP = sourceP->next;
     }
     closeDataSource(outFd);
 }
@@ -1100,9 +1100,9 @@ main(int argc, char *argv[]) {
     int const outFd = STDOUT_FILENO;
 
     struct cmdlineInfo cmdline;
-    
+
     /* In case you're wondering why we do direct file descriptor I/O
-       instead of stream (FILE *), it's because Jochen originally 
+       instead of stream (FILE *), it's because Jochen originally
        wrote this code for an embedded system with diet-libc.  Without
        the stream library, the statically linked binary was only about
        5K big.
@@ -1116,7 +1116,7 @@ main(int argc, char *argv[]) {
     else {
         jobHead(outFd, cmdline.rendergray, cmdline.jobsetup);
 
-        beginSession(outFd, cmdline.dpi, cmdline.dpi, eInch, 
+        beginSession(outFd, cmdline.dpi, cmdline.dpi, eInch,
                      FALSE, eBackChAndErrPage);
 
         printPages(outFd, cmdline.sourceP,
diff --git a/converter/other/pstopnm.c b/converter/other/pstopnm.c
index 95a97440..d8e18e93 100644
--- a/converter/other/pstopnm.c
+++ b/converter/other/pstopnm.c
@@ -16,7 +16,7 @@
 
 #define _DEFAULT_SOURCE 1 /* New name for SVID & BSD source defines */
 #define _BSD_SOURCE 1   /* Make sure strdup() is in string.h */
-#define _XOPEN_SOURCE 500  
+#define _XOPEN_SOURCE 500
     /* Make sure fdopen() is in stdio.h and strdup() is in string.h */
 
 #include <assert.h>
@@ -25,7 +25,7 @@
 #include <stdlib.h>
 #include <stdio.h>
 #include <signal.h>
-#include <sys/wait.h>  
+#include <sys/wait.h>
 #include <sys/stat.h>
 
 #include "pm_c_util.h"
@@ -38,17 +38,32 @@ static bool verbose;
 
 enum Orientation {PORTRAIT, LANDSCAPE, UNSPECIFIED};
 struct Box {
-    /* Description of a rectangle within an image; all coordinates 
-       measured in points (1/72") with lower left corner of page being the 
-       origin.
+    /* Description of a rectangle within an image; all coordinates
+       measured in points (1/72") with lower left corner of page being the
+       origin.  Negative values are OK.
     */
+    bool isDefined;
+
+    /* Nothing below is meaningful unless 'isDefined' is true */
     int llx;  /* lower left X coord */
-        /* -1 for llx means whole box is undefined. */
     int lly;  /* lower left Y coord */
     int urx;  /* upper right X coord */
     int ury;  /* upper right Y coord */
 };
 
+
+
+static void
+assertValidBox(struct Box const box) {
+
+    if (box.isDefined) {
+        assert(box.urx >= box.llx);
+        assert(box.ury >= box.lly);
+    }
+}
+
+
+
 struct Dimensions {
 /*----------------------------------------------------------------------------
   Horizontal and vertical dimensions of something, both in pixels and
@@ -107,7 +122,7 @@ parseCommandLine(int argc, char ** argv,
     unsigned int textalphabitsSpec;
 
     MALLOCARRAY_NOFAIL(option_def, 100);
-    
+
     option_def_index = 0;   /* incremented by OPTENTRY */
     OPTENT3(0, "forceplain", OPT_FLAG,  NULL, &cmdlineP->forceplain,     0);
     OPTENT3(0, "llx",        OPT_FLOAT, &llx, &llxSpec,                  0);
@@ -151,7 +166,7 @@ parseCommandLine(int argc, char ** argv,
     if (ymaxSpec) {
         if (cmdlineP->ymax == 0)
             pm_error("zero is not a valid value for -ymax");
-    } else 
+    } else
         cmdlineP->ymax = 792;
 
     if (xsizeSpec) {
@@ -163,7 +178,7 @@ parseCommandLine(int argc, char ** argv,
     if (ysizeSpec) {
         if (cmdlineP->ysize == 0)
             pm_error("zero is not a valid value for -ysize");
-    } else 
+    } else
         cmdlineP->ysize = 0;
 
     if (portraitOpt && !landscapeOpt)
@@ -185,9 +200,11 @@ parseCommandLine(int argc, char ** argv,
         cmdlineP->formatType = PPM_TYPE;
 
     /* If any one of the 4 bounding box coordinates is given on the
-       command line, we default any of the 4 that aren't.  
+       command line, we default any of the 4 that aren't.
     */
     if (llxSpec || llySpec || urxSpec || urySpec) {
+        cmdlineP->extractBox.isDefined = true;
+
         if (!llxSpec) cmdlineP->extractBox.llx = 72;
         else cmdlineP->extractBox.llx = llx * 72;
         if (!llySpec) cmdlineP->extractBox.lly = 72;
@@ -197,7 +214,7 @@ parseCommandLine(int argc, char ** argv,
         if (!urySpec) cmdlineP->extractBox.ury = 720;
         else cmdlineP->extractBox.ury = ury * 72;
     } else {
-        cmdlineP->extractBox.llx = -1;
+        cmdlineP->extractBox.isDefined = false;
     }
 
     if (dpiSpec) {
@@ -225,7 +242,7 @@ parseCommandLine(int argc, char ** argv,
         cmdlineP->inputFileName = "-";  /* stdin */
     else if (argc-1 == 1)
         cmdlineP->inputFileName = argv[1];
-    else 
+    else
         pm_error("Too many arguments (%d).  "
                  "Only need one: the Postscript file name", argc-1);
 
@@ -249,7 +266,7 @@ addPsToFileName(char          const origFileName[],
     int statRc;
 
     statRc = lstat(origFileName, &statbuf);
-    
+
     if (statRc == 0)
         *newFileNameP = strdup(origFileName);
     else {
@@ -270,34 +287,62 @@ addPsToFileName(char          const origFileName[],
 
 
 
+static unsigned int
+resolution(unsigned int const dotCt,
+           unsigned int const pointCt) {
+/*----------------------------------------------------------------------------
+   The resolution in dots per inch when 'dotCt' dots print 'pointCt' points
+   long.
+
+   When this would round to zero, we return 1 dot per inch instead so it
+   doesn't play havoc with arithmetic - it's never going to happen unless
+   something is broken anyway.
+-----------------------------------------------------------------------------*/
+    return MAX(1, (unsigned int)((float)dotCt * 72 / pointCt + 0.5));
+}
+
+
+
 static void
 computeSizeResFromSizeSpec(unsigned int        const requestedXsize,
                            unsigned int        const requestedYsize,
                            unsigned int        const imageWidth,
                            unsigned int        const imageHeight,
                            struct Dimensions * const imageDimP) {
+/*----------------------------------------------------------------------------
+   Compute output image size and assumed Postscript input resolution, assuming
+   user requested a specific size for at least one of the dimensions and the
+   input is 'imageWidth' x 'imageHeight' points.
+
+   'requestedXsize' is what the user requested for output image width in
+   pixels, or zero if he made no request.  'requestedYsize' is analogous
+   for the height.
+-----------------------------------------------------------------------------*/
+    assert(requestedXsize || requestedYsize);
+
+    assert(imageWidth > 0);
 
     if (requestedXsize) {
         imageDimP->xsize = requestedXsize;
-        imageDimP->xres = (unsigned int)
-            (requestedXsize * 72 / imageWidth + 0.5);
+        imageDimP->xres = resolution(requestedXsize, imageWidth);
         if (!requestedYsize) {
             imageDimP->yres = imageDimP->xres;
             imageDimP->ysize = (unsigned int)
                 (imageHeight * (float)imageDimP->yres/72 + 0.5);
-            }
         }
+    }
+
+    assert(imageHeight > 0);
 
     if (requestedYsize) {
         imageDimP->ysize = requestedYsize;
-        imageDimP->yres = (unsigned int)
-            (requestedYsize * 72 / imageHeight + 0.5);
+        imageDimP->yres = resolution(requestedYsize, imageHeight);
         if (!requestedXsize) {
             imageDimP->xres = imageDimP->yres;
             imageDimP->xsize = (unsigned int)
                 (imageWidth * (float)imageDimP->xres/72 + 0.5);
         }
-    } 
+    }
 }
 
 
@@ -313,8 +358,9 @@ computeSizeResBlind(unsigned int        const xmax,
     if (imageWidth == 0 || imageHeight == 0) {
         imageDimP->xres = imageDimP->yres = 72;
     } else {
-        imageDimP->xres = imageDimP->yres = MIN(xmax * 72 / imageWidth,
-                                                ymax * 72 / imageHeight);
+        imageDimP->xres = imageDimP->yres =
+            MIN(resolution(xmax, imageWidth),
+                resolution(ymax, imageHeight));
     }
 
     if (nocrop) {
@@ -331,17 +377,17 @@ computeSizeResBlind(unsigned int        const xmax,
 
 
 static void
-computeSizeRes(struct CmdlineInfo  const cmdline, 
+computeSizeRes(struct CmdlineInfo  const cmdline,
                struct Box          const borderedBox,
                struct Dimensions * const imageDimP) {
 /*----------------------------------------------------------------------------
   Figure out how big the output image should be and what output device
   resolution Ghostscript should assume (return as *imageDimP).
 
-  A resolution number is the number of pixels per inch that the a
+  A resolution number is the number of pixels per inch that the
   printer prints.  Since we're emulating a printed page with a PNM
   image, and a PNM image has no spatial dimension (you can't say how
-  many inches wide a PNM image is), it's kind of confusing.  
+  many inches wide a PNM image is), it's kind of confusing.
 
   If the user doesn't select a resolution, we choose the resolution
   that causes the image to be a certain number of pixels, knowing how
@@ -350,8 +396,8 @@ computeSizeRes(struct CmdlineInfo  const cmdline,
   inches wide.  We want the PNM image to be 1000 pixels wide.  So we
   tell Ghostscript that our horizontal output device resolution is 500
   pixels per inch.
-  
-  X and Y in all returned values is with respect to the image, not the
+
+  X and Y in all returned values are with respect to the image, not the
   page.  Note that the image might be placed sideways on the page, so that
   page X and Y would be reversed from image X and Y.
 -----------------------------------------------------------------------------*/
@@ -361,6 +407,8 @@ computeSizeRes(struct CmdlineInfo  const cmdline,
     unsigned int const sx = borderedBox.urx - borderedBox.llx;
     unsigned int const sy = borderedBox.ury - borderedBox.lly;
 
+    assertValidBox(borderedBox); assert(borderedBox.isDefined);
+
     if (cmdline.dpi) {
         /* User gave resolution; we figure out output image size */
         imageDimP->xres = imageDimP->yres = cmdline.dpi;
@@ -370,6 +418,7 @@ computeSizeRes(struct CmdlineInfo  const cmdline,
         if (sx == 0 || sy == 0)
             pm_error("Input image is zero size; we cannot satisfy your "
                      "produce your requested output dimensions");
+
         computeSizeResFromSizeSpec(cmdline.xsize, cmdline.ysize, sx, sy,
                                    imageDimP);
     } else
@@ -398,7 +447,7 @@ languageDeclaration(char const inputFileName[]) {
     enum PostscriptLanguage language;
 
     if (streq(inputFileName, "-"))
-        /* Can't read stdin, because we need it to remain positioned for the 
+        /* Can't read stdin, because we need it to remain positioned for the
            Ghostscript interpreter to read it.
         */
         language = COMMON_POSTSCRIPT;
@@ -431,12 +480,57 @@ languageDeclaration(char const inputFileName[]) {
 
 
 static struct Box
+boundingBoxFmPostscriptFile(FILE * const ifP) {
+
+    struct Box retval;
+    bool eof;
+
+    for (retval.isDefined = false, eof = false; !retval.isDefined && !eof; ) {
+        char line[200];
+        char * fgetsRc;
+
+        fgetsRc = fgets(line, sizeof(line), ifP);
+
+        if (fgetsRc == NULL)
+            eof = true;
+        else {
+            int rc;
+            int llx, lly, urx, ury;
+
+            rc = sscanf(line, "%%%%BoundingBox: %d %d %d %d",
+                        &llx, &lly, &urx, &ury);
+            if (rc == 4) {
+                /* We found a BoundingBox statement */
+
+                if (llx > urx)
+                    pm_error("%%%%BoundingBox statement in input file has "
+                             "lower left corner to the right of the "
+                             "upper right corner");
+                if (lly > ury)
+                    pm_error("%%%%BoundingBox statement in input file has "
+                             "lower left corner above the "
+                             "upper right corner");
+
+                retval.llx = llx; retval.lly = lly;
+                retval.urx = urx; retval.ury = ury;
+                retval.isDefined = true;
+            }
+        }
+    }
+    fclose(ifP);
+
+    return retval;
+}
+
+
+
+static struct Box
 computeBoxToExtract(struct Box const cmdlineExtractBox,
                     char       const inputFileName[]) {
 
     struct Box retval;
 
-    if (cmdlineExtractBox.llx != -1)
+    if (cmdlineExtractBox.isDefined)
         /* User told us what box to extract, so that's what we'll do */
         retval = cmdlineExtractBox;
     else {
@@ -447,54 +541,37 @@ computeBoxToExtract(struct Box const cmdlineExtractBox,
 
         if (streq(inputFileName, "-"))
             /* Can't read stdin, because we need it to remain
-               positioned for the Ghostscript interpreter to read it.  
+               positioned for the Ghostscript interpreter to read it.
             */
-            psBb.llx = -1;
+            psBb.isDefined = false;
         else {
             FILE * ifP;
-            bool foundBb;
-            bool eof;
 
             ifP = pm_openr(inputFileName);
-            
-            for (foundBb = FALSE, eof = FALSE; !foundBb && !eof; ) {
-                char line[200];
-                char * fgetsRc;
-
-                fgetsRc = fgets(line, sizeof(line), ifP);
-
-                if (fgetsRc == NULL)
-                    eof = TRUE;
-                else {
-                    int rc;
-                    rc = sscanf(line, "%%%%BoundingBox: %d %d %d %d",
-                                &psBb.llx, &psBb.lly, 
-                                &psBb.urx, &psBb.ury);
-                    if (rc == 4) 
-                        foundBb = TRUE;
-                }
-            }
-            fclose(ifP);
 
-            if (!foundBb) {
-                psBb.llx = -1;
+            psBb = boundingBoxFmPostscriptFile(ifP);
+
+            if (!psBb.isDefined)
                 pm_message("Warning: no %%%%BoundingBox statement "
                            "in the input or command line.  "
                            "Will use defaults");
-            }
         }
-        if (psBb.llx != -1) {
+        if (psBb.isDefined) {
             if (verbose)
                 pm_message("Using %%%%BoundingBox statement from input.");
             retval = psBb;
-        } else { 
+        } else {
             /* Use the center of an 8.5" x 11" page with 1" border all around*/
+            retval.isDefined = true;
             retval.llx = 72;
             retval.lly = 72;
             retval.urx = 540;
             retval.ury = 720;
         }
     }
+
+    assert(retval.isDefined);
+
     if (verbose)
         pm_message("Extracting the box ((%d,%d),(%d,%d))",
                    retval.llx, retval.lly, retval.urx, retval.ury);
@@ -504,7 +581,7 @@ computeBoxToExtract(struct Box const cmdlineExtractBox,
 
 
 static enum Orientation
-computeOrientation(struct CmdlineInfo const cmdline, 
+computeOrientation(struct CmdlineInfo const cmdline,
                    struct Box         const extractBox) {
 /*----------------------------------------------------------------------------
    The proper orientation of the image on the page, given the user's
@@ -532,7 +609,7 @@ computeOrientation(struct CmdlineInfo const cmdline,
         /* Dimensions of image to print, in points */
         unsigned int const imageWidPt = extractBox.urx - extractBox.llx;
         unsigned int const imageHgtPt = extractBox.ury - extractBox.lly;
-        
+
         /* Dimensions of image to print, in pixels (possibly of assumed
            resolution)
         */
@@ -580,31 +657,30 @@ computeOrientation(struct CmdlineInfo const cmdline,
 
 
 static struct Box
-addBorders(struct Box const inputBox, 
+addBorders(struct Box const inputBox,
            float      const xborderScale,
            float      const yborderScale) {
 /*----------------------------------------------------------------------------
    Return a box which is 'inputBox' plus some borders.
 
    Add left and right borders that are the fraction 'xborderScale' of the
-   width of the input box; likewise for top and bottom borders with 
+   width of the input box; likewise for top and bottom borders with
    'yborderScale'.
 -----------------------------------------------------------------------------*/
-    unsigned int const leftRightBorderSize = 
+    unsigned int const leftRightBorderSize =
         ROUNDU((inputBox.urx - inputBox.llx) * xborderScale);
-    unsigned int const topBottomBorderSize = 
+    unsigned int const topBottomBorderSize =
         ROUNDU((inputBox.ury - inputBox.lly) * yborderScale);
 
     struct Box retval;
 
-
-    assert(inputBox.urx >= inputBox.llx);
-    assert(inputBox.ury >= inputBox.lly);
+    assertValidBox(inputBox); assert(inputBox.isDefined);
 
     retval.llx = inputBox.llx - (int)leftRightBorderSize;
     retval.lly = inputBox.lly - (int)topBottomBorderSize;
     retval.urx = inputBox.urx + (int)leftRightBorderSize;
     retval.ury = inputBox.ury + (int)topBottomBorderSize;
+    retval.isDefined = true;
 
     if (verbose)
         pm_message("With borders, extracted box is ((%d,%d),(%d,%d))",
@@ -628,6 +704,8 @@ writePstrans(struct Box        const box,
 
     const char * pstrans;
 
+    assert(xres > 0); assert(yres > 0);
+
     switch (orientation) {
     case PORTRAIT: {
         int llx, lly;
@@ -648,7 +726,7 @@ writePstrans(struct Box        const box,
     if (pstrans == pm_strsol)
         pm_error("Unable to allocate memory for pstrans");
 
-    if (verbose) 
+    if (verbose)
         pm_message("Postscript prefix command: '%s'", pstrans);
 
     fprintf(pipeToGsP, "%s\n", pstrans);
@@ -679,10 +757,10 @@ computeOutfileArg(struct CmdlineInfo const cmdline) {
     else {
         char * basename;
         const char * suffix;
-        
+
         basename  = strdup(cmdline.inputFileName);
-        if (strlen(basename) > 3 && 
-            streq(basename+strlen(basename)-3, ".ps")) 
+        if (strlen(basename) > 3 &&
+            streq(basename+strlen(basename)-3, ".ps"))
             /* The input file name ends in ".ps".  Chop it off. */
             basename[strlen(basename)-3] = '\0';
 
@@ -730,7 +808,7 @@ computeGsDevice(int  const formatType,
 
 static void
 findGhostscriptProg(const char ** const retvalP) {
-    
+
     *retvalP = NULL;  /* initial assumption */
     if (getenv("GHOSTSCRIPT"))
         *retvalP = strdup(getenv("GHOSTSCRIPT"));
@@ -740,7 +818,7 @@ findGhostscriptProg(const char ** const retvalP) {
             const char * candidate;
 
             pathwork = strdup(getenv("PATH"));
-            
+
             candidate = strtok(pathwork, ":");
 
             *retvalP = NULL;
@@ -774,7 +852,7 @@ findGhostscriptProg(const char ** const retvalP) {
 static void
 execGhostscript(int               const inputPipeFd,
                 char              const ghostscriptDevice[],
-                char              const outfileArg[], 
+                char              const outfileArg[],
                 struct Dimensions const pageDim,
                 unsigned int      const textalphabits) {
 /*----------------------------------------------------------------------------
@@ -817,13 +895,13 @@ execGhostscript(int               const inputPipeFd,
                    "'%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s'",
                    ghostscriptProg, arg0,
                    deviceopt, outfileopt, gopt, ropt, textalphabitsopt,
-                   "-q", "-dNOPAUSE", 
+                   "-q", "-dNOPAUSE",
                    "-dSAFER", "-");
     }
 
     execl(ghostscriptProg, arg0, deviceopt, outfileopt, gopt, ropt, "-q",
           "-dNOPAUSE", "-dSAFER", "-", NULL);
-    
+
     pm_error("execl() of Ghostscript ('%s') failed, errno=%d (%s)",
              ghostscriptProg, errno, strerror(errno));
 }
@@ -852,26 +930,26 @@ feedPsToGhostScript(const char *            const inputFileName,
     bool eof;  /* End of file on input */
 
     pipeToGsP = fdopen(pipeToGhostscriptFd, "w");
-    if (pipeToGsP == NULL) 
+    if (pipeToGsP == NULL)
         pm_error("Unable to open stream on pipe to Ghostscript process.");
-    
+
     ifP = pm_openr(inputFileName);
     /*
       In encapsulated Postscript, we the encapsulator are supposed to
       handle showing the page (which we do by passing a showpage
-      statement to Ghostscript).  Any showpage statement in the 
+      statement to Ghostscript).  Any showpage statement in the
       input must be defined to have no effect.
-          
+
       See "Enscapsulated PostScript Format File Specification",
       v. 3.0, 1 May 1992, in particular Example 2, p. 21.  I found
-      it at 
+      it at
       http://partners.adobe.com/asn/developer/pdfs/tn/5002.EPSF_Spec.pdf
       The example given is a much fancier solution than we need
-      here, I think, so I boiled it down a bit.  JM 
+      here, I think, so I boiled it down a bit.  JM
     */
     if (language == ENCAPSULATED_POSTSCRIPT)
         fprintf(pipeToGsP, "\n/b4_Inc_state save def /showpage { } def\n");
- 
+
     writePstrans(borderedBox, imageDim, orientation, pipeToGsP);
 
     /* If our child dies, it closes the pipe and when we next write to it,
@@ -884,11 +962,11 @@ feedPsToGhostScript(const char *            const inputFileName,
     while (!eof) {
         char buffer[4096];
         size_t readCt;
-            
+
         readCt = fread(buffer, 1, sizeof(buffer), ifP);
-        if (readCt == 0) 
+        if (readCt == 0)
             eof = TRUE;
-        else 
+        else
             fwrite(buffer, 1, readCt, pipeToGsP);
     }
     pm_close(ifP);
@@ -897,7 +975,7 @@ feedPsToGhostScript(const char *            const inputFileName,
         fprintf(pipeToGsP, "\nb4_Inc_state restore showpage\n");
 
     fclose(pipeToGsP);
-}        
+}
 
 
 
@@ -940,7 +1018,7 @@ executeGhostscript(char                    const inputFileName[],
                    struct Dimensions       const imageDim,
                    enum Orientation        const orientation,
                    char                    const ghostscriptDevice[],
-                   char                    const outfileArg[], 
+                   char                    const outfileArg[],
                    unsigned int            const textalphabits,
                    enum PostscriptLanguage const language) {
 
@@ -949,12 +1027,12 @@ executeGhostscript(char                    const inputFileName[],
 
     if (strlen(outfileArg) > 80)
         pm_error("output file spec too long.");
-    
+
     rc = pm_pipe(pipefd);
     if (rc < 0)
         pm_error("Unable to create pipe to talk to Ghostscript process.  "
                  "errno = %d (%s)", errno, strerror(errno));
-    
+
     rc = fork();
     if (rc < 0)
         pm_error("Unable to fork a Ghostscript process.  errno=%d (%s)",
@@ -986,13 +1064,13 @@ executeGhostscript(char                    const inputFileName[],
 
         if (gsTermStatus != 0) {
             if (WIFEXITED(gsTermStatus))
-                pm_error("Ghostscript failed.  Exit code=%d\n", 
+                pm_error("Ghostscript failed.  Exit code=%d\n",
                          WEXITSTATUS(gsTermStatus));
             else if (WIFSIGNALED(gsTermStatus))
                 pm_error("Ghostscript process died because of a signal %d.",
                          WTERMSIG(gsTermStatus));
-            else 
-                pm_error("Ghostscript process died with exit code %d", 
+            else
+                pm_error("Ghostscript process died with exit code %d",
                          gsTermStatus);
         }
     }
@@ -1010,7 +1088,7 @@ main(int argc, char ** argv) {
         /* Size and resolution of the input image */
     struct Box extractBox;
         /* coordinates of the box within the input we are to extract; i.e.
-           that will become the output. 
+           that will become the output.
            */
     struct Box borderedBox;
         /* Same as above, but expanded to include borders */
@@ -1031,32 +1109,31 @@ main(int argc, char ** argv) {
     extractBox = computeBoxToExtract(cmdline.extractBox, inputFileName);
 
     language = languageDeclaration(inputFileName);
-    
+
     orientation = computeOrientation(cmdline, extractBox);
 
     borderedBox = addBorders(extractBox, cmdline.xborder, cmdline.yborder);
 
+    assertValidBox(borderedBox); assert(borderedBox.isDefined);
+
     computeSizeRes(cmdline, borderedBox, &imageDim);
 
-    if (imageDim.xres == 0)
-        imageDim.xres = 1;
-    if (imageDim.yres == 0)
-        imageDim.yres = 1;
-    
+    assert(imageDim.xres > 0); assert(imageDim.yres > 0);
+
     outfileArg = computeOutfileArg(cmdline);
 
-    ghostscriptDevice = 
+    ghostscriptDevice =
         computeGsDevice(cmdline.formatType, cmdline.forceplain);
-    
+
     pm_message("Writing %s format", ghostscriptDevice);
-    
+
     executeGhostscript(inputFileName, borderedBox, imageDim, orientation,
                        ghostscriptDevice, outfileArg, cmdline.textalphabits,
                        language);
 
     pm_strfree(ghostscriptDevice);
     pm_strfree(outfileArg);
-    
+
     return 0;
 }
 
diff --git a/converter/ppm/ilbmtoppm.c b/converter/ppm/ilbmtoppm.c
index 280ca939..92d4d6f2 100644
--- a/converter/ppm/ilbmtoppm.c
+++ b/converter/ppm/ilbmtoppm.c
@@ -99,10 +99,9 @@ static bool debug = FALSE;
 
 
 static char *
-ID2string(id)
-    IFF_ID id;
-{
-    static char str[] = "abcd";
+ID2string(IFF_ID const id) {
+
+    static char str[4];
 
     str[0] = (char)(id >> 24 & 0xff);
     str[1] = (char)(id >> 16 & 0xff);
@@ -141,16 +140,15 @@ alloc_cmap(void) {
 
 
 static rawtype *
-alloc_rawrow(cols)
-    int cols;
-{
-    rawtype *r;
-    int i;
+alloc_rawrow(unsigned int const cols) {
+
+    rawtype * r;
+    unsigned int col;
 
     MALLOCARRAY_NOFAIL(r, cols);
 
-    for( i = 0; i < cols; i++ )
-        r[i] = 0;
+    for (col = 0; col < cols; ++col)
+        r[col] = 0;
 
     return r;
 }
@@ -161,17 +159,17 @@ alloc_rawrow(cols)
  ****************************************************************************/
 
 static void
-readerr(f, iffid)
-    FILE *f;
-    IFF_ID iffid;
-{
-    if( ferror(f) )
+readerr(FILE * const fP,
+        IFF_ID const iffId) {
+
+    if (ferror(fP))
         pm_error("read error");
     else
-        pm_error("premature EOF in %s chunk", ID2string(iffid));
+        pm_error("premature EOF in %s chunk", ID2string(iffId));
 }
 
 
+
 static void
 read_bytes(FILE *          const ifP,
            int             const bytes,
@@ -191,21 +189,20 @@ read_bytes(FILE *          const ifP,
 
 
 static unsigned char
-get_byte(ifP, iffid, counter)
-    FILE* ifP;
-    IFF_ID iffid;
-    long *counter;
-{
+get_byte(FILE *          const ifP,
+         IFF_ID          const iffId,
+         unsigned long * const counterP) {
+
     int i;
 
-    if( counter ) {
-        if( *counter == 0 )
-            pm_error("insufficient data in %s chunk", ID2string(iffid));
-        --(*counter);
+    if (counterP) {
+        if (*counterP == 0 )
+            pm_error("insufficient data in %s chunk", ID2string(iffId));
+        --(*counterP);
     }
     i = getc(ifP);
-    if( i == EOF )
-        readerr(ifP, iffid);
+    if (i == EOF)
+        readerr(ifP, iffId);
 
     return (unsigned char) i;
 }
@@ -216,7 +213,7 @@ get_big_long(FILE *          const ifP,
              unsigned long * const counterP) {
 
     long l;
-    
+
     if (counterP) {
         if (*counterP < 4)
             pm_error("insufficient data in %s chunk", ID2string(iffid));
@@ -273,114 +270,117 @@ chunk_end(FILE *        const ifP,
 
 static void
 skip_chunk(FILE *        const ifP,
-           IFF_ID        const iffid,
-           unsigned long const chunksize) {
-    unsigned long remainingChunksize;
+           IFF_ID        const iffId,
+           unsigned long const chunkSize) {
 
-    remainingChunksize = chunksize;  /* initial value */
+    unsigned long remainingChunkSize;
 
-    while (remainingChunksize > 0)
-        get_byte(ifP, iffid, &remainingChunksize);
+    for (remainingChunkSize = chunkSize; remainingChunkSize > 0; )
+        get_byte(ifP, iffId, &remainingChunkSize);
 }
 
 
 
 static void
 display_chunk(FILE *        const ifP,
-              IFF_ID        const iffid,
-              unsigned long const chunksize) {
+              IFF_ID        const iffId,
+              unsigned long const chunkSize) {
 
     int byte;
-    unsigned long remainingChunksize;
+    unsigned long remainingChunkSize;
 
-    pm_message("contents of %s chunk:", ID2string(iffid));
+    pm_message("contents of %s chunk:", ID2string(iffId));
 
-    remainingChunksize = chunksize;  /* initial value */
-    byte = '\0';
+    for (remainingChunkSize = chunkSize, byte = '\0';
+         remainingChunkSize > 0; ) {
 
-    while (remainingChunksize > 0) {
-        byte = get_byte(ifP, iffid, &remainingChunksize);
+        byte = get_byte(ifP, iffId, &remainingChunkSize);
         if (fputc(byte, stderr) == EOF)
             pm_error("write error");
     }
-    if (byte != '\n')
-        if (fputc('\n', stderr) == EOF)
+    if (byte != '\n') {
+        int rc;
+        rc = fputc('\n', stderr);
+        if (rc == EOF)
             pm_error("write error");
+    }
 }
 
 
+
 static void
-read_cmap(FILE *     const ifP,
-          IFF_ID     const iffid,
-          long       const chunksize,
-          ColorMap * const cmap) {
+read_cmap(FILE *        const ifP,
+          IFF_ID        const iffId,
+          unsigned long const chunkSize,
+          ColorMap *    const cmapP) {
 
-    long colors;
+    unsigned long const colorCt = chunkSize / 3;
 
-    colors = chunksize / 3;
-    if( colors == 0 ) {
-        pm_error("warning - empty %s colormap", ID2string(iffid));
-        skip_chunk(ifP, iffid, chunksize);
+    if (colorCt == 0) {
+        pm_error("warning - empty %s colormap", ID2string(iffId));
+        skip_chunk(ifP, iffId, chunkSize);
     } else {
         unsigned int i;
-        if( cmap->color )               /* prefer CMAP-chunk over CMYK-chunk */
-            ppm_freerow(cmap->color);
-        cmap->color = ppm_allocrow(colors);
-        cmap->ncolors = colors;
-        
-        for( i = 0; i < colors; ++i ) {
-            int r, g, b;
-            r = get_byte(ifP, iffid, &chunksize);
-            g = get_byte(ifP, iffid, &chunksize);
-            b = get_byte(ifP, iffid, &chunksize);
-            PPM_ASSIGN(cmap->color[i], r, g, b);
+        unsigned long remainingChunkSize;
+
+        if (cmapP->color)               /* prefer CMAP-chunk over CMYK-chunk */
+            ppm_freerow(cmapP->color);
+        cmapP->color   = ppm_allocrow(colorCt);
+        cmapP->ncolors = colorCt;
+
+        for (i = 0, remainingChunkSize = chunkSize; i < colorCt; ++i ) {
+            int const r = get_byte(ifP, iffId, &remainingChunkSize);
+            int const g = get_byte(ifP, iffId, &remainingChunkSize);
+            int const b = get_byte(ifP, iffId, &remainingChunkSize);
+            PPM_ASSIGN(cmapP->color[i], r, g, b);
         }
-        chunk_end(ifP, iffid, chunksize);
+        chunk_end(ifP, iffId, remainingChunkSize);
     }
 }
 
 
 
 static void
-read_cmyk(FILE *     const ifP,
-          IFF_ID     const iffid,
-          long       const chunksize,
-          ColorMap * const cmap) {
+read_cmyk(FILE *        const ifP,
+          IFF_ID        const iffId,
+          unsigned long const chunkSize,
+          ColorMap *    const cmapP) {
 
-    if( HAS_COLORMAP(cmap) ) {      /* prefer RGB color map */
-        skip_chunk(ifP, iffid, chunksize);
+    if (HAS_COLORMAP(cmapP)) {      /* prefer RGB color map */
+        skip_chunk(ifP, iffId, chunkSize);
     } else {
-        long const colors = chunksize/4;
-        if( colors == 0 ) {
-            pm_error("warning - empty %s colormap", ID2string(iffid));
-            skip_chunk(ifP, iffid, chunksize);
+        unsigned long const colorCt = chunkSize / 4;
+        if (colorCt == 0 ) {
+            pm_error("warning - empty %s colormap", ID2string(iffId));
+            skip_chunk(ifP, iffId, chunkSize);
         } else {
             unsigned int i;
-            cmap->color = ppm_allocrow(colors);
-            cmap->ncolors = colors;
-            
-            for( i = 0; i < colors; ++i ) {
-                int c, m, y, k;
-                c = get_byte(ifP, iffid, &chunksize);
-                m = get_byte(ifP, iffid, &chunksize);
-                y = get_byte(ifP, iffid, &chunksize);
-                k = get_byte(ifP, iffid, &chunksize);
+            unsigned long remainingChunkSize;
+
+            cmapP->color   = ppm_allocrow(colorCt);
+            cmapP->ncolors = colorCt;
+
+            for (i = 0, remainingChunkSize = chunkSize; i < colorCt; ++i) {
+                int const c = get_byte(ifP, iffId, &remainingChunkSize);
+                int const m = get_byte(ifP, iffId, &remainingChunkSize);
+                int const y = get_byte(ifP, iffId, &remainingChunkSize);
+                int const k = get_byte(ifP, iffId, &remainingChunkSize);
 
                 {
-                    pixval const red = 
+                    pixval const red =
                         MAXCOLVAL - MIN(MAXCOLVAL,
-                                        c*(MAXCOLVAL-k)/MAXCOLVAL+k); 
-                    pixval const green = 
+                                        c * (MAXCOLVAL-k) / MAXCOLVAL+k);
+                    pixval const green =
                         MAXCOLVAL - MIN(MAXCOLVAL,
-                                        m*(MAXCOLVAL-k)/MAXCOLVAL+k);
-                    pixval const blue = 
+                                        m * (MAXCOLVAL-k) / MAXCOLVAL+k);
+                    pixval const blue =
                         MAXCOLVAL - MIN(MAXCOLVAL,
-                                        y*(MAXCOLVAL-k)/MAXCOLVAL+k);
+                                        y * (MAXCOLVAL-k) / MAXCOLVAL+k);
 
-                    PPM_ASSIGN(cmap->color[i], red, green, blue);
+                    PPM_ASSIGN(cmapP->color[i], red, green, blue);
                 }
             }
-            chunk_end(ifP, iffid, chunksize);
+            chunk_end(ifP, iffId, remainingChunkSize);
         }
     }
 }
@@ -389,45 +389,45 @@ read_cmyk(FILE *     const ifP,
 
 static void
 read_clut(FILE *        const ifP,
-          IFF_ID        const iffid,
-          unsigned long const chunksize,
-          ColorMap *    const cmap) {
-
-    if (chunksize != CLUTSize) {
-        pm_message("invalid size for %s chunk - skipping it", 
-                   ID2string(iffid));
-        skip_chunk(ifP, iffid, chunksize);
+          IFF_ID        const iffId,
+          unsigned long const chunkSize,
+          ColorMap *    const cmapP) {
+
+    if (chunkSize != CLUTSize) {
+        pm_message("invalid size for %s chunk - skipping it",
+                   ID2string(iffId));
+        skip_chunk(ifP, iffId, chunkSize);
     } else {
         long type;
         unsigned char * lut;
-        unsigned long remainingChunksize;
+        unsigned long remainingChunkSize;
         unsigned int i;
 
-        remainingChunksize = chunksize;  /* initial value */
+        remainingChunkSize = chunkSize;  /* initial value */
 
-        type = get_big_long(ifP, iffid, &remainingChunksize);
-        get_big_long(ifP, iffid, &remainingChunksize); /* skip reserved fld */
+        type = get_big_long(ifP, iffId, &remainingChunkSize);
+        get_big_long(ifP, iffId, &remainingChunkSize); /* skip reserved fld */
 
         MALLOCARRAY_NOFAIL(lut, 256);
         for( i = 0; i < 256; ++i )
-            lut[i] = get_byte(ifP, iffid, &remainingChunksize);
+            lut[i] = get_byte(ifP, iffId, &remainingChunkSize);
 
         switch( type ) {
         case CLUT_MONO:
-            cmap->monolut  = lut;
+            cmapP->monolut  = lut;
             break;
         case CLUT_RED:
-            cmap->redlut   = lut;
+            cmapP->redlut   = lut;
             break;
         case CLUT_GREEN:
-            cmap->greenlut = lut;
+            cmapP->greenlut = lut;
             break;
         case CLUT_BLUE:
-            cmap->bluelut  = lut;
+            cmapP->bluelut  = lut;
             break;
         default:
             pm_message("warning - %s type %ld not recognized",
-                       ID2string(iffid), type);
+                       ID2string(iffId), type);
             free(lut);
         }
     }
@@ -446,8 +446,8 @@ warnNonsquarePixels(uint8_t const xAspect,
             pm_message("%s; to fix do a 'pamscale -%cscale %g'",
                        baseMsg,
                        xAspect > yAspect ? 'x' : 'y',
-                       xAspect > yAspect ? 
-                       (float)xAspect/yAspect : 
+                       xAspect > yAspect ?
+                       (float)xAspect/yAspect :
                        (float)yAspect/xAspect);
         else
             pm_message("%s", baseMsg);
@@ -464,7 +464,7 @@ read_bmhd(FILE *        const ifP,
     BitMapHeader * bmhdP;
 
     if (chunksize != BitMapHeaderSize) {
-        pm_message("invalid size for %s chunk - skipping it", 
+        pm_message("invalid size for %s chunk - skipping it",
                    ID2string(iffid));
         skip_chunk(ifP, iffid, chunksize);
         bmhdP = NULL;
@@ -474,7 +474,7 @@ read_bmhd(FILE *        const ifP,
         MALLOCVAR_NOFAIL(bmhdP);
 
         remainingChunksize = chunksize;  /* initial value */
-        
+
         bmhdP->w = get_big_short(ifP, iffid, &remainingChunksize);
         bmhdP->h = get_big_short(ifP, iffid, &remainingChunksize);
         bmhdP->x = get_big_short(ifP, iffid, &remainingChunksize);
@@ -492,7 +492,7 @@ read_bmhd(FILE *        const ifP,
 
         if (verbose) {
             if (typeid == ID_ILBM)
-                pm_message("dimensions: %dx%d, %d planes", 
+                pm_message("dimensions: %dx%d, %d planes",
                            bmhdP->w, bmhdP->h, bmhdP->nPlanes);
             else
                 pm_message("dimensions: %dx%d", bmhdP->w, bmhdP->h);
@@ -509,11 +509,11 @@ read_bmhd(FILE *        const ifP,
                 case mskHasTransparentColor:
                     if (!maskfile)
                         pm_message("use '-maskfile <filename>' "
-                                   "to generate a PBM mask file from %s", 
+                                   "to generate a PBM mask file from %s",
                                    mskNAME[bmhdP->masking]);
                     break;
                 case mskLasso:
-                    pm_message("warning - masking type '%s' not recognized", 
+                    pm_message("warning - masking type '%s' not recognized",
                                mskNAME[bmhdP->masking]);
                     break;
                 default:
@@ -529,7 +529,7 @@ read_bmhd(FILE *        const ifP,
 
         /* fix aspect ratio */
         if (bmhdP->xAspect == 0 || bmhdP->yAspect == 0) {
-            pm_message("warning - illegal aspect ratio %d:%d, using 1:1", 
+            pm_message("warning - illegal aspect ratio %d:%d, using 1:1",
                        bmhdP->xAspect, bmhdP->yAspect);
             bmhdP->xAspect = bmhdP->yAspect = 1;
         }
@@ -647,7 +647,7 @@ decode_mask(FILE *          const ifP,
     case mskNone:
         break;
     case mskHasMask:        /* mask plane */
-        read_ilbm_plane(ifP, remainingChunksizeP, RowBytes(cols), 
+        read_ilbm_plane(ifP, remainingChunksizeP, RowBytes(cols),
                         bmhdP->compression);
         if (maskfile) {
             ilp = ilbmrow;
@@ -669,7 +669,7 @@ decode_mask(FILE *          const ifP,
     case mskHasTransparentColor:
         if (!chunkyrow)
             pm_error("decode_mask(): chunkyrow == NULL - can't happen");
-        
+
         if (maskfile) {
             for (col = 0; col < cols; ++col) {
                 if (chunkyrow[col] == bmhdP->transparentColor)
@@ -685,7 +685,7 @@ decode_mask(FILE *          const ifP,
         pm_error("This program does not know how to process Lasso masking");
         break;
     default:
-        pm_error("decode_mask(): unknown masking type %d - can't happen", 
+        pm_error("decode_mask(): unknown masking type %d - can't happen",
                  bmhdP->masking);
     }
 }
@@ -697,79 +697,82 @@ decode_mask(FILE *          const ifP,
 
 
 static void
-multi_adjust(cmap, row, palchange)
-    ColorMap *cmap;
-    int row;
-    PaletteChange *palchange;
-{
-    int i, reg;
-
-    for( i = 0; palchange[i].reg != MP_REG_END; i++ ) {
-        reg = palchange[i].reg;
-        if( reg >= cmap->ncolors ) {
+multi_adjust(ColorMap *            const cmapP,
+             unsigned int          const row,
+             const PaletteChange * const palchange) {
+
+    unsigned int i;
+
+    for (i = 0; palchange[i].reg != MP_REG_END; ++i) {
+        int const reg = palchange[i].reg;
+        if (reg >= cmapP->ncolors) {
             pm_message("warning - palette change register out of range");
-            pm_message("    row %d  change structure %d  reg=%d (max %d)", 
-                       row, i, reg, cmap->ncolors-1);
+            pm_message("    row %u  change structure %d  reg=%d (max %d)",
+                       row, i, reg, cmapP->ncolors-1);
             pm_message("    ignoring it...  "
                        "colors might get messed up from here");
-        }
-        else
-        if( reg != MP_REG_IGNORE ) {
-            PPM_ASSIGN(cmap->color[reg], 
-                       palchange[i].r, palchange[i].g, palchange[i].b);
+        } else {
+            if (reg != MP_REG_IGNORE) {
+                PPM_ASSIGN(cmapP->color[reg],
+                           palchange[i].r, palchange[i].g, palchange[i].b);
+            }
         }
     }
 }
 
+
+
 static void
-multi_init(cmap, viewportmodes)
-    ColorMap *cmap;
-    long viewportmodes;
-{
-    if( cmap->mp_init )
-        multi_adjust(cmap, -1, cmap->mp_init);
-    if( !(viewportmodes & vmLACE) )
-        cmap->mp_flags &= ~(MP_FLAGS_SKIPLACED);
+multi_init(ColorMap * const cmapP,
+           long       const viewportmodes) {
+
+    if (cmapP->mp_init)
+        multi_adjust(cmapP, -1, cmapP->mp_init);
+    if (!(viewportmodes & vmLACE) )
+        cmapP->mp_flags &= ~(MP_FLAGS_SKIPLACED);
 }
 
+
+
 static void
-multi_update(cmap, row)
-    ColorMap *cmap;
-    int row;
-{
-    if( cmap->mp_flags & MP_FLAGS_SKIPLACED ) {
-        if( ODD(row) )
+multi_update(ColorMap *   const cmapP,
+             unsigned int const row) {
+
+    if (cmapP->mp_flags & MP_FLAGS_SKIPLACED) {
+        if (ODD(row))
             return;
-        if( row/2 < cmap->mp_rows && cmap->mp_change[row/2] )
-            multi_adjust(cmap, row, cmap->mp_change[row/2]);
-    }
-    else {
-        if( row < cmap->mp_rows && cmap->mp_change[row] )
-            multi_adjust(cmap, row, cmap->mp_change[row]);
+        if (row/2 < cmapP->mp_rows && cmapP->mp_change[row/2])
+            multi_adjust(cmapP, row, cmapP->mp_change[row/2]);
+    } else {
+        if (row < cmapP->mp_rows && cmapP->mp_change[row])
+            multi_adjust(cmapP, row, cmapP->mp_change[row]);
     }
 }
 
+
+
 static void
-multi_free(cmap)
-    ColorMap *cmap;
-{
-    int i;
+multi_free(ColorMap * const cmapP) {
 
-    if( cmap->mp_init ) {
-        free(cmap->mp_init);
-        cmap->mp_init = NULL;
+    if (cmapP->mp_init) {
+        free(cmapP->mp_init);
+        cmapP->mp_init = NULL;
     }
-    if( cmap->mp_change ) {
-        for( i = 0; i < cmap->mp_rows; i++ ) {
-            if( cmap->mp_change[i] )
-                free(cmap->mp_change[i]);
+
+    if (cmapP->mp_change) {
+        unsigned int i;
+
+        for (i = 0; i < cmapP->mp_rows; ++i) {
+            if (cmapP->mp_change[i])
+                free(cmapP->mp_change[i]);
         }
-        free(cmap->mp_change);
-        cmap->mp_change = NULL;
+        free(cmapP->mp_change);
+        cmapP->mp_change = NULL;
     }
-    cmap->mp_rows = 0;
-    cmap->mp_type = 0;
-    cmap->mp_flags = 0;
+
+    cmapP->mp_rows  = 0;
+    cmapP->mp_type  = 0;
+    cmapP->mp_flags = 0;
 }
 
 
@@ -788,7 +791,7 @@ analyzeCmapSamples(const ColorMap * const cmapP,
     pixval       maxSample;
     bool         shifted;
     unsigned int i;
-        
+
     for (i = 0, maxSample = 0, shifted = true; i < cmapP->ncolors; ++i) {
         pixval const r = PPM_GETR(cmapP->color[i]);
         pixval const g = PPM_GETG(cmapP->color[i]);
@@ -857,7 +860,7 @@ transpColor(const BitMapHeader * const bmhdP,
     pixel * transpColorP;
 
     if (bmhdP) {
-        if (bmhdP->masking == mskHasTransparentColor || 
+        if (bmhdP->masking == mskHasTransparentColor ||
             bmhdP->masking == mskLasso) {
             MALLOCVAR_NOFAIL(transpColorP);
 
@@ -909,80 +912,83 @@ prepareCmap(const BitMapHeader * const bmhdP,
 
 
 static pixval
-lookup_red(cmap, oldval)
-    ColorMap *cmap;
-    int oldval;
-{
-    if( cmap && cmap->redlut && oldval < 256 )
-        return cmap->redlut[oldval];
+lookup_red(ColorMap *   const cmapP,
+           unsigned int const oldval) {
+
+    if (cmapP && cmapP->redlut && oldval < 256)
+        return cmapP->redlut[oldval];
     else
         return oldval;
 }
 
+
+
 static pixval
-lookup_green(cmap, oldval)
-    ColorMap *cmap;
-    int oldval;
-{
-    if( cmap && cmap->greenlut && oldval < 256 )
-        return cmap->greenlut[oldval];
+lookup_green(ColorMap *   const cmapP,
+             unsigned int const oldval) {
+
+    if (cmapP && cmapP->greenlut && oldval < 256)
+        return cmapP->greenlut[oldval];
     else
         return oldval;
 }
 
+
+
 static pixval
-lookup_blue(cmap, oldval)
-    ColorMap *cmap;
-    int oldval;
-{
-    if( cmap && cmap->bluelut && oldval < 256 )
-        return cmap->bluelut[oldval];
+lookup_blue(ColorMap *   const cmapP,
+            unsigned int const oldval) {
+
+    if (cmapP && cmapP->bluelut && oldval < 256)
+        return cmapP->bluelut[oldval];
     else
         return oldval;
 }
 
+
+
 static pixval
-lookup_mono(cmap, oldval)
-    ColorMap *cmap;
-    int oldval;
-{
-    if( cmap && cmap->monolut && oldval < 256 )
-        return cmap->monolut[oldval];
+lookup_mono(ColorMap *   const cmapP,
+            unsigned int const oldval) {
+
+    if (cmapP && cmapP->monolut && oldval < 256)
+        return cmapP->monolut[oldval];
     else
         return oldval;
 }
 
+
+
 static ColorMap *
-ehbcmap(cmap)
-    ColorMap *cmap;
-{
-    pixel *tempcolor = NULL;
-    int i, col;
-
-    col = cmap->ncolors;
-
-    tempcolor = ppm_allocrow(col * 2);
-    for( i = 0; i < col; i++ ) {
-        tempcolor[i] = cmap->color[i];
-        PPM_ASSIGN(tempcolor[col + i],  PPM_GETR(cmap->color[i]) / 2,
-                                        PPM_GETG(cmap->color[i]) / 2,
-                                        PPM_GETB(cmap->color[i]) / 2 );
+ehbcmap(ColorMap * const cmapP) {
+
+    pixel * tempcolor;
+    unsigned int i;
+
+    tempcolor = ppm_allocrow(cmapP->ncolors * 2);
+
+    for (i = 0; i < cmapP->ncolors; ++i) {
+        tempcolor[i] = cmapP->color[i];
+        PPM_ASSIGN(tempcolor[cmapP->ncolors + i],
+                   PPM_GETR(cmapP->color[i]) / 2,
+                   PPM_GETG(cmapP->color[i]) / 2,
+                   PPM_GETB(cmapP->color[i]) / 2);
     }
-    ppm_freerow(cmap->color);
-    cmap->color = tempcolor;
-    cmap->ncolors *= 2;
+    ppm_freerow(cmapP->color);
+    cmapP->color = tempcolor;
+    cmapP->ncolors *= 2;
 
-    return cmap;
+    return cmapP;
 }
 
 
 
 static pixval
-lut_maxval(ColorMap * const cmap, 
+lut_maxval(ColorMap * const cmap,
            pixval     const maxval) {
 
     pixval retval;
-    
+
     if (maxval >= 255)
         retval = maxval;
     else {
@@ -993,16 +999,16 @@ lut_maxval(ColorMap * const cmap,
             unsigned char maxlut;
             maxlut = maxval;
             for( i = 0; i < maxval; i++ ) {
-                if( cmap->redlut   && cmap->redlut[i]   > maxlut ) 
+                if( cmap->redlut   && cmap->redlut[i]   > maxlut )
                     maxlut = cmap->redlut[i];
-                if( cmap->greenlut && cmap->greenlut[i] > maxlut ) 
+                if( cmap->greenlut && cmap->greenlut[i] > maxlut )
                     maxlut = cmap->greenlut[i];
-                if( cmap->bluelut  && cmap->bluelut[i]  > maxlut ) 
+                if( cmap->bluelut  && cmap->bluelut[i]  > maxlut )
                     maxlut = cmap->bluelut[i];
             }
             pm_message("warning - "
                        "%d-bit index into 8-bit color lookup table, "
-                       "table maxval=%d", 
+                       "table maxval=%d",
                        pm_maxvaltobits(maxval), maxlut);
             if( maxlut != maxval )
                 retval = 255;
@@ -1017,49 +1023,49 @@ lut_maxval(ColorMap * const cmap,
 
 
 static void
-get_color(cmap, idx, red, green, blue)
-    ColorMap *cmap;
-    int idx;
-    pixval *red, *green, *blue;
-{
-    if( HAS_COLORMAP(cmap) ) {
-        pixval r, g, b;
-
-        if( idx >= cmap->ncolors )
-            pm_error("color index out of range: %d (max %d)", 
-                     idx, cmap->ncolors);
-        r = PPM_GETR(cmap->color[idx]);
-        g = PPM_GETG(cmap->color[idx]);
-        b = PPM_GETB(cmap->color[idx]);
-
-        *red    = lookup_red(cmap, r);
-        *green  = lookup_green(cmap, g);
-        *blue   = lookup_blue(cmap, b);
-    }
-    else {
-        *red = *green = *blue = lookup_mono(cmap, idx);
-    }
+get_color(ColorMap *   const cmapP,
+          unsigned int const idx,
+          pixval *     const redP,
+          pixval *     const greenP,
+          pixval *     const blueP) {
+
+    if (HAS_COLORMAP(cmapP)) {
+        if (idx >= cmapP->ncolors)
+            pm_error("color index out of range: %u (max %u)",
+                     idx, cmapP->ncolors);
+        else {
+            pixval const r = PPM_GETR(cmapP->color[idx]);
+            pixval const g = PPM_GETG(cmapP->color[idx]);
+            pixval const b = PPM_GETB(cmapP->color[idx]);
+
+            *redP    = lookup_red   (cmapP, r);
+            *greenP  = lookup_green (cmapP, g);
+            *blueP   = lookup_blue  (cmapP, b);
+        }
+    } else
+        *redP = *greenP = *blueP = lookup_mono(cmapP, idx);
 }
 
 
+
 /****************************************************************************
  Conversion functions
  ****************************************************************************/
 
 static void
-std_to_ppm(FILE *         const ifP, 
-           long           const chunksize, 
-           BitMapHeader * const bmhdP, 
-           ColorMap *     const cmap, 
+std_to_ppm(FILE *         const ifP,
+           long           const chunksize,
+           BitMapHeader * const bmhdP,
+           ColorMap *     const cmap,
            long           const viewportmodes);
 
 
 
 static void
-ham_to_ppm(FILE *         const ifP, 
-           long           const chunksize, 
-           BitMapHeader * const bmhdP, 
-           ColorMap *     const cmap, 
+ham_to_ppm(FILE *         const ifP,
+           long           const chunksize,
+           BitMapHeader * const bmhdP,
+           ColorMap *     const cmap,
            long           const viewportmodes) {
 
     int cols, rows, hambits, hammask, hamshift, hammask2, col, row;
@@ -1077,7 +1083,7 @@ ham_to_ppm(FILE *         const ifP,
     if( hambits > 8 || hambits < 1 ) {
         int const assumed_viewportmodes = viewportmodes & ~(vmHAM);
 
-        pm_message("%d-plane HAM?? - interpreting image as a normal ILBM", 
+        pm_message("%d-plane HAM?? - interpreting image as a normal ILBM",
                    bmhdP->nPlanes);
         std_to_ppm(ifP, chunksize, bmhdP, cmap, assumed_viewportmodes);
         return;
@@ -1085,8 +1091,8 @@ ham_to_ppm(FILE *         const ifP,
         unsigned long remainingChunksize;
         pixel * transpColorP;
 
-        pm_message("input is a %sHAM%d file", 
-                   HAS_MULTIPALETTE(cmap) ? "multipalette " : "", 
+        pm_message("input is a %sHAM%d file",
+                   HAS_MULTIPALETTE(cmap) ? "multipalette " : "",
                    bmhdP->nPlanes);
 
         if( HAS_COLORLUT(cmap) || HAS_MONOLUT(cmap) ) {
@@ -1095,7 +1101,7 @@ ham_to_ppm(FILE *         const ifP,
             if( cmap->greenlut )    free(cmap->greenlut);
             if( cmap->bluelut )     free(cmap->bluelut);
             if( cmap->monolut )     free(cmap->monolut);
-            cmap->redlut = cmap->greenlut = cmap->bluelut = 
+            cmap->redlut = cmap->greenlut = cmap->bluelut =
                 cmap->monolut = NULL;
         }
         if( !HAS_COLORMAP(cmap) ) {
@@ -1165,10 +1171,10 @@ ham_to_ppm(FILE *         const ifP,
 
 
 static void
-std_to_ppm(FILE *         const ifP, 
-           long           const chunksize, 
-           BitMapHeader * const bmhdP, 
-           ColorMap *     const cmap, 
+std_to_ppm(FILE *         const ifP,
+           long           const chunksize,
+           BitMapHeader * const bmhdP,
+           ColorMap *     const cmap,
            long           const viewportmodes) {
 
     if (viewportmodes & vmHAM) {
@@ -1213,7 +1219,7 @@ std_to_ppm(FILE *         const ifP,
         ppm_writeppminit( stdout, cols, rows, maxval, 0 );
 
         remainingChunksize = chunksize;  /* initial value */
-    
+
         for (row = 0; row < rows; ++row) {
 
             if( HAS_MULTIPALETTE(cmap) )
@@ -1240,9 +1246,9 @@ std_to_ppm(FILE *         const ifP,
 
 
 static void
-deep_to_ppm(FILE *         const ifP, 
-            long           const chunksize, 
-            BitMapHeader * const bmhdP, 
+deep_to_ppm(FILE *         const ifP,
+            long           const chunksize,
+            BitMapHeader * const bmhdP,
             ColorMap *     const cmap) {
 
     unsigned int const cols = bmhdP->w;
@@ -1259,9 +1265,9 @@ deep_to_ppm(FILE *         const ifP,
     if( planespercolor > MAXPLANES )
         pm_error("too many planes (max %d)", MAXPLANES * 3);
 
-    if( bmhdP->masking == mskHasTransparentColor || 
+    if( bmhdP->masking == mskHasTransparentColor ||
         bmhdP->masking == mskLasso ) {
-        pm_message("masking type '%s' in a deep ILBM?? - ignoring it", 
+        pm_message("masking type '%s' in a deep ILBM?? - ignoring it",
                    mskNAME[bmhdP->masking]);
         bmhdP->masking = mskNone;
     }
@@ -1271,7 +1277,7 @@ deep_to_ppm(FILE *         const ifP,
         pm_error("nPlanes is too large");
 
     transpColorP = transpColor(bmhdP, cmap, transpName, maxval);
-        
+
     Rrow = alloc_rawrow(cols);
     Grow = alloc_rawrow(cols);
     Brow = alloc_rawrow(cols);
@@ -1313,7 +1319,7 @@ dcol_to_ppm(FILE *         const ifP,
     unsigned int const redplanes   = dcol->r;
     unsigned int const greenplanes = dcol->g;
     unsigned int const blueplanes  = dcol->b;
-    
+
     int col, row;
     rawtype *Rrow, *Grow, *Brow;
     pixval maxval, redmaxval, greenmaxval, bluemaxval;
@@ -1324,16 +1330,16 @@ dcol_to_ppm(FILE *         const ifP,
     pm_message("input is a %d:%d:%d direct color ILBM",
                 redplanes, greenplanes, blueplanes);
 
-    if( redplanes > MAXPLANES || 
-        blueplanes > MAXPLANES || 
+    if( redplanes > MAXPLANES ||
+        blueplanes > MAXPLANES ||
         greenplanes > MAXPLANES )
         pm_error("too many planes (max %d per color component)", MAXPLANES);
 
     if( bmhdP->nPlanes != (redplanes + greenplanes + blueplanes) )
-        pm_error("%s/%s plane number mismatch", 
+        pm_error("%s/%s plane number mismatch",
                  ID2string(ID_BMHD), ID2string(ID_DCOL));
 
-    if( bmhdP->masking == mskHasTransparentColor || 
+    if( bmhdP->masking == mskHasTransparentColor ||
         bmhdP->masking == mskLasso ) {
         pm_message("masking type '%s' in a direct color ILBM?? - ignoring it",
                    mskNAME[bmhdP->masking]);
@@ -1356,7 +1362,7 @@ dcol_to_ppm(FILE *         const ifP,
 
     if( redmaxval != maxval || greenmaxval != maxval || bluemaxval != maxval )
         pm_message("scaling colors to %d bits", pm_maxvaltobits(maxval));
-    
+
     MALLOCARRAY_NOFAIL(redtable,   redmaxval   +1);
     MALLOCARRAY_NOFAIL(greentable, greenmaxval +1);
     MALLOCARRAY_NOFAIL(bluetable,  bluemaxval  +1);
@@ -1403,7 +1409,7 @@ dcol_to_ppm(FILE *         const ifP,
 
 static void
 cmapToPpm(FILE *     const ofP,
-            ColorMap * const cmapP) {
+          ColorMap * const cmapP) {
 
     ppm_colorrowtomapfile(ofP, cmapP->color, cmapP->ncolors, MAXCOLVAL);
 }
@@ -1425,11 +1431,11 @@ ipbm_to_ppm(FILE *         const ifP,
     unsigned long remainingChunksize;
     pixel * transpColorP;
 
-    pm_message("input is a %sPBM ", 
+    pm_message("input is a %sPBM ",
                HAS_MULTIPALETTE(cmap) ? "multipalette " : "");
 
     if( bmhdP->nPlanes != 8 )
-        pm_error("invalid number of planes for IFF-PBM: %d (must be 8)", 
+        pm_error("invalid number of planes for IFF-PBM: %d (must be 8)",
                  bmhdP->nPlanes);
 
     if( bmhdP->masking == mskHasMask )
@@ -1456,7 +1462,7 @@ ipbm_to_ppm(FILE *         const ifP,
     for( row = 0; row < rows; row++ ) {
         if( HAS_MULTIPALETTE(cmap) )
             multi_update(cmap, row);
-        
+
         read_ilbm_plane(ifP, &remainingChunksize, cols, bmhdP->compression);
 
         for( col = 0; col < cols; col++ ) {
@@ -1494,24 +1500,24 @@ rgbn_to_ppm(FILE *         const ifP,
     pm_message("input is a %d-bit RGB image", (typeid == ID_RGB8 ? 8 : 4));
 
     if (bmhdP->compression != 4)
-        pm_error("invalid compression mode for %s: %d (must be 4)", 
+        pm_error("invalid compression mode for %s: %d (must be 4)",
                  ID2string(typeid), bmhdP->compression);
-    
+
     switch (typeid) {
     case ID_RGBN:
         if (bmhdP->nPlanes != 13)
-            pm_error("invalid number of planes for %s: %d (must be 13)", 
+            pm_error("invalid number of planes for %s: %d (must be 13)",
                      ID2string(typeid), bmhdP->nPlanes);
         maxval = lut_maxval(cmap, 15);
         break;
     case ID_RGB8:
         if (bmhdP->nPlanes != 25)
-            pm_error("invalid number of planes for %s: %d (must be 25)", 
+            pm_error("invalid number of planes for %s: %d (must be 25)",
                      ID2string(typeid), bmhdP->nPlanes);
         maxval = 255;
         break;
     default:
-        pm_error("rgbn_to_ppm(): invalid IFF ID %s - can't happen", 
+        pm_error("rgbn_to_ppm(): invalid IFF ID %s - can't happen",
                  ID2string(typeid));
     }
 
@@ -1533,7 +1539,7 @@ rgbn_to_ppm(FILE *         const ifP,
             tries = 0;
             while (count == 0) {
                 if (typeid == ID_RGB8) {
-                    r = lookup_red(cmap,   get_byte(ifP, ID_BODY, 
+                    r = lookup_red(cmap,   get_byte(ifP, ID_BODY,
                                                     &remainingChunksize));
                     g = lookup_green(cmap, get_byte(ifP, ID_BODY,
                                                     &remainingChunksize));
@@ -1675,40 +1681,46 @@ read_4bit_mp(FILE *     const ifP,
 
 
 static void
-PCHG_DecompHuff(src, dest, tree, origsize)
-    unsigned char *src, *dest;
-    short *tree;
-    unsigned long origsize;
-{
-    unsigned long i = 0, bits = 0;
+PCHG_DecompHuff(const unsigned char * const src,
+                unsigned char *       const dst,
+                short *               const tree,
+                unsigned long         const origsize) {
+
+    const unsigned char * srcCursor;
+    unsigned char * dstCursor;
+    unsigned long i;
+    unsigned long bits;
     unsigned char thisbyte;
-    short *p;
+    short * p;
 
-    p = tree;
-    while( i < origsize ) {
-        if( bits == 0 ) {
-            thisbyte = *src++;
+    srcCursor = &src[0];  /* initial value */
+    dstCursor = &dst[0];  /* initial value */
+    i = 0;     /* initial value */
+    bits = 0;  /* initial value */
+    p = tree;  /* initial value */
+
+    while (i < origsize) {
+        if (bits == 0)  {
+            thisbyte = *srcCursor++;
             bits = 8;
         }
-        if( thisbyte & (1 << 7) ) {
-            if( *p >= 0 ) {
-                *dest++ = (unsigned char)*p;
-                i++;
+        if (thisbyte & (1 << 7)) {
+            if (*p >= 0) {
+                *dstCursor++ = (unsigned char)*p;
+                ++i;
                 p = tree;
-            }
-            else
+            } else
                 p += (*p / 2);
-        }
-        else {
-            p--;
-            if( *p > 0 && (*p & 0x100) ) {
-                *dest++ = (unsigned char )*p;
-                i++;
+        } else {
+            --p;
+            if (*p > 0 && (*p & 0x100)) {
+                *dstCursor++ = (unsigned char )*p;
+                ++i;
                 p = tree;
             }
         }
         thisbyte <<= 1;
-        bits--;
+        --bits;
     }
 }
 
@@ -1743,9 +1755,9 @@ PCHG_Decompress(PCHGHeader *     const PCHG,
             hufftree[i] = pm_uintFromBigend16(bigendComptree[i]);
 
         /* decompress the change structure data */
-        PCHG_DecompHuff(compdata, data, &hufftree[huffsize-1], 
+        PCHG_DecompHuff(compdata, data, &hufftree[huffsize-1],
                         CompHdr->OriginalDataSize);
-        
+
         free(hufftree);
     } break;
         default:
@@ -1755,99 +1767,103 @@ PCHG_Decompress(PCHGHeader *     const PCHG,
 
 
 static void
-PCHG_ConvertSmall(PCHG, cmap, mask, datasize)
-    PCHGHeader *PCHG;
-    ColorMap *cmap;
-    unsigned char *mask;
-    unsigned long datasize;
-{
+PCHG_ConvertSmall(PCHGHeader *    const pchgP,
+                  ColorMap *      const cmapP,
+                  unsigned char * const mask,
+                  unsigned long   const dataSize) {
+
     unsigned char *data;
+    unsigned long remDataSize;
     unsigned char thismask;
     int bits, row, i, changes, masklen, reg;
     unsigned char ChangeCount16, ChangeCount32;
     unsigned short SmallChange;
-    unsigned long totalchanges = 0;
-    int changedlines = PCHG->ChangedLines;
+    unsigned long totalchanges;
+    int changedlines;
+    unsigned char * maskCursor;
 
-    masklen = 4 * MaskLongWords(PCHG->LineCount);
-    data = mask + masklen; datasize -= masklen;
+    totalchanges = 0;  /* initial value */
+    changedlines = pchgP->ChangedLines;  /* initial value */
+    masklen = 4 * MaskLongWords(pchgP->LineCount);
+    maskCursor = mask;
+    data = maskCursor + masklen; remDataSize = dataSize - masklen;
 
     bits = 0;
-    for( row = PCHG->StartLine; changedlines && row < 0; row++ ) {
-        if( bits == 0 ) {
-            if( masklen == 0 ) goto fail2;
-            thismask = *mask++;
+    for (row = pchgP->StartLine; changedlines && row < 0; ++row) {
+        if (bits == 0) {
+            if (masklen == 0) goto fail2;
+            thismask = *maskCursor++;
             --masklen;
             bits = 8;
         }
-        if( thismask & (1<<7) ) {
-            if( datasize < 2 ) goto fail;
+        if (thismask & (1<<7)) {
+            if (remDataSize < 2) goto fail;
             ChangeCount16 = *data++;
             ChangeCount32 = *data++;
-            datasize -= 2;
+            remDataSize -= 2;
 
             changes = ChangeCount16 + ChangeCount32;
-            for( i = 0; i < changes; i++ ) {
-                if( totalchanges >= PCHG->TotalChanges ) goto fail;
-                if( datasize < 2 ) goto fail;
-                SmallChange = BIG_WORD(data); data += 2; datasize -= 2;
-                reg = ((SmallChange & 0xf000) >> 12) + 
+            for (i = 0; i < changes; ++i) {
+                if (totalchanges >= pchgP->TotalChanges) goto fail;
+                if (remDataSize < 2) goto fail;
+                SmallChange = BIG_WORD(data); data += 2; remDataSize -= 2;
+                reg = ((SmallChange & 0xf000) >> 12) +
                     (i >= ChangeCount16 ? 16 : 0);
-                cmap->mp_init[reg - PCHG->MinReg].reg = reg;
-                cmap->mp_init[reg - PCHG->MinReg].r = 
+                cmapP->mp_init[reg - pchgP->MinReg].reg = reg;
+                cmapP->mp_init[reg - pchgP->MinReg].r =
                     ((SmallChange & 0x0f00) >> 8) * FACTOR_4BIT;
-                cmap->mp_init[reg - PCHG->MinReg].g = 
+                cmapP->mp_init[reg - pchgP->MinReg].g =
                     ((SmallChange & 0x00f0) >> 4) * FACTOR_4BIT;
-                cmap->mp_init[reg - PCHG->MinReg].b = 
+                cmapP->mp_init[reg - pchgP->MinReg].b =
                     ((SmallChange & 0x000f) >> 0) * FACTOR_4BIT;
                 ++totalchanges;
             }
             --changedlines;
         }
         thismask <<= 1;
-        bits--;
+        --bits;
     }
 
-    for( row = PCHG->StartLine; changedlines && row < cmap->mp_rows; row++ ) {
-        if( bits == 0 ) {
-            if( masklen == 0 ) goto fail2;
-            thismask = *mask++;
+    for (row = pchgP->StartLine; changedlines && row < cmapP->mp_rows; row++) {
+        if (bits == 0) {
+            if (masklen == 0) goto fail2;
+            thismask = *maskCursor++;
             --masklen;
             bits = 8;
         }
-        if( thismask & (1<<7) ) {
-            if( datasize < 2 ) goto fail;
+        if(thismask & (1<<7)) {
+            if (remDataSize < 2) goto fail;
             ChangeCount16 = *data++;
             ChangeCount32 = *data++;
-            datasize -= 2;
+            remDataSize -= 2;
 
             changes = ChangeCount16 + ChangeCount32;
-            MALLOCARRAY_NOFAIL(cmap->mp_change[row], changes + 1);
-            for( i = 0; i < changes; i++ ) {
-                if( totalchanges >= PCHG->TotalChanges ) goto fail;
-                if( datasize < 2 ) goto fail;
-                SmallChange = BIG_WORD(data); data += 2; datasize -= 2;
-                reg = ((SmallChange & 0xf000) >> 12) + 
+            MALLOCARRAY_NOFAIL(cmapP->mp_change[row], changes + 1);
+            for (i = 0; i < changes; ++i) {
+                if (totalchanges >= pchgP->TotalChanges) goto fail;
+                if (remDataSize < 2) goto fail;
+                SmallChange = BIG_WORD(data); data += 2; remDataSize -= 2;
+                reg = ((SmallChange & 0xf000) >> 12) +
                     (i >= ChangeCount16 ? 16 : 0);
-                cmap->mp_change[row][i].reg = reg;
-                cmap->mp_change[row][i].r = 
+                cmapP->mp_change[row][i].reg = reg;
+                cmapP->mp_change[row][i].r =
                     ((SmallChange & 0x0f00) >> 8) * FACTOR_4BIT;
-                cmap->mp_change[row][i].g = 
+                cmapP->mp_change[row][i].g =
                     ((SmallChange & 0x00f0) >> 4) * FACTOR_4BIT;
-                cmap->mp_change[row][i].b = 
+                cmapP->mp_change[row][i].b =
                     ((SmallChange & 0x000f) >> 0) * FACTOR_4BIT;
                 ++totalchanges;
             }
-            cmap->mp_change[row][changes].reg = MP_REG_END;
+            cmapP->mp_change[row][changes].reg = MP_REG_END;
             --changedlines;
         }
         thismask <<= 1;
-        bits--;
+        --bits;
     }
-    if( totalchanges != PCHG->TotalChanges )
+    if (totalchanges != pchgP->TotalChanges)
         pm_message("warning - got %ld change structures, "
-                   "chunk header reports %ld", 
-                   totalchanges, PCHG->TotalChanges);
+                   "chunk header reports %ld",
+                   totalchanges, pchgP->TotalChanges);
     return;
 fail:
     pm_error("insufficient data in SmallLineChanges structures");
@@ -1872,16 +1888,16 @@ PCHG_ConvertBig(PCHGHeader *    const PCHG,
     int reg;
     unsigned long totalchanges;
     int changedlines;
-    unsigned long dataRemaining;
+    unsigned long remDataSize;
     unsigned char * mask;
 
     mask = maskStart;  /* initial value */
-    dataRemaining = datasize;  /* initial value */
+    remDataSize = datasize;  /* initial value */
     changedlines = PCHG->ChangedLines;  /* initial value */
     totalchanges = 0;  /* initial value */
 
     masklen = 4 * MaskLongWords(PCHG->LineCount);
-    data = mask + masklen; dataRemaining -= masklen;
+    data = mask + masklen; remDataSize -= masklen;
 
     for (row = PCHG->StartLine, bits = 0; changedlines && row < 0; ++row) {
         if (bits == 0) {
@@ -1894,16 +1910,16 @@ PCHG_ConvertBig(PCHGHeader *    const PCHG,
         if (thismask & (1<<7)) {
             unsigned int i;
 
-            if (dataRemaining < 2)
+            if (remDataSize < 2)
                 pm_error("insufficient data in BigLineChanges structures");
 
-            changes = BIG_WORD(data); data += 2; dataRemaining -= 2;
+            changes = BIG_WORD(data); data += 2; remDataSize -= 2;
 
             for (i = 0; i < changes; ++i) {
                 if (totalchanges >= PCHG->TotalChanges)
                     pm_error("insufficient data in BigLineChanges structures");
 
-                if (dataRemaining < 6)
+                if (remDataSize < 6)
                     pm_error("insufficient data in BigLineChanges structures");
 
                 reg = BIG_WORD(data); data += 2;
@@ -1912,7 +1928,7 @@ PCHG_ConvertBig(PCHGHeader *    const PCHG,
                 cmap->mp_init[reg - PCHG->MinReg].r = *data++;
                 cmap->mp_init[reg - PCHG->MinReg].b = *data++;  /* yes, RBG */
                 cmap->mp_init[reg - PCHG->MinReg].g = *data++;
-                dataRemaining -= 6;
+                remDataSize -= 6;
                 ++totalchanges;
             }
             --changedlines;
@@ -1933,17 +1949,17 @@ PCHG_ConvertBig(PCHGHeader *    const PCHG,
         if (thismask & (1<<7)) {
             unsigned int i;
 
-            if (dataRemaining < 2)
+            if (remDataSize < 2)
                 pm_error("insufficient data in BigLineChanges structures");
 
-            changes = BIG_WORD(data); data += 2; dataRemaining -= 2;
+            changes = BIG_WORD(data); data += 2; remDataSize -= 2;
 
             MALLOCARRAY_NOFAIL(cmap->mp_change[row], changes + 1);
             for (i = 0; i < changes; ++i) {
                 if (totalchanges >= PCHG->TotalChanges)
                     pm_error("insufficient data in BigLineChanges structures");
 
-                if (dataRemaining < 6)
+                if (remDataSize < 6)
                     pm_error("insufficient data in BigLineChanges structures");
 
                 reg = BIG_WORD(data); data += 2;
@@ -1952,7 +1968,7 @@ PCHG_ConvertBig(PCHGHeader *    const PCHG,
                 cmap->mp_change[row][i].r = *data++;
                 cmap->mp_change[row][i].b = *data++;    /* yes, RBG */
                 cmap->mp_change[row][i].g = *data++;
-                dataRemaining -= 6;
+                remDataSize -= 6;
                 ++totalchanges;
             }
             cmap->mp_change[row][changes].reg = MP_REG_END;
@@ -1963,7 +1979,7 @@ PCHG_ConvertBig(PCHGHeader *    const PCHG,
     }
     if (totalchanges != PCHG->TotalChanges)
         pm_message("warning - got %ld change structures, "
-                   "chunk header reports %ld", 
+                   "chunk header reports %ld",
                    totalchanges, PCHG->TotalChanges);
 }
 
@@ -2027,7 +2043,7 @@ read_pchg(FILE *     const ifP,
 
             datasize = CompHdr.OriginalDataSize;
             MALLOCARRAY_NOFAIL(data, datasize);
-            PCHG_Decompress(&PCHG, &CompHdr, compdata, 
+            PCHG_Decompress(&PCHG, &CompHdr, compdata,
                             compsize, comptree, data);
 
             free(comptree);
@@ -2073,7 +2089,7 @@ read_pchg(FILE *     const ifP,
             }
             else
                 pm_error("unknown palette changes structure "
-                         "format in %s chunk", 
+                         "format in %s chunk",
                          ID2string(iffid));
         }
         free(data);
@@ -2101,7 +2117,7 @@ ignored_iffid(IFF_ID       const iffid,
 
 
 
-static void 
+static void
 process_body( FILE *          const ifP,
               long            const chunksize,
               BitMapHeader *  const bmhdP,
@@ -2111,9 +2127,9 @@ process_body( FILE *          const ifP,
               int             const isdeepopt,
               DirectColor *   const dcol,
               int *           const viewportmodesP) {
-    
+
     if (bmhdP == NULL)
-        pm_error("%s chunk without %s chunk", 
+        pm_error("%s chunk without %s chunk",
                  ID2string(ID_BODY), ID2string(ID_BMHD));
 
     prepareCmap(bmhdP, cmap);
@@ -2132,12 +2148,12 @@ process_body( FILE *          const ifP,
 
         if( isdeepopt > 0 && (bmhdP->nPlanes % 3 != 0) ) {
             pm_message("cannot interpret %d-plane image as 'deep' "
-                       "(# of planes must be divisible by 3)", 
+                       "(# of planes must be divisible by 3)",
                        bmhdP->nPlanes);
             isdeep = 0;
         } else
             isdeep = isdeepopt;
-        
+
         if (isdeep > 0)
             deep_to_ppm(ifP, chunksize, bmhdP, cmap);
         else if (dcol)
@@ -2151,7 +2167,7 @@ process_body( FILE *          const ifP,
                 /* will be interpreted as grayscale */
                 std_to_ppm(ifP, chunksize, bmhdP, cmap, *viewportmodesP);
             else
-                pm_error("don't know how to interpret %d-plane image", 
+                pm_error("don't know how to interpret %d-plane image",
                          bmhdP->nPlanes);
         } else
             std_to_ppm(ifP, chunksize, bmhdP, cmap, *viewportmodesP);
@@ -2163,7 +2179,7 @@ process_body( FILE *          const ifP,
 
 
 
-static void 
+static void
 processChunk(FILE *          const ifP,
              long            const formsize,
              IFF_ID          const ignorelist[],
@@ -2200,7 +2216,7 @@ processChunk(FILE *          const ifP,
     } else if (iffid == ID_END) {
         /* END chunks are not officially valid in IFF, but
            suggested as a future expansion for stream-writing,
-           see Amiga RKM Devices, 3rd Ed, page 376 
+           see Amiga RKM Devices, 3rd Ed, page 376
         */
         if (chunksize != 0 ) {
             pm_message("warning - non-0 %s chunk", ID2string(iffid));
@@ -2212,7 +2228,7 @@ processChunk(FILE *          const ifP,
                        ID2string(iffid), formsize, 0xffffffff);
         *endchunkP = 1;
     } else if (*bodyChunkProcessedP) {
-        pm_message("%s chunk found after %s chunk - skipping", 
+        pm_message("%s chunk found after %s chunk - skipping",
                    ID2string(iffid), ID2string(ID_BODY));
         skip_chunk(ifP, iffid, chunksize);
     } else
@@ -2251,11 +2267,11 @@ processChunk(FILE *          const ifP,
             (*dcolP)->b = get_byte(ifP, iffid, NULL);
             get_byte(ifP, iffid, NULL);       /* skip pad byte */
             break;
-        case ID_BODY: 
+        case ID_BODY:
             if (cmaponly || (*bmhdP && (*bmhdP)->nPlanes == 0))
                 skip_chunk(ifP, ID_BODY,  chunksize);
             else {
-                process_body(ifP, chunksize, *bmhdP, cmap, 
+                process_body(ifP, chunksize, *bmhdP, cmap,
                              maskfile, fakeviewport, isdeepopt, *dcolP,
                              viewportmodesP);
 
@@ -2280,11 +2296,11 @@ processChunk(FILE *          const ifP,
             x = get_big_short(ifP, ID_DPI, NULL);
             y = get_big_short(ifP, ID_DPI, NULL);
             if (verbose)
-                pm_message("%s chunk:  dpi_x = %d    dpi_y = %d", 
+                pm_message("%s chunk:  dpi_x = %d    dpi_y = %d",
                            ID2string(ID_DPI), x, y);
         } break;
         default:
-            pm_message("unknown chunk type %s - skipping", 
+            pm_message("unknown chunk type %s - skipping",
                        ID2string(iffid));
             skip_chunk(ifP, iffid, chunksize);
             break;
@@ -2295,7 +2311,7 @@ processChunk(FILE *          const ifP,
     if (ODD(chunksize)) {
         get_byte(ifP, iffid, NULL);
         bytesread += 1;
-    } 
+    }
     *bytesReadP = bytesread;
 }
 
@@ -2338,7 +2354,7 @@ maybeWriteColorMap(FILE *               const ofP,
             prepareCmap(bmhdP, cmapP);
             cmapToPpm(ofP, cmapP);
         } else
-            pm_error("ILBM has neither %s or %s chunk", 
+            pm_error("ILBM has neither %s or %s chunk",
                      ID2string(ID_BODY), ID2string(ID_CMAP));
     }
 }
@@ -2413,13 +2429,13 @@ main(int argc, char *argv[]) {
                          "as argument");
             if( ignorecount >= MAX_IGNORE )
                 pm_error("max %d chunk IDs to ignore", MAX_IGNORE);
-            ignorelist[ignorecount++] = 
-                MAKE_ID(argv[argn][0], argv[argn][1], argv[argn][2], 
+            ignorelist[ignorecount++] =
+                MAKE_ID(argv[argn][0], argv[argn][1], argv[argn][2],
                         argv[argn][3]);
         } else
             pm_usage(usage);
         ++argn;
-    }    
+    }
 
     if( argn < argc ) {
         ifP = pm_openr( argv[argn] );
@@ -2439,7 +2455,7 @@ main(int argc, char *argv[]) {
         pm_error("input is not a FORM type IFF file");
     formsize = get_big_long(ifP, ID_FORM, NULL);
     typeid = get_big_long(ifP, ID_FORM, NULL);
-    if (typeid != ID_ILBM && typeid != ID_RGBN && typeid != ID_RGB8 && 
+    if (typeid != ID_ILBM && typeid != ID_RGBN && typeid != ID_RGB8 &&
         typeid != ID_PBM)
         pm_error("input is not an ILBM, RGBN, RGB8 or PBM "
                  "type FORM IFF file");
@@ -2474,7 +2490,7 @@ main(int argc, char *argv[]) {
 
     {
         unsigned int skipped;
-        
+
         for (skipped = 0; fgetc(ifP) != EOF; ++skipped)
             ++bytesread;
 
@@ -2492,3 +2508,6 @@ main(int argc, char *argv[]) {
 
     return 0;
 }
+
+
+