/* pamscale.c - rescale (resample) a PNM image

   This program evolved out of Jef Poskanzer's program Pnmscale from
   his Pbmplus package (which was derived from Poskanzer's 1989
   Ppmscale).  The resampling logic was taken from Michael Reinelt's
   program Pnmresample, somewhat recoded to follow Netpbm conventions.
   Michael submitted that for inclusion in Netpbm in December 2003.
   The frame of the program is by Bryan Henderson, and the old scaling
   algorithm is based on that in Jef Poskanzer's Pnmscale, but
   completely rewritten by Bryan Henderson ca. 2000.  Plenty of other
   people contributed code changes over the years.

   Copyright (C) 2003 by Michael Reinelt <reinelt@eunet.at>
  
   Copyright (C) 1989, 1991 by Jef Poskanzer.
  
   Permission to use, copy, modify, and distribute this software and its
   documentation for any purpose and without fee is hereby granted, provided
   that the above copyright notice appear in all copies and that both that
   copyright notice and this permission notice appear in supporting
   documentation.  This software is provided "as is" without express or
   implied warranty.
*/

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <assert.h>

#include "pam.h"
#include "pm_gamma.h"
#include "shhopt.h"
#include "mallocvar.h"

enum sampleScale {INTENSITY_SAMPLE, GAMMA_SAMPLE};
/* This indicates a scale for a PAM sample value.  INTENSITY_SAMPLE means
   the value is proportional to light intensity; GAMMA_SAMPLE means the 
   value is gamma-corrected as defined in the PGM/PPM spec.  In both
   scales, the values are continuous and normalized to the range 0..1.

   This scale has no meaning if the PAM is not a visual image.  
*/

/****************************/
/****************************/
/********* filters **********/
/****************************/
/****************************/

/* Most of the filters are FIR (finite impulse respone), but some
** (sinc, bessel) are IIR (infinite impulse respone).
** They should be windowed with hanning, hamming, blackman or
** kaiser window.
** For sinc and bessel the blackman window will be used per default.
*/

#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

#define EPSILON 1e-7


/* x^2 and x^3 helper functions */
static __inline__ double 
pow2 (double x)
{
  return x*x;
}

static __inline__ double 
pow3 (double x) 
{
  return x*x*x;
}


/* box, pulse, Fourier window, */
/* 1st order (constant) b-spline */

#define radius_point (0.0)
#define radius_box (0.5)

static double 
filter_box (double x)
{
    if (x <  0.0) x = -x;
    if (x <= 0.5) return 1.0;
    return 0.0;
}


/* triangle, Bartlett window, */
/* 2nd order (linear) b-spline */

#define radius_triangle (1.0)

static double 
filter_triangle (double x)
{
    if (x <  0.0) x = -x;
    if (x < 1.0) return 1.0-x;
    return 0.0;
}


/* 3rd order (quadratic) b-spline */

#define radius_quadratic (1.5)

static double 
filter_quadratic(double x)
{
    if (x <  0.0) x = -x;
    if (x < 0.5) return 0.75-pow2(x);
    if (x < 1.5) return 0.50*pow2(x-1.5);
    return 0.0;
}


/* 4th order (cubic) b-spline */

#define radius_cubic (2.0)

static double 
filter_cubic(double x)
{
    if (x <  0.0) x = -x;
    if (x < 1.0) return 0.5*pow3(x) - pow2(x) + 2.0/3.0;
    if (x < 2.0) return pow3(2.0-x)/6.0;
    return 0.0;
}


/* Catmull-Rom spline, Overhauser spline */

#define radius_catrom (2.0)

static double 
filter_catrom(double x)
{
    if (x <  0.0) x = -x;
    if (x < 1.0) return  1.5*pow3(x) - 2.5*pow2(x)         + 1.0;
    if (x < 2.0) return -0.5*pow3(x) + 2.5*pow2(x) - 4.0*x + 2.0;
    return 0.0;
}


/* Mitchell & Netravali's two-param cubic */
/* see Mitchell&Netravali,  */
/* "Reconstruction Filters in Computer Graphics", SIGGRAPH 88 */

#define radius_mitchell (2.0)

static double 
filter_mitchell(double x)
{

    double b = 1.0/3.0;
    double c = 1.0/3.0;

    double p0 = (  6.0 -  2.0*b         ) / 6.0;
    double p2 = (-18.0 + 12.0*b +  6.0*c) / 6.0;
    double p3 = ( 12.0 -  9.0*b -  6.0*c) / 6.0;
    double q0 = (         8.0*b + 24.0*c) / 6.0;
    double q1 = (      - 12.0*b - 48.0*c) / 6.0;
    double q2 = (         6.0*b + 30.0*c) / 6.0;
    double q3 = (      -      b -  6.0*c) / 6.0;

    if (x <  0.0) x = -x;
    if (x <  1.0) return p3*pow3(x) + p2*pow2(x)        + p0;
    if (x < 2.0) return q3*pow3(x) + q2*pow2(x) + q1*x + q0;
    return 0.0;
}


/* Gaussian filter (infinite) */

#define radius_gauss (1.25)

static double 
filter_gauss(double x)
{
    return exp(-2.0*pow2(x)) * sqrt(2.0/M_PI);
}


/* sinc, perfect lowpass filter (infinite) */

#define radius_sinc (4.0)

static double 
filter_sinc(double x)
{
    /* Note: Some people say sinc(x) is sin(x)/x.  Others say it's
       sin(PI*x)/(PI*x), a horizontal compression of the former which is
       zero at integer values.  We use the latter.
    */
    if (x == 0.0) return 1.0;
    return sin(M_PI*x)/(M_PI*x);
}


/* Bessel (for circularly symm. 2-d filt, infinite) */
/* See Pratt "Digital Image Processing" p. 97 for Bessel functions */

#define radius_bessel (3.2383)

static double 
filter_bessel(double x)
{
    if (x == 0.0) return M_PI/4.0;
    return j1(M_PI*x)/(2.0*x);
}


/* Hanning window (infinite) */

#define radius_hanning (1.0)

static double 
filter_hanning(double x)
{
    return 0.5*cos(M_PI*x) + 0.5;
}


/* Hamming window (infinite) */

#define radius_hamming (1.0)

static double 
filter_hamming(double x)
{
  return 0.46*cos(M_PI*x) + 0.54;
}


/* Blackman window (infinite) */

#define radius_blackman (1.0)

static double 
filter_blackman(double x)
{
    return 0.5*cos(M_PI*x) + 0.08*cos(2.0*M_PI*x) + 0.42;
}


/* parameterized Kaiser window (infinite) */
/* from Oppenheim & Schafer, Hamming */

#define radius_kaiser (1.0)

/* modified zeroth order Bessel function of the first kind. */
static double 
bessel_i0(double x)
{
  
    int i;
    double sum, y, t;
  
    sum = 1.0;
    y = pow2(x)/4.0;
    t = y;
    for (i=2; t>EPSILON; i++) {
        sum += t;
        t   *= (double)y/pow2(i);
    }
    return sum;
}

static double 
filter_kaiser(double x)
{
    /* typically 4<a<9 */
    /* param a trades off main lobe width (sharpness) */
    /* for side lobe amplitude (ringing) */
  
    double a   = 6.5;
    double i0a = 1.0/bessel_i0(a);
  
    return i0a*bessel_i0(a*sqrt(1.0-pow2(x)));
}


/* normal distribution (infinite) */
/* Normal(x) = Gaussian(x/2)/2 */

#define radius_normal (1.0)

static double 
filter_normal(double x)
{
    return exp(-pow2(x)/2.0) / sqrt(2.0*M_PI);
    return 0.0;
}


/* Hermite filter */

#define radius_hermite  (1.0)

static double 
filter_hermite(double x)
{
    /* f(x) = 2|x|^3 - 3|x|^2 + 1, -1 <= x <= 1 */
    if (x <  0.0) x = -x;
    if (x <  1.0) return 2.0*pow3(x) - 3.0*pow2(x) + 1.0;
    return 0.0;
}


/* Lanczos filter */

#define radius_lanczos (3.0)

static double 
filter_lanczos(double x)
{
    if (x <  0.0) x = -x;
    if (x <  3.0) return filter_sinc(x) * filter_sinc(x/3.0);
    return(0.0);
}



typedef struct {
    const char *name;
    double (*function)(double);
    double radius;
        /* This is how far from the Y axis (on either side) the
           function has significant value.  (You can use this to limit
           how much of your domain you bother to compute the function
           over).  
        */
    bool windowed;
} filter;


static filter Filters[] = {
    { "point",     filter_box,       radius_point,     FALSE },
    { "box",       filter_box,       radius_box,       FALSE },
    { "triangle",  filter_triangle,  radius_triangle,  FALSE },
    { "quadratic", filter_quadratic, radius_quadratic, FALSE },
    { "cubic",     filter_cubic,     radius_cubic,     FALSE },
    { "catrom",    filter_catrom,    radius_catrom,    FALSE },
    { "mitchell",  filter_mitchell,  radius_mitchell,  FALSE },
    { "gauss",     filter_gauss,     radius_gauss,     FALSE },
    { "sinc",      filter_sinc,      radius_sinc,      TRUE  },
    { "bessel",    filter_bessel,    radius_bessel,    TRUE  },
    { "hanning",   filter_hanning,   radius_hanning,   FALSE },
    { "hamming",   filter_hamming,   radius_hamming,   FALSE },
    { "blackman",  filter_blackman,  radius_blackman,  FALSE },
    { "kaiser",    filter_kaiser,    radius_kaiser,    FALSE },
    { "normal",    filter_normal,    radius_normal,    FALSE },
    { "hermite",   filter_hermite,   radius_hermite,   FALSE },
    { "lanczos",   filter_lanczos,   radius_lanczos,   FALSE },
   { NULL },
};


typedef double (*filterFunction_t)(double);


/****************************/
/****************************/
/****** end of filters ******/
/****************************/
/****************************/



enum scaleType {SCALE_SEPARATE, SCALE_BOXFIT, SCALE_BOXFILL, SCALE_PIXELMAX};
    /* This is a way of specifying the output dimensions.

       SCALE_SEPARATE means specify the horizontal and vertical scaling
       separately.  One or both may be unspecified.

       SCALE_BOXFIT means specify height and width of a box, and the
       image must be scaled, preserving aspect ratio, to the largest
       size that will fit in the box.

       SCALE_BOXFILL means specify height and width of a box, and the
       image must be scale, preserving aspect ratio, to the smallest
       size that completely fills the box.  

       SCALE_PIXELMAX means specify the maximum number of pixels the result
       should have and scale preserving aspect ratio and maximizing image
       size.
    */

struct cmdlineInfo {
    /* All the information the user supplied in the command line,
     * in a form easy for the program to use.
     */
    const char *input_filespec;  /* Filespec of input file */
    unsigned int nomix;
    filterFunction_t filterFunction; /* NULL if not using resample method */
    filterFunction_t windowFunction;
    double filterRadius;           
    enum scaleType scaleType;
    /* 'xsize' and 'ysize' are numbers of pixels.  Their meaning depends upon
       'scaleType'.  for SCALE_BOXFIT and SCALE_BOXFILL, they are the box 
       dimensions.  For SCALE_SEPARATE, they are the separate dimensions, or
       zero to indicate unspecified.
    */
    unsigned int xsize;
    unsigned int ysize;
    /* 'xscale' and 'yscale' are meaningful only for scaleType == 
       SCALE_SEPARATE and only where the corresponding xsize/ysize is
       unspecified.  0.0 means unspecified.
    */
    float xscale;
    float yscale;
    /* 'pixels' is meaningful only for scaleType == SCALE_PIXELMAX */
    unsigned int pixels; 
    unsigned int linear;
    unsigned int verbose;
};



static void
lookupFilterByName(const char * const filtername,
                   filter *     const filterP) {

    unsigned int i;
    bool found;

    found = FALSE;  /* initial assumption */

    for (i=0; Filters[i].name; ++i) {
        if (strcmp(filtername, Filters[i].name) == 0) {
            *filterP = Filters[i];
            found = TRUE;
        }
    }
    if (!found) {
        unsigned int i;
        char known_filters[1024];
        strcpy(known_filters, "");
        for (i = 0; Filters[i].name; ++i) {
            const char * const name = Filters[i].name;
            if (strlen(known_filters) + strlen(name) + 1 + 1 < 
                sizeof(known_filters)) {
                strcat(known_filters, name);
                strcat(known_filters, " ");
            }
        }
        pm_error("No such filter as '%s'.  Known filter names are: %s",
                 filtername, known_filters);
    }
}



static void
processFilterOptions(unsigned int const         filterSpec,
                     const char                 filterOpt[],
                     unsigned int const         windowSpec,
                     const char                 windowOpt[],
                     struct cmdlineInfo * const cmdline_p) {

    if (filterSpec) {
        filter baseFilter;
        lookupFilterByName(filterOpt, &baseFilter);
        cmdline_p->filterFunction = baseFilter.function; 
        cmdline_p->filterRadius   = baseFilter.radius;

        if (windowSpec) {
            filter windowFilter;
            lookupFilterByName(windowOpt, &windowFilter);
            
            if (cmdline_p->windowFunction == filter_box)
                cmdline_p->windowFunction = NULL;
            else
                cmdline_p->windowFunction = windowFilter.function;
        } else {
            /* Default for most filters is no window.  Those that _require_
               a window function get Blackman.
               */
            if (baseFilter.windowed)
                cmdline_p->windowFunction = filter_blackman;
            else
                cmdline_p->windowFunction = NULL;
        }
    } else
        cmdline_p->filterFunction = NULL;
}



static void
parseXyParms(int                  const argc, 
             char **              const argv,
             struct cmdlineInfo * const cmdline_p) {

    /* parameters are box width (columns), box height (rows), and
       optional filespec 
    */
    if (argc-1 < 2)
        pm_error("You must supply at least two parameters with "
                 "-xyfit/xyfill/xysize: "
                 "x and y dimensions of the bounding box.");
    else if (argc-1 > 3)
        pm_error("Too many arguments.  With -xyfit/xyfill/xysize, "
                 "you need 2 or 3 arguments.");
    else {
        char * endptr;
        cmdline_p->xsize = strtol(argv[1], &endptr, 10);
        if (strlen(argv[1]) > 0 && *endptr != '\0')
            pm_error("horizontal size argument not an integer: '%s'", 
                     argv[1]);
        if (cmdline_p->xsize <= 0)
            pm_error("horizontal size argument is not positive: %d", 
                     cmdline_p->xsize);
        
        cmdline_p->ysize = strtol(argv[2], &endptr, 10);
        if (strlen(argv[2]) > 0 && *endptr != '\0')
            pm_error("vertical size argument not an integer: '%s'", 
                     argv[2]);
        if (cmdline_p->ysize <= 0)
            pm_error("vertical size argument is not positive: %d", 
                     cmdline_p->ysize);
        
        if (argc-1 < 3)
            cmdline_p->input_filespec = "-";
        else
            cmdline_p->input_filespec = argv[3];
    }
}



static void
parseScaleParms(int                   const argc, 
                char **               const argv,
                struct cmdlineInfo  * const cmdline_p) {

    /* parameters are scale factor and optional filespec */
    if (argc-1 < 1)
        pm_error("With no dimension options, you must supply at least "
                 "one parameter: the scale factor.");
    else {
        cmdline_p->xscale = cmdline_p->yscale = atof(argv[1]);
        
        if (cmdline_p->xscale == 0.0)
            pm_error("The scale parameter %s is not a positive number.",
                     argv[1]);
        else {
            if (argc-1 < 2)
                cmdline_p->input_filespec = "-";
            else
                cmdline_p->input_filespec = argv[2];
        }
    }
}



static void
parseFilespecOnlyParms(int                   const argc, 
                       char **               const argv,
                       struct cmdlineInfo  * const cmdline_p) {

    /* Only parameter allowed is optional filespec */
    if (argc-1 < 1)
        cmdline_p->input_filespec = "-";
    else
        cmdline_p->input_filespec = argv[1];
}


static void 
parseCommandLine(int argc, 
                 char ** argv, 
                 struct cmdlineInfo  * const cmdlineP) {
/* --------------------------------------------------------------------------
   Parse program command line described in Unix standard form by argc
   and argv.  Return the information in the options as *cmdlineP.  

   If command line is internally inconsistent (invalid options, etc.),
   issue error message to stderr and abort program.

   Note that the strings we return are stored in the storage that
   was passed to us as the argv array.  We also trash *argv.
--------------------------------------------------------------------------*/
    optEntry *option_def = malloc( 100*sizeof( optEntry ) );
    /* Instructions to optParseOptions3 on how to parse our options. */
    optStruct3 opt;
  
    unsigned int option_def_index;
    unsigned int xyfit, xyfill;
    int xsize, ysize, pixels;
    int reduce;
    float xscale, yscale;
    const char *filterOpt, *window;
    unsigned int filterSpec, windowSpec;

    option_def_index = 0;   /* incremented by OPTENTRY */
    OPTENT3(0, "xsize",     OPT_UINT,    &xsize,     NULL,                 0);
    OPTENT3(0, "width",     OPT_UINT,    &xsize,     NULL,                 0);
    OPTENT3(0, "ysize",     OPT_UINT,    &ysize,     NULL,                 0);
    OPTENT3(0, "height",    OPT_UINT,    &ysize,     NULL,                 0);
    OPTENT3(0, "xscale",    OPT_FLOAT,   &xscale,    NULL,                 0);
    OPTENT3(0, "yscale",    OPT_FLOAT,   &yscale,    NULL,                 0);
    OPTENT3(0, "pixels",    OPT_UINT,    &pixels,    NULL,                 0);
    OPTENT3(0, "reduce",    OPT_UINT,    &reduce,    NULL,                 0);
    OPTENT3(0, "xysize",    OPT_FLAG,    NULL,       &xyfit,               0);
    OPTENT3(0, "xyfit",     OPT_FLAG,    NULL,       &xyfit,               0);
    OPTENT3(0, "xyfill",    OPT_FLAG,    NULL,       &xyfill,              0);
    OPTENT3(0, "verbose",   OPT_FLAG,    NULL,       &cmdlineP->verbose,  0);
    OPTENT3(0, "filter",    OPT_STRING,  &filterOpt, &filterSpec,          0);
    OPTENT3(0, "window",    OPT_STRING,  &window,    &windowSpec,          0);
    OPTENT3(0, "nomix",     OPT_FLAG,    NULL,       &cmdlineP->nomix,    0);
    OPTENT3(0, "linear",    OPT_FLAG,    NULL,       &cmdlineP->linear,   0);
  
    /* Set the defaults. -1 = unspecified */

    /* (Now that we're using ParseOptions3, we don't have to do this -1
     * nonsense, but we don't want to risk screwing these complex 
     * option compatibilities up, so we'll convert that later.
     */
    xsize = -1;
    ysize = -1;
    xscale = -1.0;
    yscale = -1.0;
    pixels = -1;
    reduce = -1;
    
    opt.opt_table = option_def;
    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
    opt.allowNegNum = FALSE;   /* We have no parms that are negative numbers */

    optParseOptions3( &argc, argv, opt, sizeof(opt), 0 );
    /* Uses and sets argc, argv, and some of *cmdlineP and others. */

    if (cmdlineP->nomix && filterSpec) 
        pm_error("You cannot specify both -nomix and -filter.");

    processFilterOptions(filterSpec, filterOpt, windowSpec, window,
                         cmdlineP);

    if (xsize == 0)
        pm_error("-xsize/width must be greater than zero.");
    if (ysize == 0)
        pm_error("-ysize/height must be greater than zero.");
    if (xscale != -1.0 && xscale <= 0.0)
        pm_error("-xscale must be greater than zero.");
    if (yscale != -1.0 && yscale <= 0.0)
        pm_error("-yscale must be greater than zero.");
    if (reduce <= 0 && reduce != -1)
        pm_error("-reduce must be greater than zero.");

    if (xsize != -1 && xscale != -1)
        pm_error("Cannot specify both -xsize/width and -xscale.");
    if (ysize != -1 && yscale != -1)
        pm_error("Cannot specify both -ysize/height and -yscale.");
    
    if ((xyfit || xyfill) &&
        (xsize != -1 || xscale != -1 || ysize != -1 || yscale != -1 || 
         reduce != -1 || pixels != -1) )
        pm_error("Cannot specify -xyfit/xyfill/xysize with other "
                 "dimension options.");
    if (xyfit && xyfill)
        pm_error("Cannot specify both -xyfit and -xyfill");
    if (pixels != -1 && 
        (xsize != -1 || xscale != -1 || ysize != -1 || yscale != -1 ||
         reduce != -1) )
        pm_error("Cannot specify -pixels with other dimension options.");
    if (reduce != -1 && 
        (xsize != -1 || xscale != -1 || ysize != -1 || yscale != -1) )
        pm_error("Cannot specify -reduce with other dimension options.");

    if (pixels == 0)
        pm_error("-pixels must be greater than zero");

    /* Get the program parameters */

    if (xyfit || xyfill) {
        cmdlineP->scaleType = xyfit ? SCALE_BOXFIT : SCALE_BOXFILL;
        parseXyParms(argc, argv, cmdlineP);
    } else if (reduce != -1) {
        cmdlineP->scaleType = SCALE_SEPARATE;
        parseFilespecOnlyParms(argc, argv, cmdlineP);
        cmdlineP->xscale = cmdlineP->yscale = 
            ((double) 1.0) / ((double) reduce);
        pm_message("reducing by %d gives scale factor of %f.", 
                   reduce, cmdlineP->xscale);
    } else if (pixels != -1) {
        cmdlineP->scaleType = SCALE_PIXELMAX;
        parseFilespecOnlyParms(argc, argv, cmdlineP);
        cmdlineP->pixels = pixels;
    } else if (xsize == -1 && xscale == -1 && ysize == -1 && yscale == -1
               && pixels == -1 && reduce == -1) {
        cmdlineP->scaleType = SCALE_SEPARATE;
        parseScaleParms(argc, argv, cmdlineP);
        cmdlineP->xsize = cmdlineP->ysize = 0;
    } else {
        cmdlineP->scaleType = SCALE_SEPARATE;
        parseFilespecOnlyParms(argc, argv, cmdlineP);
        cmdlineP->xsize = xsize == -1 ? 0 : xsize;
        cmdlineP->ysize = ysize == -1 ? 0 : ysize;
        cmdlineP->xscale = xscale == -1.0 ? 0.0 : xscale;
        cmdlineP->yscale = yscale == -1.0 ? 0.0 : yscale;
    }
}



static void 
compute_output_dimensions(struct cmdlineInfo  const cmdline, 
                          int                 const rows, 
                          int                 const cols, 
                          int *               const newrowsP, 
                          int *               const newcolsP) {

    switch(cmdline.scaleType) {
    case SCALE_PIXELMAX: {
        if (rows * cols <= cmdline.pixels) {
            *newrowsP = rows;
            *newcolsP = cols;
        } else {
            const double scale =
                sqrt( (float) cmdline.pixels / ((float) cols * (float) rows));
            *newrowsP = rows * scale;
            *newcolsP = cols * scale;
        }
    } break;
    case SCALE_BOXFIT:
    case SCALE_BOXFILL: {
        double const aspect_ratio = (float) cols / (float) rows;
        double const box_aspect_ratio = 
            (float) cmdline.xsize / (float) cmdline.ysize;
        
        if ((box_aspect_ratio > aspect_ratio && 
             cmdline.scaleType == SCALE_BOXFIT) ||
            (box_aspect_ratio < aspect_ratio &&
             cmdline.scaleType == SCALE_BOXFILL)) {
            *newrowsP = cmdline.ysize;
            *newcolsP = *newrowsP * aspect_ratio + 0.5;
        } else {
            *newcolsP = cmdline.xsize;
            *newrowsP = *newcolsP / aspect_ratio + 0.5;
        }
    } break;
    case SCALE_SEPARATE: {
        if (cmdline.xsize)
            *newcolsP = cmdline.xsize;
        else if (cmdline.xscale)
            *newcolsP = cmdline.xscale * cols + .5;
        else if (cmdline.ysize)
            *newcolsP = cols * ((float) cmdline.ysize/rows) +.5;
        else
            *newcolsP = cols;

        if (cmdline.ysize)
            *newrowsP = cmdline.ysize;
        else if (cmdline.yscale)
            *newrowsP = cmdline.yscale * rows +.5;
        else if (cmdline.xsize)
            *newrowsP = rows * ((float) cmdline.xsize/cols) +.5;
        else
            *newrowsP = rows;
    }
    }

    /* If the calculations above yielded (due to rounding) a zero 
     * dimension, we fudge it up to 1.  We do this rather than considering
     * it a specification error (and dying) because it's friendlier to 
     * automated processes that work on arbitrary input.  It saves them
     * having to check their numbers to avoid catastrophe.
     */
  
    if (*newcolsP < 1) *newcolsP = 1;
    if (*newrowsP < 1) *newrowsP = 1;
}




/****************************/
/****************************/
/******* resampling *********/
/****************************/
/****************************/

/* The resample code was inspired by Paul Heckbert's zoom program.
** http://www.cs.cmu.edu/~ph/zoom
*/

typedef struct {
    int    index;
    double weight;
} WEIGHT;

typedef struct {
    int    nWeight;
    WEIGHT *Weight;
} WLIST;

typedef struct {
    int y;
    tuple *tuplerow;
} SCANLINE;

typedef struct {
    int width;
    int height;
    SCANLINE *line;
} SCAN;



static int
appendWeight (WLIST *WList, int index, double weight)
{
    int n;
  
    if (weight == 0.0) 
        return 0;
  
    n=WList->nWeight;
  
    WList->Weight = realloc(WList->Weight, sizeof(*(WList->Weight))*(n+1));
    if (WList->Weight == NULL)
        pm_error ("appendWeight: realloc(%d) failed", 
                  sizeof(*(WList->Weight))*(n+1));
  
    WList->Weight[n].index  = index;
    WList->Weight[n].weight = weight;
    WList->nWeight++;
  
    return 0;
}



static sample
normalizedToSample(double const normalized,
                   sample const maxval) {

    return MAX(0, MIN(maxval, (sample)(normalized + 0.5)));
}



static void
createWeightList(unsigned int const targetPos,
                 unsigned int const sourceSize,
                 double       const scale,
                 double       const fscale,
                 double       const radius,
                 double       const filterRadius,
                 filterFunction_t   filterFunction,
                 filterFunction_t   windowFunction,
                 WLIST *      const weightListP) {
/*----------------------------------------------------------------------------
   Create a weight list for computing target pixel number 'targetPos' from
   a set of source pixels.  The weight list is a list of weights to give
   each source pixel in the set.
   
   The source pixel set is a window of source pixels whose size is
   determined by 'radius'.  The weights are defined by the function
   'filterFunction' of the position within the window, and normalized
   to add up to 1.0.

   For example, assume 'targetPos' is 5.  That means we're computing weights
   for either Column 5 or Row 5 of the target image.  Assume it's Column 5.
   Assume 'radius' is 1.  That means a window of two pixels' worth of a
   source row determines the color of the Column 5 pixel of a target
   row.  Assume 'filterFunction' is a triangle function -- 1 at 0, sloping
   down to 0 at -1 and 1.

   Now assume that the scale factor is 2 -- the target image will be
   twice the size of the source image.  That means the two-pixel-wide
   window of the source row that affects Column 5 of the target row
   (centered at target position 5.5) goes from position 1.75 to
   3.75, centered at 2.75.  That means the window covers 1/4 of
   Column 1, all of Column 2, and 3/4 of Column 3 of the source row.

   We want to calculate 3 weights, one to be applied to each source pixel
   in computing the target pixel.  Ideally, we would compute the average
   height of the filter function over each source pixel region.  But 
   that's too hard.  So we approximate by assuming that the filter function
   is constant within each region, at the value the function has at the
   _center_ of the region.

   So for the Column 1 region, which goes from 1.75 to 2.00, centered
   -.875 from the center of the window, we assume a constant function
   value of triangle(-.875), which equals .125.  For the 2.00-3.00
   region, we get triangle(-.25) = .75.  For the 3.00-3.75 region, we
   get triangle(.125) = .875.  So the weights for the 3 regions, which
   we get by multiplying this constant function value by the width of
   the region and normalizing so they add up to 1 are:

      Source Column 1:  .125*.25 / 1.4375 = .022
      Source Column 2:  .75*1.00 / 1.4375 = .521
      Source Column 3:  .875*.75 / 1.4375 = .457

   These are the weights we return.  Thus, if we assume that the source
   pixel 1 has value 10, source pixel 2 has value 20, and source pixel 3
   has value 30, Caller would compute target pixel 5's value as

      10*.022 + 20*.521 + 30*.457 = 24


   Actually, the filter function isn't exactly 'filterFunction'.
   That's the fundamental function, but we modify it with 'fscale' and
   'windowFunction':

   'fscale' is the amount by which we stretch the filter function
   horizontally.  In the example above, it is 1.0.  If it were 2.0 instead,
   then we would use the function f(x) = triangle(x/2.0), which is a
   function that slopes down to 0 at -2 and 2 instead of -1 and 1.

   'windowFunction' is a function we multiply by the fundamental
   filter function, after scaling horizontally according to
   'filterRadius' to fit it.  If 'windowFunction' is NULL, we don't
   do this multiplication.

-----------------------------------------------------------------------------*/
    /* 'windowCenter', is the continous position within the source of
       the center of the window that will influence target pixel
       'targetPos'.  'left' and 'right' are the edges of the window.
       'leftPixel' and 'rightPixel' are the pixel positions of the
       pixels at the edges of that window.  Note that if we're
       doing vertical weights, "left" and "right" mean top and
       bottom.  
    */
    double const windowCenter = ((double)targetPos + 0.5) / scale;
    double left = MAX(0.0, windowCenter - radius - EPSILON);
    unsigned int const leftPixel = floor(left);
    double right = MIN((double)sourceSize - EPSILON, 
                       windowCenter + radius + EPSILON);
    unsigned int const rightPixel = floor(right);

    double norm;
    unsigned int j;

    weightListP->nWeight = 0;
    weightListP->Weight = NULL;

    /* calculate weights */
    norm = 0.0;  /* initial value */

    for (j = leftPixel; j <= rightPixel; ++j) {
        /* Calculate the weight that source pixel 'j' will have in the 
           value of target pixel 'targetPos'.
        */
        double const regionLeft   = MIN(right, (double)(j + 1));
        double const regionRight  = MAX(left, (double)j);
        double const regionWidth  = regionRight - regionLeft;
        double const regionCenter = (regionRight + regionLeft) / 2;
        double const dist = regionCenter - windowCenter;
        double weight;
        weight = filterFunction(dist/fscale);
        if (windowFunction)
            weight *= windowFunction(dist/fscale/filterRadius);
        assert(regionWidth <= 1.0);
        weight *= regionWidth;
        norm += weight;
        appendWeight(weightListP, j, weight);
    }

    if (norm == 0.0)
        pm_error("INTERNAL ERROR: No source pixels contribute to target "
                 "pixel %u", targetPos);

    /* normalize the weights so they add up to 1.0 */
    if (norm != 1.0) {
        unsigned int n;
        for (n = 0; n < weightListP->nWeight; ++n) {
            weightListP->Weight[n].weight /= norm;
        }
    }
}



static void
createWeightListSet(unsigned int const sourceSize,
                    unsigned int const targetSize,
                    filterFunction_t   filterFunction,
                    double       const filterRadius,
                    filterFunction_t   windowFunction,
                    WLIST **     const weightListSetP) {
    
    double const scale = (double)targetSize / sourceSize;
    double const radius = filterRadius;
    double const fscale = 1.0;
    
    WLIST *weightListSet;  /* malloc'ed */
    int i;

    /* The original code from Michael Reinelt inflated the radius and
       fscale by 1/scale for scale < 1.0, thus changing this from a
       simple resample into a combination of that and averaging of
       pixels.  We don't do that because we want to keep things clean.
       Resample is resample.
       
       We should probably add some kind of option to cleanly formalize 
       and expose that mixture of resampling and averaging, because it
       appears to be a useful function.  
    */

    MALLOCARRAY_NOFAIL(weightListSet, targetSize);

    for (i = 0; i < targetSize; ++i)
        createWeightList(i, sourceSize, scale, fscale, radius, filterRadius,
                         filterFunction, windowFunction,
                         &weightListSet[i]);

    *weightListSetP = weightListSet;
}



static void
destroyWeightListSet(WLIST *      const weightListSet, 
                     unsigned int const size) {

    unsigned int i;

    for (i = 0; i < size; ++i)
        free(weightListSet[i].Weight);

    free(weightListSet);
}



static void
createScanBuf(struct pam * const pamP,
              double       const radius,
              bool         const verbose,
              SCAN *       const scanbufP) {

    SCAN scanbuf;
    unsigned int lineNumber;

    scanbuf.width = pamP->width;
    scanbuf.height = ceil(2.0*radius + 1e-7);
    MALLOCARRAY_NOFAIL(scanbuf.line, scanbuf.height);
  
    for (lineNumber = 0; lineNumber < scanbuf.height; ++lineNumber) {
        scanbuf.line[lineNumber].y = -1;
        scanbuf.line[lineNumber].tuplerow = pnm_allocpamrow(pamP);
    }
  
    if (verbose)
        pm_message ("scanline buffer: %d lines of %d pixels", 
                    scanbuf.height, scanbuf.width);

    *scanbufP = scanbuf;
}



static void
destroyScanbuf(SCAN const scanbuf) {

    unsigned int lineNumber;

    for (lineNumber = 0; lineNumber < scanbuf.height; ++lineNumber)
        pnm_freepamrow(scanbuf.line[lineNumber].tuplerow);

    free(scanbuf.line);
}



static void
resampleDimensionMessage(struct pam * const inpamP,
                         struct pam * const outpamP) {

    pm_message ("resampling from %d*%d to %d*%d (%f, %f)", 
                inpamP->width, inpamP->height, 
                outpamP->width, outpamP->height,
                (double)outpamP->width/inpamP->width, 
                (double)outpamP->height/inpamP->height);
}



static void
outputOneResampledRow(const struct pam * const outpamP,
                      SCAN               const scanbuf,
                      WLIST              const YW,
                      const WLIST *      const XWeight,
                      tuple *            const line,
                      double *           const weight) {
/*----------------------------------------------------------------------------
   From the data in 'scanbuf' and weights in 'YW' and 'XWeight', 
   generate one output row for the image described by *outpamP and
   output it.

   'line' and 'weight' are just working space that Caller provides us
   with to save us the time of allocating it.  'line' is at least big
   enough to hold an output row; 'weight' is at least outpamP->depth
   big.
-----------------------------------------------------------------------------*/
    unsigned int col;

    for (col = 0; col < outpamP->width; ++col) {
        WLIST const XW = XWeight[col];

        unsigned int i;
        {
            unsigned int plane;
            for (plane = 0; plane < outpamP->depth; ++plane)
                weight[plane] = 0.0;
        }
        
        for (i = 0; i < YW.nWeight; ++i) {
            int   const yp   = YW.Weight[i].index;
            float const yw   = YW.Weight[i].weight;
            int   const slot = yp % scanbuf.height;

            unsigned int j;
            
            for (j = 0; j < XW.nWeight; ++j) {
                int   const xp    = XW.Weight[j].index;
                float const xw    = XW.Weight[j].weight;
                tuple const tuple = scanbuf.line[slot].tuplerow[xp];
                
                unsigned int plane;
                
                for (plane = 0; plane < outpamP->depth; ++plane) {
                    weight[plane] += tuple[plane] * xw * yw;
                    line[col][plane] = 
                        normalizedToSample(weight[plane], outpamP->maxval);
                }                            
            }
        }
    }
    pnm_writepamrow(outpamP, line);
}



static void
resample(struct pam *     const inpamP,
         struct pam *     const outpamP,
         filterFunction_t const filterFunction,
         double           const filterRadius,
         filterFunction_t const windowFunction,
         bool             const verbose) {
/*---------------------------------------------------------------------------
  Resample the image in the input file, described by *inpamP,
  so as to create the image in the output file, described by *outpamP.
  
  Input and output differ by height, width, and maxval only.

  Use the resampling filter function 'filterFunction', applied over
  radius 'filterRadius'.
  
  The input file is positioned past the header, to the beginning of the
  raster.  The output file is too.
---------------------------------------------------------------------------*/
    int row_in, row_out;
    WLIST *XWeight;
    WLIST *YWeight;
    SCAN scanbuf;

    tuple * line;
        /* This is just work space for outputOneSampleRow() */
    double * weight;
        /* This is just work space for outputOneSampleRow() */
  
    createWeightListSet(inpamP->width, outpamP->width, 
                        filterFunction, filterRadius, 
                        windowFunction, &XWeight);
    
    createWeightListSet(inpamP->height, outpamP->height, 
                        filterFunction, filterRadius,
                        windowFunction, &YWeight);

    createScanBuf(inpamP, filterRadius, verbose, &scanbuf);

    if (verbose)
        resampleDimensionMessage(inpamP, outpamP);

    line = pnm_allocpamrow(outpamP);
    MALLOCARRAY_NOFAIL(weight, outpamP->depth);
    
    row_out = 0;
    for (row_in = 0; row_in < inpamP->height; ++row_in) {
        bool targetRowsReady;
        int slot;
    
        /* read source row */
        slot = row_in % scanbuf.height;
        scanbuf.line[slot].y = row_in;
        pnm_readpamrow(inpamP, scanbuf.line[slot].tuplerow);

        targetRowsReady = TRUE; /* initial assumption */
    
        /* check if target rows are ready */
        while (row_out < outpamP->height && targetRowsReady) {
            WLIST const YW = YWeight[row_out];

            unsigned int i;

            i = 0;

            while (i < YW.nWeight && targetRowsReady) {
                int const yp = YW.Weight[i].index;
                int const slot = yp % scanbuf.height;
                if (scanbuf.line[slot].y != yp)
                    targetRowsReady = FALSE;
                ++i;
            }
            if (targetRowsReady) {
                outputOneResampledRow(outpamP, scanbuf, YW, XWeight, 
                                      line, weight);
                ++row_out;
            }
        }
    }

    pnm_freepamrow(line);
    destroyScanbuf(scanbuf);
    destroyWeightListSet(XWeight, outpamP->width);
    destroyWeightListSet(YWeight, outpamP->height);
}


/****************************/
/****************************/
/**** end of resampling *****/
/****************************/
/****************************/



static void
zeroNewRow(struct pam * const pamP,
           tuplen *     const tuplenrow) {
    
    unsigned int col;

    for (col = 0; col < pamP->width; ++col) {
        unsigned int plane;

        for (plane = 0; plane < pamP->depth; ++plane)
            tuplenrow[col][plane] = 0.0;
    }
}



static void
accumOutputCol(struct pam * const pamP,
               tuplen       const intuplen,
               float        const fraction, 
               tuplen       const accumulator) {

    unsigned int plane;

    for (plane = 0; plane < pamP->depth; ++plane)
        accumulator[plane] += fraction * intuplen[plane];
}



static void
horizontal_scale(tuplen *     const inputtuplenrow, 
                 tuplen *     const newtuplenrow,
                 struct pam * const inpamP,
                 struct pam * const outpamP,
                 float        const xscale,
                 float *      const stretchP) {
/*----------------------------------------------------------------------------
  Take the input row 'inputtuplenrow', decribed by *inpamP, and scale
  it by a factor of 'xscale', to create the output row 'newtuplenrow',
  described by *outpamP.

  Assume maxval and depth of input and output are the same.
-----------------------------------------------------------------------------*/
    float fraccoltofill, fraccolleft;
    unsigned int col;
    unsigned int newcol;

    newcol = 0;
    fraccoltofill = 1.0;  /* Output column is "empty" now */

    zeroNewRow(outpamP, newtuplenrow);

    for (col = 0; col < inpamP->width; ++col) {
        /* Process one tuple from input ('inputtuplenrow') */
        fraccolleft = xscale;
        /* Output all columns, if any, that can be filled using information
           from this input column, in addition to what's already in the output
           column.
        */
        while (fraccolleft >= fraccoltofill) {
            /* Generate one output pixel in 'newtuplerow'.  It will
               consist of anything accumulated from prior input pixels
               in accumulator[], plus a fraction of the current input
               pixel.  
            */
            assert(newcol < outpamP->width);
            accumOutputCol(inpamP, inputtuplenrow[col], fraccoltofill,
                           newtuplenrow[newcol]);

            fraccolleft -= fraccoltofill;
            /* Set up to start filling next output column */
            ++newcol;
            fraccoltofill = 1.0;
        }
        /* There's not enough left in the current input pixel to fill up 
           a whole output column, so just accumulate the remainder of the
           pixel into the current output column.  Due to rounding, we may
           have a tiny bit of pixel left and have run out of output pixels.
           In that case, we throw away what's left.
        */
        if (fraccolleft > 0.0 && newcol < outpamP->width) {
            accumOutputCol(inpamP, inputtuplenrow[col], fraccolleft,
                           newtuplenrow[newcol]);
            fraccoltofill -= fraccolleft;
        }
    }

    if (newcol < outpamP->width-1 || newcol > outpamP->width)
        pm_error("Internal error: last column filled is %d, but %d "
                 "is the rightmost output column.",
                 newcol, outpamP->width-1);

    if (newcol < outpamP->width) {
        /* We were still working on the last output column when we 
           ran out of input columns.  This would be because of rounding
           down, and we should be missing only a tiny fraction of that
           last output column.
        */
        accumOutputCol(inpamP, inputtuplenrow[inpamP->width-1], 
                       fraccoltofill,
                       newtuplenrow[newcol]);
        
        *stretchP = fraccoltofill;
    } else 
        *stretchP = 0.0;
}



static void
zeroAccum(struct pam * const pamP,
          tuplen *     const accumulator) {

    unsigned int plane;

    for (plane = 0; plane < pamP->depth; ++plane) {
        unsigned int col;
        for (col = 0; col < pamP->width; ++col)
            accumulator[col][plane] = 0.0;
    }
}



static void
accumOutputRow(struct pam * const pamP,
               tuplen *     const tuplenrow, 
               float        const fraction, 
               tuplen *     const accumulator) {
/*----------------------------------------------------------------------------
   Take 'fraction' times the samples in row 'tuplenrow' and add it to 
   'accumulator'.

   'fraction' is less than 1.0.
-----------------------------------------------------------------------------*/
    unsigned int plane;

    for (plane = 0; plane < pamP->depth; ++plane) {
        unsigned int col;
        
        for (col = 0; col < pamP->width; ++col)
            accumulator[col][plane] += fraction * tuplenrow[col][plane];
    }
}



static void
readARow(struct pam *     const pamP,
         tuplen *         const tuplenRow,
         enum sampleScale const scale) {
/*----------------------------------------------------------------------------
  Read a row from the input file described by *pamP, as values
  proportional to light intensity.

  By contrast, libnetpbm provides only sample values that are
  gamma-corrected, which means they are almost proportional to
  subjective brightness, and not to light intensity.
-----------------------------------------------------------------------------*/
    pnm_readpamrown(pamP, tuplenRow);

    if (scale == INTENSITY_SAMPLE) {
        unsigned int col;
    
        for (col = 0; col < pamP->width; ++col) {
            unsigned int plane;
            for (plane = 0; plane < pamP->depth; ++plane)
                tuplenRow[col][plane] = pm_ungamma709(tuplenRow[col][plane]);
        }
    }
}



static void
writeARow(struct pam *     const pamP,
          tuplen *         const tuplenRow,
          enum sampleScale const scale) {
/*----------------------------------------------------------------------------
  Write a row to the output file described by *pamP, from values
  proportional to light intensity.

  By contrast, libnetpbm takes only sample values that are
  gamma-corrected, which means they are almost proportional to
  subjective brightness, and not to light intensity.

  We destroy *tuplenRow in the process.
-----------------------------------------------------------------------------*/
    if (scale == INTENSITY_SAMPLE) {
        unsigned int col;
    
        for (col = 0; col < pamP->width; ++col) {
            unsigned int plane;
            for (plane = 0; plane < pamP->depth; ++plane)
                tuplenRow[col][plane] = pm_gamma709(tuplenRow[col][plane]);
        }
    }
    pnm_writepamrown(pamP, tuplenRow);
}



static void
issueStretchWarning(bool   const verbose, 
                    double const fracrowtofill) {

    /* We need another input row to fill up this
       output row, but there aren't any more.
       That's because of rounding down on our
       scaling arithmetic.  So we go ahead with
       the data from the last row we read, which
       amounts to stretching out the last output
       row.  
    */
    if (verbose)
        pm_message("%f of bottom row stretched due to "
                   "arithmetic imprecision", 
                   fracrowtofill);
}



static void
scaleWithMixing(struct pam * const inpamP,
                struct pam * const outpamP,
                float        const xscale, 
                float        const yscale,
                bool         const assumeLinear,
                bool         const verbose) {
/*----------------------------------------------------------------------------
  Scale the image described by *inpamP by xscale horizontally and
  yscale vertically and write the result as the image described by
  *outpamP.

  The input file is positioned past the header, to the beginning of the
  raster.  The output file is too.

  Mix colors from input rows together in the output rows.

  'assumeLinear' means to assume that the sample values in the input
  image vary from standard PAM in that they are proportional to
  intensity, (This makes the computation a lot faster, so you might
  use this even if the samples are actually standard PAM, to get
  approximate but fast results).
-----------------------------------------------------------------------------*/
    /* Here's how we think of the color mixing scaling operation:  
       
       First, I'll describe scaling in one dimension.  Assume we have
       a one row image.  A raster row is ordinarily a sequence of
       discrete pixels which have no width and no distance between
       them -- only a sequence.  Instead, think of the raster row as a
       bunch of pixels 1 unit wide adjacent to each other.  For
       example, we are going to scale a 100 pixel row to a 150 pixel
       row.  Imagine placing the input row right above the output row
       and stretching it so it is the same size as the output row.  It
       still contains 100 pixels, but they are 1.5 units wide each.
       Our goal is to make the output row look as much as possible
       like the stretched input row, while observing that a pixel can
       be only one color.

       Output Pixel 0 is completely covered by Input Pixel 0, so we
       make Output Pixel 0 the same color as Input Pixel 0.  Output
       Pixel 1 is covered half by Input Pixel 0 and half by Input
       Pixel 1.  So we make Output Pixel 1 a 50/50 mix of Input Pixels
       0 and 1.  If you stand back far enough, input and output will
       look the same.

       This works for all scale factors, both scaling up and scaling down.
       
       This program always stretches or squeezes the input row to be the
       same length as the output row; The output row's pixels are always
       1 unit wide.

       The same thing works in the vertical direction.  We think of
       rows as stacked strips of 1 unit height.  We conceptually
       stretch the image vertically first (same process as above, but
       in place of a single-color pixels, we have a vector of colors).
       Then we take each row this vertical stretching generates and
       stretch it horizontally.  
    */
    enum sampleScale const sampleScale = 
        assumeLinear ? INTENSITY_SAMPLE : GAMMA_SAMPLE;

    tuplen * tuplenrow;     /* An input row */
    tuplen * newtuplenrow;  /* An output row */
    float rowsleft;
    /* The number of rows of output that need to be formed from the
       current input row (the one in tuplerow[]), less the number that 
       have already been formed (either in accumulator[]
       or output to the file).  This can be fractional because of the
       way we define rows as having height.
    */
    float fracrowtofill;
        /* The fraction of the current output row (the one in vertScaledRow[])
           that hasn't yet been filled in from an input row.
        */
    tuplen * rowAccumulator;
        /* The red, green, and blue color intensities so far accumulated
           from input rows for the current output row.  The ultimate value
           of this is an output row after vertical scaling, but before
           horizontal scaling.
        */
    int rowsread;
        /* Number of rows of the input file that have been read */
    int row;
    
    tuplenrow = pnm_allocpamrown(inpamP); 
    rowAccumulator = pnm_allocpamrown(inpamP);

    rowsread = 0;
    rowsleft = 0.0;
    fracrowtofill = 1.0;

    newtuplenrow = pnm_allocpamrown(outpamP);

    for (row = 0; row < outpamP->height; ++row) {
        /* First scale Y from tuplerow[] into rowAccumulator[]. */

        zeroAccum(inpamP, rowAccumulator);

        if (outpamP->height == inpamP->height) {
            /* shortcut Y scaling */
            readARow(inpamP, rowAccumulator, sampleScale);
        } else {
            while (fracrowtofill > 0) {
                if (rowsleft <= 0.0) {
                    if (rowsread < inpamP->height) {
                        readARow(inpamP, tuplenrow, sampleScale);
                        ++rowsread;
                    } else
                        issueStretchWarning(verbose, fracrowtofill);
                    rowsleft = yscale;
                }
                if (rowsleft < fracrowtofill) {
                    accumOutputRow(inpamP, tuplenrow, rowsleft, 
                                   rowAccumulator);
                    fracrowtofill -= rowsleft;
                    rowsleft = 0.0;
                } else {
                    accumOutputRow(inpamP, tuplenrow, fracrowtofill, 
                                   rowAccumulator);
                    rowsleft = rowsleft - fracrowtofill;
                    fracrowtofill = 0.0;
                }
            }
            fracrowtofill = 1.0;
        }
        /* 'rowAccumulator' now contains the contents of a single
           output row, but not yet horizontally scaled.  Scale it now
           horizontally into 'newtuplenrow' and write it out.
        */

        if (outpamP->width == inpamP->width)    
            /* shortcut X scaling */
            writeARow(outpamP, rowAccumulator, sampleScale);
                /* This destroys 'rowAccumulator' */
        else {
            float stretch;
            
            horizontal_scale(rowAccumulator, newtuplenrow, inpamP, outpamP,
                             xscale, &stretch);
            
            if (verbose && row == 0)
                pm_message("%f of right column stretched due to "
                           "arithmetic imprecision", 
                           stretch);
            
            writeARow(outpamP, newtuplenrow, sampleScale);
                /* This destroys 'newtuplenrow' */
        }
    }
    pnm_freepamrown(rowAccumulator);
    pnm_freepamrown(newtuplenrow);
    pnm_freepamrown(tuplenrow);
}



static void
scaleWithoutMixing(const struct pam * const inpamP,
                   const struct pam * const outpamP,
                   float              const xscale, 
                   float              const yscale) {
/*----------------------------------------------------------------------------
  Scale the image described by *inpamP by xscale horizontally and
  yscale vertically and write the result as the image described by
  *outpamP.

  The input file is positioned past the header, to the beginning of the
  raster.  The output file is too.
  
  Don't mix colors from different input pixels together in the output
  pixels.  Each output pixel is an exact copy of some corresponding 
  input pixel.
-----------------------------------------------------------------------------*/
    tuple * tuplerow;  /* An input row */
    tuple * newtuplerow;
    int row;
    int rowInInput;

    tuplerow = pnm_allocpamrow(inpamP); 
    rowInInput = -1;

    newtuplerow = pnm_allocpamrow(outpamP);

    for (row = 0; row < outpamP->height; ++row) {
        int col;
        
        int const inputRow = (int) (row / yscale);

        for (; rowInInput < inputRow; ++rowInInput) 
            pnm_readpamrow(inpamP, tuplerow);
        
        for (col = 0; col < outpamP->width; ++col) {
            int const inputCol = (int) (col / xscale);
            
            pnm_assigntuple(inpamP, newtuplerow[col], tuplerow[inputCol]);
        }

        pnm_writepamrow(outpamP, newtuplerow);
    }
    pnm_freepamrow(tuplerow);
    pnm_freepamrow(newtuplerow);
}



int
main(int argc, char **argv ) {

    struct cmdlineInfo cmdline;
    FILE* ifP;
    struct pam inpam, outpam;
    float xscale, yscale;

    pnm_init(&argc, argv);

    parseCommandLine(argc, argv, &cmdline);

    ifP = pm_openr(cmdline.input_filespec);

    pnm_readpaminit(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));

    outpam = inpam;  /* initial value */
    outpam.file = stdout;

    if (PNM_FORMAT_TYPE(inpam.format) == PBM_TYPE) {
        outpam.format = PGM_TYPE;
        outpam.maxval = PGM_MAXMAXVAL;
        pm_message("promoting from PBM to PGM");
    } else {
        outpam.format = inpam.format;
        outpam.maxval = inpam.maxval;
    }

    compute_output_dimensions(cmdline, inpam.height, inpam.width,
                              &outpam.height, &outpam.width);

    xscale = (float) outpam.width / inpam.width;
    yscale = (float) outpam.height / inpam.height;

    if (cmdline.verbose) {
        pm_message("Scaling by %f horizontally to %d columns.", 
                   xscale, outpam.width);
        pm_message("Scaling by %f vertically to %d rows.", 
                   yscale, outpam.height);
    }

    if (xscale * inpam.width < outpam.width - 1 ||
        yscale * inpam.height < outpam.height - 1) 
        pm_error("Arithmetic precision of this program is inadequate to "
                 "do the specified scaling.  Use a smaller input image "
                 "or a slightly different scale factor.");

    pnm_writepaminit(&outpam);

    if (cmdline.nomix) {
        if (cmdline.verbose)
            pm_message("Using nomix method");
        scaleWithoutMixing(&inpam, &outpam, xscale, yscale);
    } else if (!cmdline.filterFunction) {
        if (cmdline.verbose)
            pm_message("Using regular rescaling method");
        scaleWithMixing(&inpam, &outpam, xscale, yscale, 
                        cmdline.linear, cmdline.verbose);
    } else {
        if (cmdline.verbose)
            pm_message("Using general filter method");
        resample(&inpam, &outpam,
                 cmdline.filterFunction, cmdline.filterRadius,
                 cmdline.windowFunction, cmdline.verbose);
    }
    pm_close(ifP);
    pm_close(stdout);
    
    exit(0);
}
