/* PROGRAM NAME: mim2hpTrans.c                                              */
/* DATE:   May 01, 1995                                                     */
/* AUTHOR: Sheeja Malaveetil, U.S. Department of Commerce, Census Bureau,   */
/*              Geography Division, Tiger Mapping Branch                    */
/* DESC:                                                                    */
/*         This function is designed to read a MIM and to output a HPGL/2 file.     */ 
/*         It assumes that the MIM is in a format matching the MIM specification.   */ 
/* CREDITS:                                                                 */
/*   This program is largely based on mim2psTrans.c (mim to postscript) written by: */ 
/*       F.R.Broome, Leslie Godwin, Les Libelo, Fred Malkus, and Lisa Nyman */
/*       U.S. Department of Commerce, Census Bureau, Geography Division     */
/*==========================================================================*/
/* Modification History                                                     */
/* 05/01/95  sm - original program                                          */
/* 09/13/95  sm - modified routine so that rotation conditions for plotter 
                  output will be dependent on whether the Y-axis size is 
                  greater than the X-axis size. Laser rotation is the 
                  opposite, ie rotation happens if X-axis size is greater 
                  than Y-axis size.                                         */
/* 09/21/95  sm - modified routine so line attributes are butt ends 
                  mitred/BEVELED joins and miter limit is the device 
                  dependent default                                         */
/* 10/31/95  sm - modified so that *cmt Param_LINE_ATTRIBUTES is interpreted 
                  for specifying line ends, joins, and mitre limits.      */
/* 11/07/95  sm - modified for non-Raster Graphics plotter: .005 will be not 
                  be added to line weights in an attempt to eliminate gaps 
                  in lines    */
/* 11/28/95  sm - modified so font file directory path specification is 
                  passed in from mim2hp.c and passed to mobTexthp.c       */
/* 12/05/95  sm - modified so that Lines have rounded ends by default 
                  (see LA1) in "cmt" code.  This was done to cover up the 
                  Raster Graphics limitation of no line joins              */
/* 12/06/95  sm - modified so that Lines have rounded ends only when printing
                 to a Raster Graphics device, otherwise will have butt ends.*/
/* 12/11/95  sm - modified so that wctype.h is not included. Done for PC 
                  compilation hopefully this is not used                    */
/* 02/05/96  sm - For PC version changed the way a pattern is stored from a */
/*                2-dimensional array to a 1 dimensional array.             */
/* 03/05/96  sm - modified calls to patternSethp.c so that argument list is 
                  shorter */
/*                removed arguments that were unnecessary.                  */
/* 03/11/96  sm - modified so that for laser printers the resolution is set 
                  from the mim file *msz command.                           */
/* 03/20/96  sm - modified for testing so that *cmt Param_MC and *cmt 
                  Param_TR are interpreted for merge control and transparency
                  mode.      */
/* 03/20/96  sm - modified so default line join is beveled (2,5) not 
                  mitred/beveled */
/* 03/25/96  sm - modified so that the "*cmt Param_Spanish" is interpreted. 
                  Also added the "*cmt" if checks.              *
/* HISTORY:                                                     */
/*          04/24/96 - Sheeja did the following:                */
/*                        1. added #include "parseTokens.h"     */
/*                        2. deleted prototype for parseTokens  */
/*                        3. deleted declarations for arrays    */
/*                            tokenStrings & tokenStrPtrs       */
/*                     This was done because parseTokens.h now  */
/*                     contains the declarations as extern and  */
/*                     includes the prototype                   */
/*                                                              */
/*==========================================================================*/
/*VERSION:  01 May 1995                                                     */
/*  Does not process some commands.                                         */
/*  Among them are: *dep and *aka                                           */
/*                                                                          */

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>
#include <malloc.h> 
#include <errno.h>
#include "mim2hpll.h"
#include "parseTokens.h"

#define DOUBLEQUOTE 34
#define ESC 27

#ifndef MIM_POINTS

#define MIM_POINTS 1

typedef struct {
  float   x, y;
  } MIMPOINT;

typedef struct {
  float   x, y;
  } POLYPOINT;

#define POLY_STRTS 1

typedef struct
{
        int poly_points_tot;
        POLYPOINT *points_ptr;
} POLYSTRT;

/* Prototypes */
int  mim2hpSkip(char *c, char *r,long *n); 
int  mobTexthp(char *c,float x,float y,float h,float a,char *s,char f);  
void patternSethp(FILE *f, char *c, char cmd_src); 
int  mimCMDdep( char *d, long *n); 
int  mimDOdep( char *d ); 
void census2ISO( char *t ); 
int  mimDLThp( char *d, char *p, long  *n );
int mimLcvhp (char inRec[], long *numRecsRead); 
int mimLcphp (char inRec[], long *numRecsRead); 
int mimLcshp (char inRec[], long *numRecsRead); 
int  mimRgbhp( char *c, long n ); 
int  mimLwshp( char *c, long n ); 
int  mimLwvhp( char *c, long n ); 
int  mimLwphp( char *c, long n ); 
int  mimStrhp(MIMPOINT *mimPts,long numPts,int solidLineFlag,char str_src); 
int mimDPAhp(char *inRec, long *numRecsRead);
/*
 C int mimPgxhp_outline(POLYSTRT *poly_ptr,int num_polys,int solidLineFlag,char pgx_src);
*/
int mim2hpTrans(void);

long  numMallocedPoints = 0;
long  numMallocedPolyPts = 0;
long  numMallocedPolys = 0;

#endif

int mim2hpTrans()
{
POLYPOINT       *pPts = NULL;
MIMPOINT        *mimPts = NULL; /* Pointer to array to hold points. */
MIMPOINT        *temp_ptr=NULL;
MIMPOINT        mimPoint;
POLYSTRT        *poly_ptr = NULL; /* Pointer to array of structure that holds poly points */ 
extern int      ROTATEFLAG, COPIESFLAG;
extern int      DEBUG_FLAG;
extern int      TEST_FLAG;
extern FILE     *mimfile, *hpfile;
extern char     mimfilename[127];
extern char           fcs[32], fcp[32], fcv[32],  /* Fill color      */
                               fpp[32], fpv[32],  /* Fill pattern    */
                      lcs[32], lcp[32], lcv[32],  /* Line color      */
                      lps[32], lpp[32], lpv[32],  /* Line pattern    */
                      lts[32], ltp[32], ltv[32],  /* Line type       */
                      lws[32], lwp[32], lwv[32];  /* Line weight     */
extern char     currentColor[32], currentLineWeight[32],currentLineType[32];
extern char     currentLinePattern[32],currentPolyPattern[32];
extern char     FOB, currentFont[64];
extern char     FOBpgX;
extern float    BoundingBoxLeft, BoundingBoxBottom;
extern float    adjscale;
extern int      befDepth;
extern float    mszXsize, mszYsize;    /* msz MIM size.             */
extern int      mszResolution;
extern int      firstPatternFlag;
extern float    deviceFactor;        /* For converting msz res to hp */
extern float    relArrayX[128], relArrayY[128], offsetX, offsetY;
extern float    ltsValues[64];
extern int      ltsNumVals;
extern int      pu_i;               /*sm: in int: Plotter units/inch from argument list */
extern int      dpi_i;              /*sm: in int: Dots per inch (DPI) from agrument list */
extern int      pcl_flag;           /*sm: Output format flag from argument list, if "1"
                                             will include PCL commands also, else pure HPGL/2 */
extern int      plot_flag;   /*sm: set from command line, = 1 if output device is plotter */
extern int      rg_flag;   /*sm: set from command line, = 1 if output device is Raster Graphics */
                                    /* color plotter */
extern char     ch_fontpath[80];     /*sm: Directory path containing font files. Default is
                                             current directory */
extern int      pageSizeFlag;
extern int      convertSpanishFlag;
extern float    mobCharSpacingVal, mobCharAngleVal, mobCharWidthFac; 
extern int      OLD_LETTER_SPACING, mobCharKerning;
long            numRecsRead = 0;
FILE            *holdOldFilePointer;
char            fileName[128];
char            inRec[256];            /* Input record              */
int             numToks;               /* Token count.              */
char            tokStr[256];           /* Holder for token string.  */
unsigned long   tokVal;
float 		xSide, ySide;
float           xPos, yPos, hei, ang;  /* vtx arguments.            */
char            textString[256];
float           redValue, greenValue, blueValue;
float           polyLowX, polyLowY, polyHiX, polyHiY;
 
int             i=0, j=0, k=0, tmp=0;      /* Working variable.         */
int             num_str_pts=0,str_pt_ct=0; 
int             firstPointFlag = 0;    
int             num, moreFlag = 1;
char            chr;             /* Single char working var.  */
char            work[255];             /* Char array working var.   */
int             solidLineFlag;
float           x, y, ltypeLength;
int             ltsFlag;
int		num_polys=0;
int		num_polys_loaded=0;
int 		num_pts_in_poly=0;
int		num_pts_loaded=0;
int		init_flag=0;
int		msz_flag=0;
int             cls_flag=0;
int		ret_stat=0;
int             mc_flag=0;
int             tr_flag=0;
float		anchor_x,anchor_y;
char 		*line_attr="\0";
char		*mlptr="\0";
int	ml_val=0;

/*-----------------------------------------------------------------*/
/*                NOW PROCESS MIM COMMAND RECORDS.                 */
/* Note:                                                           */
/* There is a fundamental difference between MIM and HPGL/2 in */
/* the way entity (line, polygon, and text) attribute states are   */
/* set. HPGL/2 settings for color, lineweight, and so forth are*/
/* effective for ALL successive entities drawn. MIM is more precise*/
/* in that it allows each entity type to have separate attribute   */
/* states, i.e., the color red can be active for lines (*str's) at */
/* the same time that blue is the active for text (*vtx's).   In   */
/* HPGL if red is the current color, it is so for all follow-*/
/* entities.  This means that MIM to HPGL/2 translators must do*/
/* much more attribute state checking to assure the proper states  */
/* are set for the entity type being output.  This program does the*/
/* required checking.                                              */
/*                                                                 */
if(DEBUG_FLAG==0)
   TEST_FLAG=0;
if (!mimfile)
{
if(DEBUG_FLAG==1)
   printf(" ERROR: Unable to find file pointer. ABORTING......\n");
   exit(errno);
}
  while(moreFlag)
  {
     numRecsRead++; /* Count MIM records read. */
     fgets(inRec, 255, mimfile);
     if(feof(mimfile))
     {
        moreFlag = 0;
        if(mimfile)
        fclose(mimfile);
        break;
     }
     numToks = parseTokens( inRec );
     if(numToks < 1)          /* Bypass obviously blank records. */
     continue;
     strcpy(tokStr, tokenStrPtrs[0]);
     if((strlen(tokStr) == 4) && (tokStr[0] == '*'))
     {
        tokVal = (unsigned long)(tokStr[0]);
        tokVal = (tokVal << 8) | (unsigned long)(tokStr[1]);
        tokVal = (tokVal << 8) | (unsigned long)(tokStr[2]);
        tokVal = (tokVal << 8) | (unsigned long)(tokStr[3]);
        switch (tokVal)
        {
           case 711222640:    /* MIM *dep command */
if(TEST_FLAG)
   printf("\nRead in a *dep command!\n");
              k = mimCMDdep(inRec, &numRecsRead); 
              break;
           case 711159156:    /* MIM *cmt command */
        /* Test for special comment commands. */
if(TEST_FLAG)
   printf("\nRead in a *cmt command!\n");
              if(strncmp(tokenStrPtrs[1], "Param_OLD_LETTER_SPACING",24) == 0)  
              {
                 OLD_LETTER_SPACING = 1;
                 continue;
              }
              if(strncmp(tokenStrPtrs[1], "Param_ORIENTATION_LANDSCAPE",27)==0)
              {   /* Assumes that this comment preceeds the *msz command. */
                 if(plot_flag != 1)
                 {
if(DEBUG_FLAG==1)
   printf("  ROTATEFLAG requested via a Param entry.\n");
                    ROTATEFLAG = 1;
                 }
                 continue;
              }
              if( (strncmp(tokenStrPtrs[1], "Param_SPANISH",13)==0) 
               || (strncmp(tokenStrPtrs[1], "Param_Spanish",13)==0) 
               || (strncmp(tokenStrPtrs[1], "Param_spanish",13)==0) )
              {   
                 convertSpanishFlag=1;
if(DEBUG_FLAG==1)
   printf("  Spanish characters requested via a Param entry.\n");
                 continue;
              }
              if(strncmp(tokenStrPtrs[1], "Param_ORIENTATION_PORTRAIT",26)==0)
              {   /* Assumes that this comment preceeds the *msz command. */
                 if(plot_flag == 1)
                 {
if(DEBUG_FLAG==1)
   printf("  ROTATEFLAG requested via a Param entry.\n");
                    ROTATEFLAG = 1;
                 }
                 continue;
              }
              if(strncmp(tokenStrPtrs[1], "Param_MC",8)==0)
              {
                if(strcmp(tokenStrPtrs[2],"0"))
                   fprintf(hpfile, "MC1;\n"); /* Merge colors at intersections */
                else
                   fprintf(hpfile, "MC0;\n"); /* Don't merge colors at intersections */
                mc_flag = 1;
                continue;
              }
              if(strncmp(tokenStrPtrs[1], "Param_TR",8)==0)
              {
                if(strcmp(tokenStrPtrs[2],"0"))
                   fprintf(hpfile, "TR1;\n"); /* Set transparency mode on */
                else
                   fprintf(hpfile, "TR0;\n"); /* Set transparency mode off */
                tr_flag = 1;
                continue;
              }

              if(strncmp(tokenStrPtrs[1], "Param_LINE_ATTRIBUTES_",22)==0)
              {
                 strcpy(line_attr,"LA");
	  /* Evaluate Line Ends */
                 if(strstr(tokenStrPtrs[1],"_Ends:Butt"))
	            strcat(line_attr,"1,1");
                 else
                    if(strstr(tokenStrPtrs[1],"_Ends:Square"))
                       strcat(line_attr,"1,2");
                    else 
                      if(strstr(tokenStrPtrs[1],"_Ends:Triangular"))
                         strcat(line_attr,"1,3");
                      else 
                         if(strstr(tokenStrPtrs[1],"_Ends:Round"))
                            strcat(line_attr,"1,4");
                         else 
                            strcat(line_attr,"1,1");
	  /* Evaluate Line Joins */
                 if(strstr(tokenStrPtrs[1],"_Join:Mitred/Default"))
	            strcat(line_attr,",2,1");
                 else
                    if(strstr(tokenStrPtrs[1],"_Join:Mitred/Beveled"))
                       strcat(line_attr,",2,2");
                    else 
                       if(strstr(tokenStrPtrs[1],"_Join:Triangular"))
                          strcat(line_attr,",2,3");
                       else 
                          if(strstr(tokenStrPtrs[1],"_Join:Round"))
                             strcat(line_attr,",2,4");
                          else 
                             if(strstr(tokenStrPtrs[1],"_Join:Beveled"))
                                strcat(line_attr,",2,5");
                             else 
                                if(strstr(tokenStrPtrs[1],"_Join:None"))
                                   strcat(line_attr,",2,6");
                                else 
                                   strcat(line_attr,",2,1");
	  /* Evaluate Mitre Limit */
                 if(strstr(tokenStrPtrs[1],"_MitreLimit:Default"))
	            strcat(line_attr,",3,5;");
                 else
                    if(strstr(tokenStrPtrs[1],"_MitreLimit:None"))
	               strcat(line_attr,",3,5;");
                    else
                       if(mlptr = strstr(tokenStrPtrs[1],"MitreLimit:"))
                       {
                          mlptr=mlptr+11;
                          ml_val=strtol(mlptr,'\0',0);
                          if(ml_val)
                          {
                             strcat(line_attr,",3,");
                             strcat(line_attr,mlptr);
                             strcat(line_attr,";");
                          }
		          else
                             strcat(line_attr,",3,5;");
                       }
                       else
                          strcat(line_attr,",3,5;");
                 fprintf(hpfile, line_attr); /* Set line attributes */
                 continue;
              }
              break;
           case 712406136:    /* MIM *vtx command */
if(TEST_FLAG)
   printf("\nRead in a *vtx command at line %d!\n",numRecsRead);
              if((strcmp(tokenStrPtrs[numToks-1], "Xdel") == 0)  ||
                 (strcmp(tokenStrPtrs[numToks-1], "Xref") == 0))
              {
                 ret_stat = mim2hpSkip("*vtx", inRec,&numRecsRead); 
                 break;  /* Do not process this feature. */
              } 
              if(numToks > 4)
              {
                 xPos = (atof(tokenStrPtrs[1])+offsetX);
                 yPos = (atof(tokenStrPtrs[2])+offsetY);
                 hei  = atof(tokenStrPtrs[3]);
                 ang  = atof(tokenStrPtrs[4]);
                 numRecsRead++; /* Count MIM records read. */
                 fgets(inRec, 255, mimfile);   /* Get text record. */
if(TEST_FLAG)
   printf("input: %s\n",inRec);
                 numToks = parseTokens(inRec); 
                 if(convertSpanishFlag ) 
                    census2ISO(tokenStrPtrs[0]);
                 strcpy(textString, tokenStrPtrs[0]);
if(TEST_FLAG)
   printf("   *vtx: textString=%s currentFont=%s xPos=%1.3f yPos=%1.3f hei=%1.3f FOB=%c!\n",textString,currentFont,xPos,yPos,hei,FOB);
                 tmp = mobTexthp(currentFont,xPos,yPos,hei,ang,textString,FOB); 
                 if(!tmp)
                 {
if(DEBUG_FLAG)
{
   printf("  ERROR:  MIM line %d; ",numRecsRead);
   printf("on return from mobTexthp.c.  ABORTING ......... \n");
}
                    exit(0);
                 }

              }
              else
if(DEBUG_FLAG==1)
{
   printf("  WARNING: MIM line %d; ",numRecsRead);
   printf("illegal number of arguments.\n");
}
              break;
           case 711749747:    /* MIM *lps command */
        /* IMPORTANT NOTE:  These are set by a define pattern command  */
if(TEST_FLAG)
{
   printf("\nRead in a *lps command at line %d!\n",numRecsRead );
   printf("\n   *lps: tokenStrPtrs[1]=%s currentLinePattern=%s lps=%s !!!!\n",tokenStrPtrs[1],currentLinePattern,lps);
}
              if(numToks < 1 )
              {
if(DEBUG_FLAG==1)
{
   printf("  WARNING: At MIM line %d; ",numRecsRead);
   printf("a *lps-command has no pattern name.  Ignoring.\n");
}
                 break;
              }
              strcpy(lps,tokenStrPtrs[1]);
              if(strcmp(lps,currentLinePattern) != 0) 
              {
                /* current Pattern does not match what lps says */
if(TEST_FLAG)
   printf("\n    *lps: Reset: currentLinePattern=%s lps=%s!!\n",currentLinePattern,lps);
                 strcpy(currentLinePattern, lps);
                 patternSethp(hpfile,currentLinePattern,'L');
                 strcpy(lps,currentLinePattern);
if(TEST_FLAG)
   printf("      *lps: After Reset:currentLinePattern=%s lps=%s !!\n",currentLinePattern,lps);
              }  
              break;
           case 712205940:    /* MIM *sft command */
if(TEST_FLAG)
   printf("\nRead in a *sft command!\n");
              if(numToks > 1)
              {
                 strcpy(currentFont, "");
                 if(ch_fontpath)
                    strcat(currentFont, ch_fontpath); 
                 strcat(currentFont, tokenStrPtrs[1]);
                 if(numToks > 2)
                 {
                    FOB = *tokenStrPtrs[2];        /*Set as default*/
                    for(i = 2; i < numToks; i++)   /*Loop thru args for flags*/
                    {
                       if(strncmp(tokenStrPtrs[i], "-fillFlag", 9) == 0) /*Match*/
                          FOB = *tokenStrPtrs[i+1];  /* Get FOB if any. */ 
                       if(strncmp(tokenStrPtrs[i], "-spaceFac", 9) == 0) /*Match*/
                          mobCharSpacingVal = atof(tokenStrPtrs[i+1]);/*Get, if any.*/ 
                       if(strncmp(tokenStrPtrs[i], "-slopeFac", 9) == 0) /*Match*/
                          mobCharAngleVal = atof(tokenStrPtrs[i+1]); /* Get, if any.*/ 
                       if(strncmp(tokenStrPtrs[i], "-widthFac", 9) == 0) /*Match*/
                          mobCharWidthFac = atof(tokenStrPtrs[i+1]); /* Get, if any.*/ 
                       if(strncmp(tokenStrPtrs[i], "-kernFlag", 9) == 0) /*Match*/
                       {
                          if(strncmp(tokenStrPtrs[i], "ON", 2) == 0)
                             mobCharKerning = 1; /* Set to TRUE, if any.*/ 
                          else
                             mobCharKerning = 0; /* Set to FALSE. */ 
                       }
                    }
                 }
                 else
                    FOB = 'N';               /* Set to none.    */
              }
                 else
if(DEBUG_FLAG==1)
{
   printf("  WARNING: MIM line %d; ",numRecsRead);
   printf("illegal number of arguments.\n");
}
              break;
           case 712009560:    /* MIM *pgX command */
if(TEST_FLAG)
   printf("\nRead in a *pgX command at line %d!\n",numRecsRead);
if(TEST_FLAG)
   printf("input: %s\n",inRec);
              if((strcmp(tokenStrPtrs[numToks-1], "Xdel") == 0)  ||
                 (strcmp(tokenStrPtrs[numToks-1], "Xref") == 0))
              {
                 tmp = mim2hpSkip("*pgX", inRec,&numRecsRead); 
                 break;  /* Do not process this feature. */
              }
/* lwp - handle line weight polygon	*/
              if((strcmp(lwp, currentLineWeight)) != NULL )
              {
                 strcpy(currentLineWeight, lwp);
 	/* Convert lwp to plotter units and then to millimeters */
                 x = (atof(lwp) * deviceFactor) / 40;
                 fprintf(hpfile, "PW%1.3f;",x); 
              }
/* ltp - handle line type polygon */
              i = MIMlinetypeSearch( ltp, &num, ltsValues );
              if((strcmp(ltp, "solid") == 0)  || (strcmp(ltp, "Solid") == 0) || num == 0)
                 solidLineFlag = 1;
              else
                 solidLineFlag = 0;
/* fcp - handle fill color polygon	*/
if(TEST_FLAG)
   printf("    pgX:fcp:Before: currentColor=%s fcp=%s!",currentColor,fcp);
              if(strcmp(fcp, currentColor) != 0)
              {
                 tmp =  MIMcolorSearch(fcp, &redValue, &greenValue, &blueValue); 
                 if(!tmp)  /*If color not found, default to black. */
                 {
                    MIMcolorSearch("black",&redValue,&greenValue,&blueValue); 
if(DEBUG_FLAG==1)
{
   printf("  WARNING: Color requested in *fcp-command at MIM line");
   printf(" %d not\n    previously defined.  Defaulting to black.\n");
}
                    strcpy(fcp, "black");
                 }
                 strcpy(currentColor, fcp);
	         fprintf(hpfile, "PC1,%1.2f,%1.2f,%1.2f;SP1;",redValue,greenValue,blueValue);
              }
if(TEST_FLAG)
{
   printf("\n    pgX:fcp:After: currentColor=%s fcp=%s!\n",currentColor,fcp);
   printf("\n    pgX:fpp:Before: currentPolyPattern=%s fpp=%s!\n",currentPolyPattern,fpp);
}
/* fpp - handle fill pattern poly */
              FOBpgX = *tokenStrPtrs[3];   /*Get Fill/Outline/Both flag value.  */
              if((FOBpgX=='F') || (FOBpgX=='B') )
              {
                 if(strcmp(currentPolyPattern, fpp) != 0)
	         {
                    strcpy(currentPolyPattern, fpp);
                    patternSethp(hpfile,currentPolyPattern,'P');
                    strcpy(fpp,currentPolyPattern);
                 }
              }
if(TEST_FLAG)
   printf("     pgX:fpp:After: currentPolyPattern=%s fpp=%s!\n",currentPolyPattern,fpp);
/* Write out polygon */
/* Start working with number of polys and poly points */
              k = atol(tokenStrPtrs[1]);   /*Get number of polygon boundaries.  */ 
	      num_polys=0;
	      num_polys=atol(tokenStrPtrs[1]);
              j = atol(tokenStrPtrs[2]);   /*Get number of points in 1st poly.  */
	      num_pts_in_poly = 0;
	      num_pts_in_poly = atol(tokenStrPtrs[2]);
              i = 0;                       /*Set a working value.               */
              firstPointFlag = 0;
        /*Initialize poly envelope */
              polyLowX = 99.0 * mszXsize; polyLowY = 99.0 * mszYsize;
              polyHiX = -99.0 * mszXsize; polyHiY = -99.0 * mszYsize;
	      num_polys_loaded = 0;
	      num_pts_loaded=0;
              while( k > 0 )                 /* For each polygon boundary . . . */
              {
                 while( j > 0 )         /* Get points for this polygon boundary. */
                 {
                    numRecsRead++; /* Count MIM records read. */
                    fgets(inRec, 255, mimfile);
                    numToks = parseTokens( inRec );
                    if(numToks < 2)
                    {
if(DEBUG_FLAG==1)
{
   printf("  WARNING: MIM line %d; ",numRecsRead);
   printf("illegal number of tokens found.\n");
   printf("    Ignoring record.\n");
}
                       continue;
                    }
                    j = j - (numToks / 2);   /*Subtract number of points this rec.*/
                    for(i = 0; i < numToks; i++) /* Process this boundary string. */
                    { 
                       x = (atof(tokenStrPtrs[i])+offsetX);
                       if( polyLowX > x ) polyLowX = x;
                       if( polyHiX < x )  polyHiX = x;
                       i++;
                       num_pts_loaded++; 
                       if( polyLowY > y ) polyLowY = y;
                       y = (atof(tokenStrPtrs[i])+offsetY);
                       if( polyLowY > y ) polyLowY = y;
                       if( polyHiY < y )  polyHiY = y;
                       x *= deviceFactor;
                       y *= deviceFactor;
                          if(!firstPointFlag )
                          {
		             if(k==num_polys)
		             {
      		                fprintf(hpfile, "PU%1.3f,%1.3f;",x,y);
		                anchor_x=x;
		                anchor_y=y;
      		                fprintf(hpfile, "PM0;PD%1.3f,%1.3f",x,y);
		             }
		             else
		             {
      		                fprintf(hpfile, "PU%1.3f,%1.3f;",x,y);
      		                fprintf(hpfile, "PD%1.3f,%1.3f",x,y);
		             }
                             firstPointFlag = 1;
                          }
                          else
      		             fprintf(hpfile, ",%1.3f,%1.3f",x,y);
                    }    /*End for-loop reading one line of points. */
                 }       /*End while j>0, while there are more points to read */
  	         if (FOBpgX != 'O')
      	            fprintf(hpfile, ";");
                 if(num_pts_in_poly != num_pts_loaded)
                 {
if(DEBUG_FLAG==1)
{
   printf("Polygon error at record %d: Number of points specified: %d \n", numRecsRead,num_pts_in_poly);
   printf("    DOES NOT equal actual number of points in *pgX record: %d. \n", num_pts_loaded);
   printf("    ABORTING .......\n");
}
                    exit(0);
                 }
if(TEST_FLAG)
   printf("You loaded poly #%d so far!\n",num_polys_loaded);
                 k--;
                 if(k > 0 )     /* Check for more polygon boundary strings. */
                 {
                    num_polys_loaded++;
                    numRecsRead++; /* Count MIM records read. */
                    fgets(inRec, 255, mimfile);
                    numToks = parseTokens( inRec );
                    j = atol(tokenStrPtrs[1]);/*Get number of points in 1st poly.*/
                    num_pts_in_poly = 0;
                    num_pts_in_poly = atol(tokenStrPtrs[1]);
                    num_pts_loaded=0;
                    firstPointFlag = 0;
      	            fprintf(hpfile, "PM1;");
                 }
                 else
                 {      /* Print out the polygon and all it's exclusions. */
                    if((FOBpgX != 'F') && (FOBpgX != 'B') && (FOBpgX != 'O') )
                    {
if(DEBUG_FLAG==1)
   printf("  WARNING: No FOB.  Unpredictable pgX results.\n");
      	               fprintf(hpfile, "PM2;");
                       fprintf(hpfile,"EP;");
                    }
	            else
                    {
      	               fprintf(hpfile, "PM2;");
                       if(FOBpgX != 'O') 
                       {   /* fill polygon */
      	                  fprintf(hpfile, "FP;");
if(TEST_FLAG)
   printf("     pgx: Filled polygon with fcp=%s currentColor=%s currentPolyPattern=%s!\n",fcp,currentColor,currentPolyPattern);
                       }
                       if(FOBpgX != 'F')
                       {  /* outline polygon */
/* lcp - Handle line color polygon */
if(TEST_FLAG)
   printf("    *pgx:*lcp:Before: currentColor=%s lcp=%s!",currentColor,lcp);
		          if(strcmp(lcp, currentColor) != 0)
		          {
  		             tmp =  MIMcolorSearch(lcp, &redValue, &greenValue, &blueValue);
		             if(!tmp)  /*If color not found, default to black. */
		             {
		                MIMcolorSearch("black",&redValue,&greenValue,&blueValue);
		                strcpy(lcp, "black");
		             }
		             strcpy(currentColor, lcp);
		             fprintf(hpfile, "PC1,%1.2f,%1.2f,%1.2f;SP1;",redValue,greenValue,blueValue);
	                  }
/* lpp - handle line pattern poly */
                          if(strcmp(lpp, currentLinePattern) != 0) /* Set line pattern. */
                          {
                             strcpy(currentLinePattern, lpp);
                             patternSethp(hpfile, currentLinePattern, 'L');
                             strcpy(lpp,currentLinePattern);
                          }
      	                  fprintf(hpfile, "EP;");
                       }   /* end if(FOBpgX != 'F') */
                    } /* end else: if ( (FOBpgX != 'F') || (FOBpgX != 'B') || (FOBpgX != 'O') ) */
                 } /* end else: if( k > 0 )  Check for more polygon boundary strings.  */
              } /* end while k > 0 */
              break;
           case 711750768:    /* MIM *ltp command */
if(DEBUG_FLAG==1)
   printf("  WARNING: *ltp commands are NOT yet processed.\n");        
        /* IMPORTANT NOTE:  These are set by a define line pattern cmd */
if(TEST_FLAG)
   printf("\nRead in a *ltp command!\n");
              if(numToks < 1) 
	      {
if(DEBUG_FLAG==1)
{
   printf("  WARNING: At MIM line %d: ",numRecsRead);
   printf("  No line type name given.  Ignoring *ltp command.\n");
}
	         break;
              }
              else
              {
                 strcpy(ltp, tokenStrPtrs[1]); 
                 k = MIMlinetypeSearch(ltp, &i, ltsValues);
                 if(k == 0 )
                 {
if(DEBUG_FLAG==1)
{
   printf("  WARNING: MIM line %d. Line type %s is not defined.\n",numRecsRead,ltp);
   printf("    Defaulting to solid.\n");
}
                    strcpy(ltp, "solid");
                 }
                 ltsNumVals = i;       /*Get number of values this line type.*/
              }
              break;
           case 711356528:    /* MIM *fpp command */
        /* IMPORTANT NOTE:  These are set by a define pattern command  */
if(TEST_FLAG)
{
   printf("\nRead in a *fpp command at line %d!\n",numRecsRead );
   printf("\n   *fpp: numToks=%d tokenStrPtrs[1]=%s currentPolyPattern=%s fpp=%s !!!!\n",numToks,tokenStrPtrs[1],currentPolyPattern,fpp);
}
              if(numToks < 1 )
              {
if(DEBUG_FLAG==1)
{
   printf("  WARNING: At MIM line %d; ",numRecsRead);
   printf("a *fpp-command has no pattern name.  Ignoring.\n");
}
                 break;
              }
              strcpy(fpp,tokenStrPtrs[1]);
              if(strcmp(fpp,currentPolyPattern) != 0) 
              {
                /* current Pattern does not match what fpp says */
if(TEST_FLAG)
   printf("\n      fpp: Reset:  currentPolyPattern=%s fpp=%s !!!!\n",currentPolyPattern,fpp);
                 strcpy(currentPolyPattern, fpp);
                 patternSethp(hpfile,currentPolyPattern,'P');
                 strcpy(fpp,currentPolyPattern);
              }
if(TEST_FLAG)
   printf("          fpp: After:  currentPolyPattern=%s fpp=%s !!!!\n",currentPolyPattern,fpp);
              break;
           case 711749744:    /* MIM *lpp command */
        /* IMPORTANT NOTE:  These are set by a define pattern command  */
if(TEST_FLAG)
{
   printf("\nRead in a *lpp command at line %d!\n",numRecsRead);
   printf("\n   *lpp: numToks=%d tokenStrPtrs[1]=%s currentLinePattern=%s lpp=%s !!!!\n",numToks,tokenStrPtrs[1],currentLinePattern,lpp);
}
              if(numToks < 1 )
              {
if(DEBUG_FLAG==1)
{
   printf("  WARNING: At MIM line %d; ",numRecsRead);
   printf("a *lpp-command has no pattern name.  Ignoring.\n");
}
                 break;
              }
              strcpy(lpp,tokenStrPtrs[1]);
              if(strcmp(currentLinePattern, lpp) != 0)
              {
if(TEST_FLAG)
   printf("      *lpp: Reset:  currentLinePattern=%s lpp=%s !!",currentLinePattern,lpp);
                strcpy(currentLinePattern, lpp);
                patternSethp(hpfile,currentLinePattern,'L');
                strcpy(lpp,currentLinePattern);
if(TEST_FLAG)
   printf("\n      *lpp: After Reset:  currentLinePattern=%s lpp=%s !!\n",currentLinePattern,lpp);
              }
              break;
           case 711751542:    /* MIM *lwv command */
if(TEST_FLAG)
   printf("\nRead in a *lwv command at line %d!\n",numRecsRead);
              i = mimLwvhp(inRec, numRecsRead); 
              break;
           case 711751536:    /* MIM *lwp command */
if(TEST_FLAG)
   printf("\nRead in a *lwp command!\n");
              if(numToks < 2)
if(DEBUG_FLAG==1)
{
   printf("  WARNING: MIM line %d; ",numRecsRead);
   printf("Too few arguments in *lwp command.  Ignoring.\n");
}
	      else
	         i = mimLwphp(inRec, numRecsRead);
	      break;
           case 712209522:    /* MIM *str command */
if(TEST_FLAG)
   printf("\nRead in a *str command at line %d!\n",numRecsRead);
	      if((strcmp(tokenStrPtrs[numToks-1], "Xdel") == 0)  ||
		 (strcmp(tokenStrPtrs[numToks-1], "Xref") == 0))
              {
		 tmp = mim2hpSkip("*str", inRec,&numRecsRead);
		 break;  /* Do not process this feature. */
	      }
	      num_str_pts = atol(tokenStrPtrs[1]);   /*Get number of points to be output. */
	      if(num_str_pts > numMallocedPoints )
	      {
if(TEST_FLAG)
   printf("    *str: numMallocedPoints=%d num_str_pts=%d!   Freeing up space....\n",numMallocedPoints, num_str_pts);
		 if(mimPts) free(mimPts);  /* Free space is used. */
	         mimPts = (MIMPOINT *)(malloc( num_str_pts * sizeof(MIMPOINT)) );
		 if(!mimPts)
                 {
if(DEBUG_FLAG==1)
   printf(" ERROR allocating memory in *str! EXITING......\n");
		    exit(errno);
		 }
		 numMallocedPoints = num_str_pts;
              }
	      i = 0;                /*Set a working value.               */
	      firstPointFlag = 1;
/* lws - handle line weight string */
	      if(strcmp(lws, currentLineWeight) != 0)
	      {
		 strcpy(currentLineWeight, lws);
		 x = (atof(lws) * deviceFactor) / 40; /* Set lws to plott units, to milmtrs */
		 fprintf(hpfile, "PW%1.3f;",x);
              }
/* lcs - handle line color string */
	      if(strcmp(lcs, currentColor) != 0)   /* Set line color state. */
	      {
		 tmp =  MIMcolorSearch(lcs, &redValue, &greenValue, &blueValue);
		 if(!tmp)  /*If color not found, default to black. */
		 {
	            MIMcolorSearch("black",&redValue,&greenValue,&blueValue);
		    strcpy(lcs, "black");
		 }
		 strcpy(currentColor, lcs);
		 fprintf(hpfile, "PC1,%1.2f,%1.2f,%1.2f;SP1;",redValue,greenValue,blueValue);
              }
/*  solidLineFlag - set via lts (line type string) */
              tmp = MIMlinetypeSearch( lts, &num, ltsValues );
	      if((strcmp(lts, "solid") == 0)  || (strcmp(lts, "Solid") == 0) || num == 0)
		 solidLineFlag = 1;
              else
		 solidLineFlag = 0;
if(TEST_FLAG)
   printf("mim2hpTrans.c:  lts=%s num=%d, solidLineFlag = %d!\n",lts,num,solidLineFlag);

/* lps - handle line pattern string */
	      if(strcmp(lps, currentLinePattern) != 0) /* Set line pattern. */
	      {
		 strcpy(currentLinePattern, lps);
		 patternSethp(hpfile,currentLinePattern,'L');
		 strcpy(lps,currentLinePattern);
	      }
/* lts - handle line type string, if not solid */
              if(!solidLineFlag)
	      {
		 tmp = MIMlinetypeSearch( lts, &num, ltsValues );
		 ltypeLength = ltsValues[0];  /*Initialize*/
		 ltsFlag = 1;
              }
	      str_pt_ct = 0;  /* Counter of points loaded into mimPts. */
	      while( num_str_pts > 0 )
	      {
		 numRecsRead++; /* Count MIM records read. */
		 fgets(inRec, 255, mimfile);
		 numToks = parseTokens( inRec );
		 if(numToks < 2)
		 {
if(DEBUG_FLAG==1)
{
   printf("  WARNING: Illegal number of tokens found at input ");
   printf("line %d\n    Ignoring record.\n", numRecsRead);
}
		    continue;
	         }
  /* load the string points into an array of structures, this array
		will be sent to mimStrhp.c which will output code to display the
		string according to it's line type (lts) */
		 for(i = 0; i < numToks; i++)
		 {
		    mimPoint.x = atof(tokenStrPtrs[i]);
		    i++;
		    mimPoint.y = atof(tokenStrPtrs[i]);
	            *(mimPts+str_pt_ct) = mimPoint;
		    str_pt_ct++;
	         }     /*End for-loop reading one line of points. */
		 num_str_pts = num_str_pts - (numToks / 2);     /*Subtract number of points this rec.*/
	      }       /*End reading points for this *str feature.*/
if(TEST_FLAG)
   printf("    *str:str_pt_ct=%d solidLineFlag=%d num_str_pts=%d!\n",str_pt_ct,solidLineFlag,num_str_pts);
	      tmp = mimStrhp( mimPts, str_pt_ct, solidLineFlag,'S');
	      break;
           case 711746419:    /* MIM *lcs command */
if(TEST_FLAG)
{
   printf("\nRead in a *lcs command at line %d!\n",numRecsRead);
   printf("   *lcs:Before: currentColor:%s lcs:%s!",currentColor,tokenStrPtrs[1]);
}
              k = mimLcshp(inRec, &numRecsRead); 
if(TEST_FLAG)
   printf("\n   *lcs:After: currentColor:%s lcs:%s!\n",currentColor,lcs);
              break;
           case 711225441:    /* MIM *dpa command */
if(TEST_FLAG)
   printf("\nRead in a *dpa command!\n");
        /* IMPORTANT NOTE:  This routine accepts two type of bit   */
        /* bit patterns:                                           */
        /*   Packed - where the 1's and 0's are consecutive with no*/
        /*     spaces, comers, of similar between them.            */
        /*   Extended - where the 1's and 0's are separated by a   */
        /*     space.                                              */
/*
if(TEST_FLAG)
   printf("\ninTrans:numRecsRead=%d\n",numRecsRead);
*/
              k = mimDPAhp( inRec, &numRecsRead); 
              if(!k )
if(DEBUG_FLAG==1)
   printf("  WARNING: *dpa error detected.  Ignoring command.\n");
if(TEST_FLAG)
   printf("\nFinished processing a *dpa command!\n");
              break;
           case 711224436:    /* MIM *dlt command */
if(TEST_FLAG)
   printf("\nRead in a *dlt command!\n");
              if(numToks < 3)
              {
if(DEBUG_FLAG==1)
{
   printf(" FATAL ERROR: At MIM line %d; the *dlt-command",numRecsRead);
   printf(" has too few arguments.\n  Cannot determine how many more ");
   printf("records to read.  Command may or \n  may not");
   printf(" have additional records.  ABORTING!!\n\n");
}
                 exit(0);
              }
              strcpy(work, inRec);
              k = atol(tokenStrPtrs[1]);
              inRec[0] = ' ';              /* Effectively make a blank record. */
              inRec[1] = '\0';
              if(k > 0 )   /* Is there a line defining record. */
              {
                 numRecsRead++;
                 fgets(inRec, 255, mimfile );
                 inRec[strlen(inRec)] = '\0';
              }
              i = mimDLThp( work, inRec, &numRecsRead); 
              break;
           case 711552611:    /* MIM *inc command */
if(TEST_FLAG)
   printf("\nRead in a *inc command!\n");
              if(numToks < 2)
              {
if(DEBUG_FLAG==1)
{
   printf("  WARNING: At MIM line %d; ",numRecsRead);
   printf("No file name given on *inc-command.  Ignoring *inc\n");
}
                 break;
              }
              strcpy(fileName, mimfilename); /*Store the current mimfile name. */
              strcpy(mimfilename, tokenStrPtrs[1]);
              holdOldFilePointer = mimfile;  /*Store the current mimfile pointer*/
              if((mimfile = fopen(mimfilename,"r")) == NULL)
              {
if(DEBUG_FLAG==1)
{
   printf(" SERIOUS ERROR: MIM line %d Cannot",numRecsRead);
   printf(" open include file:%s\n",mimfilename);
   printf("  Ignoring *inc-command!.... . .  .\n\n");
}
                 mimfile = holdOldFilePointer;/*Restore current mimfile pointer*/
                 strcpy(mimfilename, fileName);
                 break; 
              }
              else
              {
if(DEBUG_FLAG==1)
   printf("Now processing MIM include file %s\n",mimfilename);
                 k = mim2hpTrans(); 
              }
              mimfile = holdOldFilePointer;/*Restore the current mimfile pointer*/
              strcpy(mimfilename, fileName); /*Restore current mimfile name.    */
              break;
           case 711750771:    /* MIM *lts command */
if(TEST_FLAG)
   printf("\nRead in a *lts command at line %d!\n",numRecsRead);
              if(numToks < 1)
              {
if(DEBUG_FLAG==1)
{
   printf("  WARNING: At MIM line %d: ",numRecsRead);
   printf("  No line type name given.  Ignoring *lts command.\n");
}
              }
              else
	      {
                 strcpy(lts, tokenStrPtrs[1]); 
                 k = MIMlinetypeSearch(lts, &i, ltsValues);
if(TEST_FLAG)
   printf("  lts found=%s\n",lts);
                 if(k == 0 )
                 {
if(DEBUG_FLAG==1)
{
   printf("  WARNING: MIM line %d. Line type %s is not defined.\n",numRecsRead,lts);
   printf("    Defaulting to solid.\n");
}
                    strcpy(lts, "solid");
                 }
                 ltsNumVals = i;       /*Get number of values this line type.*/
              }
              break;
           case 711751539:    /* MIM *lws command */
if(TEST_FLAG)
   printf("\nRead in a *lws command at line %d!\n",numRecsRead);
              i = mimLwshp(inRec, numRecsRead); 
              break;
           case 711353200:    /* MIM *fcp command */
if(TEST_FLAG)
   printf("\nRead in a *fcp command at line %d!\n",numRecsRead);
              if(numToks < 1 )
              {
if(DEBUG_FLAG==1)
{
   printf("  WARNING: At MIM line %d; ",numRecsRead);
   printf(" a *fcp-command has no color name.  Ignoring.\n");
}
                 break;
              }
              strcpy(fcp, tokenStrPtrs[1]);
if(TEST_FLAG)
   printf("    *fcp:Before: currentColor=%s fcp=%s!",currentColor,fcp);
             if(strcmp(fcp, currentColor) != 0)
             {
                k =  MIMcolorSearch(fcp, &redValue, &greenValue, &blueValue);
if(TEST_FLAG)
   printf("  After search for fcp=%s, k=%d!\n",fcp,k);
                if(!k)  /*If color not found, default to black. */
                {
                   MIMcolorSearch("black",&redValue,&greenValue,&blueValue); 
                   strcpy(fcp, "black");
                } 
if(TEST_FLAG)
   printf("    *fcp being reset from currentColor=%s to fcp=%s!\n",currentColor,fcp);
                strcpy(currentColor, fcp);
                fprintf(hpfile, "PC1,%1.2f,%1.2f,%1.2f;SP1;",redValue,greenValue,blueValue);
             }
if(TEST_FLAG)
             printf("\n    *fcp:After: currentColor=%s fcp=%s!\n",currentColor,fcp);
             break;
      case 711746416:    /* MIM *lcp command */
if(TEST_FLAG)
{
   printf("\nRead in a *lcp command at line %d!\n",numRecsRead);
   printf("    *lcp:Before: currentColor=%s lcp=%s!",currentColor,tokenStrPtrs[1]);
}
        k = mimLcphp(inRec, &numRecsRead);
if(TEST_FLAG)
   printf("\n    *lcp:After: currentColor=%s lcp=%s!\n",currentColor,lcp);
        break;
      case 711353203:    /* MIM *fcs command */
if(DEBUG_FLAG==1)
   printf("  WARNING: *fcs commands are NOT yet processed.\n");
if(TEST_FLAG)
   printf("\nRead in a *fcs command!\n");
/*
        if( numToks < 1 )
        {
if(DEBUG_FLAG==1)
{
   printf("  WARNING: At MIM line %d; ",numRecsRead);
   printf(" a *fcs-command has no color name.  Ignoring.\n");
}
          break;
        }
        strcpy(fcs, tokenStrPtrs[1]);
if(TEST_FLAG)
   printf("    *fcs:Before: currentColor=%s fcs=%s!",currentColor,fcs);
        if(strcmp(fcs, currentColor) != 0)
        {
          k =  MIMcolorSearch(fcs, &redValue, &greenValue, &blueValue); 
          if(!k)  /%If color not found, default to black. %/
          {
            MIMcolorSearch("black",&redValue,&greenValue,&blueValue); 
            strcpy(fcs, "black");
          }
          fprintf(hpfile, "PC1,%1.2f,%1.2f,%1.2f;SP1;",redValue,greenValue,blueValue); 
          strcpy(currentColor, fcs);
        }
if(TEST_FLAG)
   printf("\n    *fcs:After: currentColor=%s fcs=%s!\n",currentColor,fcs);
*/
        break;
      case 711746422:    /* MIM *lcv command */
if(TEST_FLAG)
{
   printf("\nRead in a *lcv command at line %d!\n",numRecsRead);
   printf("   *lcv:Before: currentColor:%s lcv:%s!",currentColor,tokenStrPtrs[1]);
}
        k = mimLcvhp(inRec, &numRecsRead); 
if(TEST_FLAG)
   printf("\n   *lcv:After: currentColor:%s lcv:%s!\n",currentColor,lcv);
        break;
      case 711749750:    /* MIM *lpv command */
if(TEST_FLAG)
{
   printf("\nRead in a *lpv command at line %d!\n",numRecsRead);
   printf("\n   *lpv: numToks=%d tokenStrPtrs[1]=%s currentLinePattern=%s lpv=%s !!!!\n",numToks,tokenStrPtrs[1],currentLinePattern,lpv);
}
        if( numToks < 1 )
        {
if(DEBUG_FLAG==1)
{
   printf("  WARNING: At MIM line %d; ",numRecsRead);
   printf("a *lpv-command has no pattern name.  Ignoring.\n");
}
          break;
        }
        strcpy(lpv,tokenStrPtrs[1]);
        if(strcmp(currentLinePattern, lpv) != 0)
        {
if(TEST_FLAG)
   printf("      *lpv: Reset:  currentLinePattern=%s lpv=%s !!",currentLinePattern,lpv);
          strcpy(currentLinePattern, lpv);
          patternSethp(hpfile, currentLinePattern,'L');
          strcpy(lpv,currentLinePattern);
if(TEST_FLAG)
   printf("\n      *lpv: After Reset:  currentLinePattern=%s lpv=%s !!\n",currentLinePattern,lpv);
        }
        break;
      case 711750774:    /* MIM *ltv command */
if(DEBUG_FLAG==1)
   printf("  WARNING: *ltv commands are NOT yet processed.\n");        
if(TEST_FLAG)
   printf("\nRead in a *ltv command at line %d!\n",numRecsRead);
        if(numToks < 1)
        {
if(DEBUG_FLAG==1)
{
   printf("  WARNING: At MIM line %d: ",numRecsRead);
   printf("  No line type name given.  Ignoring *ltv command.\n");
}
        }
        else
	{
           strcpy(ltv, tokenStrPtrs[1]); 
           k = MIMlinetypeSearch(ltv, &i, ltsValues);
           if( k == 0 )
           {
if(DEBUG_FLAG==1)
{
   printf("  WARNING: MIM line %d. Line type %s is not defined.\n",numRecsRead,ltv);
   printf("    Defaulting to solid.\n");
}
             strcpy(ltv, "solid");
           }
           ltsNumVals = i;       /*Get number of values this line type.*/
        }
        break;
      case 711353206:    /* MIM *fcv command */
if(TEST_FLAG)
   printf("\nRead in a *fcv command at line %d!\n",numRecsRead);
        if( numToks < 1 )
        {
if(DEBUG_FLAG==1)
{
   printf("  WARNING: At MIM line %d; ",numRecsRead);
   printf(" a *fcv-command has no color name.  Ignoring.\n");
}
          break;
        }
        strcpy(fcv, tokenStrPtrs[1]);
if(TEST_FLAG)
   printf("    *fcv:Before: currentColor=%s fcv=%s!",currentColor,fcv);
        if(strcmp(fcv, currentColor) != 0)
        {
          k =  MIMcolorSearch(fcv, &redValue, &greenValue, &blueValue); 
          if(!k)  /*If color not found, default to black. */
          {
            MIMcolorSearch("black",&redValue,&greenValue,&blueValue); 
            strcpy(fcv, "black");
          } 
          strcpy(currentColor, fcv);
	  fprintf(hpfile, "PC1,%1.2f,%1.2f,%1.2f;SP1;",redValue,greenValue,blueValue);
        }
if(TEST_FLAG)
   printf("\n    *fcv:After: currentColor=%s fcv=%s!\n",currentColor,fcv);
        break;
      case 711356534:    /* MIM *fpv command */
if(TEST_FLAG)
   printf("\nRead in a *fpv command!\n");
        /* IMPORTANT NOTE:  These are set by a define pattern command  */
        if( numToks < 1 )
        {
if(DEBUG_FLAG==1)
{
   printf("  WARNING: At MIM line %d; ",numRecsRead);
   printf("a *fpv-command has no pattern name.  Ignoring.\n");
}
          break;
        }
        strcpy(fpv,tokenStrPtrs[1]);
        if(strcmp(fpv,currentPolyPattern) != 0)
        {
if(TEST_FLAG)
  printf("\n      fpv: Reset: currentPolyPattern=%s fpv=%s!!\n",currentPolyPattern,fpv);
          strcpy(currentPolyPattern, fpv);
          patternSethp(hpfile, currentPolyPattern,'P');
          strcpy(fpv,currentPolyPattern);
        }
if(TEST_FLAG)
  printf("\n         fpv: After: currentPolyPattern=%s fpv=%s!!\n",currentPolyPattern,fpv);
        break;
      case 712140642:    /* MIM *rgb command */
        /* IMPORTANT NOTE: This merely sets up color names.               */
if(TEST_FLAG)
  printf("\nRead in a *rgb command!\n");
        i = mimRgbhp( inRec, numRecsRead); 
        break;
      case 711091558:    /* MIM *bef command */
if(TEST_FLAG)
  printf("\nRead in a *bef command at line %d!\n",numRecsRead);
        befDepth++;                  /* Increment bef depth, 128 max.     */ 
        if(befDepth > 128)
          {
if(DEBUG_FLAG==1)
{
   printf(" FATAL ERROR: nested *bef-commands exceed 128 deep!\n");
   printf("  Must abort run.. .  . \n\n");
}
          exit(0);
          }
        relArrayX[befDepth] = 0.0;   /* Default until a rel comes in.     */
        relArrayY[befDepth] = 0.0;   
        break;
      case 711290470:    /* MIM *enf command */
if(TEST_FLAG)
   printf("\nRead in a *enf command at line %d!\n",numRecsRead);
        offsetX  -= relArrayX[befDepth]; /* Remove impact of any  */
        offsetY  -= relArrayY[befDepth]; /* *rel commands at this */
        befDepth--;                               /* level before ending bef*/
        break;
      case 712140140:    /* MIM *rel command */
if(TEST_FLAG)
   printf("\nRead in a *rel command!\n");
        if(numToks < 3)
          { 
if(DEBUG_FLAG==1)
{
   printf("  WARNING: At MIM line %d; ",numRecsRead);
   printf(" *rel command has too few arguments.\n");
}
          break;
          }
        relArrayX[befDepth] = atof(tokenStrPtrs[1]);
        relArrayY[befDepth] = atof(tokenStrPtrs[2]);
        offsetX += relArrayX[befDepth];   /*Apply rel value */
        offsetY += relArrayY[befDepth];   /*to offsets      */
        break;
      case 711816058:    /* MIM *msz command */
if(TEST_FLAG)
   printf("\nRead in a *msz command!\n");
        if (msz_flag==1)
           break;
        if(init_flag != 1)
        {
if(DEBUG_FLAG==1)
{
   printf(" FATAL ERROR: MIM *int is missing.\n");
   printf("  ABORTING run! ... .  .    .\n");
}
          exit(0);
        }
	  
        if(numToks < 5)
          {
if(DEBUG_FLAG==1)
{
   printf(" FATAL ERROR: MIM *msz has too few arguments.\n");
   printf("  ABORTING run! ... .  .    .\n");
}
          exit(0);
          }
        mszXsize = atof(tokenStrPtrs[1]);
        mszYsize = atof(tokenStrPtrs[2]);
        mszResolution = atoi(tokenStrPtrs[4]);    /*Store resolution value.*/
        if(pcl_flag)
        {
           if(mszResolution>0)
              fprintf(hpfile, "%c%s%d%c\n",ESC,"*t",mszResolution,'R'); /* Set resolution */
           else
              fprintf(hpfile, "%c%s\n",ESC,"*t200R"); /* Set resolution */
        }

/* ----------------------------------------- */
/* scz  set rotateflag if x > y              */
 if ( plot_flag != 1) 
 {
  if( mszXsize > mszYsize )
    {
    ROTATEFLAG = 1;
if(DEBUG_FLAG==1)
   printf("  ROTATEFLAG requested via *msz values\n");
    }
 }
 else
 {
  if( mszYsize > mszXsize )
    {
    ROTATEFLAG = 1;
if(DEBUG_FLAG==1)
   printf("  ROTATEFLAG requested via *msz values\n");
    }
 }
/* ----------------------------------------- */

        deviceFactor = 1.0;                       /* Default value.        */
        deviceFactor *= adjscale;                 /*Adjust by runtime arg. */
        strcpy(work,tokenStrPtrs[3]);      /* Find out what kind of units. */
        for(i = 1; i < strlen(work); i++)  /*Make lower for test. */
           work[i] = tolower(work[i]);
/*sm: Convert all units to inches -- will make output HPGL file uniform in terms of coord sys */
        if(strncmp(work, "cm", 2) == 0)
            deviceFactor = deviceFactor/2.54;
          else
            if(strncmp(work, "mm", 2) == 0)
              deviceFactor =  deviceFactor/25.4;
            else
              if(strncmp(work, "centimeter", 10) == 0)
                deviceFactor = deviceFactor/2.54;
              else
                if(strncmp(work, "milimeter", 9) == 0)
                  deviceFactor = deviceFactor/25.4; 
	deviceFactor *= pu_i; /* convert inch measurement into HPGL plotter units */

        xSide = mszXsize; 
        ySide = mszYsize; 
	

        /* scz 1/25/95 multiply side dimension by deviceFactor to 
           allow scaling of hpgl file  */
        xSide *= deviceFactor;
        ySide *= deviceFactor;

     /* if pcl_flag, set picture frame size */
        if (pcl_flag)
        {
           if (!pageSizeFlag)
           {
if(TEST_FLAG)
{
   printf("xSide = %1.3f ySide = %1.3f pu_i=%d deviceFacor=%1.3f.\n",xSide,ySide,pu_i,deviceFactor); 
   printf("deciX=%d deciY=%d inchesX=%1.3f inchesY=%1.3f.\n",(int)(720*(xSide/pu_i)),(int)(720*(ySide/pu_i)), (xSide/pu_i), (ySide/pu_i)); 
}

              /* issue PCL top margin command p.5-18 */ 
/*
              fprintf(hpfile,"%c%s%d%c\n",ESC,"&l",0,'E');
*/

              /* issue PCL line spacing command, 6 lines per inch p.5-26 */ 
/*
              fprintf(hpfile,"%c%s%d%c\n",ESC,"&l",6,'D');
*/

              /* issue PCL text length command (bottom margin) p.5-20 */ 
/*
              fprintf(hpfile,"%c%s%d%c\n",ESC,"&l",69,'F');
*/

              /* move to position 0,0 p.6-7 & p.6-12 */
/*
              fprintf(hpfile,"%c%s%d%c%d%c\n",ESC,"*p",0,'x',0,'Y');
*/

              /* PCL command to set HPGL/2 pict frame in decipts: 1inch=720decipoints p.18-10 */
/*
              fprintf(hpfile,"%c%s%d%c\n",ESC,"*c",(int)(720*(xSide/pu_i)),'X');
              fprintf(hpfile,"%c%s%d%c\n",ESC,"*c",(int)(720*(ySide/pu_i)),'Y');
*/

              /* set PCL anchor point at point specified p.18-12 */
/*
              fprintf(hpfile,"%c%s\n",ESC,"*c0T");
*/

              /* issue PCL top offset registration command p.4-11 */
/*
              fprintf(hpfile,"%c%s%d%c\n",ESC,"&l",-2,'Z');
*/

              /* issue PCL left offset registration command p.4-10 */
/*
              fprintf(hpfile,"%c%s%d%c\n",ESC,"&l",-2,'U');
*/
 
              /* issue PCL left margin command p.5-15  */ 
/*
              fprintf(hpfile,"%c%s%d%c\n",ESC,"&a",0,'L');
*/

              /* in PCL, specify HPGL/2 plot size in inches p.18-14 */
/*
              fprintf(hpfile,"%c%s%1.2f%c\n",ESC,"*c",(xSide/pu_i),'K');
              fprintf(hpfile,"%c%s%1.2f%c\n",ESC,"*c",(ySide/pu_i),'L');
*/

              /* Disable Perforation Skip p.5-21 */
/*
              fprintf(hpfile,"%c%s%d%c\n",ESC,"&l",0,'L');
*/

              /* code to enter HPGL/2 mode p.18-16 */
	      /* fprintf(hpfile, "%c%s\n",ESC,"%0B"); */    /* Enter HP-GL/2 at previous HPGL */
	      /* fprintf(hpfile, "%c%s\n",ESC,"%-1B"); */   /* Enter HP-GL/2 as recommended */
	      fprintf(hpfile, "%c%s\n",ESC,"%1B");          /* Enter HP-GL/2 at PCL position */
           }
           else           /* for 8.5 X 11 printouts */
           {
/* **************************************************************************** */
              /* set PCL picture frame in decipoints: 1inch=720decipoints */
/*
              fprintf(hpfile,"%c%s%d%c\n",ESC,"*c",6120,'X');
              fprintf(hpfile,"%c%s%d%c\n",ESC,"*c",7920,'Y');
*/
              /* set PCL anchor point */
/*
              fprintf(hpfile,"%c%s\n",ESC,"*c0T");
*/
              /* specify HPGL/2 size in inches */
/*
              fprintf(hpfile,"%c%s%1.3f%c\n",ESC,"*c",8.5,'K');
              fprintf(hpfile,"%c%s%1.3f%c\n",ESC,"*c",11.0,'L');
*/
              /* code to enter HPGL/2 mode */
	      fprintf(hpfile, "%c%s\n",ESC,"%-1B");       /* Enter HP-GL/2 */
           }
        }

	fprintf(hpfile, "BP3,0,4,0,5,1;\n");          /* Begin HP-GL/2 Plot */
	fprintf(hpfile, "IN;\n");          /* Initialize HP-GL/2 Mode */
/*
        if(pcl_flag)
           fprintf(hpfile, "SC0,%1.2f,0,%1.2f,1;\n",xSide,ySide);
        if( !pageSizeFlag )
           fprintf(hpfile, "PS%1.3f,%1.3f;\n",xSide,ySide);
           fprintf(hpfile, "PS%1.3f,%1.3f;\n",ySide,xSide);
	   fprintf(hpfile, "PS;\n"); 
           fprintf(hpfile, "PS%1.3f,%1.3f;\n",ySide,ySide);
           fprintf(hpfile, "IP;\n");
        else
        {
	   fprintf(hpfile, "PS;\n"); /@ Specify plot size@/
	   fprintf(hpfile, "PS8900,7350;\n"); /@ Specify plot size@/
	   fprintf(hpfile, "PS8636,11176;\n"); /@ Specify plot size @/
           fprintf(hpfile, "SC0,8636,0,11176,1,0,0;\n");
           fprintf(hpfile, "IP;\n");
        }
*/
        if( !pageSizeFlag )
          {
          /*If rotate global set, then output rotate/translate cmds */
                if (ROTATEFLAG)
                {
/*
          	   if ( (!plot_flag) || ((plot_flag) && (!pcl_flag)) )
                   {
*/
            		fprintf(hpfile, "RO270;\n"); 
                        fprintf(hpfile, "IP;\n");
/*
                   }
*/
                }
                else
                   fprintf(hpfile, "IP;\n");
          }
        else
        {
if(DEBUG_FLAG==1)
   printf("  Page Size Output requested.\n");
          /*If rotate global set, then output rotate/translate cmds */
          if (ROTATEFLAG)
          {
/*
             if ( (!plot_flag) || ( (plot_flag) && (!pcl_flag) ))
             {
*/
                   fprintf(hpfile, "IP0,0,8636,11176;\n");
                   fprintf(hpfile, "SC0,8636,0,11176,1,0,0;\n");
                   fprintf(hpfile, "RO90;\n"); 
                   fprintf(hpfile, "IP;\n");
/*
             }
*/
          }
          else
          {
             fprintf(hpfile, "IP0,0,8636,11176;\n");
             fprintf(hpfile, "SC0,8636,0,11176,1,0,0;\n");
             fprintf(hpfile, "IP;\n");
          }

        }
	fprintf(hpfile, "SP1;\n"); /* Select pen 1 black */
	fprintf(hpfile, "WU0;\n"); /* Set pen widths units to be  millimeters */
	fprintf(hpfile, "PA;\n");  /* Plot absolute */
        if(!tr_flag)
          fprintf(hpfile, "TR1;\n"); /* Set transparency mode on */
        if(!mc_flag)
          fprintf(hpfile, "MC1;\n"); /* Merge Colors at intersections */
/*
        if (rg_flag)
           fprintf(hpfile, "LA1,4,2,2,3,5;\n");*/ /* Set line attributes to the following: */
                   /* 12/05/95 round ends:1,4; mitred/beveled joins:2,2; mitre ratio=default*/
/*
        else
*/
           fprintf(hpfile, "LA1,1,2,5,3,5;\n"); /* Set line attributes to the following: */
                           /* butt ends:1,1; beveled joins:2,5; mitre ratio=default*/
	fprintf(hpfile, "CO%cMIM file input: %s.%c;\n",DOUBLEQUOTE,mimfilename,DOUBLEQUOTE);

/* Code to establish color */
/*
	fprintf(hpfile, "NP;\n");  /% Establishes the size (number of pens) of 
					the HPGL/2 color palette. Defaults to device %/
*/
/*	fprintf(hpfile, "CR;\n"); */  /* Set color range in terms of RGB, default to */ 
	fprintf(hpfile, "CR0,255,0,255,0,255;\n");/* Set color range in terms of RGB, */
                                                   /* white=255,255,255 black=0,0,0 */
        /* Setup default state values for the entities. This assures that  */
        /* there will be a value for each.                                 */
        strcpy(lws,"0.005");
        strcpy(lwv,"0.005");
        strcpy(lwp,"0.005");
        strcpy(currentLineWeight, lws);
        x = (atof(lws) * deviceFactor) / 40; /* Set lws to plot units, to millimeters */
        fprintf(hpfile, "PW%1.3f;",x); 
        MIMinsertColor( "black", 0.0, 0.0, 0.0 );
        strcpy(fcs, "black");
        strcpy(fcp, "black");
        strcpy(fcv, "black");
        strcpy(lcs, "black");
        strcpy(lcp, "black");
        strcpy(lcv, "black");
        fprintf(hpfile, "PC1,%1.2f,%1.2f,%1.2f;SP1;",0.0,0.0,0.0); 
        msz_flag = 1;
        break;
      case 711552628:    /* MIM *int command */
if(TEST_FLAG)
   printf("\nRead in a *int command!\n");
        if(init_flag==1)
           break;
	if(pcl_flag)
	{
	   fprintf(hpfile, "%c%s\n",ESC,"%-12345X");  /* reset the printer */
	   fprintf(hpfile, "%c%s\n",ESC,"E");         /* <esc>E to reset the printer */
        }
        init_flag = 1;
        break;
      case 711158899:    /* MIM *cls command */
/*
        if(cls_flag == 1) 
           break;
*/
if(TEST_FLAG)
   printf("\nRead in a *cls command!\n");
	fprintf(hpfile, "\nPU;\nSP0;\n");  /* Pen up */
/*
        if(!pcl_flag)
        {
*/
           i=0;
           i=fprintf(hpfile, "PG;\n"); 	/* sm: page eject, plot the file */
           if(i<0)
           {
              printf(" FATAL ERROR: Incomplete file.  ABORTING......\n");
              exit(errno);
           }
/*
        }
*/
/*
        if(COPIESFLAG > 0)
*/
        if( (COPIESFLAG > 0) && (!pcl_flag) )
        {
           i=0;
           i=fprintf(hpfile, "RP%d;\n",COPIESFLAG);
           if(i<0)
           {
              printf(" FATAL ERROR: Incomplete file.  ABORTING......\n");
              exit(errno);
           }
        }
 
   /*      fprintf(hpfile, "OE;\n"); */ 	/* output error */
    /*     fprintf(hpfile, "OH;\n"); */ 	/* output hard-clip limits*/
     /*    fprintf(hpfile, "OP;\n"); */ 	/* output P1 and P2 */
	if(pcl_flag)
	{
           fprintf(hpfile,"\n");
	   fprintf(hpfile, "%c%s\n",ESC,"%0A");       /* enter PCL at previous CAP */
           if(COPIESFLAG > 0) /* PCL copies since HPGL/2 RP not handled for HPGL/2 printer*/
              fprintf(hpfile, "%c%s%d%c\n",ESC,"&l",COPIESFLAG,'X');

/* sm:05/23/95: The next four lines represent attempts to eliminate the extra blank page */
/* 		that comes out of the HP laser jet 4 after the file is printed */
/*
           chr = 23;        /% adding signal for end of transmission block %/
       	   fprintf(hpfile, "%c\n",chr); 
*/
/*
           chr = 4;        /% adding 'CNTRL D' to signal End Of Transmission %/
       	   fprintf(hpfile, "%c\n",chr); 
*/
/* end of attempt to eliminate blank page at end */
	   fprintf(hpfile, "%c%s\n",ESC,"E");       /* Reset to end job/eject page */
           i=0;
	   i=fprintf(hpfile, "%c%s\n",ESC,"%-12345X");  /* reset the printer */
           if(i<0)
           {
              printf(" FATAL ERROR: Incomplete file.  ABORTING......\n");
              exit(errno);
           }
	}
        cls_flag=1;
        break;
      default:           /* Unknown command */
if(DEBUG_FLAG==1)
{
   printf("\nI don't know what I've just read!\n");
   printf("This one is UNKNOWN:\n");
   printf("Token: %s, tokVal = %d\n",tokenStrPtrs[0],tokVal);
}
      }  /* End of switch. */
    }
  else    /* First token is not a standard star-command. */
    {
if(DEBUG_FLAG==1)
{
   printf(" EXTREMELY IMPORTANT ERROR CONDITION FOUND!!!\n");
   printf("  Input record: %s",inRec);
   printf("A non-MIM standard command found at MIM line %d.",numRecsRead);
   printf("  It may be a user\n  defined command.  THESE ARE NOT HANDLED.\n");
   printf("  Continuing to process.\n");
   printf("  TESTING FOR A DEP-DEFINED COMMAND.\n");
}
    k = mimDOdep( inRec ); 
    }
 
  }  /* End outside while-loop */
  return(0);
}