/* pnmflip.c - perform one or more flip operations on a portable anymap
**
** Copyright (C) 1989 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.
*/

/* 
   There is some fancy virtual memory management in this program to avoid
   page thrashing when you flip a large image in a columns-for-rows
   way (e.g. -transpose).
   
   The page thrashing we're trying to avoid could happen because the
   output of the transformation is stored in an array of xels in
   virtual memory.  An xel array is stored in column-first order,
   meaning that all the columns of particular row are contiguous, the
   next row is next to that, etc.  If you fill up that array by
   filling in Column 0 sequentially in every row from top to bottom,
   you will touch a lot of different virtual memory pages, and every
   one has to be paged in as you touch it.

   If the number of virtual memory pages you touch exceeds the amount
   of real memory the process can get, then by the time you hit the bottom
   of the xel array, the pages that hold the top are already paged out.
   So if you go back and do Column 1 from top to bottom, you will again
   touch lots of pages and have to page in every one of them.  Do this 
   for 100 columns, and you might page in every page in the array 100 times
   each, putting a few bytes in the page each time.

   That is very expensive.  Instead, you'd like to keep the same pages in
   real memory as long as possible and fill them up as much as you can 
   before paging them out and working on a new set of pages.  You can do
   that by doing Column 0 from top to say Row 10, then Column 1 from top
   to Row 10, etc. all the way across the image.  Assuming 10 rows fits
   in real memory, you will keep the virtual memory for the first 10 rows
   of the xel array in real memory until you've filled them in completely.
   Now you go back and do Column 0 from Row 11 to Row 20, then Column 1
   from Row 11 to Row 20, and so on.

   So why are we even trying to fill in column by column instead of just
   filling in row by row?  Because we're reading an input image row by row
   and transforming it in such a way that a row of the input becomes
   a column of the output.  In order to fill in a whole row of the output,
   we'd have to read a whole column of the input, and then we have the same
   page thrashing problem in the input.

   So the optimal procedure is to do N output rows in each pass, where
   N is the largest number of rows we can fit in real memory.  In each
   pass, we read certain columns of every row of the input and output
   every column of certain rows of the output.  The output rows get
   paged in once per pass and stay in real memory throughout the pass.
   Note that every page of the input gets paged in in each pass too.

*/

#include <limits.h>
#include "pnm.h"
#include "shhopt.h"

enum flipType {LEFTRIGHT, TOPBOTTOM, TRANSPOSE, ROT90, ROT180, ROT270};

struct cmdlineInfo {
    /* All the information the user supplied in the command line,
       in a form easy for the program to use.
    */
    const char *inputFilespec;  /* Filespec of input file */
    enum flipType flipType;
    unsigned int availableMemory;
    unsigned int pageSize;
    unsigned int verbose;
};



static void
parseCommandLine(int argc, char ** const argv,
                 struct cmdlineInfo * const cmdlineP) {
/*----------------------------------------------------------------------------
   Note that the file spec array we return is stored in the storage that
   was passed to us as the argv array.
-----------------------------------------------------------------------------*/
    optEntry *option_def = malloc(100*sizeof(optEntry));
        /* Instructions to OptParseOptions3 on how to parse our options.
         */
    optStruct3 opt;

    unsigned int option_def_index;

    unsigned int lr, tb, xy, r90, r270, r180;
    unsigned int memsizeSpec, pagesizeSpec;
    unsigned int memsizeOpt;

    option_def_index = 0;   /* incremented by OPTENTRY */
    OPTENT3(0, "lr",        OPT_FLAG,    NULL, &lr,      0);
    OPTENT3(0, "leftright", OPT_FLAG,    NULL, &lr,      0);
    OPTENT3(0, "tb",        OPT_FLAG,    NULL, &tb,      0);
    OPTENT3(0, "topbottom", OPT_FLAG,    NULL, &tb,      0);
    OPTENT3(0, "xy",        OPT_FLAG,    NULL, &xy,      0);
    OPTENT3(0, "transpose", OPT_FLAG,    NULL, &xy,      0);
    OPTENT3(0, "r90",       OPT_FLAG,    NULL, &r90,     0);
    OPTENT3(0, "rotate90",  OPT_FLAG,    NULL, &r90,     0);
    OPTENT3(0, "ccw",       OPT_FLAG,    NULL, &r90,     0);
    OPTENT3(0, "r180",      OPT_FLAG,    NULL, &r180,    0);
    OPTENT3(0, "rotate180", OPT_FLAG,    NULL, &r180,    0);
    OPTENT3(0, "r270",      OPT_FLAG,    NULL, &r270,    0);
    OPTENT3(0, "rotate270", OPT_FLAG,    NULL, &r270,    0);
    OPTENT3(0, "cw",        OPT_FLAG,    NULL, &r270,    0);
    OPTENT3(0, "verbose",   OPT_FLAG,    NULL, &cmdlineP->verbose,       0);
    OPTENT3(0, "memsize",   OPT_UINT,    &memsizeOpt, 
            &memsizeSpec,       0);
    OPTENT3(0, "pagesize",  OPT_UINT,    &cmdlineP->pageSize,
            &pagesizeSpec,      0);

    opt.opt_table = option_def;
    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
    opt.allowNegNum = FALSE;  /* We don't parms that are negative numbers */

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

    if (lr + tb + xy + r90 + r180 + r270 > 1)
        pm_error("You may specify only one type of flip.");

    if (lr)
        cmdlineP->flipType = LEFTRIGHT;
    else if (tb)
        cmdlineP->flipType = TOPBOTTOM;
    else if (xy)
        cmdlineP->flipType = TRANSPOSE;
    else if (r90)
        cmdlineP->flipType = ROT90;
    else if (r180)
        cmdlineP->flipType = ROT180;
    else if (r270)
        cmdlineP->flipType = ROT270;
    else
        pm_error("You must specify an option such as -topbottom to indicate "
                 "what kind of flip you want.");

    if (memsizeSpec) {
        if (memsizeOpt > UINT_MAX / 1024 / 1024)
            pm_error("-memsize value too large: %u MiB.  Maximum this program "
                     "can handle is %u MiB", 
                     memsizeOpt, UINT_MAX / 1024 / 1024);
        cmdlineP->availableMemory = memsizeOpt * 1024 *1024;
    } else
        cmdlineP->availableMemory = UINT_MAX;

    if (!pagesizeSpec)
        cmdlineP->pageSize = 4*1024;         

    if (argc-1 == 0) 
        cmdlineP->inputFilespec = "-";
    else if (argc-1 != 1)
        pm_error("Program takes zero or one argument (filename).  You "
                 "specified %d", argc-1);
    else
        cmdlineP->inputFilespec = argv[1];
}



struct xformMatrix {
    int a;
    int b;
    int c;
    int d;
    int e;
    int f;
};



static void
leftright(struct xformMatrix * const xformP) {
    xformP->a = - xformP->a;
    xformP->c = - xformP->c;
    xformP->e = - xformP->e + 1;
}



static void
topbottom(struct xformMatrix * const xformP) {
    xformP->b = - xformP->b;
    xformP->d = - xformP->d;
    xformP->f = - xformP->f + 1;
}



static void
swap(int * const xP, int * const yP) {

    int const t = *xP;

    *xP = *yP;
    *yP = t;
}



static void
transpose(struct xformMatrix * const xformP) {
    swap(&xformP->a, &xformP->b);
    swap(&xformP->c, &xformP->d);
    swap(&xformP->e, &xformP->f);
}



static void
computeXformMatrix(struct xformMatrix * const xformP, 
                   enum flipType        const flipType) {

    struct xformMatrix const nullTransform = {1, 0, 0, 1, 0, 0};

    *xformP = nullTransform;   /* initial value */

    switch (flipType) {
    case LEFTRIGHT: 
        leftright(xformP);
        break;
    case TOPBOTTOM:
        topbottom(xformP);
        break;
    case TRANSPOSE:
        transpose(xformP);
        break;
    case ROT90:
        transpose(xformP);
        topbottom(xformP);
        break;
    case ROT180:
        leftright(xformP);
        topbottom(xformP);
        break;
    case ROT270:
        transpose(xformP);
        leftright(xformP);
        break;
    }
}



static void
transformRowByRow( FILE * const ifP, int const rows, int const cols, 
                   int const newrows, int const newcols, xelval const maxval,
                   int const format, struct xformMatrix const xform ) {
    xel* xelrow;
    xel* newxelrow;
    int row;
    
    xelrow = pnm_allocrow( cols );
    newxelrow = pnm_allocrow( newcols );
    pnm_writepnminit( stdout, newcols, newrows, maxval, format, 0 );
    
    for ( row = 0; row < rows; ++row ) {
        int col;
        pnm_readpnmrow( ifP, xelrow, cols, maxval, format );
        for ( col = 0; col < cols; ++col ) {
            /* Transform a point:
            **
            **            [ a b 0 ]
            **  [ x y 1 ] [ c d 0 ] = [ x2 y2 1 ]
            **            [ e f 1 ]
            */
            int const newcol = xform.a * col + xform.c * row + 
                xform.e * ( newcols - 1 );
            newxelrow[newcol] = xelrow[col];
        }
        pnm_writepnmrow( stdout, newxelrow, newcols, maxval, format, 0 );
    }
    pnm_freerow( xelrow );
    pnm_freerow( newxelrow );
}



static void __inline__
transformPoint( int const col, int const newcols,
                int const row, int const newrows, 
                struct xformMatrix const xform, 
                int * const newcolP, int * const newrowP ) {
    /* Transform a point:
    **
    **            [ a b 0 ]
    **  [ x y 1 ] [ c d 0 ] = [ x2 y2 1 ]
    **            [ e f 1 ]
    */
    *newcolP = xform.a * col + xform.c * row + 
        xform.e * ( newcols - 1 );
    *newrowP = xform.b * col + xform.d * row + 
        xform.f * ( newrows - 1 );
}



static unsigned int 
optimalSegmentSize(struct xformMatrix  const xform, 
                   int                 const outputCols,
                   int                 const format,
                   unsigned int        const availableMemory,
                   unsigned int        const pageSize) {
/*----------------------------------------------------------------------------
   Compute the maximum number of columns that can be transformed, one row
   at a time, without causing page thrashing.

   See comments at the top of this file for an explanation of the kind
   of page thrashing using segments avoids.

   'availableMemory' is the amount of real memory in bytes that this
   process should expect to be able to use.

   'pageSize' is the size of a page in bytes.  A page means the unit that
   is paged in or out.
   
   'outputCols' is the number of columns in each row of the output array.

   'format' is the format of the output array (PPM, etc.).
-----------------------------------------------------------------------------*/
    unsigned int segmentSize;

    if (xform.b == 0)
        segmentSize = UINT_MAX;
    else {
        unsigned int const otherNeeds = 200*1024;
            /* A wild guess at how much real memory is needed by the program
               for purposes other than the output xel array.
            */
        if (otherNeeds > availableMemory)
            segmentSize = UINT_MAX;  /* Can't prevent thrashing */
        else {
            unsigned int const availablePages = 
                (availableMemory - otherNeeds) / pageSize;
            if (availablePages <= 1)
                segmentSize = UINT_MAX; /* Can't prevent thrashing */
            else {
                unsigned int bytesPerXel = 
                    PNM_FORMAT_TYPE(format) == PBM_TYPE ? 1 : sizeof(xelval)*3;
                unsigned int const bytesPerRow = 
                    outputCols * bytesPerXel;
                unsigned int rowsPerPage = 
                    MAX(1, (pageSize + (pageSize/2)) / bytesPerRow);
                    /* This is how many consecutive rows we can touch
                       on average while staying within the same page.  
                    */
                segmentSize = availablePages * rowsPerPage;
            }
        }
    }    
    return segmentSize;
}



static void
transformNonPbm( FILE * const ifP, 
                 int const rows, int const cols,
                 int const newrows, int const newcols, 
                 xelval const maxval, int const format, 
                 struct xformMatrix const xform,
                 unsigned int const segmentSize,
                 bool const verbose) {
/*----------------------------------------------------------------------------
  Do the transform using "pnm" library functions, as oppose to "pbm"
  ones.

  Assume input file is positioned to the raster (just after the
  header).

  'segmentSize' is the number of columns we are to process in each
  pass.  We do each segment going from left to right.  For each
  segment, we do each row, going from top to bottom.  For each row of
  the segment, we do each column, going from left to right.  (The
  reason Caller wants it done by segments is to improve virtual memory
  reference locality.  See comments at the top of this file).

  if 'segmentSize' is less than the whole image, ifP must be a seekable
  file.
-----------------------------------------------------------------------------*/
    int imagepos;
        /* The input file position of the raster.  But defined only if
           segment size is less than whole image.
        */
    xel* xelrow;
    xel** newxels;
    unsigned int startCol;

    xelrow = pnm_allocrow( cols );
    newxels = pnm_allocarray( newcols, newrows );
    
    if (segmentSize < cols)
        imagepos = pm_tell(ifP);

    for (startCol = 0; startCol < cols; startCol += segmentSize) {
        /* Do one set of columns which is small enough not to cause
           page thrashing.
        */
        unsigned int const endCol = MIN(cols, startCol + segmentSize);
        unsigned int row;

        if (verbose)
            pm_message("Transforming Columns %u up to %u", 
                       startCol, endCol);

        if (startCol > 0)
            /* Go back to read from Row 0 again */
            pm_seek(ifP, imagepos);

        for (row = 0; row < rows; ++row) {
            unsigned int col;
            pnm_readpnmrow(ifP, xelrow, cols, maxval, format);

            for (col = startCol; col < endCol; ++col) {
                int newcol, newrow;
                transformPoint(col, newcols, row, newrows, xform,
                               &newcol, &newrow);
                newxels[newrow][newcol] = xelrow[col];
            }
        }
    }
    
    pnm_writepnm(stdout, newxels, newcols, newrows, maxval, format, 0);
    
    pnm_freearray(newxels, newrows);
    pnm_freerow(xelrow);
}



static void
transformPbm(FILE * const ifP, int const rows, int const cols, 
             int const newrows, int const newcols, int const format,
             struct xformMatrix const xform) { 
/*----------------------------------------------------------------------------
   This is the same as transformNonPbm, except that it uses less 
   memory, since the PBM buffer format uses one bit per pixel instead
   of twelve bytes
-----------------------------------------------------------------------------*/
    bit* bitrow;
    bit** newbits;
    int row;
            
    bitrow = pbm_allocrow(cols);
    newbits = pbm_allocarray(pbm_packed_bytes(newcols), newrows);
            
    /* Initialize entire array to zeroes.  One bits will be or'ed in later */
    for (row = 0; row < newrows; ++row) {
        int col;
        for (col = 0; col < pbm_packed_bytes(newcols); ++col) 
             newbits[row][col] = 0; 
    }
     
    for (row = 0; row < rows; ++row) {
        int col;
        pbm_readpbmrow( ifP, bitrow, cols, format );
        for (col = 0; col < cols; ++col) {
            int newcol, newrow;
            transformPoint(col, newcols, row, newrows, xform,
                           &newcol, &newrow);
            newbits[newrow][newcol/8] |= bitrow[col] << (7 - newcol % 8);
                /* Use of "|=" patterned after pbm_readpbmrow_packed. */
         }
    }
    
    pbm_writepbminit(stdout, newcols, newrows, 0);
    for (row = 0; row < newrows; ++row)
        pbm_writepbmrow_packed(stdout, newbits[row], newcols, 0);
    
    pbm_freearray(newbits, newrows);
    pbm_freerow(bitrow);
}



int
main(int argc, char * argv[]) {
    struct cmdlineInfo cmdline;
    FILE* ifP;
    int cols, rows, format, newrows, newcols;
    xelval maxval;
    struct xformMatrix xform;

    pnm_init(&argc, argv);

    parseCommandLine(argc, argv, &cmdline);

    if (cmdline.availableMemory < UINT_MAX)
        ifP = pm_openr_seekable(cmdline.inputFilespec);
    else
        ifP = pm_openr(cmdline.inputFilespec);
    
    pnm_readpnminit(ifP, &cols, &rows, &maxval, &format);

    computeXformMatrix(&xform, cmdline.flipType);

    newcols = abs(xform.a) * cols + abs(xform.c) * rows;
    newrows = abs(xform.b) * cols + abs(xform.d) * rows;
    
    if (xform.b == 0 && xform.d == 1 && xform.f == 0) {
        /* In this case newrow is always equal to row, so we can do the
        ** transform line by line and avoid in-memory buffering altogether.
        */
        if (cmdline.verbose)
            pm_message("Transforming row by row");
        transformRowByRow(ifP, rows, cols, newrows, newcols, maxval, 
                          format, xform);
	} else {
        unsigned int const segmentSize = 
            optimalSegmentSize(xform, newcols, format, 
                               cmdline.availableMemory, cmdline.pageSize);
    
        if (cmdline.verbose) {
            if (segmentSize < newcols)
                pm_message("Transforming %u columns of %u total at a time", 
                           segmentSize, newcols);
            else
                pm_message("Transforming entire image at once");
        }

        /* Generic case.  Read in the anymap a line at a time and transform
        ** it into an in-memory array.
        */
        switch (PNM_FORMAT_TYPE(format)) {
        case PBM_TYPE: 
            transformPbm(ifP, rows, cols, newrows, newcols, format, xform);
            break;
        default:
            transformNonPbm(ifP, rows, cols, newrows, newcols, maxval,
                            format, xform, segmentSize, cmdline.verbose);
            break;
        }
	}
    
    pm_close(ifP);
    pm_close(stdout);
    
    exit(0);
}

