/* COPYRIGHT (C) 1990, 1992 Aladdin Enterprises.  All rights reserved.
   Distributed by Free Software Foundation, Inc.
   
   This file is part of Ghostscript.
   
   Ghostscript is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY.  No author or distributor accepts responsibility
   to anyone for the consequences of using it or for whether it serves any
   particular purpose or works at all, unless he says so in writing.  Refer
   to the Ghostscript General Public License for full details.
   
   Everyone is granted permission to copy, modify and redistribute
   Ghostscript, but only under the conditions described in the Ghostscript
   General Public License.  A copy of this license is supposed to have been
   given to you along with Ghostscript so you can know your rights and
   responsibilities.  It should be in a file named COPYING.  Among other
   things, the copyright notice and this notice must be preserved on all
   copies.  */

/* gdevdmpr.c
 * $Id: GDEVDMPR.C 1.1 1994/08/30 14:22:52 kaz Exp kaz $
 *
 * Dot matrix printer driver for Ghostscript
 *
 * The first version written by ...                 K.Asayama  Nov 1992
 * NEC PC-H98 high resolution mode supported by ... OkI        Dec 1992
 * IBM PC AT/Compatible machines supported by ...   hero.h     Mar 1993
 * Modified for 386BSD by ...                       FKR        Mar 1993
 * Modified for Ghostscript version 2.5.2 by ...    K.Asayama  Mar 1993
 * Modified for Ghostscript version 2.6.1 by ...    K.Asayama  Oct 1993
 */

#include "gdevprn.h"
#include "gp.h"
#include "errors.h"
#include "gsprops.h"
#include "gsstate.h"
#include "math_.h"
#include "malloc_.h"

/* include library header. */
#include "dviprlib.h"

extern FILE *lib_fopen(P1(const char *));

#define LOCAL_DEBUG 0

#define DEVICE_NAME "dmprt"
#define DEVICE_VERSION 200  /* 2.00 */

typedef struct gx_device_dmprt_local_s gx_device_dmprt_local;
struct gx_device_dmprt_local_s {
  int orig_x_dpi;
  int orig_y_dpi;
  
  int x_offset;
  int y_offset;
  int spec_width;
  int spec_height;
  int max_width;
  int max_height;
  int dev_margin[4]; /* left bottom right top */
  
  int Orientation;
  int MirrorPrint;
  
  int NegativePrint;
  int Separations; /* not implemented yet. */
  
  int prtcfg_init_f;
  int verbose_f;
  int debug_f;
  dviprt_cfg_t prtcfg;
  dviprt_print prtinfo;
};

/* declaration of the structure to describe `DMPRT' device driver */
typedef struct gx_device_dmprt_s gx_device_dmprt;
struct gx_device_dmprt_s {
  gx_device_common;
  gx_prn_device_common;
  
  gx_device_dmprt_local dmprt;
};

/* declarations of main functions */
private dev_proc_get_props(gdev_dmprt_get_props);
private dev_proc_put_props(gdev_dmprt_put_props);
private dev_proc_get_initial_matrix(gdev_dmprt_get_initial_matrix);
private dev_proc_open_device(gdev_dmprt_open);
private dev_proc_print_page(gdev_dmprt_print_page);
private dev_proc_close_device(gdev_dmprt_close);
private dev_proc_map_rgb_color(gdev_dmprt_map_rgb_color);
private dev_proc_map_color_rgb(gdev_dmprt_map_color_rgb);

/* declarations of sub functions to get printer properties. */
private void gdev_dmprt_init_printer_props(P1(gx_device_dmprt *));
private int gdev_dmprt_get_printer_props(P2(gx_device_dmprt *,char *));
private int gdev_dmprt_check_code_props(P2(byte * ,int ));
private FILE *gdev_dmprt_dviprt_lib_fopen(P2(const char *,char *));

private int gdev_dmprt_error_no_dviprt_to_gs(P1(int ));

/* The device descriptor */
gx_device_procs prn_dmprt_procs = {
  gdev_dmprt_open,
  gdev_dmprt_get_initial_matrix,
  0, /* sync_output */
  gdev_prn_output_page,
  gdev_dmprt_close,
  gdev_dmprt_map_rgb_color,
  gdev_dmprt_map_color_rgb,
  0, /* fill_rectangle */
  0, /* tile_rectangle */
  0, /* copy_mono */
  0, /* copy_color */
  0, /* draw_line */
  0, /* get_bits */
  gdev_dmprt_get_props,
  gdev_dmprt_put_props,
  gx_default_map_cmyk_color,
  0,
};

#define DEFAULT_DPI   180
#define DEFAULT_WIDTH   8.3
#define DEFAULT_HEIGHT 11.7

gx_device_dmprt gs_dmprt_device = {
  prn_device_body(gx_device_dmprt, prn_dmprt_procs, DEVICE_NAME,
      DEFAULT_WIDTH*10,       /* width 10'th */
      DEFAULT_HEIGHT*10,      /* height 10'th */
      DEFAULT_DPI,            /* X resolution */
      DEFAULT_DPI,            /* Y resolution */
      0,0,0,0,                /* margins (top,left,bottom,right) */
      1,1,1,1,2,2,            /* color info. */
      gdev_dmprt_print_page),

  {
    DEFAULT_DPI,  DEFAULT_DPI,
    0, 0,          /* offset */
    DEFAULT_DPI*DEFAULT_WIDTH,  /* specified width */
    DEFAULT_DPI*DEFAULT_HEIGHT, /* specified height */
    -1,-1,			/* maximal width,height */
    { 0,0,0,0 },      /* margins */
    0,0,              /* Orientation, MirrorPrint */
    
    0,				/* NegativePrint */
    0,				/* Separations */
  /* status of the device */
      0,    /* printer configuration is not initialized */
      0,    /* verbose mode */
      0,    /* debug flag */
  },
};

#define ppdev ((gx_device_printer *)pdev)
#define pddev ((gx_device_dmprt *)pdev)


private gx_color_index
gdev_dmprt_map_rgb_color(gx_device *pdev,
			 gx_color_value r, gx_color_value g, gx_color_value b)
{
  return (pddev->dmprt.NegativePrint) ? gx_default_map_rgb_color(pdev,r,g,b) :
    gdev_prn_map_rgb_color(pdev,r,g,b) ;
}

private int
gdev_dmprt_map_color_rgb(gx_device *pdev, gx_color_index color,
			 gx_color_value prgb[3])
{
  return (pddev->dmprt.NegativePrint) ?
    gx_default_map_color_rgb(pdev,color,prgb) :
    gdev_prn_map_color_rgb(pdev,color,prgb) ;
}

/* --- Device properties. --- */
/* Propaties starting with 'dviprt.' are in relation to dviprt.
 * Propaties starting with 'dmprt.' are depending on this device driver.
 * Other propaties are defined as standard 'page device' propaties in PS.
 */
private const gs_prop_item props_dmprt[] = {
  prop_def("dviprt.Pins",prt_int),
  prop_def("dviprt.MinimalUnit",prt_int),
  prop_def("dviprt.MaximalUnit",prt_int),
  prop_def("dviprt.dpi",prt_int),
  prop_def("dviprt.Transpose",prt_bool),
  prop_def("dviprt.Reverse",prt_bool),
  prop_def("dviprt.Constant",prt_int), /* 6 */
  prop_def("dviprt.Dpi",prt_int),
  
  prop_def("dviprt.BitImageMode",prt_string), /* 8 */
  prop_def("dviprt.SendBitImage",prt_string),
  prop_def("dviprt.BitRowHeader",prt_string),
  prop_def("dviprt.AfterBitImage",prt_string),
  prop_def("dviprt.LineFeed",prt_string),
  prop_def("dviprt.FormFeed",prt_string),
  prop_def("dviprt.NormalMode",prt_string),
  prop_def("dviprt.SkipSpaces",prt_string), /* 15 */
  
  prop_def("dviprt.Name",prt_string), /* 16 */
  prop_def("dviprt.Encoding",prt_string), /* 17 */
  prop_def("dviprt.NonMoving",prt_bool), /* 18 */
  
  prop_def("Margins",prt_int_array), /* 19 */
  prop_def("dmprt.MaxSize",prt_int_array), /* if negative or zero, infinite. */
  
  prop_def("Orientation",prt_int),
  prop_def("MirrorPrint",prt_bool),
  
  prop_def("NegativePrint",prt_bool),
  prop_def("Separations",prt_bool), /* 25 */
  
  prop_def("dmprt.Margins",prt_int_array),  /* margins */
  prop_def("dmprt.Debug",prt_bool),         /* debug flag */
  prop_def("dmprt.Verbose",prt_bool),         /* verbose mode */
  
  prop_int,prop_int,                           /* offsets */
  prop_int,prop_int,                           /* maximal size */
  prop_int,prop_int,prop_int,prop_int,         /* margins */
};
#define LOCAL_PROPS_SIZE (sizeof(props_dmprt)/sizeof(gs_prop_item))
#define LOCAL_PROPS_COUNT (LOCAL_PROPS_SIZE-8)

private const gs_prop_item props_dmprt_put_only[] = {
  prop_def("dviprt.FileName",prt_string),
};
#define LOCAL_PUT_ONLY_PROPS_SIZE \
  (sizeof(props_dmprt_put_only)/sizeof(gs_prop_item))
#define LOCAL_PUT_ONLY_PROPS_COUNT LOCAL_PUT_ONLY_PROPS_SIZE

private const gs_prop_item props_dmprt_get_only[] = {
  prop_def("dmprt.Version",prt_int),
};
#define LOCAL_GET_ONLY_PROPS_SIZE \
  (sizeof(props_dmprt_get_only)/sizeof(gs_prop_item))
#define LOCAL_GET_ONLY_PROPS_COUNT   LOCAL_GET_ONLY_PROPS_SIZE

typedef struct {
  char *name;
  int no;
} dmprt_encoding;
private dmprt_encoding gdev_dmprt_encode_list[] = {
  {"Null",CFG_ENCODE_NULL},
  {"AsciiHex",CFG_ENCODE_HEX },
  {"CCITTFax",CFG_ENCODE_FAX },
  {"PCLMode1Compress",CFG_ENCODE_PCL1 },
  {"PCLMode2Compress",CFG_ENCODE_PCL2 },
  {0},
};

/* --- Get properties of printer device. --- */
private int
gdev_dmprt_get_props(gx_device *pdev, gs_prop_item *plist)
{
  int code;
  int i;
  
  code = gdev_prn_get_props(pdev, 0);
  if ( plist != 0 ) {
    gs_prop_item *pi,*pi_i,*pi_c,*pi_o,*pi_v;
    gs_prop_item *pi_g;
    dviprt_cfg_t *pprt;
    
    if (!pddev->dmprt.prtcfg_init_f)
      gdev_dmprt_init_printer_props(pddev);
    pprt = &pddev->dmprt.prtcfg;
    
    pi = plist + code;
    memcpy(pi, props_dmprt, sizeof(props_dmprt));
    pi_g = pi + LOCAL_PROPS_SIZE;
    memcpy(pi_g, props_dmprt_get_only, sizeof(props_dmprt_get_only));
    
    pi_i = pi;
    pi_c = pi_i + CFG_INTEGER_TYPE_COUNT;
    pi_o = pi_c + CFG_PRTCODE_TYPE_COUNT;
    pi_v = pi + LOCAL_PROPS_COUNT;
    
    for (i=0;i<CFG_INTEGER_TYPE_COUNT;i++) {
      if (i != CFG_UPPER_POS && i != CFG_ENCODE)
        pi_i[i].value.i = pprt->integer[i];
    }
    pi_i[CFG_DPI].value.i = pddev->dmprt.orig_x_dpi; /* dpi */
    pi_i[CFG_Y_DPI].value.i = pddev->dmprt.orig_y_dpi;
    pi_i[CFG_PINS].value.i *= 8; /* pins */
    pi_i[CFG_UPPER_POS].value.b =                   /* transpose */
      pprt->integer[CFG_UPPER_POS] & CFG_NON_TRANSPOSE_BIT ? 0 : 1;
    pi_i[CFG_ENCODE].value.b =                   /* reverse */
      pprt->integer[CFG_UPPER_POS] & CFG_REVERSE_BIT ? 1 : 0;
    
    for (i=0;i<CFG_PRTCODE_TYPE_COUNT;i++) {
      if (pprt->prtcode[i]) {
        pi_c[i].value.a.size = pprt->prtcode_size[i];
        pi_c[i].value.a.p.s = pprt->prtcode[i];
      }
      else {
        pi_c[i].value.a.size = 0;
        pi_c[i].value.a.p.s = (byte*)"";
      }
    }
    
    if (pprt->strings[CFG_NAME]) {
      pi_o[0].value.a.p.s = pprt->strings[CFG_NAME];
      pi_o[0].value.a.size = strlen(pprt->strings[CFG_NAME]);
    }
    else {
      pi_o[0].value.a.p.s = (byte*)"";
      pi_o[0].value.a.size = 0;
    }
    
    for (i=0;gdev_dmprt_encode_list[i].name;i++) {
      if (pprt->integer[CFG_ENCODE] == gdev_dmprt_encode_list[i].no) {
        pi_o[1].value.a.p.s = gdev_dmprt_encode_list[i].name;
        pi_o[1].value.a.size = strlen(gdev_dmprt_encode_list[i].name);
        break;
      }
    }
    if (gdev_dmprt_encode_list[i].name == 0) {
      pi_o[1].value.a.p.s = gdev_dmprt_encode_list[0].name;
      pi_o[1].value.a.size = strlen(gdev_dmprt_encode_list[0].name);
    }
    
    pi_o[2].value.b = (pprt->integer[CFG_UPPER_POS] & CFG_NON_MOVING) ? 1 : 0;
    
    /* offset */
    pi_o[3].value.a.size = 2;
    pi_o[3].value.a.p.v = pi_v;
    pi_v[0].value.i = pddev->dmprt.x_offset;
    pi_v[1].value.i = pddev->dmprt.y_offset;
    
    /* maximal size */
    pi_o[4].value.a.size = 2;
    pi_o[4].value.a.p.v = pi_v+2;
    pi_v[2].value.i = pddev->dmprt.max_width;
    pi_v[3].value.i = pddev->dmprt.max_height;
    
    /* transformation */
    pi_o[5].value.i = pddev->dmprt.Orientation;
    pi_o[6].value.b = pddev->dmprt.MirrorPrint;
    
    /* color */
    pi_o[7].value.b = pddev->dmprt.NegativePrint;
    pi_o[8].value.b = pddev->dmprt.Separations;
    
    /* margins */
    pi_o[9].value.a.size = 4;
    pi_o[9].value.a.p.v = pi_v+4;
    for (i=0;i<4;i++) {
      pi_v[4+i].value.i = pddev->dmprt.dev_margin[i];
    }
    pi_o[10].value.b = pddev->dmprt.debug_f;
    pi_o[11].value.b = pddev->dmprt.verbose_f;
    
    pi_g[0].value.i = DEVICE_VERSION;
    {
      int w = pddev->width;
      int h = pddev->height;
      pddev->width = pddev->dmprt.spec_width;
      pddev->height = pddev->dmprt.spec_height;
      code = gdev_prn_get_props(pdev, plist);
      pddev->width = w;
      pddev->height = h;
    }
  }
  return code + LOCAL_PROPS_SIZE + LOCAL_GET_ONLY_PROPS_SIZE;
}

/* --- Put properties of printer device. --- */
private int
gdev_dmprt_put_props(gx_device *pdev, gs_prop_item *plist, int count)
{
  gs_prop_item *known[LOCAL_PROPS_COUNT + LOCAL_PUT_ONLY_PROPS_COUNT];
  gs_prop_item **ppi_po,**ppi_i,**ppi_c,**ppi_o;
  dviprt_cfg_t *pprt = &pddev->dmprt.prtcfg;
  int up = 0;
  int code = 0;
  int i;
  
  if (!pddev->dmprt.prtcfg_init_f)
    gdev_dmprt_init_printer_props(pddev);
  
  ppi_po = known;
  ppi_i = ppi_po + LOCAL_PUT_ONLY_PROPS_COUNT;
  ppi_c = ppi_i + CFG_INTEGER_TYPE_COUNT;
  ppi_o = ppi_c + CFG_PRTCODE_TYPE_COUNT;
  props_extract(plist, count,
		props_dmprt_put_only, LOCAL_PUT_ONLY_PROPS_COUNT,ppi_po, 0);
  props_extract(plist, count, props_dmprt, LOCAL_PROPS_COUNT, ppi_i, 0);
  
  if (ppi_o[10]) {  /* set debug flag */
     pddev->dmprt.debug_f = ppi_o[10]->value.b;
    if (code == 0) code = 1;
  }
  
  dviprt_setmessagestream(pddev->dmprt.debug_f ? stderr : NULL);
  
  /* read CFG/SRC */
  if (ppi_po[0]) {
    if (ppi_po[0]->value.a.size > 0) {
      int ccode;
      char *filename = gs_malloc(ppi_po[0]->value.a.size+1,1,
				 "gdev_dmprt_put_props(filename)");
      if (filename == 0) {
        code = e_VMerror;
        goto error_end;
      }
      strncpy(filename,ppi_po[0]->value.a.p.s,ppi_po[0]->value.a.size);
      filename[ppi_po[0]->value.a.size] = 0;
      ccode = gdev_dmprt_get_printer_props(pddev,filename);
      if (ccode < 0) code = ccode;
      if (code == 0) code = 1;
      gs_free(filename,ppi_po[0]->value.a.size+1,1,
	      "gdev_dmprt_put_props(filename)");
      if (code < 0) goto error_end;
    }
  }
  
  for (i=0;i<CFG_INTEGER_TYPE_COUNT;i++) {
    if (i != CFG_UPPER_POS && i != CFG_ENCODE) {
      if (ppi_i[i]) {
        pprt->integer[i] = ppi_i[i]->value.i;
        if (i == CFG_PINS) pprt->integer[i] /= 8;
        else if (i == CFG_DPI)
          pddev->dmprt.orig_x_dpi = pprt->integer[i];
        else if (i == CFG_Y_DPI)
          pddev->dmprt.orig_y_dpi = pprt->integer[i];
        if (code == 0) code = 1;
      }
    }
  }
  if (ppi_i[CFG_UPPER_POS]) {
    if (!ppi_i[CFG_UPPER_POS]->value.b)
      up |= CFG_NON_TRANSPOSE_BIT;
    if (code == 0) code = 1;
  }
  else up |= pprt->integer[CFG_UPPER_POS] & CFG_NON_TRANSPOSE_BIT;
  
  if (ppi_i[CFG_ENCODE]) {
    if (ppi_i[CFG_ENCODE]->value.b)
      up |= CFG_REVERSE_BIT;
    if (code == 0) code = 1;
  }
  else up |= pprt->integer[CFG_UPPER_POS] & CFG_REVERSE_BIT;
  
  for (i=0;i<CFG_PRTCODE_TYPE_COUNT;i++) {
    if (ppi_c[i]) {
      byte *pbyte = 0;
      int len = ppi_c[i]->value.a.size;
      byte *str = ppi_c[i]->value.a.p.s;
      int ccode = gdev_dmprt_check_code_props(str,len);
      if (ccode < 0) {
        code = e_rangecheck;
        goto error_end;
      }
      pbyte = (byte *)malloc(len+1);
      if (pbyte == 0) {
        code = e_VMerror;
        goto error_end;
      }
      memcpy(pbyte,str,len);
      pbyte[len] = 0;
      pprt->prtcode[i] = pbyte;
      pprt->prtcode_size[i] = len;
      if (code == 0) code = 1;
    }
  }
  
  /* name */
  if (ppi_o[0]) {
    byte *pbyte;
    int len = ppi_o[0]->value.a.size;
    pbyte = (byte *)malloc(len+1);
    if (pbyte == 0) {
      code = e_VMerror;
      goto error_end;
    }
    memcpy(pbyte,ppi_o[0]->value.a.p.s,len);
    pbyte[len] = 0;
    pprt->strings[CFG_NAME] = pbyte;
    if (code == 0) code = 1;
  }
  
  /* encode */
  if (ppi_o[1]) {
    for (i=0;gdev_dmprt_encode_list[i].name;i++) {
      if (strlen(gdev_dmprt_encode_list[i].name) == ppi_o[1]->value.a.size) {
	if (strncmp(gdev_dmprt_encode_list[i].name,
		    ppi_o[1]->value.a.p.s,ppi_o[1]->value.a.size) == 0) {
	  pprt->integer[CFG_ENCODE] = gdev_dmprt_encode_list[i].no;
	  break;
	}
      }
    }
    if (gdev_dmprt_encode_list[i].name == 0) {
      code = e_rangecheck;
      goto error_end;
    }
    else if (code == 0) code = 1;
  }
  
  if (ppi_o[2]) {
    if (ppi_o[2]->value.b)
      up |= CFG_NON_MOVING;
    if (code == 0) code = 1;
  }
  else up |= pprt->integer[CFG_UPPER_POS] & CFG_NON_MOVING;
  
  if (ppi_o[3]) {
    if (ppi_o[3]->value.a.size != 2) {
      ppi_o[3]->status = pv_typecheck;
      code = e_typecheck;
      goto error_end;
    }
    else {
      gs_prop_item *pai = ppi_o[3]->value.a.p.v;
      pddev->dmprt.x_offset = pai[0].value.i;
      pddev->dmprt.y_offset = pai[1].value.i;
      if (code == 0) code = 1;
    }
  }
  if (ppi_o[4]) {
    if (ppi_o[4]->value.a.size != 2) {
      ppi_o[4]->status = pv_typecheck;
      code = e_typecheck;
      goto error_end;
    }
    else {
      gs_prop_item *pai = ppi_o[4]->value.a.p.v;
      pddev->dmprt.max_width = pai[0].value.i;
      pddev->dmprt.max_height = pai[1].value.i;
      if (code == 0) code = 1;
    }
  }
  if (ppi_o[5]) {
    pddev->dmprt.Orientation = ppi_o[5]->value.i;
    if (code == 0) code = 1;
  }
  if (ppi_o[6]) {
    pddev->dmprt.MirrorPrint = ppi_o[6]->value.b;
    if (code == 0) code = 1;
  }
  if (ppi_o[7]) {
    pddev->dmprt.NegativePrint = ppi_o[7]->value.b;
    if (code == 0) code = 1;
  }
  if (ppi_o[8]) {
    pddev->dmprt.Separations = ppi_o[8]->value.b;
    if (code == 0) code = 1;
  }
  
  /* margins */
  if (ppi_o[9]) {
    if (ppi_o[9]->value.a.size != 4) {
      ppi_o[9]->status = pv_typecheck;
      code = e_typecheck;
      goto error_end;
    }
    else {
      gs_prop_item *pai = ppi_o[9]->value.a.p.v;
      for (i=0;i<4;i++)
        pddev->dmprt.dev_margin[i] = pai[i].value.i;
      if (code == 0) code = 1;
    }
  }
  
  if (ppi_o[11]) {
     pddev->dmprt.verbose_f = ppi_o[11]->value.b;
    if (code == 0) code = 1;
  }
  
  error_end:
  if (code < 0) return code;
  if (pdev->is_open && code) {
    int ccode = gs_closedevice(pdev);
    if (ccode < 0) return ccode;
  }
  
  pprt->integer[CFG_UPPER_POS] = up;
  
  { int ccode;
    pddev->width = pddev->dmprt.spec_width;
    pddev->height = pddev->dmprt.spec_height;
    ccode = gdev_prn_put_props(pdev, plist, count);
    pddev->dmprt.spec_width = pddev->width;
    pddev->dmprt.spec_height = pddev->height;
    pddev->width -= (pddev->dmprt.dev_margin[0] + pddev->dmprt.dev_margin[2]);
    pddev->height -= (pddev->dmprt.dev_margin[1] + pddev->dmprt.dev_margin[3]);
    if (ccode < 0) return ccode;
    if (code == 0) code = ccode;
  }
  
  if (pddev->dmprt.max_width>0 && pddev->dmprt.max_width<pddev->width)
    pddev->width = pddev->dmprt.max_width;
  if (pddev->dmprt.max_height>0 && pddev->dmprt.max_height<pddev->height)
    pddev->height = pddev->dmprt.max_height;
  
  dviprt_setmessagestream(pddev->dmprt.debug_f ? stderr : NULL);
  
  return code;
}

/* --- Get initial matrix. --- */
private void
gdev_dmprt_get_initial_matrix(gx_device *pdev, gs_matrix *pmat)
{
  gs_matrix mata,matb;
  
  gx_default_get_initial_matrix(pdev,pmat);

  /* MirrorPrint */
  if (pddev->dmprt.MirrorPrint) {
    gs_make_identity(&matb);
    matb.xx = -1;
    matb.tx = pdev->width;
    gs_matrix_multiply(pmat,&matb,&mata);
  }
  else mata = *pmat;
  
  /* Orientation */
  { int rotation = pddev->dmprt.Orientation%4;
    floatp tx=0,ty=0;
    gs_make_rotation(90*rotation,&matb);
    gs_matrix_multiply(&mata,&matb,pmat);
    if (rotation == 1) { tx = pdev->height; }
    else if (rotation == 2) { tx = pdev->width; ty = pdev->height; }
    else if (rotation == 3) { ty = pdev->width; }
    pmat->tx += tx; pmat->ty += ty;
  }
  
  pmat->tx += (pddev->dmprt.x_offset - pddev->dmprt.dev_margin[0]);
  pmat->ty += (-pddev->dmprt.y_offset + pddev->dmprt.dev_margin[3]);
}

/* --- Open printer device. --- */
private int
gdev_dmprt_open(gx_device *pdev)
{
  int code;
  dviprt_cfg_t *pcfg;
  dviprt_print *pprint;

  pprint = &pddev->dmprt.prtinfo;
  pcfg = &pddev->dmprt.prtcfg;
  
  if ((code = gdev_prn_open(pdev)) < 0)
    return code;
  pcfg->integer[CFG_DPI] = (int)ppdev->x_pixels_per_inch;
  pcfg->integer[CFG_Y_DPI] = (int)ppdev->y_pixels_per_inch;
  code = dviprt_initlibrary(pprint,pcfg,gdev_prn_raster(pdev),pdev->height);
  if (code < 0) return gdev_dmprt_error_no_dviprt_to_gs(code);
  code = dviprt_setbuffer(pprint,NULL);
  if (code < 0) return gdev_dmprt_error_no_dviprt_to_gs(code);
  
  return 0;
}

/* --- Close printer device. --- */
private int
gdev_dmprt_close(gx_device *pdev)
{
  int code;
  dviprt_print *pprint;
  
  pprint = &pddev->dmprt.prtinfo;

  if (!strchr(pddev->fname,'%')) {
    code = dviprt_endbitmap(pprint);
    if (code < 0) return gdev_dmprt_error_no_dviprt_to_gs(code);
  }
  if (pddev->dmprt.verbose_f && pddev->page_count>0) {
    eprintf2("%s: Total %lu bytes output.\n",
      pddev->dname,dviprt_getoutputbytes(pprint));
  }
  code = dviprt_unsetbuffer(pprint);
  if (code < 0) return gdev_dmprt_error_no_dviprt_to_gs(code);
  return gdev_prn_close(pdev);
}

/* Output the PAGE. */
private int
gdev_dmprt_print_page(gx_device_printer *pdev, FILE *prn_stream)
{
  int code = 0;
  dviprt_print *pprint = &pddev->dmprt.prtinfo;
  int line_size = gdev_prn_raster((gx_device *)pdev);
  int pins = dviprt_getscanlines(pprint);
  int i_buf_size = pins * line_size;
  int lnum = 0;
  ulong prev_bytes;
  byte *in;
  
  /* get work buffer */
  in = (byte *)gs_malloc(1, i_buf_size ,"gdev_dmprt_print_page(in)");
  if ( in == 0 )
    return e_VMerror;
  
  /* Initialize this printer driver */
  if (pdev->file_is_new) {
    code = dviprt_setstream(pprint,NULL,prn_stream);
    if (code < 0) return gdev_dmprt_error_no_dviprt_to_gs(code);
  }
  if (pddev->dmprt.verbose_f) {
    if (pddev->page_count == 1)
      eprintf2("%s: %s\n", pddev->dname,  pddev->dmprt.prtcfg.strings[CFG_NAME]);
    eprintf2("%s: [%d]",pddev->dname, pddev->page_count);
  }
  prev_bytes = dviprt_getoutputbytes(pprint);
  code = dviprt_beginpage(pprint);
  if (code < 0) return gdev_dmprt_error_no_dviprt_to_gs(code);
  
  /* Transfer pixels to printer */
  while ( lnum < pdev->height ) {   
    int num_lines;
    
    num_lines = pdev->height-lnum;
    if (num_lines > pins)
      num_lines = pins;
    
    code = gdev_prn_copy_scan_lines(pdev,lnum,in,line_size*num_lines);
    if (code < 0) goto error_ex;
    
    lnum += num_lines;
    if (num_lines < pins) {
      memset(in+line_size*num_lines,0,line_size*(pins-num_lines));
    }
    
    code = dviprt_outputscanlines(pprint,in);
    if (code < 0) {
      code = gdev_dmprt_error_no_dviprt_to_gs(code);
      goto error_ex;
    }
  }
  
  /* Eject the page and set printer normal mode. */
  if (strchr(pdev->fname,'%')) {
    code = dviprt_endbitmap(pprint);
    if (code < 0) return gdev_dmprt_error_no_dviprt_to_gs(code);
  }
  fflush(pddev->file);
  if (pddev->dmprt.verbose_f) {
    eprintf1(" %lu bytes\n",dviprt_getoutputbytes(pprint)-prev_bytes);
  }
error_ex:
  gs_free((char *)in, 1, i_buf_size,"gdev_dmprt_print_page(in)");
  
  return code;
}


/************************** Internal Routines **************************/

/************************ Get printer properties. ***********************/
private int
gdev_dmprt_check_code_props(byte *str,int len)
{
  byte *end = str+len;
  while (str < end) {
    byte fmt = *str++;
    if (fmt & CFG_FMT_BIT) {
      int s = *str++;
      str += s;
      if (str > end) return e_rangecheck;
      if ((fmt & CFG_FMT_FORMAT_BIT) == CFG_FMT_STRINGS) {
        s = *str++;
        str += s;
        if (str > end) return e_rangecheck;
      }
    }
    else {
      str += fmt;
      if (str > end) return e_rangecheck;
    }
  }
  return str == end ? 0 : e_rangecheck;
}

private void
gdev_dmprt_init_printer_props(gx_device_dmprt *pdev)
{
  dviprt_cfg_t *pprt;
  int i;

  pprt = &pdev->dmprt.prtcfg;
  
  for (i=0;i<CFG_INTEGER_TYPE_COUNT;i++)
    pprt->integer[i] = 0;
  for (i=0;i<CFG_STRINGS_TYPE_COUNT;i++)
    pprt->strings[i] = 0;
  for (i=0;i<CFG_PRTCODE_TYPE_COUNT;i++) {
    pprt->prtcode[i] = 0;
    pprt->prtcode_size[i] = 0;
  }
  pdev->dmprt.prtcfg_init_f = 1;
}

private int
gdev_dmprt_get_printer_props(gx_device_dmprt *pdev,char *fnamebase)
{
  int code;
  FILE *fp;
  dviprt_cfg_t cfg;
  byte *readbuf;
  char *fname;

  fname = gs_malloc(256,1,"dviprt_lib_fname");
  if (fname == NULL) return e_VMerror;
  
  fp = gdev_dmprt_dviprt_lib_fopen(fnamebase,fname);
  if (fp == NULL) {
    return e_undefinedfilename;
  }
  if (fseek(fp,18,0) < 0)
    return e_ioerror;
  code = fgetc(fp);
  fclose(fp);
  
  if (code == EOF)
    code = e_ioerror;
  else if (code == 0xff) {
    code = dviprt_readcfg(fname,&cfg,NULL,0,NULL,0);
  }
  else {
    code = dviprt_readsrc(fname,&cfg,NULL,0,NULL,0);
  }
  
  if (code < 0) {
    code = gdev_dmprt_error_no_dviprt_to_gs(code);
  }
  else { /* success */
    memcpy(&pdev->dmprt.prtcfg,&cfg,sizeof(dviprt_cfg_t));
    pddev->dmprt.orig_x_dpi = cfg.integer[CFG_DPI];
    pddev->dmprt.orig_y_dpi =
      cfg.integer[CFG_Y_DPI] > 0 ? cfg.integer[CFG_Y_DPI] : pddev->dmprt.orig_x_dpi;
  }
  
  gs_free(fname,256,1,"dviprt_lib_fname");
  
  return code;
}

private FILE *
gdev_dmprt_dviprt_lib_fopen(const char *fnamebase,char *fname)
{
  FILE *fp;
  char *env;

  strcpy(fname,fnamebase);
  fp = lib_fopen(fname);
  if (fp == NULL) {
    env = getenv("TEXCFG");
    if (env) {
      strcpy(fname,env);
      strcat(fname,
        gp_file_name_concat_string(env,strlen(env),fname,strlen(fnamebase)));
      strcat(fname,fnamebase);
      fp = fopen(fname,gp_fmode_rb);
    }
  }
  return fp;
}

/* Misc. */
private int
gdev_dmprt_error_no_dviprt_to_gs(int code)
{
  switch (code) {
  case CFG_ERROR_MEMORY:
    return e_VMerror;
  case CFG_ERROR_FILE_OPEN:
  case CFG_ERROR_OUTPUT:
    return e_ioerror;
  default:
    return -1;
  }
}
