/* $XConsortium: type1.c,v 1.7 94/02/07 15:30:22 gildea Exp $ */
/* Copyright International Business Machines, Corp. 1991
 * All Rights Reserved
 * Copyright Lexmark International, Inc. 1991
 * All Rights Reserved
 * Portions Copyright (c) 1990 Adobe Systems Incorporated.
 * All Rights Reserved
 *
 * License to use, copy, modify, and distribute this software and its
 * documentation for any purpose and without fee is hereby granted,
 * provided that the above copyright notice appear in all copies and that
 * both that copyright notice and this permission notice appear in
 * supporting documentation, and that the name of IBM or Lexmark or Adobe
 * not be used in advertising or publicity pertaining to distribution of
 * the software without specific, written prior permission.
 *
 * IBM, LEXMARK, AND ADOBE PROVIDE THIS SOFTWARE "AS IS", WITHOUT ANY
 * WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT
 * LIMITED TO ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.  THE
 * ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE, INCLUDING
 * ANY DUTY TO SUPPORT OR MAINTAIN, BELONGS TO THE LICENSEE.  SHOULD ANY
 * PORTION OF THE SOFTWARE PROVE DEFECTIVE, THE LICENSEE (NOT IBM,
 * LEXMARK, OR ADOBE) ASSUMES THE ENTIRE COST OF ALL SERVICING, REPAIR AND
 * CORRECTION.  IN NO EVENT SHALL IBM, LEXMARK, OR ADOBE BE LIABLE FOR ANY
 * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
 * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
 * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*********************************************************************/
/*                                                                   */
/* Type 1 module - Converting fonts in Adobe Type 1 Font Format      */
/*                 to scaled and hinted paths for rasterization.     */
/*                 Files: type1.c, type1.h, and blues.h.             */
/*                                                                   */
/* Authors:   Sten F. Andler, IBM Almaden Research Center            */
/*                 (Type 1 interpreter, stem & flex hints)           */
/*                                                                   */
/*            Patrick A. Casey, Lexmark International, Inc.          */
/*                 (Font level hints & stem hints)                   */
/*                                                                   */
/*********************************************************************/

// TetiSoft: Moved all statics in T1GlyphEngine.t1

/******************/
/* Include Files: */
/******************/
#ifndef T1GST
#include "global.h"
#endif


/**********************************/
/* Type1 Constants and Structures */
/**********************************/
#define MAXSTACK 24		/* Adobe Type1 limit */
#define MAXCALLSTACK 10		/* Adobe Type1 limit */
#define MAXPSFAKESTACK 32	/* Max depth of fake PostScript stack (local) */
#define MAXSTRLEN 512		/* Max length of a Type 1 string (local) */
//#define MAXLABEL 256		/* Maximum number of new hints */
#define MAXSTEMS 128		/* Maximum number of VSTEM and HSTEM hints */
#define EPS 0.001		/* Small number for comparisons */


/************************************/
/* Adobe Type 1 CharString commands */
/************************************/
#define HSTEM        1
#define VSTEM        3
#define VMOVETO      4
#define RLINETO      5
#define HLINETO      6
#define VLINETO      7
#define RRCURVETO    8
#define CLOSEPATH    9
#define CALLSUBR    10
#define RETURN      11
#define ESCAPE      12
#define HSBW        13
#define ENDCHAR     14
#define RMOVETO     21
#define HMOVETO     22
#define VHCURVETO   30
#define HVCURVETO   31


/*******************************************/
/* Adobe Type 1 CharString Escape commands */
/*******************************************/
#define DOTSECTION       0
#define VSTEM3           1
#define HSTEM3           2
#define SEAC             6
#define SBW              7
#define DIV             12
#define CALLOTHERSUBR   16
#define POP             17
#define SETCURRENTPOINT 33


/*****************/
/* Useful macros */
/*****************/
#if 0	// TetiSoft: Use auto variables to avoid global data
static double tmpx;		/* Store macro argument in tmpx to avoid re-evaluation */
static long tmpi;		/* Store converted value in tmpi to avoid re-evaluation */
#endif

#define FABS(x) (((tmpx = (x)) < 0.0) ? -tmpx : tmpx)

#define CEIL(x) (((tmpi = (long) (tmpx = (x))) < tmpx) ? ++tmpi : tmpi)

#define FLOOR(x) (((tmpi = (long) (tmpx = (x))) > tmpx) ? --tmpi : tmpi)

#define ROUND(x) FLOOR((x) + 0.5)

#define ODD(x) (((int)(x)) & 01)

#define Error {engine->t1.errflag = TRUE; return;}
#define ErrorRet(ret) {engine->t1.errflag = TRUE; return (ret);}

#define Error0(errmsg) {IfTrace0(TRUE, errmsg); Error;}
#define Error0Ret(errmsg, ret) {IfTrace0(TRUE, errmsg); ErrorRet(ret);}

#define Error1(errmsg,arg) {IfTrace1(TRUE, errmsg, arg); Error;}


/********************/
/* global variables */
/********************/
#if 0	// TetiSoft: In global.h
struct stem
{										/* representation of a STEM hint */
	int vertical;						/* TRUE if vertical, FALSE otherwise */
	double x, dx;						/* interval of vertical stem */
	double y, dy;						/* interval of horizontal stem */
	struct segment *lbhint, *lbrevhint;	/* left  or bottom hint adjustment */
	struct segment *rthint, *rtrevhint;	/* right or top    hint adjustment */
};
#endif

//static double escapementX, escapementY;
//static double sidebearingX, sidebearingY;
//static double accentoffsetX, accentoffsetY;
//static struct segment *path;
//static int errflag;


/*************************************************/
/* Global variables to hold Type1Char parameters */
/*************************************************/
//static psfont *Environment;
//static struct XYspace *CharSpace;
//static psobj *CharStringP, *SubrsP, *OtherSubrsP;
//static int *ModeP;


/************************/
/* Forward declarations */
/************************/
static void ComputeAlignmentZones(struct T1GlyphEngine *engine);
static void InitStems(struct T1GlyphEngine *engine);
static void FinitStems(struct T1GlyphEngine *engine);
static void ComputeStem(struct T1GlyphEngine *engine, int stemno);
static struct segment *Applyhint(struct T1GlyphEngine *engine, struct segment *p, int stemnumber, int half);
static struct segment *Applyrevhint(struct T1GlyphEngine *engine, struct segment *p, int stemnumber, int half);
static struct segment *FindStems(struct T1GlyphEngine *engine, double x, double y, double dx, double dy);
static void ClearStack(struct T1GlyphEngine *engine);
static void Push(struct T1GlyphEngine *engine, double Num);
static void ClearCallStack(struct T1GlyphEngine *engine);
static void PushCall(struct T1GlyphEngine *engine, psobj *CurrStrP, int CurrIndex, unsigned short CurrKey);
static void PopCall(struct T1GlyphEngine *engine, psobj **CurrStrPP, int *CurrIndexP, unsigned short *CurrKeyP);
static void ClearPSFakeStack(struct T1GlyphEngine *engine);
static void PSFakePush(struct T1GlyphEngine *engine, double Num);
static double PSFakePop(struct T1GlyphEngine *engine);
static struct segment *CenterStem(struct T1GlyphEngine *engine, double edge1, double edge2);
static unsigned char Decrypt(struct T1GlyphEngine *engine, unsigned char cipher);
static int DoRead(struct T1GlyphEngine *engine, int *CodeP);
static void StartDecrypt(struct T1GlyphEngine *engine);
static void Decode(struct T1GlyphEngine *engine, int Code);
static void DoCommand(struct T1GlyphEngine *engine, int Code);
static void Escape(struct T1GlyphEngine *engine, int Code);
static void HStem(struct T1GlyphEngine *engine, double y, double dy);
static void VStem(struct T1GlyphEngine *engine, double x, double dx);
static void RLineTo(struct T1GlyphEngine *engine, double dx, double dy);
static void RRCurveTo(struct T1GlyphEngine *engine, double dx1, double dy1, double dx2, double dy2, double dx3, double dy3);
static void DoClosePath(struct T1GlyphEngine *engine);
static void CallSubr(struct T1GlyphEngine *engine, int subrno);
static void Return(struct T1GlyphEngine *engine);
static void EndChar(struct T1GlyphEngine *engine);
static void RMoveTo(struct T1GlyphEngine *engine, double dx, double dy);
static void DotSection(struct T1GlyphEngine *engine);
static void Seac(struct T1GlyphEngine *engine, double asb, double adx, double ady, unsigned char bchar, unsigned char achar);
static void Sbw(struct T1GlyphEngine *engine, double sbx, double sby, double wx, double wy);
static double Div(struct T1GlyphEngine *engine, double num1, double num2);
static void FlxProc(struct T1GlyphEngine *engine, double c1x2, double c1y2, double c3x0, double c3y0, double c3x1, double c3y1, double c3x2, double c3y2, double c4x0, double c4y0, double c4x1, double c4y1, double c4x2, double c4y2, double epY, double epX, int idmin);
static void FlxProc1(struct T1GlyphEngine *engine);
static void FlxProc2(struct T1GlyphEngine *engine);
static void HintReplace(struct T1GlyphEngine *engine);
static void CallOtherSubr(struct T1GlyphEngine *engine, int othersubrno);
static void SetCurrentPoint(struct T1GlyphEngine *engine, double x, double y);


/*****************************************/
/* statics for Flex procedures (FlxProc) */
/*****************************************/
//static struct segment *FlxOldPath;	/* save path before Flex feature */


/******************************************************/
/* statics for Font level hints (Blues) (see blues.h) */
/******************************************************/
//static struct blues_struct *blues;	/* the blues structure */
//static struct alignmentzone alignmentzones[MAXALIGNMENTZONES];
//static int numalignmentzones;		/* total number of alignment zones */


/****************************************************************/
/* Subroutines for the Font level hints (Alignment zones, etc.) */
/****************************************************************/


/******************************************/
/* Fill in the alignment zone structures. */
/******************************************/
static void ComputeAlignmentZones(struct T1GlyphEngine *engine)
{
	int i;
	double dummy, bluezonepixels, familyzonepixels;
	double tmpx;	// TetiSoft: Use auto variables to avoid global data
	struct segment *p;

	engine->t1.numalignmentzones = 0;	/* initialize total # of zones */

	/* do the BlueValues zones */
	for (i = 0; i < engine->t1.blues->numBlueValues; i += 2, ++engine->t1.numalignmentzones)
	{
		/* the 0th & 1st numbers in BlueValues are for a bottom zone */
		/* the rest are topzones */
		if (i == 0)	/* bottom zone */
			engine->t1.alignmentzones[engine->t1.numalignmentzones].topzone = FALSE;
		else		/* top zone */
			engine->t1.alignmentzones[engine->t1.numalignmentzones].topzone = TRUE;
		if (i < engine->t1.blues->numFamilyBlues)
		{		/* we must consider FamilyBlues */
			p = ILoc(engine, engine->t1.CharSpace, 0, engine->t1.blues->BlueValues[i] - engine->t1.blues->BlueValues[i + 1]);
			QueryLoc(engine, p, engine->IDENTITY, &dummy, &bluezonepixels);
			t1_Destroy(engine, (struct xobject *)p);
			p = ILoc(engine, engine->t1.CharSpace, 0, engine->t1.blues->FamilyBlues[i] - engine->t1.blues->FamilyBlues[i + 1]);
			QueryLoc(engine, p, engine->IDENTITY, &dummy, &familyzonepixels);
			t1_Destroy(engine, (struct xobject *)p);
			/* is the difference in size of the zones less than 1 pixel? */
			if (FABS(bluezonepixels - familyzonepixels) < 1.0)
			{
				/* use the Family zones */
				engine->t1.alignmentzones[engine->t1.numalignmentzones].bottomy =
				    engine->t1.blues->FamilyBlues[i];
				engine->t1.alignmentzones[engine->t1.numalignmentzones].topy =
				    engine->t1.blues->FamilyBlues[i + 1];
				continue;
			}
		}
		/* use this font's Blue zones */
		engine->t1.alignmentzones[engine->t1.numalignmentzones].bottomy = engine->t1.blues->BlueValues[i];
		engine->t1.alignmentzones[engine->t1.numalignmentzones].topy = engine->t1.blues->BlueValues[i + 1];
	}

	/* do the OtherBlues zones */
	for (i = 0; i < engine->t1.blues->numOtherBlues; i += 2, ++engine->t1.numalignmentzones)
	{
		/* all of the OtherBlues zones are bottom zones */
		engine->t1.alignmentzones[engine->t1.numalignmentzones].topzone = FALSE;
		if (i < engine->t1.blues->numFamilyOtherBlues)
		{		/* consider FamilyOtherBlues  */
			p = ILoc(engine, engine->t1.CharSpace, 0, engine->t1.blues->OtherBlues[i] - engine->t1.blues->OtherBlues[i + 1]);
			QueryLoc(engine, p, engine->IDENTITY, &dummy, &bluezonepixels);
			t1_Destroy(engine, (struct xobject *)p);
			p = ILoc(engine, engine->t1.CharSpace, 0, engine->t1.blues->FamilyOtherBlues[i] -
				 engine->t1.blues->FamilyOtherBlues[i + 1]);
			QueryLoc(engine, p, engine->IDENTITY, &dummy, &familyzonepixels);
			t1_Destroy(engine, (struct xobject *)p);
			/* is the difference in size of the zones less than 1 pixel? */
			if (FABS(bluezonepixels - familyzonepixels) < 1.0)
			{
				/* use the Family zones */
				engine->t1.alignmentzones[engine->t1.numalignmentzones].bottomy =
				    engine->t1.blues->FamilyOtherBlues[i];
				engine->t1.alignmentzones[engine->t1.numalignmentzones].topy =
				    engine->t1.blues->FamilyOtherBlues[i + 1];
				continue;
			}
		}
		/* use this font's Blue zones (as opposed to the Family Blues */
		engine->t1.alignmentzones[engine->t1.numalignmentzones].bottomy = engine->t1.blues->OtherBlues[i];
		engine->t1.alignmentzones[engine->t1.numalignmentzones].topy = engine->t1.blues->OtherBlues[i + 1];
	}
}


/**********************************************************************/
/* Subroutines and statics for handling of the VSTEM and HSTEM hints. */
/**********************************************************************/
//static int InDotSection;		/* DotSection flag */
//static struct stem stems[MAXSTEMS];	/* All STEM hints */
//static int numstems;			/* Number of STEM hints */
//static int currstartstem;		/* The current starting stem. */
//static int oldvert, oldhor;		/* Remember hint in effect */
//static int oldhorhalf, oldverthalf;	/* Remember which half of the stem */
//static double wsoffsetX, wsoffsetY;	/* White space offset - for VSTEM3,HSTEM3 */
//static int wsset;			/* Flag for whether we've set wsoffsetX,Y */

static void InitStems(struct T1GlyphEngine *engine)	/* Initialize the STEM hint data structures */
{
	engine->t1.InDotSection = FALSE;
	engine->t1.currstartstem = engine->t1.numstems = 0;
	engine->t1.oldvert = engine->t1.oldhor = -1;
}


static void FinitStems(struct T1GlyphEngine *engine)	/* Terminate the STEM hint data structures */
{
	int i;

	for (i = 0; i < engine->t1.numstems; i++)
	{
		t1_Destroy(engine, (struct xobject *)engine->t1.stems[i].lbhint);
		t1_Destroy(engine, (struct xobject *)engine->t1.stems[i].lbrevhint);
		t1_Destroy(engine, (struct xobject *)engine->t1.stems[i].rthint);
		t1_Destroy(engine, (struct xobject *)engine->t1.stems[i].rtrevhint);
	}
}


/*******************************************************************/
/* Compute the dislocation that a stemhint should cause for points */
/* inside the stem.                                                */
/*******************************************************************/
static void ComputeStem(struct T1GlyphEngine *engine, int stemno)
{
	int verticalondevice, idealwidth;
	double stemstart, stemwidth;
	struct segment *p;
	int i;
	double stembottom, stemtop, flatposition;
	double Xpixels, Ypixels;
	double unitpixels, onepixel;
	int suppressovershoot, enforceovershoot;
	double stemshift, flatpospixels, overshoot;
	double widthdiff;	/* Number of character space units to adjust width */
	double lbhintvalue, rthintvalue;
	double cxx, cyx, cxy, cyy;	/* Transformation matrix */
	double tmpx;		// TetiSoft: Use auto variables to avoid global data
	long tmpi;		// TetiSoft: Use auto variables to avoid global data
	int rotated;		/* TRUE if character is on the side, FALSE if upright */

	/************************************************/
	/* DETERMINE ORIENTATION OF CHARACTER ON DEVICE */
	/************************************************/

	QuerySpace(engine, engine->t1.CharSpace, &cxx, &cyx, &cxy, &cyy);	/* Transformation matrix */

	if (FABS(cxx) < 0.00001 || FABS(cyy) < 0.00001)
		rotated = TRUE;	/* Char is on side (90 or 270 degrees), possibly oblique. */
	else if (FABS(cyx) < 0.00001 || FABS(cxy) < 0.00001)
		rotated = FALSE;/* Char is upright (0 or 180 degrees), possibly oblique. */
	else
	{
		engine->t1.stems[stemno].lbhint = NULL;	/* Char is at non-axial angle, ignore hints. */
		engine->t1.stems[stemno].lbrevhint = NULL;
		engine->t1.stems[stemno].rthint = NULL;
		engine->t1.stems[stemno].rtrevhint = NULL;
		return;
	}

	/* Determine orientation of stem */

	if (engine->t1.stems[stemno].vertical)
	{
		verticalondevice = !rotated;
		stemstart = engine->t1.stems[stemno].x;
		stemwidth = engine->t1.stems[stemno].dx;
	}
	else
	{
		verticalondevice = rotated;
		stemstart = engine->t1.stems[stemno].y;
		stemwidth = engine->t1.stems[stemno].dy;
	}

	/* Determine how many pixels (non-negative) correspond to 1 character space
     unit (unitpixels), and how many character space units (non-negative)
     correspond to one pixel (onepixel). */

	if (engine->t1.stems[stemno].vertical)
		p = ILoc(engine, engine->t1.CharSpace, 1, 0);
	else
		p = ILoc(engine, engine->t1.CharSpace, 0, 1);
	QueryLoc(engine, p, engine->IDENTITY, &Xpixels, &Ypixels);
	t1_Destroy(engine, (struct xobject *)p);
	if (verticalondevice)
		unitpixels = FABS(Xpixels);
	else
		unitpixels = FABS(Ypixels);

	onepixel = 1.0 / unitpixels;

	/**********************/
	/* ADJUST STEM WIDTHS */
	/**********************/

	widthdiff = 0.0;

	/* Find standard stem with smallest width difference from this stem */
	if (engine->t1.stems[stemno].vertical)
	{			/* vertical stem */
		if (engine->t1.blues->StdVW != 0)	/* there is an entry for StdVW */
			widthdiff = engine->t1.blues->StdVW - stemwidth;
		for (i = 0; i < engine->t1.blues->numStemSnapV; ++i)
		{		/* now look at StemSnapV */
			if (engine->t1.blues->StemSnapV[i] - stemwidth < widthdiff)
				/* this standard width is the best match so far for this stem */
				widthdiff = engine->t1.blues->StemSnapV[i] - stemwidth;
		}
	}
	else
	{			/* horizontal stem */
		if (engine->t1.blues->StdHW != 0)	/* there is an entry for StdHW */
			widthdiff = engine->t1.blues->StdHW - stemwidth;
		for (i = 0; i < engine->t1.blues->numStemSnapH; ++i)
		{		/* now look at StemSnapH */
			if (engine->t1.blues->StemSnapH[i] - stemwidth < widthdiff)
				/* this standard width is the best match so far for this stem */
				widthdiff = engine->t1.blues->StemSnapH[i] - stemwidth;
		}
	}

	/* Only expand or contract stems if they differ by less than 1 pixel from
     the closest standard width, otherwise make the width difference = 0. */
	if (FABS(widthdiff) > onepixel)
		widthdiff = 0.0;

	/* Expand or contract stem to the nearest integral number of pixels. */
	idealwidth = ROUND((stemwidth + widthdiff) * unitpixels);
	/* Ensure that all stems are at least one pixel wide. */
	if (idealwidth == 0)
		idealwidth = 1;
	/* Apply ForceBold to vertical stems. */
	if (engine->t1.blues->ForceBold && engine->t1.stems[stemno].vertical)
		/* Force this vertical stem to be at least DEFAULTBOLDSTEMWIDTH wide. */
		if (idealwidth < DEFAULTBOLDSTEMWIDTH)
			idealwidth = DEFAULTBOLDSTEMWIDTH;
	/* Now compute the number of character space units necessary */
	widthdiff = idealwidth * onepixel - stemwidth;

	/*********************************************************************/
	/* ALIGNMENT ZONES AND OVERSHOOT SUPPRESSION - HORIZONTAL STEMS ONLY */
	/*********************************************************************/

//	stemshift = 0.0;	// TetiSoft

	if (!engine->t1.stems[stemno].vertical)
	{

		/* Get bottom and top boundaries of the stem. */
		stembottom = stemstart;
		stemtop = stemstart + stemwidth;

		/* Find out if this stem intersects an alignment zone (the BlueFuzz  */
		/* entry in the Private dictionary specifies the number of character */
		/* units to extend (in both directions) the effect of an alignment   */
		/* zone on a horizontal stem.  The default value of BlueFuzz is 1.   */
		for (i = 0; i < engine->t1.numalignmentzones; ++i)
		{
			if (engine->t1.alignmentzones[i].topzone)
			{
				if (stemtop >= engine->t1.alignmentzones[i].bottomy &&
				    stemtop <= engine->t1.alignmentzones[i].topy + engine->t1.blues->BlueFuzz)
				{
					break;	/* We found a top-zone */
				}
			}
			else
			{
				if (stembottom <= engine->t1.alignmentzones[i].topy &&
				    stembottom >= engine->t1.alignmentzones[i].bottomy - engine->t1.blues->BlueFuzz)
				{
					break;	/* We found a bottom-zone */
				}
			}
		}

		if (i < engine->t1.numalignmentzones)
		{		/* We found an intersecting zone (number i). */
			suppressovershoot = FALSE;
			enforceovershoot = FALSE;

			/* When 1 character space unit is rendered smaller than BlueScale
         device units (pixels), we must SUPPRESS overshoots.  Otherwise,
         if the top (or bottom) of this stem is more than BlueShift character
         space units away from the flat position, we must ENFORCE overshoot. */

			if (unitpixels < engine->t1.blues->BlueScale)
				suppressovershoot = TRUE;
			else if (engine->t1.alignmentzones[i].topzone)
				if (stemtop >= engine->t1.alignmentzones[i].bottomy + engine->t1.blues->BlueShift)
					enforceovershoot = TRUE;
				else if (stembottom <= engine->t1.alignmentzones[i].topy - engine->t1.blues->BlueShift)
					enforceovershoot = TRUE;

			/*************************************************/
			/* ALIGN THE FLAT POSITION OF THE ALIGNMENT ZONE */
			/*************************************************/

			/* Compute the position of the alignment zone's flat position in
         device space and the amount of shift needed to align it on a
         pixel boundary. Move all stems this amount. */

			if (engine->t1.alignmentzones[i].topzone)
				flatposition = engine->t1.alignmentzones[i].bottomy;
			else
				flatposition = engine->t1.alignmentzones[i].topy;

			/* Find the flat position in pixels */
			flatpospixels = flatposition * unitpixels;

			/* Find the stem shift necessary to align the flat
         position on a pixel boundary, and use this shift for all stems */
			stemshift = (ROUND(flatpospixels) - flatpospixels) * onepixel;

			/************************************************/
			/* HANDLE OVERSHOOT ENFORCEMENT AND SUPPRESSION */
			/************************************************/

			/* Compute overshoot amount (non-negative) */
			if (engine->t1.alignmentzones[i].topzone)
				overshoot = stemtop - flatposition;
			else
				overshoot = flatposition - stembottom;

			if (overshoot > 0.0)
			{
				/* ENFORCE overshoot by shifting the entire stem (if necessary) so that
           it falls at least one pixel beyond the flat position. */

				if (enforceovershoot)
					if (overshoot < onepixel)
						if (engine->t1.alignmentzones[i].topzone)
							stemshift += onepixel - overshoot;
						else
							stemshift -= onepixel - overshoot;

				/* SUPPRESS overshoot by aligning the stem to the alignment zone's
           flat position. */

				if (suppressovershoot)
					if (engine->t1.alignmentzones[i].topzone)
						stemshift -= overshoot;
					else
						stemshift += overshoot;
			}

			/************************************************************/
			/* COMPUTE HINT VALUES FOR EACH SIDE OF THE HORIZONTAL STEM */
			/************************************************************/

			/* If the stem was aligned by a topzone, we expand or contract the stem
         only at the bottom - since the stem top was aligned by the zone.
         If the stem was aligned by a bottomzone, we expand or contract the stem
         only at the top - since the stem bottom was aligned by the zone. */
			if (engine->t1.alignmentzones[i].topzone)
			{
				lbhintvalue = stemshift - widthdiff;	/* bottom */
				rthintvalue = stemshift;	/* top    */
			}
			else
			{
				lbhintvalue = stemshift;	/* bottom */
				rthintvalue = stemshift + widthdiff;	/* top    */
			}

			engine->t1.stems[stemno].lbhint = (struct segment *)t1_Permanent(engine, (struct xobject *)t1_Loc(engine, engine->t1.CharSpace, 0.0, lbhintvalue));
			engine->t1.stems[stemno].lbrevhint = (struct segment *)t1_Permanent(engine, (struct xobject *)t1_Loc(engine, engine->t1.CharSpace, 0.0, -lbhintvalue));
			engine->t1.stems[stemno].rthint = (struct segment *)t1_Permanent(engine, (struct xobject *)t1_Loc(engine, engine->t1.CharSpace, 0.0, rthintvalue));
			engine->t1.stems[stemno].rtrevhint = (struct segment *)t1_Permanent(engine, (struct xobject *)t1_Loc(engine, engine->t1.CharSpace, 0.0, -rthintvalue));

			return;

		}		/* endif (i < numalignmentzones) */

		/* We didn't find any alignment zones intersecting this stem, so
       proceed with normal stem alignment below. */

	}			/* endif (!stems[stemno].vertical) */

	/* Align stem with pixel boundaries on device */
	stemstart = stemstart - widthdiff / 2;
	stemshift = ROUND(stemstart * unitpixels) * onepixel - stemstart;

	/* Adjust the boundaries of the stem */
	lbhintvalue = stemshift - widthdiff / 2;	/* left  or bottom */
	rthintvalue = stemshift + widthdiff / 2;	/* right or top    */

	if (engine->t1.stems[stemno].vertical)
	{
		engine->t1.stems[stemno].lbhint = (struct segment *)t1_Permanent(engine, (struct xobject *)t1_Loc(engine, engine->t1.CharSpace, lbhintvalue, 0.0));
		engine->t1.stems[stemno].lbrevhint = (struct segment *)t1_Permanent(engine, (struct xobject *)t1_Loc(engine, engine->t1.CharSpace, -lbhintvalue, 0.0));
		engine->t1.stems[stemno].rthint = (struct segment *)t1_Permanent(engine, (struct xobject *)t1_Loc(engine, engine->t1.CharSpace, rthintvalue, 0.0));
		engine->t1.stems[stemno].rtrevhint = (struct segment *)t1_Permanent(engine, (struct xobject *)t1_Loc(engine, engine->t1.CharSpace, -rthintvalue, 0.0));
	}
	else
	{
		engine->t1.stems[stemno].lbhint = (struct segment *)t1_Permanent(engine, (struct xobject *)t1_Loc(engine, engine->t1.CharSpace, 0.0, lbhintvalue));
		engine->t1.stems[stemno].lbrevhint = (struct segment *)t1_Permanent(engine, (struct xobject *)t1_Loc(engine, engine->t1.CharSpace, 0.0, -lbhintvalue));
		engine->t1.stems[stemno].rthint = (struct segment *)t1_Permanent(engine, (struct xobject *)t1_Loc(engine, engine->t1.CharSpace, 0.0, rthintvalue));
		engine->t1.stems[stemno].rtrevhint = (struct segment *)t1_Permanent(engine, (struct xobject *)t1_Loc(engine, engine->t1.CharSpace, 0.0, -rthintvalue));
	}
}

#define LEFT   1
#define RIGHT  2
#define BOTTOM 3
#define TOP    4

/*********************************************************************/
/* Adjust a point using the given stem hint.  Use the left/bottom    */
/* hint value or the right/top hint value depending on where the     */
/* point lies in the stem.                                           */
/*********************************************************************/
static struct segment *Applyhint(struct T1GlyphEngine *engine, struct segment *p, int stemnumber, int half)
{
	if (half == LEFT || half == BOTTOM)
		return t1_Join(engine, p, engine->t1.stems[stemnumber].lbhint);	/* left  or bottom hint */
	else
		return t1_Join(engine, p, engine->t1.stems[stemnumber].rthint);	/* right or top    hint */
}


/*********************************************************************/
/* Adjust a point using the given reverse hint.  Use the left/bottom */
/* hint value or the right/top hint value depending on where the     */
/* point lies in the stem.                                           */
/*********************************************************************/
static struct segment *Applyrevhint(struct T1GlyphEngine *engine, struct segment *p, int stemnumber, int half)
{
	if (half == LEFT || half == BOTTOM)
		return t1_Join(engine, p, engine->t1.stems[stemnumber].lbrevhint);	/* left  or bottom hint */
	else
		return t1_Join(engine, p, engine->t1.stems[stemnumber].rtrevhint);	/* right or top    hint */
}


/***********************************************************************/
/* Find the vertical and horizontal stems that the current point       */
/* (x, y) may be involved in.  At most one horizontal and one vertical */
/* stem can apply to a single point, since there are no overlaps       */
/* allowed.                                                            */
/*   The actual hintvalue is returned as a location.                   */
/* Hints are ignored inside a DotSection.                              */
/***********************************************************************/
static struct segment *FindStems(struct T1GlyphEngine *engine, double x, double y, double dx, double dy)
{
	int i;
	int newvert, newhor;
	struct segment *p;
	int newhorhalf, newverthalf;

	if (engine->t1.InDotSection)
		return (NULL);

	newvert = newhor = -1;
	newhorhalf = newverthalf = -1;

	for (i = engine->t1.currstartstem; i < engine->t1.numstems; i++)
	{
		if (engine->t1.stems[i].vertical)
		{		/* VSTEM hint */
			if ((x >= engine->t1.stems[i].x - EPS) &&
			    (x <= engine->t1.stems[i].x + engine->t1.stems[i].dx + EPS))
			{
				newvert = i;
				if (dy != 0.0)
				{
					if (dy < 0)
						newverthalf = LEFT;
					else
						newverthalf = RIGHT;
				}
				else
				{
					if (x < engine->t1.stems[i].x + engine->t1.stems[i].dx / 2)
						newverthalf = LEFT;
					else
						newverthalf = RIGHT;
				}
			}
		}
		else
		{		/* HSTEM hint */
			if ((y >= engine->t1.stems[i].y - EPS) &&
			    (y <= engine->t1.stems[i].y + engine->t1.stems[i].dy + EPS))
			{
				newhor = i;
				if (dx != 0.0)
				{
					if (dx < 0)
						newhorhalf = TOP;
					else
						newhorhalf = BOTTOM;
				}
				else
				{
					if (y < engine->t1.stems[i].y + engine->t1.stems[i].dy / 2)
						newhorhalf = BOTTOM;
					else
						newhorhalf = TOP;
				}
			}
		}
	}

	p = NULL;

	if (newvert == -1 && engine->t1.oldvert == -1) ;	/* Outside of any hints */
	else if (newvert == engine->t1.oldvert &&
		 newverthalf == engine->t1.oldverthalf) ;	/* No hint change */
	else if (engine->t1.oldvert == -1)
	{			/* New vertical hint in effect */
		p = Applyhint(engine, p, newvert, newverthalf);
	}
	else if (newvert == -1)
	{			/* Old vertical hint no longer in effect */
		p = Applyrevhint(engine, p, engine->t1.oldvert, engine->t1.oldverthalf);
	}
	else
	{			/* New vertical hint in effect, old hint no longer in effect */
		p = Applyrevhint(engine, p, engine->t1.oldvert, engine->t1.oldverthalf);
		p = Applyhint(engine, p, newvert, newverthalf);
	}

	if (newhor == -1 && engine->t1.oldhor == -1) ;	/* Outside of any hints */
	else if (newhor == engine->t1.oldhor &&
		 newhorhalf == engine->t1.oldhorhalf) ;	/* No hint change */
	else if (engine->t1.oldhor == -1)
	{			/* New horizontal hint in effect */
		p = Applyhint(engine, p, newhor, newhorhalf);
	}
	else if (newhor == -1)
	{			/* Old horizontal hint no longer in effect */
		p = Applyrevhint(engine, p, engine->t1.oldhor, engine->t1.oldhorhalf);
	}
	else
	{			/* New horizontal hint in effect, old hint no longer in effect */
		p = Applyrevhint(engine, p, engine->t1.oldhor, engine->t1.oldhorhalf);
		p = Applyhint(engine, p, newhor, newhorhalf);
	}

	engine->t1.oldvert = newvert;
	engine->t1.oldverthalf = newverthalf;
	engine->t1.oldhor = newhor;
	engine->t1.oldhorhalf = newhorhalf;

	return p;
}


/******************************************************/
/* Subroutines and statics for the Type1Char routines */
/******************************************************/

//static int strindex;		/* index into PostScript string being interpreted */
//static double currx, curry;	/* accumulated x and y values for hints */

#if 0	// TetiSoft: In global.h
struct callstackentry
{
	psobj *currstrP;	/* current CharStringP */
	int currindex;		/* current strindex */
	unsigned short currkey;	/* current decryption key */
};
#endif

//static double Stack[MAXSTACK];
//static int Top;
//static struct callstackentry CallStack[MAXCALLSTACK];
//static int CallTop;
//static double PSFakeStack[MAXPSFAKESTACK];
//static int PSFakeTop;

static void ClearStack(struct T1GlyphEngine *engine)
{
	engine->t1.Top = -1;
}

static void Push(struct T1GlyphEngine *engine, double Num)
{
	if (++engine->t1.Top < MAXSTACK)
		engine->t1.Stack[engine->t1.Top] = Num;
	else
		Error0("Push: Stack full\n");
}

static void ClearCallStack(struct T1GlyphEngine *engine)
{
	engine->t1.CallTop = -1;
}

static void PushCall(struct T1GlyphEngine *engine, psobj *CurrStrP, int CurrIndex, unsigned short CurrKey)
{
	if (++engine->t1.CallTop < MAXCALLSTACK)
	{
		engine->t1.CallStack[engine->t1.CallTop].currstrP = CurrStrP;	/* save CharString pointer */
		engine->t1.CallStack[engine->t1.CallTop].currindex = CurrIndex;	/* save CharString index */
		engine->t1.CallStack[engine->t1.CallTop].currkey = CurrKey;	/* save decryption key */
	}
	else
		Error0("PushCall: Stack full\n");
}

static void PopCall(struct T1GlyphEngine *engine, psobj **CurrStrPP, int *CurrIndexP, unsigned short *CurrKeyP)
{
	if (engine->t1.CallTop >= 0)
	{
		*CurrStrPP = engine->t1.CallStack[engine->t1.CallTop].currstrP;	/* restore CharString pointer */
		*CurrIndexP = engine->t1.CallStack[engine->t1.CallTop].currindex;	/* restore CharString index */
		*CurrKeyP = engine->t1.CallStack[engine->t1.CallTop--].currkey;	/* restore decryption key */
	}
	else
		Error0("PopCall: Stack empty\n");
}

static void ClearPSFakeStack(struct T1GlyphEngine *engine)
{
	engine->t1.PSFakeTop = -1;
}

/* PSFakePush: Pushes a number onto the fake PostScript stack */
static void PSFakePush(struct T1GlyphEngine *engine, double Num)
{
	if (++engine->t1.PSFakeTop < MAXPSFAKESTACK)
		engine->t1.PSFakeStack[engine->t1.PSFakeTop] = Num;
	else
		Error0("PSFakePush: Stack full\n");
}

/* PSFakePop: Removes a number from the top of the fake PostScript stack */
static double PSFakePop(struct T1GlyphEngine *engine)
{
	if (engine->t1.PSFakeTop < 0)
		Error0Ret("PSFakePop : Stack empty\n", 0.0);

	return (engine->t1.PSFakeStack[engine->t1.PSFakeTop--]);
}

/***********************************************************************/
/* Center a stem on the pixel grid -- used by HStem3 and VStem3        */
/***********************************************************************/
static struct segment *CenterStem(struct T1GlyphEngine *engine, double edge1, double edge2)
{
	int idealwidth, verticalondevice;
	double leftx, lefty, rightx, righty, center, width;
	double widthx, widthy;
	double shift, shiftx, shifty;
	double Xpixels, Ypixels;
	double tmpx;	// TetiSoft: Use auto variables to avoid global data
	long tmpi;	// TetiSoft: Use auto variables to avoid global data
	struct segment *p;

	p = t1_Loc(engine, engine->t1.CharSpace, edge1, 0.0);
	QueryLoc(engine, p, engine->IDENTITY, &leftx, &lefty);

	p = t1_Join(engine, p, t1_Loc(engine, engine->t1.CharSpace, edge2, 0.0));
	QueryLoc(engine, p, engine->IDENTITY, &rightx, &righty);
	t1_Destroy(engine, (struct xobject *)p);

	widthx = FABS(rightx - leftx);
	widthy = FABS(righty - lefty);

	if (widthy <= EPS)
	{			/* verticalondevice hint */
		verticalondevice = TRUE;
		center = (rightx + leftx) / 2.0;
		width = widthx;
	}
	else if (widthx <= EPS)
	{			/* horizontal hint */
		verticalondevice = FALSE;
		center = (righty + lefty) / 2.0;
		width = widthy;
	}
	else
	{			/* neither horizontal nor verticalondevice and not oblique */
		return (NULL);
	}

	idealwidth = ROUND(width);
	if (idealwidth == 0)
		idealwidth = 1;
	if (ODD(idealwidth))
	{			/* is ideal width odd? */
		/* center stem over pixel */
		shift = FLOOR(center) + 0.5 - center;
	}
	else
	{
		/* align stem on pixel boundary */
		shift = ROUND(center) - center;
	}

	if (verticalondevice)
	{
		shiftx = shift;
		shifty = 0.0;
	}
	else
	{
		shifty = shift;
		shiftx = 0.0;
	}

	p = t1_Loc(engine, engine->IDENTITY, shiftx, shifty);
	QueryLoc(engine, p, engine->t1.CharSpace, &Xpixels, &Ypixels);
	engine->t1.wsoffsetX = Xpixels;
	engine->t1.wsoffsetY = Ypixels;
	engine->t1.currx += engine->t1.wsoffsetX;
	engine->t1.curry += engine->t1.wsoffsetY;

	return (p);
}

/*-----------------------------------------------------------------------
  Decrypt - From Adobe Type 1 book page 63, with some modifications
-----------------------------------------------------------------------*/
#define KEY 4330		/* Initial key (seed) for CharStrings decryption */
#define C1 52845		/* Multiplier for pseudo-random number generator */
#define C2 22719		/* Constant for pseudo-random number generator */

//static unsigned short r;	/* Pseudo-random sequence of keys */

static unsigned char Decrypt(struct T1GlyphEngine *engine, unsigned char cipher)
{
	unsigned char plain;

	plain = cipher ^ (engine->t1.r >> 8);
	engine->t1.r = (cipher + engine->t1.r) * C1 + C2;
	return plain;
}

/* Get the next byte from the codestring being interpreted */
static int DoRead(struct T1GlyphEngine *engine, int *CodeP)
{
	if (engine->t1.strindex >= engine->t1.CharStringP->len)
		return (FALSE);	/* end of string */
	*CodeP = Decrypt(engine, (unsigned char)engine->t1.CharStringP->data.stringP[engine->t1.strindex++]);
	return (TRUE);
}

/* Strip blues->lenIV bytes from CharString and update encryption key */
/* (the lenIV entry in the Private dictionary specifies the number of */
/* random bytes at the beginning of each CharString; default is 4)    */
static void StartDecrypt(struct T1GlyphEngine *engine)
{
	int Code;

	engine->t1.r = KEY;		/* Initial key (seed) for CharStrings decryption */
	for (engine->t1.strindex = 0; engine->t1.strindex < engine->t1.blues->lenIV;)
		if (!DoRead(engine, &Code))	/* Read a byte and update decryption key */
			Error0("StartDecrypt: Premature end of CharString\n");
}

static void Decode(struct T1GlyphEngine *engine, int Code)
{
	int Code1, Code2, Code3, Code4;

	if (Code <= 31)		/* Code is [0,31]    */
		DoCommand(engine, Code);
	else if (Code <= 246)	/* Code is [32,246]  */
		Push(engine, (double)(Code - 139));
	else if (Code <= 250)
	{			/* Code is [247,250] */
		if (!DoRead(engine, &Code2))
			goto ended;
		Push(engine, (double)(((Code - 247) << 8) + Code2 + 108));
	}
	else if (Code <= 254)
	{			/* Code is [251,254] */
		if (!DoRead(engine, &Code2))
			goto ended;
		Push(engine, (double)(-((Code - 251) << 8) - Code2 - 108));
	}
	else
	{			/* Code is 255 */
		if (!DoRead(engine, &Code1))
			goto ended;
		if (!DoRead(engine, &Code2))
			goto ended;
		if (!DoRead(engine, &Code3))
			goto ended;
		if (!DoRead(engine, &Code4))
			goto ended;
		Push(engine, (double)((((((Code1 << 8) + Code2) << 8) + Code3) << 8) + Code4));
	}
	return;

      ended:Error0("Decode: Premature end of Type 1 CharString");
}

/* Interpret a command code */
static void DoCommand(struct T1GlyphEngine *engine, int Code)
{
	switch (Code)
	{
	case HSTEM:		/* |- y dy HSTEM |- */
		/* Vertical range of a horizontal stem zone */
		if (engine->t1.Top < 1)
			Error0("DoCommand: Stack low\n");
		HStem(engine, engine->t1.Stack[0], engine->t1.Stack[1]);
		ClearStack(engine);
		break;
	case VSTEM:		/* |- x dx VSTEM |- */
		/* Horizontal range of a vertical stem zone */
		if (engine->t1.Top < 1)
			Error0("DoCommand: Stack low\n");
		VStem(engine, engine->t1.Stack[0], engine->t1.Stack[1]);
		ClearStack(engine);
		break;
	case VMOVETO:		/* |- dy VMOVETO |- */
		/* Vertical MOVETO, equivalent to 0 dy RMOVETO */
		if (engine->t1.Top < 0)
			Error0("DoCommand: Stack low\n");
		RMoveTo(engine, 0.0, engine->t1.Stack[0]);
		ClearStack(engine);
		break;
	case RLINETO:		/* |- dx dy RLINETO |- */
		/* Like RLINETO in PostScript */
		if (engine->t1.Top < 1)
			Error0("DoCommand: Stack low\n");
		RLineTo(engine, engine->t1.Stack[0], engine->t1.Stack[1]);
		ClearStack(engine);
		break;
	case HLINETO:		/* |- dx HLINETO |- */
		/* Horizontal LINETO, equivalent to dx 0 RLINETO */
		if (engine->t1.Top < 0)
			Error0("DoCommand: Stack low\n");
		RLineTo(engine, engine->t1.Stack[0], 0.0);
		ClearStack(engine);
		break;
	case VLINETO:		/* |- dy VLINETO |- */
		/* Vertical LINETO, equivalent to 0 dy RLINETO */
		if (engine->t1.Top < 0)
			Error0("DoCommand: Stack low\n");
		RLineTo(engine, 0.0, engine->t1.Stack[0]);
		ClearStack(engine);
		break;
	case RRCURVETO:
		/* |- dx1 dy1 dx2 dy2 dx3 dy3 RRCURVETO |- */
		/* Relative RCURVETO, equivalent to dx1 dy1 */
		/* (dx1+dx2) (dy1+dy2) (dx1+dx2+dx3) */
		/* (dy1+dy2+dy3) RCURVETO in PostScript */
		if (engine->t1.Top < 5)
			Error0("DoCommand: Stack low\n");
		RRCurveTo(engine, engine->t1.Stack[0], engine->t1.Stack[1], engine->t1.Stack[2], engine->t1.Stack[3],
			          engine->t1.Stack[4], engine->t1.Stack[5]);
		ClearStack(engine);
		break;
	case CLOSEPATH:	/* - CLOSEPATH |- */
		/* Closes a subpath without repositioning the */
		/* current point */
		DoClosePath(engine);
		ClearStack(engine);
		break;
	case CALLSUBR:		/* subr# CALLSUBR - */
		/* Calls a CharString subroutine with index */
		/* subr# from the Subrs array */
		if (engine->t1.Top < 0)
			Error0("DoCommand: Stack low\n");
		CallSubr(engine, (int)engine->t1.Stack[engine->t1.Top--]);
		break;
	case RETURN:		/* - RETURN - */
		/* Returns from a Subrs array CharString */
		/* subroutine called with CALLSUBR */
		Return(engine);
		break;
	case ESCAPE:		/* ESCAPE to two-byte command code */
		if (!DoRead(engine, &Code))
			Error0("DoCommand: ESCAPE is last byte\n");
		Escape(engine, Code);
		break;
	case HSBW:		/* |- sbx wx HSBW |- */
		/* Set the left sidebearing point to (sbx,0), */
		/* set the character width vector to (wx,0). */
		/* Equivalent to sbx 0 wx 0 SBW.  Space */
		/* character should have sbx = 0 */
		if (engine->t1.Top < 1)
			Error0("DoCommand: Stack low\n");
		Sbw(engine, engine->t1.Stack[0], 0.0, engine->t1.Stack[1], 0.0);
		ClearStack(engine);
		break;
	case ENDCHAR:		/* - ENDCHAR |- */
		/* Finishes a CharString outline */
		EndChar(engine);
		ClearStack(engine);
		break;
	case RMOVETO:		/* |- dx dy RMOVETO |- */
		/* Behaves like RMOVETO in PostScript */
		if (engine->t1.Top < 1)
			Error0("DoCommand: Stack low\n");
		RMoveTo(engine, engine->t1.Stack[0], engine->t1.Stack[1]);
		ClearStack(engine);
		break;
	case HMOVETO:		/* |- dx HMOVETO |- */
		/* Horizontal MOVETO. Equivalent to dx 0 RMOVETO */
		if (engine->t1.Top < 0)
			Error0("DoCommand: Stack low\n");
		RMoveTo(engine, engine->t1.Stack[0], 0.0);
		ClearStack(engine);
		break;
	case VHCURVETO:	/* |- dy1 dx2 dy2 dx3 VHCURVETO |- */
		/* Vertical-Horizontal CURVETO, equivalent to */
		/* 0 dy1 dx2 dy2 dx3 0 RRCURVETO */
		if (engine->t1.Top < 3)
			Error0("DoCommand: Stack low\n");
		RRCurveTo(engine, 0.0, engine->t1.Stack[0], engine->t1.Stack[1], engine->t1.Stack[2],
			          engine->t1.Stack[3], 0.0);
		ClearStack(engine);
		break;
	case HVCURVETO:	/* |- dx1 dx2 dy2 dy3 HVCURVETO |- */
		/* Horizontal-Vertical CURVETO, equivalent to */
		/* dx1 0 dx2 dy2 0 dy3 RRCURVETO */
		if (engine->t1.Top < 3)
			Error0("DoCommand: Stack low\n");
		RRCurveTo(engine, engine->t1.Stack[0], 0.0, engine->t1.Stack[1], engine->t1.Stack[2], 0.0, engine->t1.Stack[3]);
		ClearStack(engine);
		break;
	default:		/* Unassigned command code */
		ClearStack(engine);
//		Error1("DoCommand: Unassigned code %d\n", Code);
		Error1("DoCommand: Unassigned code %ld\n", Code);
	}
}

static void Escape(struct T1GlyphEngine *engine, int Code)
{
	int i, Num;
	struct segment *p;

	switch (Code)
	{
	case DOTSECTION:	/* - DOTSECTION |- */
		/* Brackets an outline section for the dots in */
		/* letters such as "i", "j", and "!". */
		DotSection(engine);
		ClearStack(engine);
		break;
	case VSTEM3:		/* |- x0 dx0 x1 dx1 x2 dx2 VSTEM3 |- */
		/* Declares the horizontal ranges of three */
		/* vertical stem zones between x0 and x0+dx0, */
		/* x1 and x1+dx1, and x2 and x2+dx2. */
		if (engine->t1.Top < 5)
			Error0("DoCommand: Stack low\n");
		if (!engine->t1.wsset && engine->ProcessHints)
		{
			/* Shift the whole character so that the middle stem is centered. */
			p = CenterStem(engine, engine->t1.Stack[2] + engine->t1.sidebearingX, engine->t1.Stack[3]);
			engine->t1.path = t1_Join(engine, engine->t1.path, p);
			engine->t1.wsset = 1;
		}

		VStem(engine, engine->t1.Stack[0], engine->t1.Stack[1]);
		VStem(engine, engine->t1.Stack[2], engine->t1.Stack[3]);
		VStem(engine, engine->t1.Stack[4], engine->t1.Stack[5]);
		ClearStack(engine);
		break;
	case HSTEM3:		/* |- y0 dy0 y1 dy1 y2 dy2 HSTEM3 |- */
		/* Declares the vertical ranges of three hori- */
		/* zontal stem zones between y0 and y0+dy0, */
		/* y1 and y1+dy1, and y2 and y2+dy2. */
		if (engine->t1.Top < 5)
			Error0("DoCommand: Stack low\n");
		HStem(engine, engine->t1.Stack[0], engine->t1.Stack[1]);
		HStem(engine, engine->t1.Stack[2], engine->t1.Stack[3]);
		HStem(engine, engine->t1.Stack[4], engine->t1.Stack[5]);
		ClearStack(engine);
		break;
	case SEAC:		/* |- asb adx ady bchar achar SEAC |- */
		/* Standard Encoding Accented Character. */
		if (engine->t1.Top < 4)
			Error0("DoCommand: Stack low\n");
		Seac(engine, engine->t1.Stack[0], engine->t1.Stack[1], engine->t1.Stack[2],

// TetiSoft: Since neither mathieeedoubbas.library nor mathffp.library
// (nor the 6881/2?) contain a function to convert a floating point
// value to an UNSIGNED int value, we would force SAS/C to use _CXV52(), which could
// call _CXFERR(), which would raise an exception... slink would link the exception
// code handler, which would need CXBRK(), which needs _exit(), which can't be used
// in a run-time shared library...
// So we convert to SIGNED int with IEEEDPFix()/SPFix() if possible.
// This works only with math=ieee or math=ffp, since this here is the only
// part of the whole source where _CXFERR() would be linked in we avoid it
// to save space.
// With math=standard or math=68881, _CXV52() or _CXV53() is used at many places,
// for this cases the _CXFERR() replacement in type1lib.c is used.
#ifdef _MATHCXFERR
		     (unsigned char)engine->t1.Stack[3],
		     (unsigned char)engine->t1.Stack[4]);
#else
		     (char)engine->t1.Stack[3],
		     (char)engine->t1.Stack[4]);
#endif
		ClearStack(engine);
		break;
	case SBW:		/* |- sbx sby wx wy SBW |- */
		/* Set the left sidebearing point to (sbx,sby), */
		/* set the character width vector to (wx,wy). */
		if (engine->t1.Top < 3)
			Error0("DoCommand: Stack low\n");
		Sbw(engine, engine->t1.Stack[0], engine->t1.Stack[1], engine->t1.Stack[2], engine->t1.Stack[3]);
		ClearStack(engine);
		break;
	case DIV:		/* num1 num2 DIV quotient */
		/* Behaves like DIV in the PostScript language */
		if (engine->t1.Top < 1)
			Error0("DoCommand: Stack low\n");
		engine->t1.Stack[engine->t1.Top - 1] = Div(engine, engine->t1.Stack[engine->t1.Top - 1], engine->t1.Stack[engine->t1.Top]);
		engine->t1.Top--;
		break;
	case CALLOTHERSUBR:
		/* arg1 ... argn n othersubr# CALLOTHERSUBR - */
		/* Make calls on the PostScript interpreter */
		if (engine->t1.Top < 1)
			Error0("DoCommand: Stack low\n");
		Num = engine->t1.Stack[engine->t1.Top - 1];
		if (engine->t1.Top < Num + 1)
			Error0("DoCommand: Stack low\n");
		for (i = 0; i < Num; i++)
			PSFakePush(engine, engine->t1.Stack[engine->t1.Top - i - 2]);
		engine->t1.Top -= Num + 2;
		CallOtherSubr(engine, (int)engine->t1.Stack[engine->t1.Top + Num + 2]);
		break;
	case POP:		/* - POP number */
		/* Removes a number from the top of the */
		/* PostScript interpreter stack and pushes it */
		/* onto the Type 1 BuildChar operand stack */
		Push(engine, PSFakePop(engine));
		break;
	case SETCURRENTPOINT:	/* |- x y SETCURRENTPOINT |- */
		/* Sets the current point to (x,y) in absolute */
		/* character space coordinates without per- */
		/* forming a CharString MOVETO command */
		if (engine->t1.Top < 1)
			Error0("DoCommand: Stack low\n");
		SetCurrentPoint(engine, engine->t1.Stack[0], engine->t1.Stack[1]);
		ClearStack(engine);
		break;
	default:		/* Unassigned escape code command */
		ClearStack(engine);
//		Error1("Escape: Unassigned code %d\n", Code);
		Error1("Escape: Unassigned code %ld\n", Code);
	}
}

/* |- y dy HSTEM |- */
/* Declares the vertical range of a horizontal stem zone */
/* between coordinates y and y + dy */
/* y is relative to the left sidebearing point */
static void HStem(struct T1GlyphEngine *engine, double y, double dy)
{
//	IfTrace2((engine->FontDebug), "Hstem %f %f\n", &y, &dy);
	IfTrace2((engine->FontDebug), "Hstem %lx %lx\n", &y, &dy);
	if (engine->ProcessHints)
	{
		if (engine->t1.numstems >= MAXSTEMS)
			Error0("HStem: Too many hints\n");
		if (dy < 0.0)
		{
			y += dy;
			dy = -dy;
		}
		engine->t1.stems[engine->t1.numstems].vertical = FALSE;
		engine->t1.stems[engine->t1.numstems].x = 0.0;
		engine->t1.stems[engine->t1.numstems].y = engine->t1.sidebearingY + y + engine->t1.wsoffsetY;
		engine->t1.stems[engine->t1.numstems].dx = 0.0;
		engine->t1.stems[engine->t1.numstems].dy = dy;
		ComputeStem(engine, engine->t1.numstems);
		engine->t1.numstems++;
	}
}

/* |- x dx VSTEM |- */
/* Declares the horizontal range of a vertical stem zone */
/* between coordinates x and x + dx */
/* x is relative to the left sidebearing point */
static void VStem(struct T1GlyphEngine *engine, double x, double dx)
{
//	IfTrace2((engine->FontDebug), "Vstem %f %f\n", &x, &dx);
	IfTrace2((engine->FontDebug), "Vstem %lx %lx\n", &x, &dx);
	if (engine->ProcessHints)
	{
		if (engine->t1.numstems >= MAXSTEMS)
			Error0("VStem: Too many hints\n");
		if (dx < 0.0)
		{
			x += dx;
			dx = -dx;
		}
		engine->t1.stems[engine->t1.numstems].vertical = TRUE;
		engine->t1.stems[engine->t1.numstems].x = engine->t1.sidebearingX + x + engine->t1.wsoffsetX;
		engine->t1.stems[engine->t1.numstems].y = 0.0;
		engine->t1.stems[engine->t1.numstems].dx = dx;
		engine->t1.stems[engine->t1.numstems].dy = 0.0;
		ComputeStem(engine, engine->t1.numstems);
		engine->t1.numstems++;
	}
}

/* |- dx dy RLINETO |- */
/* Behaves like RLINETO in PostScript */
static void RLineTo(struct T1GlyphEngine *engine, double dx, double dy)
{
	struct segment *B;

//	IfTrace2((engine->FontDebug), "RLineTo %f %f\n", &dx, &dy);
	IfTrace2((engine->FontDebug), "RLineTo %lx %lx\n", &dx, &dy);

	B = t1_Loc(engine, engine->t1.CharSpace, dx, dy);

	if (engine->ProcessHints)
	{
		engine->t1.currx += dx;
		engine->t1.curry += dy;
		/* B = t1_Join(B, FindStems(engine->t1.currx, engine->t1.curry)); */
		B = t1_Join(engine, B, FindStems(engine, engine->t1.currx, engine->t1.curry, dx, dy));
	}

	engine->t1.path = t1_Join(engine, engine->t1.path, Line(engine, B));
}

/* |- dx1 dy1 dx2 dy2 dx3 dy3 RRCURVETO |- */
/* Relative RCURVETO, equivalent to dx1 dy1 */
/* (dx1+dx2) (dy1+dy2) (dx1+dx2+dx3) */
/* (dy1+dy2+dy3) RCURVETO in PostScript */
static void RRCurveTo(struct T1GlyphEngine *engine, double dx1, double dy1, double dx2, double dy2, double dx3, double dy3)
{
	struct segment *B, *C, *D;

//	IfTrace4((engine->FontDebug), "RRCurveTo %f %f %f %f ", &dx1, &dy1, &dx2, &dy2);
	IfTrace4((engine->FontDebug), "RRCurveTo %lx %lx %lx %lx ", &dx1, &dy1, &dx2, &dy2);
//	IfTrace2((engine->FontDebug), "%f %f\n", &dx3, &dy3);
	IfTrace2((engine->FontDebug), "%lx %lx\n", &dx3, &dy3);

	B = t1_Loc(engine, engine->t1.CharSpace, dx1, dy1);
	C = t1_Loc(engine, engine->t1.CharSpace, dx2, dy2);
	D = t1_Loc(engine, engine->t1.CharSpace, dx3, dy3);

	if (engine->ProcessHints)
	{
		/* For a Bezier curve, we apply the full hint value to
       the Bezier C point (and thereby D point). */
		engine->t1.currx += dx1 + dx2 + dx3;
		engine->t1.curry += dy1 + dy2 + dy3;
		/* C = t1_Join(C, FindStems(engine->t1.currx, engine->t1.curry)); */
		C = t1_Join(engine, C, FindStems(engine, engine->t1.currx, engine->t1.curry, dx3, dy3));
	}

	/* Since XIMAGER is not completely relative, */
	/* we need to add up the delta values */

	C = t1_Join(engine, C, (struct segment *) t1_Dup(engine, (struct xobject *)B));
	D = t1_Join(engine, D, (struct segment *) t1_Dup(engine, (struct xobject *)C));

	engine->t1.path = t1_Join(engine, engine->t1.path, (struct segment *)Bezier(engine, B, C, D));
}

/* - CLOSEPATH |- */
/* Closes a subpath WITHOUT repositioning the */
/* current point */
static void DoClosePath(struct T1GlyphEngine *engine)
{
	struct segment *CurrentPoint;

	IfTrace0((engine->FontDebug), "DoClosePath\n");
	CurrentPoint = t1_Phantom(engine, (struct xobject *)engine->t1.path);
	engine->t1.path = t1_ClosePath(engine, engine->t1.path, 0);
	engine->t1.path = t1_Join(engine, (struct segment *) t1_Snap(engine, engine->t1.path), CurrentPoint);
}

/* subr# CALLSUBR - */
/* Calls a CharString subroutine with index */
/* subr# from the Subrs array */
static void CallSubr(struct T1GlyphEngine *engine, int subrno)
{
//	IfTrace1((engine->FontDebug), "CallSubr %d\n", subrno);
	IfTrace1((engine->FontDebug), "CallSubr %ld\n", subrno);
	if ((subrno < 0) || (subrno >= engine->t1.SubrsP->len))
		Error0("CallSubr: subrno out of range\n");
	PushCall(engine, engine->t1.CharStringP, engine->t1.strindex, engine->t1.r);
	engine->t1.CharStringP = &engine->t1.SubrsP->data.arrayP[subrno];
	StartDecrypt(engine);
}

/* - RETURN - */
/* Returns from a Subrs array CharString */
/* subroutine called with CALLSUBR */
static void Return(struct T1GlyphEngine *engine)
{
	IfTrace0((engine->FontDebug), "Return\n");
	PopCall(engine, &engine->t1.CharStringP, &engine->t1.strindex, &engine->t1.r);
}

/* - ENDCHAR |- */
/* Finishes a CharString outline */
/* Executes SETCHACHEDEVICE using a bounding box */
/* it computes directly from the character outline */
/* and using the width information acquired from a previous */
/* HSBW or SBW.  It then calls a special version of FILL */
/* or STROKE depending on the value of PaintType in the */
/* font dictionary */
static void EndChar(struct T1GlyphEngine *engine)
{
	IfTrace0((engine->FontDebug), "EndChar\n");

	/* There is no need to compute and set bounding box for
     the cache, since XIMAGER does that on the fly. */

	/* Perform a Closepath just in case the command was left out */
	engine->t1.path = t1_ClosePath(engine, engine->t1.path, 0);

	/* Set character width */
	engine->t1.path = t1_Join(engine, (struct segment *) t1_Snap(engine, engine->t1.path), t1_Loc(engine, engine->t1.CharSpace, engine->t1.escapementX, engine->t1.escapementY));

}

/* |- dx dy RMOVETO |- */
/* Behaves like RMOVETO in PostScript */
static void RMoveTo(struct T1GlyphEngine *engine, double dx, double dy)
{
	struct segment *B;

//	IfTrace2((engine->FontDebug), "RMoveTo %f %f\n", &dx, &dy);
	IfTrace2((engine->FontDebug), "RMoveTo %lx %lx\n", &dx, &dy);

	B = t1_Loc(engine, engine->t1.CharSpace, dx, dy);

	if (engine->ProcessHints)
	{
		engine->t1.currx += dx;
		engine->t1.curry += dy;
		/* B = t1_Join(engine, B, FindStems(engine->t1.currx, engine->t1.curry)); */
		B = t1_Join(engine, B, FindStems(engine, engine->t1.currx, engine->t1.curry, 0.0, 0.0));
	}

	engine->t1.path = t1_Join(engine, engine->t1.path, B);
}

/* - DOTSECTION |- */
/* Brackets an outline section for the dots in */
/* letters such as "i", "j", and "!". */
static void DotSection(struct T1GlyphEngine *engine)
{
	IfTrace0((engine->FontDebug), "DotSection\n");
	engine->t1.InDotSection = !engine->t1.InDotSection;
}

/* |- asb adx ady bchar achar SEAC |- */
/* Standard Encoding Accented Character. */
static void Seac(struct T1GlyphEngine *engine, double asb, double adx, double ady, unsigned char bchar, unsigned char achar)
{
	int Code;
	struct segment *mypath;

//	IfTrace4((engine->FontDebug), "SEAC %f %f %f %d ", &asb, &adx, &ady, bchar);
	IfTrace4((engine->FontDebug), "SEAC %lx %lx %lx %lx ", &asb, &adx, &ady, bchar);
//	IfTrace1((engine->FontDebug), "%d\n", achar);
	IfTrace1((engine->FontDebug), "%ld\n", achar);

	/* Move adx - asb, ady over and up from base char's sbpoint. */
	/* (We use adx - asb to counteract the accents sb shift.) */
	/* The variables accentoffsetX/Y modify sidebearingX/Y in Sbw(). */
	/* Note that these incorporate the base character's sidebearing shift by */
	/* using the current sidebearingX, Y values. */
	engine->t1.accentoffsetX = engine->t1.sidebearingX + adx - asb;
	engine->t1.accentoffsetY = engine->t1.sidebearingY + ady;

	/* Set path = NULL to avoid complaints from Sbw(). */
	engine->t1.path = NULL;

	/* Go find the CharString for the accent's code via an upcall */
	engine->t1.CharStringP = GetType1CharString(engine, engine->t1.Environment, achar);
	StartDecrypt(engine);

	ClearStack(engine);
	ClearPSFakeStack(engine);
	ClearCallStack(engine);

	for (;;)
	{
		if (!DoRead(engine, &Code))
			break;
		Decode(engine, Code);
		if (engine->t1.errflag)
			return;
	}
	/* Copy snapped path to mypath and set path to NULL as above. */
	mypath = (struct segment *) t1_Snap(engine, engine->t1.path);
	engine->t1.path = NULL;

	/* We must reset these to null now. */
	engine->t1.accentoffsetX = engine->t1.accentoffsetY = 0;

	/* go find the CharString for the base char's code via an upcall */
	engine->t1.CharStringP = GetType1CharString(engine, engine->t1.Environment, bchar);
	StartDecrypt(engine);

	ClearStack(engine);
	ClearPSFakeStack(engine);
	ClearCallStack(engine);

	FinitStems(engine);
	InitStems(engine);

	for (;;)
	{
		if (!DoRead(engine, &Code))
			break;
		Decode(engine, Code);
		if (engine->t1.errflag)
			return;
	}
	engine->t1.path = t1_Join(engine, mypath, engine->t1.path);
}


/* |- sbx sby wx wy SBW |- */
/* Set the left sidebearing point to (sbx,sby), */
/* set the character width vector to (wx,wy). */
static void Sbw(struct T1GlyphEngine *engine, double sbx, double sby, double wx, double wy)
{
//	IfTrace4((engine->FontDebug), "SBW %f %f %f %f\n", &sbx, &sby, &wx, &wy);
	IfTrace4((engine->FontDebug), "SBW %lx %lx %lx %lx\n", &sbx, &sby, &wx, &wy);

	engine->t1.escapementX = wx;	/* Character width vector */
	engine->t1.escapementY = wy;

	/* Sidebearing values are sbx, sby args, plus accent offset from Seac(). */
	engine->t1.sidebearingX = sbx + engine->t1.accentoffsetX;
	engine->t1.sidebearingY = sby + engine->t1.accentoffsetY;

	engine->t1.path = t1_Join(engine, engine->t1.path, t1_Loc(engine, engine->t1.CharSpace, engine->t1.sidebearingX, engine->t1.sidebearingY));
	if (engine->ProcessHints)
	{
		engine->t1.currx = engine->t1.sidebearingX;
		engine->t1.curry = engine->t1.sidebearingY;
	}
}

 /* num1 num2 DIV quotient */
/* Behaves like DIV in the PostScript language */
static double Div(struct T1GlyphEngine *engine, double num1, double num2)
{
//	IfTrace2((engine->FontDebug), "Div %f %f\n", &num1, &num2);
	IfTrace2((engine->FontDebug), "Div %lx %lx\n", &num1, &num2);
	return (num1 / num2);
}

/*
  The following four subroutines (FlxProc, FlxProc1, FlxProc2, and
  HintReplace) are C versions of the OtherSubrs Programs, which were
  were published in the Adobe Type 1 Font Format book.

  The Flex outline fragment is described by
    c1: (x0, y0) = c3: (x0, yshrink(y0)) or (xshrink(x0), y0)
     "  (x1, y1) =  "  (x1, yshrink(y1)) or (xshrink(x1), y1)
     "  (x2, y2) - reference point
    c2: (x0, y0) = c4: (x0, yshrink(y0)) or (xshrink(x0), y0)
     "  (x1, y1) =  "  (x1, yshrink(y1)) or (xshrink(x1), y1)
     "  (x2, y2) =  "  (x2, y2), rightmost endpoint
    c3: (x0, y0) - control point, 1st Bezier curve
     "  (x1, y1) - control point,      -"-
     "  (x2, y2) - end point,          -"-
    c4: (x0, y0) - control point, 2nd Bezier curve
     "  (x1, y1) - control point,      -"-
     "  (x2, y2) - end point,          -"-
    ep: (epY, epX) - final endpoint (should be same as c4: (x2, y2))
    idmin - minimum Flex height (1/100 pixel) at which to render curves
*/

#define dtransform(e,dxusr,dyusr,dxdev,dydev) { \
  register struct segment *point = t1_Loc(e, e->t1.CharSpace, (double)dxusr, (double)dyusr); \
  QueryLoc(e, point, e->IDENTITY, dxdev, dydev); \
  t1_Destroy(e, (struct xobject *)point); \
}

#define itransform(e,xdev,ydev,xusr,yusr) { \
  register struct segment *point = t1_Loc(e, e->IDENTITY, xdev, ydev); \
  QueryLoc(e, point, e->t1.CharSpace, xusr, yusr); \
  t1_Destroy(e, (struct xobject *)point); \
}

#define transform(e,xusr,yusr,xdev,ydev) dtransform(e,xusr,yusr,xdev,ydev)

#define PaintType (0)

#define lineto(e,x,y) { \
  struct segment *CurrentPoint; \
  double CurrentX, CurrentY; \
  CurrentPoint = t1_Phantom(e, (struct xobject *)e->t1.path); \
  QueryLoc(e, CurrentPoint, e->t1.CharSpace, &CurrentX, &CurrentY); \
  t1_Destroy(e, (struct xobject *)CurrentPoint); \
  RLineTo(e, x - CurrentX, y - CurrentY); \
}

#define curveto(e,x0,y0,x1,y1,x2,y2) { \
  struct segment *CurrentPoint; \
  double CurrentX, CurrentY; \
  CurrentPoint = t1_Phantom(e, (struct xobject *)e->t1.path); \
  QueryLoc(e, CurrentPoint, e->t1.CharSpace, &CurrentX, &CurrentY); \
  t1_Destroy(e, (struct xobject *)CurrentPoint); \
  RRCurveTo(e, x0 - CurrentX, y0 - CurrentY, x1 - x0, y1 - y0, x2 - x1, y2 - y1); \
}

#define xshrink(x) ((x - c4x2) * shrink +c4x2)
#define yshrink(y) ((y - c4y2) * shrink +c4y2)

#define PickCoords(flag) \
  if (flag) { /* Pick "shrunk" coordinates */ \
    x0 = c1x0; y0 = c1y0; \
    x1 = c1x1; y1 = c1y1; \
    x2 = c1x2; y2 = c1y2; \
    x3 = c2x0; y3 = c2y0; \
    x4 = c2x1; y4 = c2y1; \
    x5 = c2x2; y5 = c2y2; \
  } else { /* Pick original coordinates */ \
    x0 = c3x0; y0 = c3y0; \
    x1 = c3x1; y1 = c3y1; \
    x2 = c3x2; y2 = c3y2; \
    x3 = c4x0; y3 = c4y0; \
    x4 = c4x1; y4 = c4y1; \
    x5 = c4x2; y5 = c4y2; \
  }

#if 0	// TetiSoft
/* Added by Amish 1/7/95 to get rid of a bunch of SAS complaints (uninitialied vars) */
#define PickOriginalCoords \
  { /* Pick original coordinates */ \
    x0 = c3x0; y0 = c3y0; \
    x1 = c3x1; y1 = c3y1; \
    x2 = c3x2; y2 = c3y2; \
    x3 = c4x0; y3 = c4y0; \
    x4 = c4x1; y4 = c4y1; \
    x5 = c4x2; y5 = c4y2; \
  }
#endif

/* FlxProc() = OtherSubrs[0]; Main part of Flex          */
/*   Calling sequence: 'idmin epX epY 3 0 callothersubr' */
/*   Computes Flex values, and renders the Flex path,    */
/*   and returns (leaves) ending coordinates on stack    */
static void FlxProc(
		struct T1GlyphEngine *engine,
		double c1x2, double c1y2, double c3x0, double c3y0,
		double c3x1, double c3y1, double c3x2, double c3y2,
		double c4x0, double c4y0, double c4x1, double c4y1,
		double c4x2, double c4y2, double epY, double epX, int idmin)
{
	double dmin;
	double c1x0, c1y0, c1x1, c1y1;
	double c2x0, c2y0, c2x1, c2y1, c2x2, c2y2;
	char yflag;
	double x0, y0, x1, y1, x2, y2, x3, y3, x4, y4, x5, y5;
	double cxx, cyx, cxy, cyy;	/* Transformation matrix */
	int flipXY;
	double x, y;
	double erosion = 1;	/* Device parameter */
	/* Erosion may have different value specified in 'internaldict' */
	double shrink;
	double dX, dY;
	char erode;
	double eShift;
	double cx, cy;
	double ex, ey;
	double tmpx;	// TetiSoft: Use auto variables to avoid global data
	long tmpi;	// TetiSoft: Use auto variables to avoid global data

// TetiSoft: taken from X11R6.5.1
	c1x0 = c1y0 = c1x1 = c1y1 = c2x0 = c2y0 = c2x1 = c2y1 = c2x2 = c2y2 = 0.0;

	t1_Destroy(engine, (struct xobject *)engine->t1.path);
	engine->t1.path = engine->t1.FlxOldPath;	/* Restore previous path (stored in FlxProc1) */

	if (engine->ProcessHints)
	{
		dmin = ABS(idmin) / 100.0;	/* Minimum Flex height in pixels */

		c2x2 = c4x2;
		c2y2 = c4y2;	/* Point c2 = c4 */

		yflag = FABS(c1y2 - c3y2) > FABS(c1x2 - c3x2);	/* Flex horizontal? */

		QuerySpace(engine, engine->t1.CharSpace, &cxx, &cyx, &cxy, &cyy);	/* Transformation matrix */

		if (FABS(cxx) < 0.00001 || FABS(cyy) < 0.00001)
			flipXY = -1;	/* Char on side */
		else if (FABS(cyx) < 0.00001 || FABS(cxy) < 0.00001)
			flipXY = 1;	/* Char upright */
		else
			flipXY = 0;	/* Char at angle */

		if (yflag)
		{		/* Flex horizontal */
			if (flipXY == 0 || c3y2 == c4y2)
			{	/* Char at angle or Flex height = 0 */
				PickCoords(FALSE);	/* Pick original control points */
//				PickOriginalCoords;
			}
			else
			{
				shrink = FABS((c1y2 - c4y2) / (c3y2 - c4y2));	/* Slope */

				c1x0 = c3x0;
				c1y0 = yshrink(c3y0);
				c1x1 = c3x1;
				c1y1 = yshrink(c3y1);
				c2x0 = c4x0;
				c2y0 = yshrink(c4y0);
				c2x1 = c4x1;
				c2y1 = yshrink(c4y1);

				dtransform(engine, 0.0, ROUND(c3y2 - c1y2), &x, &y);	/* Flex height in pixels */
				dY = FABS((flipXY == 1) ? y : x);
				PickCoords(dY < dmin);	/* If Flex small, pick 'shrunk' control points */

				if (FABS(y2 - c1y2) > 0.001)
				{	/* Flex 'non-zero'? */
					transform(engine, c1x2, c1y2, &x, &y);

					if (flipXY == 1)
					{
						cx = x;
						cy = y;
					}
					else
					{
						cx = y;
						cy = x;
					}

					dtransform(engine, 0.0, ROUND(y2 - c1y2), &x, &y);
					dY = (flipXY == 1) ? y : x;
					if (ROUND(dY) != 0)
						dY = ROUND(dY);
					else
						dY = (dY < 0) ? -1 : 1;

					erode = PaintType != 2 && erosion >= 0.5;
					if (erode)
						cy -= 0.5;
					ey = cy + dY;

/* TetiSoft: from X11R6.5.1 */
//					ey = CEIL(ey) - ey + FLOOR(ey);
					ey = CEIL(ey) - ey;
					ey = ey + FLOOR(cy + dY);

					if (erode)
						ey += 0.5;

					if (flipXY == 1)
					{
						itransform(engine, cx, ey, &x, &y);
					}
					else
					{
						itransform(engine, ey, cx, &x, &y);
					}

					eShift = y - y2;
					y1 += eShift;
					y2 += eShift;
					y3 += eShift;
				}
			}
		}
		else
		{		/* Flex vertical */
			if (flipXY == 0 || c3x2 == c4x2)
			{	/* Char at angle or Flex height = 0 */
				PickCoords(FALSE);	/* Pick original control points */
//				PickOriginalCoords;
			}
			else
			{
				shrink = FABS((c1x2 - c4x2) / (c3x2 - c4x2));	/* Slope */

				c1x0 = xshrink(c3x0);
				c1y0 = c3y0;
				c1x1 = xshrink(c3x1);
				c1y1 = c3y1;
				c2x0 = xshrink(c4x0);
				c2y0 = c4y0;
				c2x1 = xshrink(c4x1);
				c2y1 = c4y1;

				dtransform(engine, ROUND(c3x2 - c1x2), 0.0, &x, &y);	/* Flex height in pixels */
				dX = FABS((flipXY == -1) ? y : x);
				PickCoords(dX < dmin);	/* If Flex small, pick 'shrunk' control points */

				if (FABS(x2 - c1x2) > 0.001)
				{
					transform(engine, c1x2, c1y2, &x, &y);
					if (flipXY == -1)
					{
						cx = y;
						cy = x;
					}
					else
					{
						cx = x;
						cy = y;
					}

					dtransform(engine, ROUND(x2 - c1x2), 0.0, &x, &y);
					dX = (flipXY == -1) ? y : x;
					if (ROUND(dX) != 0)
						dX = ROUND(dX);
					else
						dX = (dX < 0) ? -1 : 1;

					erode = PaintType != 2 && erosion >= 0.5;
					if (erode)
						cx -= 0.5;
					ex = cx + dX;

/* TetiSoft: from X11R6.5.1 */
//					ex = CEIL(ex) - ex + FLOOR(ex);
					ex = CEIL(ex) - ex;
					ex = ex + FLOOR(cx + dX);

					if (erode)
						ex += 0.5;

					if (flipXY == -1)
					{
						itransform(engine, cy, ex, &x, &y);
					}
					else
					{
						itransform(engine, ex, cy, &x, &y);
					}

					eShift = x - x2;
					x1 += eShift;
					x2 += eShift;
					x3 += eShift;
				}
			}
		}

		if (x2 == x5 || y2 == y5)
		{
			lineto(engine, x5, y5);
		}
		else
		{
			curveto(engine, x0, y0, x1, y1, x2, y2);
			curveto(engine, x3, y3, x4, y4, x5, y5);
		}
	}
	else
	{			/* ProcessHints is off */
		PickCoords(FALSE);	/* Pick original control points */
//		PickOriginalCoords;
		curveto(engine, x0, y0, x1, y1, x2, y2);
		curveto(engine, x3, y3, x4, y4, x5, y5);
	}

	PSFakePush(engine, epY);
	PSFakePush(engine, epX);
}

/* FlxProc1() = OtherSubrs[1]; Part of Flex            */
/*   Calling sequence: '0 1 callothersubr'             */
/*   Saves and clears path, then restores currentpoint */
static void FlxProc1(struct T1GlyphEngine *engine)
{
	struct segment *CurrentPoint;

	CurrentPoint = t1_Phantom(engine, (struct xobject *)engine->t1.path);

	engine->t1.FlxOldPath = engine->t1.path;
	engine->t1.path = CurrentPoint;
}

/* FlxProc2() = OtherSubrs[2]; Part of Flex */
/*   Calling sequence: '0 2 callothersubr'  */
/*   Returns currentpoint on stack          */
static void FlxProc2(struct T1GlyphEngine *engine)
{
	struct segment *CurrentPoint;
	double CurrentX, CurrentY;

	CurrentPoint = t1_Phantom(engine, (struct xobject *)engine->t1.path);
	QueryLoc(engine, CurrentPoint, engine->t1.CharSpace, &CurrentX, &CurrentY);
	t1_Destroy(engine, (struct xobject *)CurrentPoint);

	/* Push CurrentPoint on fake PostScript stack */
	PSFakePush(engine, CurrentX);
	PSFakePush(engine, CurrentY);
}

/* HintReplace() = OtherSubrs[3]; Hint Replacement            */
/*   Calling sequence: 'subr# 1 3 callothersubr pop callsubr' */
/*   Reinitializes stem hint structure                        */
static void HintReplace(struct T1GlyphEngine *engine)
{
	/* Effectively retire the current stems, but keep them around for */
	/* revhint use in case we are in a stem when we replace hints. */
	engine->t1.currstartstem = engine->t1.numstems;

	/* 'subr#' is left on PostScript stack (for 'pop callsubr') */
}

/* arg1 ... argn n othersubr# CALLOTHERSUBR - */
/* Make calls on the PostScript interpreter (or call equivalent C code) */
/* NOTE: The n arguments have been pushed on the fake PostScript stack */
static void CallOtherSubr(struct T1GlyphEngine *engine, int othersubrno)
{
//	IfTrace1((engine->FontDebug), "CallOtherSubr %d\n", othersubrno);
	IfTrace1((engine->FontDebug), "CallOtherSubr %ld\n", othersubrno);

	switch (othersubrno)
	{
	case 0:		/* OtherSubrs[0]; Main part of Flex */
		if (engine->t1.PSFakeTop < 16)
			Error0("CallOtherSubr: PSFakeStack low");
		ClearPSFakeStack(engine);
		FlxProc(       engine,
			       engine->t1.PSFakeStack[0], engine->t1.PSFakeStack[1], engine->t1.PSFakeStack[2], engine->t1.PSFakeStack[3],
			       engine->t1.PSFakeStack[4], engine->t1.PSFakeStack[5], engine->t1.PSFakeStack[6], engine->t1.PSFakeStack[7],
			       engine->t1.PSFakeStack[8], engine->t1.PSFakeStack[9], engine->t1.PSFakeStack[10], engine->t1.PSFakeStack[11],
			       engine->t1.PSFakeStack[12], engine->t1.PSFakeStack[13], engine->t1.PSFakeStack[14], engine->t1.PSFakeStack[15],
			       (int)engine->t1.PSFakeStack[16]
		    );
		break;
	case 1:		/* OtherSubrs[1]; Part of Flex */
		FlxProc1(engine);
		break;
	case 2:		/* OtherSubrs[2]; Part of Flex */
		FlxProc2(engine);
		break;
	case 3:		/* OtherSubrs[3]; Hint Replacement */
		HintReplace(engine);
		break;
	default:
		{		/* call OtherSubrs[4] or higher if PostScript is present */
		}
	}
}

/* |- x y SETCURRENTPOINT |- */
/* Sets the current point to (x,y) in absolute */
/* character space coordinates without per- */
/* forming a CharString MOVETO command */
static void SetCurrentPoint(struct T1GlyphEngine *engine, double x, double y)
{
//	IfTrace2((engine->FontDebug), "SetCurrentPoint %f %f\n", &x, &y);
	IfTrace2((engine->FontDebug), "SetCurrentPoint %lx %lx\n", &x, &y);

	engine->t1.currx = x;
	engine->t1.curry = y;
}

/* The Type1Char routine for use by PostScript. */
/************************************************/
struct xobject *Type1Char(
		struct T1GlyphEngine *engine,
		psfont *env,
		struct XYspace *S,
		psobj *charstrP,
		psobj *subrsP,
//		psobj *osubrsP,
		struct blues_struct *bluesP)	/* FontID's ptr to the blues struct */
//		int *modeP)
{
	int Code;

	engine->t1.path = NULL;
	engine->t1.errflag = FALSE;

	/* Make parameters available to all Type1 routines */
	engine->t1.Environment = env;
	engine->t1.CharSpace = S;		/* used when creating path elements */
	engine->t1.CharStringP = charstrP;
	engine->t1.SubrsP = subrsP;
//	engine->t1.OtherSubrsP = osubrsP;	// TetiSoft: Unused
//	engine->t1.ModeP = modeP;		// TetiSoft: Unused

	engine->t1.blues = bluesP;

	/* compute the alignment zones */
	ComputeAlignmentZones(engine);

	StartDecrypt(engine);

	ClearStack(engine);
	ClearPSFakeStack(engine);
	ClearCallStack(engine);

	InitStems(engine);

	engine->t1.currx = engine->t1.curry = 0;
	engine->t1.escapementX = engine->t1.escapementY = 0;
	engine->t1.sidebearingX = engine->t1.sidebearingY = 0;
	engine->t1.accentoffsetX = engine->t1.accentoffsetY = 0;
	engine->t1.wsoffsetX = engine->t1.wsoffsetY = 0;	/* No shift to preserve whitspace. */
	engine->t1.wsset = 0;					/* wsoffsetX,Y haven't been set yet. */

	for (;;)
	{
		if (!DoRead(engine, &Code))
			break;
		Decode(engine, Code);
		if (engine->t1.errflag)
			break;
	}

	FinitStems(engine);


	/* Clean up if an error has occurred */
	if (engine->t1.errflag)
	{
		if (engine->t1.path != NULL)
		{
			t1_Destroy(engine, (struct xobject *)engine->t1.path);	/* Reclaim storage */
			engine->t1.path = NULL;	/* Indicate that character could not be built */
		}
	}

	return ((struct xobject *)engine->t1.path);
}
