/*
 * -------------------------------------------------------------
 *
 *  (C) 2002 Jochen Karrer, Linuxdata GbR
 *
 *      convert a pnm to PCL-XL image 
 *
 * -------------------------------------------------------------
 */

/* Engineering note: One PCL-XL printer prints an error message like
   this when it doesn't like the PCL it sees:

   PCL XL error
      Subsystem:  IMAGE
      Error:      IllegalAttributeValue
      Operator:   ReadImage
      Position:   8

   "Position" is the sequence number of the PCL operator it was trying
   to execute.
*/

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <ctype.h>

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

enum MediaSize {
    eLetterPaper,
    eLegalPaper,
    eA4Paper,
    eExecPaper,
    eLedgerPaper,
    eA3Paper,
    eCOM10Envelope,
    eMonarchEnvelope,
    eC5Envelope,
    eDLEnvelope,
    eJB4Paper,
    eJB5Paper,
    etralala,
    eB5Envelope,
    eJPostcard,
    eJDoublePostcard,
    eA5Paper,
    eA6Paper,
    eJB6Paper
};

enum DuplexPageMode {
    eDuplexHorizontalBinding,
    eDuplexVerticalBinding
}; 

struct sPaperFormat {
    const char *name;
    int xl_nr;
    float width,height; /* inch */
} xlPaperFormats[] = {
    {"letter",eLetterPaper,8.5,11.0},
    {"legal",eLegalPaper,8.5,14},
    {"a4",eA4Paper,8.26389,11.6944},
    {"exec",eExecPaper,190/2.54,254/2.54},
    {"ledger",eLedgerPaper,279/2.54,432/2.54},
    {"a3",eA3Paper,11.6944,16.5278},
    {"com10envelope",eCOM10Envelope,105/2.54,241/2.54},
    {"monarchenvelope",eMonarchEnvelope,98/2.54,191/2.54},
    {"c5envelope",eC5Envelope,162/2.54,229/2.54},
    {"dlenvelope",eDLEnvelope,110/2.54,220/2.54},
    {"jb4",eJB4Paper,257/2.54,364/2.54},
    {"jb5",eJB5Paper,182/2.54,257/2.54},
    {"b5envelope",eB5Envelope,176/2.54,250/2.54},
    {"",-1,0,0},
    {"jpostcard",eJPostcard,148/2.54,200/2.54},
    {"jdoublepostcard",eJDoublePostcard,100/2.54,148/2.54},
    {"a5",eA5Paper, 5.84722,8.26389},
    {"a6",eA6Paper,4.125,5.84722},
    {"jb6",eJB6Paper,0,0},
    {NULL,0,0,0}
};
#define PAPERWIDTH(format) (xlPaperFormats[format].width)
#define PAPERHEIGHT(format) (xlPaperFormats[format].height)



typedef struct InputSource {
    const char *name; 
    struct InputSource *next;   
}InputSource;



struct cmdlineInfo {
    /* All the information the user supplied in the command line,
       in a form easy for the program to use.
    */
    InputSource * sourceP;
    int dpi;
    enum MediaSize format;
    unsigned int feederSpec;
    int feeder;
    unsigned int outtraySpec;
    int outtray;
    unsigned int duplexSpec;
    enum DuplexPageMode duplex;
    unsigned int copiesSpec;
    int copies;
    unsigned int center;
    float xoffs;
    float yoffs;
    unsigned int colorok;
    unsigned int verbose;
};



static void
parseCommandLine ( int argc, char ** argv,
                   struct cmdlineInfo *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;

    char *formatOpt;
    char *duplexOpt;
    unsigned int dpiSpec, xoffsSpec, yoffsSpec, formatSpec;

    option_def_index = 0;   /* incremented by OPTENT3 */
    OPTENT3(0, "dpi",       OPT_UINT,    &cmdlineP->dpi,
            &dpiSpec,         0);
    OPTENT3(0, "xoffs",     OPT_FLOAT,   &cmdlineP->xoffs, 
            &xoffsSpec,        0);
    OPTENT3(0, "yoffs",     OPT_FLOAT,   &cmdlineP->yoffs, 
            &yoffsSpec,        0);
    OPTENT3(0, "format",    OPT_STRING,  &formatOpt, 
            &formatSpec,        0);
    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,                  
            &cmdlineP->colorok, 0);
    OPTENT3(0, "center",    OPT_FLAG,    NULL,                  
            &cmdlineP->center, 0 );
    OPTENT3(0, "feeder",    OPT_STRING,  &cmdlineP->feeder,
            &cmdlineP->feederSpec,        0);
    OPTENT3(0, "outtray",   OPT_STRING,  &cmdlineP->outtray,
            &cmdlineP->outtraySpec,       0);
    OPTENT3(0, "verbose",   OPT_FLAG,    NULL,                  
            &cmdlineP->verbose, 0);

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

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

    if (!dpiSpec)
        cmdlineP->dpi = 300;
    if (!xoffsSpec)
        cmdlineP->xoffs = 0.0;
    if (!yoffsSpec)
        cmdlineP->yoffs = 0.0;

    if (cmdlineP->duplexSpec) {
        if (strncmp(duplexOpt, "vertical", strlen(duplexOpt)) == 0)
            cmdlineP->duplex = eDuplexVerticalBinding;
        else if (strncmp(duplexOpt, "horizontal", strlen(duplexOpt)) == 0)
            cmdlineP->duplex = eDuplexHorizontalBinding;
        else
            pm_error("Invalid value '%s' for -duplex option", duplexOpt);
    }

    if (formatSpec) {
        bool found;
        int i;
        for (i = 0, found=FALSE; xlPaperFormats[i].name && !found; ++i) {
            if (strcmp(xlPaperFormats[i].name, formatOpt) == 0) {
                found = TRUE;
                cmdlineP->format = xlPaperFormats[i].xl_nr;
            }
        }
        if (!found) {
            int i;
            pm_message("Valid -format values:");
            for (i = 0; xlPaperFormats[i].name; ++i) {
                if (xlPaperFormats[i].width > 0)
                    pm_message("   %s", xlPaperFormats[i].name);
            }
            pm_error("Invalid -format option '%s' specified.", formatOpt);
        }
    } else
        cmdlineP->format = eLetterPaper;

    if (argc-1 < 1) {
        MALLOCVAR(cmdlineP->sourceP);
        cmdlineP->sourceP->name = "-";
    } else {
        int i;
        InputSource ** nextLinkP;

        nextLinkP = &cmdlineP->sourceP;
        for (i = 1; i < argc; ++i) {
            InputSource * sourceP;
            MALLOCVAR(sourceP);
            sourceP->name = argv[i];
            *nextLinkP = sourceP;
            nextLinkP = &sourceP->next;
            *nextLinkP = NULL;
        }
    }
}



#define XY_RLE_FBUFSIZE (1024)
typedef struct XY_rle {
    int error;
    unsigned char buf[128];
    int bpos;
    int state;  
    unsigned char *fbuf;
    int fbpos;
    int fbufsize;
    int fd;
} XY_rle;


enum {
    eSTART,
    eRLE,
    eLIT 
} RLEstates;

static void 
XY_RLEreset(XY_rle *rle) 
{   
    rle->state = eSTART;
    rle->bpos = 0;
    rle->fbpos=0;
    rle->error=0;
}
static XY_rle * 
XY_RLEnew(int size) {
    XY_rle *rle;

    MALLOCVAR(rle);
    if(rle==NULL)
        return rle;
    if(size<1024)
        size=1024;
    rle->fbuf=malloc(size);
    rle->fbufsize=size;
    if(!rle->fbuf) {
        free(rle);
        return NULL;
    }
    return rle;
}
static void
XY_RLEdelete(XY_rle *rle) {
    free(rle->fbuf);
    free(rle);
}

static int 
out(XY_rle *rle,int count) {
    if(rle->state==eRLE) {
        rle->fbuf[rle->fbpos++]=-count+1;
        rle->fbuf[rle->fbpos++]=rle->buf[0];
    } else if(rle->bpos>0) {
        rle->fbuf[rle->fbpos++]=count-1;
        memcpy(rle->fbuf+rle->fbpos,rle->buf,count);
        rle->fbpos+=count;
    }
    if(rle->fbpos+129>rle->fbufsize) {
        rle->fbufsize*=1.2; 
        rle->fbuf=realloc(rle->fbuf,rle->fbufsize);
        if(rle->fbuf==NULL) {
            rle->error=-1;
            rle->fbpos=0;
            return -1;
        }
    }
    rle->bpos=0;
    rle->state=eSTART;
    return 0;
}
static int
XY_RLEfinish (XY_rle *rle) {
    out(rle,rle->bpos);
    if(rle->error<0) 
        return rle->error;
    else
        return rle->fbpos;
}
static  void
rle_putbyte(XY_rle *rle,unsigned char u) 
{
    switch (rle->state) {
        case eRLE:
            if(u!=rle->buf[0]) {
                out(rle,rle->bpos);
            }   
            break;
        case eLIT:
            if((u==rle->buf[rle->bpos-1])&&(u==rle->buf[rle->bpos-2])) {
                out(rle,rle->bpos-2);
                rle->buf[0]=u;
                rle->bpos+=2;
                rle->state=eRLE;
            }   
            break;
        case eSTART:
            if(rle->bpos==1) {
                if(u==rle->buf[rle->bpos-1]) {
                    rle->state=eRLE;
                } else {
                    rle->state=eLIT;
                }   
            }
            break;
    
    }
    rle->buf[rle->bpos++]=u;
    if(rle->bpos==128) {
        out(rle,rle->bpos);
    }
}



static void
XY_RLEput(XY_rle *rle,const unsigned char buf[],int count) 
{
    int i;
    for(i=0;i<count;i++) {
        rle_putbyte(rle,buf[i]);
    }
    
}


static int
XY_Write(int fd, const void *buf,int cnt) {
        int len=0;
        while(len<cnt) {
                int n = write(fd,(char*)buf+len,cnt-len);
                if(n<=0)
                        return n;
                len+=n;
        }
        return len;
}
#define XY_Puts(fd,str)  XY_Write(fd,str,strlen(str))

enum ArcDirection {
    eClockWise,
    eCounterClockWise
};

enum CharSubModeArray {
    eNoSubstitution,
    eVerticalSubstitution
};

enum ClipRegion {
    eInterior,
    eExterior
};

enum ColorDepth {
    e1Bit,
    e4Bit,
    e8Bit
};

enum ColrMapping {
    eDirectPixel,
    eIndexedPixel
};

enum Colorspace {
    eGray=1,
    eRGB=2
};

enum Compression {
    eNoCompression,
    eRLECompression,
    eJPEGCompression
};

enum DataOrg {
    eBinaryHighByteFirst,
    eBinaryLowByteFirst
};

enum DataSource {
    eDefault
};

enum DataType {
    eUByte,
    eSByte,
    eUint16,
    eSint16
};

enum DitherMatrix {  
    eDeviceBest
}; 


enum DuplexPageSide {
    eFrontMediaSide,
    eBackMediaSide
};

enum ErrorReport {
    eNoReporting,   
    eBackChannel,
    eErrorPage,
    eBackChAndErrPage,
    eNWBackChannel,
    eNWErrorPage,
    eNWBackChAndErrPage
};

enum FillMode {
    eNonZeroWinding,
    eEvenOdd
};

enum LineCap {
    eButtCap,
    eRoundCap,
    eSquareCap,
    eTriangleCap
};

enum LineJoin {
    eMiterJoin,
    eRoundJoin,
    eBevelJoin,
    eNoJoin
};

enum Measure {
    eInch,
    eMillimeter,
    eTenthsOfAMillimeter    
};

enum MediaSource {
    eDefaultSource,
    eAutoSelect,
    eManualFeed,
    eMultiPurposeTray,
    eUpperCassette,
    eEnvelopeTray,
    eThirdCassette
};

enum MediaDestination {
    eDefaultDestination,
    eFaceDownBin,
    eFaceUpBin,
    eJobOffsetBin
};

enum Orientation {
    ePortraitOrientation,
    eLandscapeOrientation,
    eReversePortrait,
    eReverseLandscape   
};

enum PatternPersistence {
    eTempPatter,
    ePagePatter,
    eSessionPattern
};

enum SimplexPageMode {
    eSimplexFrontSide
};

enum TxMode {
    eOpaque,
    eTransparent
};

enum WritingMode{
    eHorizontal,
    eVertical
};

enum Attribute {
    aPaletteDepth        =   2,
    aColorSpace          =   3,
    aNullBrush           =   4,
    aNullPen             =   5,
    aPaletteData         =   6,
    aPatternSelectID     =   8,
    aGrayLevel           =   9,
    aRGBColor            =  11,
    aPatternOrigin       =  12,
    aNewDestinationSize  =  13,
    aPrimaryArray        =  14,
    aPrimaryDepth        =  15,
    aDeviceMatrix        =  33,
    aDitherMatrixDataType=  34,
    aDitherOrigin        =  35,
    aMediaDestination    =  36,
    aMediaSize           =  37,
    aMediaSource         =  38,
    aMediaType           =  39,
    aOrientation         =  40,
    aPageAngle           =  41,
    aPageOrigin          =  42,
    aPageScale           =  43,
    aROP3                =  44,
    aTxMode              =  45,
    aCustomMediaSize     =  47,
    aCustomMediaUnits    =  48,
    aPageCopies          =  49,
    aDitherMatrixSize    =  50,
    aDitherMatrixDepth   =  51,
    aSimplexPageMode     =  52,
    aDuplexPageMode      =  53,
    aDuplexPageSide      =  54,
    aArcDirection        =  65,
    aBoundingBox         =  66,
    aDashOffset          =  67,
    aEllipseDimension    =  68,
    aEndPoint            =  69,
    aFillMode            =  70,
    aLineCapStyle        =  71,
    aLineJoinStyle       =  72,
    aMiterLength         =  73,
    aLineDashStyle       =  74,
    aPenWidth            =  75,
    aPoint               =  76,
    aNumberOfPoints      =  77,
    aSolidLine           =  78,
    aStartPoint          =  79,
    aPointType           =  80,
    aControlPoint1       =  81,
    aControlPoint2       =  82,
    aClipRegion          =  83,
    aClipMode            =  84,
    aColorDepth          =  98,
    aBlockHeight         =  99,
    aColorMapping        = 100,
    aCompressMode        = 101,
    aDestinationBox      = 102,
    aDestinationSize     = 103,
    aPatternPersistence  = 104,
    aPatternDefineID     = 105,
    aSourceHeight        = 107,
    aSourceWidth         = 108,
    aStartLine           = 109,
    aPadBytesMultiple    = 110,
    aBlockByteLength     = 111,
    aNumberOfScanLines   = 115,
    aColorTreatment      = 120,
    aCommentData         = 129,
    aDataOrg             = 130,
    aMeasure             = 134,
    aSourceType          = 136,
    aUnitsPerMeasure     = 137,
    aStreamName          = 139,
    aStreamDataLength    = 140,
    aErrorReport         = 143,
    aCharAngle           = 161,
    aCharCode            = 162,
    aCharDataSize        = 163,
    aCharScale           = 164,
    aCharShear           = 165,
    aCharSize            = 166,
    aFontHeaderLength    = 167,
    aFontName            = 168,
    aFontFormat          = 169,
    aSymbolSet           = 170,
    aTextData            = 171,
    aCharSubModeArray    = 172,
    aXSpacingData        = 175,
    aYSpacingData        = 176,
    aCharBoldValue       = 177
};
                                          
enum Operator {
    oBeginSession        = 0x41,
    oEndSession          = 0x42,
    oBeginPage           = 0x43,
    oEndPage             = 0x44,
    oComment             = 0x47,
    oOpenDataSource      = 0x48,
    oCloseDataSource     = 0x49,
    oBeginFontHeader     = 0x4f,
    oReadFontHeader      = 0x50,
    oEndFontHeader       = 0x51,
    oBeginChar           = 0x52,
    oReadChar            = 0x53,
    oEndChar             = 0x54,
    oRemoveFont          = 0x55,
    oSetCharAttributes   = 0x56,
    oBeginStream         = 0x5b,
    oReadStream          = 0x5c,
    oEndStream           = 0x5d,
    oExecStream          = 0x5e,
    oRemoveStream        = 0x5f,
    oPopGS               = 0x60,
    oPushGS              = 0x61,
    oSetClipReplace      = 0x62,
    oSetBrushSource      = 0x63,
    oSetCharAngle        = 0x64,
    oSetCharScale        = 0x65,
    oSetCharShear        = 0x66,
    oSetClipIntersect    = 0x67,
    oSetClipRectangle    = 0x68,
    oSetClipToPage       = 0x69,
    oSetColorSpace       = 0x6a,
    oSetCursor           = 0x6b,
    oSetCursorRel        = 0x6c,
    oSetHalftoneMethod   = 0x6d,
    oSetFillMode         = 0x6e,
    oSetFont             = 0x6f,
    oSetLineDash         = 0x70,
    oSetLineCap          = 0x71,
    oSetLineJoin         = 0x72,
    oSetMiterLimit       = 0x73,
    oSetPageDefaultCTM   = 0x74,
    oSetPageOrigin       = 0x75,
    oSetPageRotation     = 0x76,
    oSetPageScale        = 0x77,
    oSetPatternTxMode    = 0x78,
    oSetPenSource        = 0x79,
    oSetPenWidth         = 0x7a,
    oSetROP              = 0x7b,
    oSetSourceTxMode     = 0x7c,
    oSetCharBoldValue    = 0x7d,
    oSetClipMode         = 0x7f,
    oSetPathToClip       = 0x80,
    oSetCharSubMode      = 0x81,
    oCloseSubPath        = 0x84,
    oNewPath             = 0x85,
    oPaintPath           = 0x86,
    oArcPath             = 0x91,
    oBezierPath          = 0x93,
    oBezierRelPath       = 0x95,
    oChord               = 0x96,
    oChordPath           = 0x97,
    oEllipse             = 0x98,
    oEllipsePath         = 0x99,
    oLinePath            = 0x9b,
    oLineRelPath         = 0x9d,
    oPie                 = 0x9e,
    oPiePath             = 0x9f,
    oRectangle           = 0xa0,
    oRectanglePath       = 0xa1,
    oRoundRectangle      = 0xa2,  
    oRoundRectanglePath  = 0xa3,
    oText                = 0xa8,
    oTextPath            = 0xa9,
    oBeginImage          = 0xb0,
    oReadImage           = 0xb1,
    oEndImage            = 0xb2,
    oBeginRastPattern    = 0xb3,
    oReadRastPattern     = 0xb4,
    oEndRastPattern      = 0xb5,
    oBeginScan           = 0xb6,
    oEndScan             = 0xb8,
    oScanLineRel         = 0xb9
};


typedef struct pcl_img {
    unsigned char colorDepth;
    unsigned char colorSpace;
    int width,height;
    int linelen; /* bytes per line */
    unsigned char *data;
} XL_pcl_img;

struct tPrinter 
{ 
    const char *name;
    float topmargin;
    float bottommargin;
    float leftmargin;
    float rightmargin;
} xlPrinters[] = {
    { "lj2200",0,0,0,0 }
};

static  int
out_ubyte(int fd,unsigned char data) {
    return XY_Write(fd,&data,1);
}
static  int 
XL_Operator(int fd,enum Operator const data)  {
    return out_ubyte(fd,data);
}
static int
out_uint16(int fd,unsigned short data ) {
    unsigned char c[2];
    c[0]=data&0xff; c[1]=data>>8;
    return XY_Write(fd,c,2);
}
static int
out_uint32(int fd,unsigned int data ) {
    unsigned char c[4];
    c[0] = data&0xff; c[1]=(data>>8)&0xff; c[2]=(data>>16)&0xff; c[3]=data>>24;
    return XY_Write(fd,c,4);
}
static int
out_sint16(int fd,signed short sdata ) {
    unsigned short data=(unsigned short)sdata;    
    unsigned char c[2];
    c[0]=data&0xff; c[1]=data>>8;
    return XY_Write(fd,c,2);
}
#if 0
static int
out_sint32(int fd,signed int sdata ) {
    unsigned int data=(unsigned int)sdata;
    unsigned char c[4];
    c[0] = data&0xff; c[1]=(data>>8)&0xff; c[2]=(data>>16)&0xff; c[3]=data>>24;
    return XY_Write(fd,c,4);
}
#endif

static int
xl_ubyte(int fd,unsigned char data) {
    unsigned char const tag=0xc0;
    XY_Write(fd,&tag,1);
    return out_ubyte(fd,data);
}
static int
xl_uint16(int fd,unsigned short data ) {
    unsigned char const tag=0xc1;
    XY_Write(fd,&tag,1);
    return out_uint16(fd,data);
}
#if 0
static int
xl_uint32(int fd,unsigned int data ) {
    unsigned char const c=0xc2;
    XY_Write(fd,&c,1);
    return out_uint32(fd,data);
}
static int
xl_sint16(int fd,signed short data ) {
    unsigned char const c=0xc3;
    XY_Write(fd,&c,1);
    return out_sint16(fd,data);
}
static int
xl_sint32(int fd,signed int data ) {
    unsigned char const c=0xc4;
    XY_Write(fd,&c,1);
    return out_sint32(fd,data);
}
#endif
static int
xl_ubyte_array(int fd,unsigned char *data,int len) {
    int i;
    unsigned char head[4];
    head[0]=0xc8;head[1]=0xc1;head[2]=len&0xff;head[3]=(len>>8)&0xff;
    XY_Write(fd,head,4);
    for(i=0;i<len;i++) {
        out_ubyte(fd,data[i]);
    }
    return 0;
}
#if 0
static int
xl_uint16_array(int fd,unsigned short *data,int len) {
    int i;
    unsigned char head[4];
    head[0]=0xc9;head[1]=0xc1;head[2]=len&0xff;head[3]=(len>>8)&0xff;
    XY_Write(fd,head,4);
    for(i=0;i<len;i++) {
        out_uint16(fd,data[i]);
    }
    return 0;
}
static int
xl_uint32_array(int fd,unsigned int *data,int len) {
    int i;
    unsigned char head[4];
    head[0]=0xca;head[1]=0xc1;head[2]=len&0xff;head[3]=(len>>8)&0xff;
    XY_Write(fd,head,4);
    for(i=0;i<len;i++) {
        out_uint32(fd,data[i]);
    }
    return 0;
}
static int
xl_sint16_array(int fd,signed short *data,int len) {
    int i;
    unsigned char head[4];
    head[0]=0xcb;head[1]=0xc1;head[2]=len&0xff;head[3]=(len>>8)&0xff;
    XY_Write(fd,head,4);
    for(i=0;i<len;i++) {
        out_sint16(fd,data[i]);
    }
    return 0;
}
static int
xl_sint32_array(int fd,signed int *data,int len) {
    int i;
    unsigned char head[4];
    head[0]=0xcc;head[1]=0xc1;head[2]=len&0xff;head[3]=(len>>8)&0xff;
    XY_Write(fd,head,4);
    for(i=0;i<len;i++) {
        out_sint32(fd,data[i]);
    }
    return 0;
}

static int
xl_ubyte_xy(int fd,unsigned char xdata,unsigned char ydata) {
    unsigned char const tag=0xd0;
    XY_Write(fd,&data,1);
    out_ubyte(fd,ydata);
    return out_ubyte(fd,xdata);
}
#endif
static int
xl_uint16_xy(int fd,unsigned short xdata,unsigned short ydata ) {
    unsigned char const tag=0xd1;
    XY_Write(fd,&tag,1);
    out_uint16(fd,xdata);
    return out_uint16(fd,ydata);
}
#if 0
static int
xl_uint32_xy(int fd,unsigned int xdata,unsigned int ydata ) {
    unsigned char const tag=0xd2;
    XY_Write(fd,&tag,1);
    out_uint32(fd,xdata);
    return out_uint32(fd,ydata);
}
#endif
static int
xl_sint16_xy(int fd,signed short xdata,signed short ydata ) {
    unsigned char const tag=0xd3;
    XY_Write(fd,&tag,1);
    out_sint16(fd,xdata);
    return out_sint16(fd,ydata);
}

#if 0
static int
xl_sint32_xy(int fd,signed int xdata,signed int ydata ) {
    unsigned char const tag=0xd4;
    XY_Write(fd,&tag,1);
    out_sint32(fd,xdata);
    return out_sint32(fd,ydata);
}
#endif

static int
xl_attr_ubyte(int fd,enum Attribute const data) {
    unsigned char const tag=0xf8;
    XY_Write(fd,&tag,1);
    return out_ubyte(fd,data);
}
#if 0
static int
xl_attr_uint16(int fd,enum Attribute const data ) {
    unsigned char const tag=0xf9;
    XY_Write(fd,&tag,1);
    return out_uint16(fd,data);
}
#endif
static int
xl_dataLength(int fd,unsigned int dataLength ) {
    unsigned char const tag=0xfa;
    XY_Write(fd,&tag,1);
    return out_uint32(fd,dataLength);
}

#if 0
static int
xl_dataLengthbytes(int fd,unsigned char dataLengthBytes) {
    unsigned char const tag=0xfb;
    XY_Write(fd,&tag,1);
    return out_ubyte(fd,dataLengthBytes);
}
#endif 
/*
 * ---------------------------------------------------- 
 * job_head/job_end:  
 *  switch printer to PCL-XL mode / reset 
 * ---------------------------------------------------- 
 */
static int 
job_head(int fd) {
    XY_Puts(fd,"\033%-12345X@PJL ENTER LANGUAGE=PCLXL\n");  
    XY_Puts(fd,") HP-PCL XL;1;1;Generated by Netpbm Pnmtopclxl\n");  
    return 0;
}
static int 
job_end(int fd) {
    XY_Puts(fd,"\033%-12345X");  
    return 0;
}

static void
XL_WriteRleBlock(int const s,
                 XL_pcl_img * const img,
                 int const firstLine,
                 int const nlines,
                 XY_rle * const rle) {

    const unsigned char pad[4] = {0,0,0,0};
    unsigned int const paddedLinelen = ((img->linelen+3)/4)*4;
    int rlelen;
    unsigned int line;
    
    XY_RLEreset(rle);

    for(line=firstLine;line<firstLine+nlines;++line) {
        XY_RLEput(rle,img->data+img->linelen*line,img->linelen);
        XY_RLEput(rle,pad,paddedLinelen - img->linelen);
    }
    rlelen=XY_RLEfinish(rle);
    if(rlelen<0) 
        pm_error("Error on Making rle");
    xl_dataLength(s,rlelen); 
    XY_Write(s,rle->fbuf,rlelen);
}


/*
 * ------------------------------------------------------------
 * XL_WriteImage
 *  Write a PCL-XL image to the datastream 
 * ------------------------------------------------------------
 */
static void 
XL_WriteImage(int s,XL_pcl_img *img) 
{
    int blockStartLine;
    XY_rle *rle;

    xl_ubyte(s,eDirectPixel); xl_attr_ubyte(s,aColorMapping);
    xl_ubyte(s,img->colorDepth); xl_attr_ubyte(s,aColorDepth);
    xl_uint16(s,img->width); xl_attr_ubyte(s,aSourceWidth);  
    xl_uint16(s,img->height); xl_attr_ubyte(s,aSourceHeight);    
    xl_uint16_xy(s,img->width*1,img->height*1); 
    xl_attr_ubyte(s,aDestinationSize);   
    XL_Operator(s,oBeginImage);

    rle = XY_RLEnew(img->linelen*20);
    if(!rle) 
        pm_error("Unable to allocate %d bytes for the RLE buffer",
                 img->linelen*20);

    blockStartLine=0;
    while (blockStartLine<img->height) {
        int const blockHeight=MIN(20,img->height-blockStartLine);
        xl_uint16(s,blockStartLine); xl_attr_ubyte(s,aStartLine); 
        xl_uint16(s,blockHeight); xl_attr_ubyte(s,aBlockHeight);
        xl_ubyte(s,eRLECompression); xl_attr_ubyte(s,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(s,1); xl_attr_ubyte(s,aPadBytesMultiple); 
        */
        XL_Operator(s,oReadImage);
        XL_WriteRleBlock(s,img,blockStartLine,blockHeight,rle);
        blockStartLine+=blockHeight;
    }
    XY_RLEdelete(rle);
    XL_Operator(s,oEndImage);
}



static void
print_page(int                 const s,
           XL_pcl_img *        const img,
           enum MediaSize      const format,
           int                 const dpi,
           bool                const center,
           float               const xoffs,
           float               const yoffs,
           bool                const doDuplex,
           enum DuplexPageMode const duplex,
           bool                const doCopies,
           unsigned int        const copies,
           bool                const doMediaSource,
           int                 const mediaSource,
           bool                const doMediaDestination,
           int                 const mediaDestination) 
{
    float xpos=xoffs,ypos=yoffs;
    if(doDuplex) {
        xl_ubyte(s,duplex);  xl_attr_ubyte(s,aDuplexPageMode);
    }
    if(doMediaSource) { 
        /* if not included same as last time in same session is selected */
        xl_ubyte(s,mediaSource);  xl_attr_ubyte(s,aMediaSource);
    }
    if(doMediaDestination) {
        xl_ubyte(s,mediaDestination);  xl_attr_ubyte(s,aMediaDestination);
    }
    xl_ubyte(s,ePortraitOrientation); xl_attr_ubyte(s,aOrientation);
    xl_ubyte(s,format); xl_attr_ubyte(s,aMediaSize);
    XL_Operator(s,oBeginPage);
        xl_ubyte(s,img->colorSpace); xl_attr_ubyte(s,aColorSpace);   
        XL_Operator(s,oSetColorSpace);
        
        if(center) {
            float width = 1.0*img->width/dpi;  
            float height = 1.0*img->height/dpi;    
            xpos = (PAPERWIDTH(format) - width)/2;
            ypos = (PAPERHEIGHT(format) - height)/2;
        } 
        /* cursor positioning */
        xl_sint16_xy(s,xpos*dpi,ypos*dpi); xl_attr_ubyte(s,aPoint);
        XL_Operator(s,oSetCursor);
        XL_WriteImage(s,img);   
    if(doCopies) {
        /* wrong in example in PCL-XL manual. Type is uint16 ! */
        xl_uint16(s,copies); xl_attr_ubyte(s,aPageCopies);
    }
    XL_Operator(s,oEndPage);
}


/*
 * ---------------------------------------------- 
 * StartSession:  
 *  Prepare for print
 * ---------------------------------------------- 
 */
static void
start_session(int s,int dpi)   { 
    xl_uint16_xy(s,dpi,dpi); 
    xl_attr_ubyte(s,aUnitsPerMeasure); 
    xl_ubyte(s,eInch); 
    xl_attr_ubyte(s,aMeasure);
    /* xl_ubyte(s,eNoReporting); xl_attr_ubyte(s,aErrorReport); */
    xl_ubyte(s,eBackChAndErrPage); 
    xl_attr_ubyte(s,aErrorReport);
    XL_Operator(s,oBeginSession);
}        



static void 
end_session(int s) {
    XL_Operator(s,oEndSession);
}



static void
pnm_to_pclimg_packbits(struct pam * pamP,XL_pcl_img * img) {
    /* Samples are black or white and packed 8 to a byte */

    tuple * tuplerow;
        
    img->colorDepth=e1Bit;
    img->colorSpace=eGray;
    img->linelen=((pamP->width+7)/8);
    img->height=pamP->height;
    img->width=(pamP->width);

    img->data=(unsigned char *)malloc(((pamP->width+7)/8)
                                      *pamP->height*pamP->depth);
    tuplerow=pnm_allocpamrow(pamP);
    {
        int row;
        unsigned int pcl_cursor;

        pcl_cursor=0;
        for (row=0;row<pamP->height;++row) {
            unsigned char accum;
            unsigned char bitmask;
            int col;

            pnm_readpamrow(pamP, tuplerow);

            bitmask=0x80; accum=0x00;
            for (col=0;col<pamP->width;++col) {
                if (tuplerow[col][0]==PAM_PBM_WHITE)
                    accum |= bitmask;
                bitmask>>=1;
                if (bitmask==0) {
                    img->data[pcl_cursor++]=accum;
                    bitmask=0x80; accum=0x0;
                } 
            }
	    if(bitmask!=0x80) {
                    img->data[pcl_cursor++]=accum;
	    }
        }
    }
    pnm_freepamrow(tuplerow);
}




static void
pnm_to_pclimg_wholebytes(struct pam * pamP,XL_pcl_img *img) {
    /* One sample per byte */
    
    tuple * tuplerow;
        
    if (pamP->depth==1)
        img->colorSpace=eGray;
    else
        img->colorSpace=eRGB;

    img->colorDepth=e8Bit;
    img->height=pamP->height;
    img->width=pamP->width;
    img->linelen=pamP->width*pamP->depth;

    img->data=(unsigned char *)malloc(pamP->width*pamP->height*pamP->depth);
    tuplerow=pnm_allocpamrow(pamP);
    {
        int row;
        unsigned int pcl_cursor;

        pcl_cursor=0;
        for (row=0;row<pamP->height;++row) {
            int col;
            pnm_readpamrow(pamP, tuplerow);
            for (col=0;col<pamP->width;++col) {
                int plane;
                for (plane=0;plane<pamP->depth;++plane)
                    img->data[pcl_cursor++] = 
                        pnm_scalesample(tuplerow[col][plane], 
                                        pamP->maxval, 255);
            }
        }
    }
    pnm_freepamrow(tuplerow);
}



static void 
pnm_to_pclimg(struct pam *        const pamP,
              XL_pcl_img *        const img,
              bool                const colorok) {

    if (pamP->depth > 1 && !colorok)
        pm_message("WARNING: generating a color print stream because the "
                   "input image is PPM.  "
                   "To generate a black and white print stream, run the input "
                   "through Ppmtopgm.  To suppress this warning, use the "
                   "-colorok option.");

    if (pamP->depth==1 && pamP->maxval==1) 
        pnm_to_pclimg_packbits(pamP,img);
    else 
        pnm_to_pclimg_wholebytes(pamP,img);
}



/*
 * -------------------------------------------------------------------
 * print_pages
 *  Loop over all input files, and each file, all images.
 * -------------------------------------------------------------------
 */

static int
print_pages(int                 const s,
            InputSource *       const firstSourceP,
            enum MediaSize      const format,
            int                 const dpi,
            bool                const center,
            float               const xoffs,
            float               const yoffs,
            bool                const doDuplex,
            enum DuplexPageMode const duplex,
            bool                const doCopies,
            unsigned int        const copies,
            bool                const doMediaSource,
            int                 const mediaSource,
            bool                const doMediaDestination,
            int                 const mediaDestination,
            bool                const colorok) {

    InputSource *sourceP;
    unsigned int sourceNum;

    sourceP = firstSourceP;    
    xl_ubyte(s, eBinaryLowByteFirst); xl_attr_ubyte(s,aDataOrg);
    xl_ubyte(s, eDefaultSource); xl_attr_ubyte(s,aSourceType);
    XL_Operator(s,oOpenDataSource);

    sourceNum = 0;   /* initial value */

    while(sourceP) {
        FILE *in_file;
        struct pam pam;
        bool eof;
        unsigned int pageNum;

        in_file = pm_openr(sourceP->name);

        ++sourceNum;

        pageNum = 0;  /* initial value */

        eof = FALSE;
        while(!eof) {
            pnm_nextimage(in_file, &eof);
            if (!eof) {
                XL_pcl_img pcl_img;

                ++pageNum;
                pm_message("Processing File %u, Page %u", sourceNum, pageNum);

                pnm_readpaminit(in_file, &pam, PAM_STRUCT_SIZE(tuple_type));
                
                pnm_to_pclimg(&pam, &pcl_img, colorok);

                print_page(s, &pcl_img,
                           format, dpi, center, xoffs, yoffs, doDuplex,duplex,
                           doCopies, copies, doMediaSource, mediaSource,
                           doMediaDestination, mediaDestination);

                free(pcl_img.data);
            }
        }
        pm_close(in_file);
        sourceP = sourceP->next; 
    }
    XL_Operator(s,oCloseDataSource);
    return 0;
}



static void
freeSource(InputSource * const firstSourceP) {
    
    InputSource * sourceP;

    sourceP = firstSourceP;
    while(sourceP) {
        InputSource * const nextP = sourceP->next;
        free(sourceP);
        sourceP = nextP;
    }
}



int
main(int argc,char *argv[]) {
    struct cmdlineInfo cmdline;
    int const out_fd = 1;

    pnm_init(&argc, argv);

    parseCommandLine(argc, argv, &cmdline);

    job_head(out_fd);
    start_session(out_fd,cmdline.dpi);
    print_pages(out_fd,cmdline.sourceP,
                cmdline.format, cmdline.dpi, cmdline.center,
                cmdline.xoffs, cmdline.yoffs,
                cmdline.duplexSpec, cmdline.duplex,
                cmdline.copiesSpec, cmdline.copies,
                cmdline.feederSpec, cmdline.feeder,
                cmdline.outtraySpec, cmdline.outtray,
                cmdline.colorok
        );
    end_session(out_fd);
    job_end(out_fd);

    freeSource(cmdline.sourceP);

    exit(0);
}
