File:  [LON-CAPA] / loncom / cgi / mimeTeX / mimetex.c
Revision 1.4: download - view: text, annotated - select for diffs
Thu Dec 4 12:17:13 2008 UTC (15 years, 5 months ago) by riegler
Branches: MAIN
CVS tags: version_2_9_X, version_2_9_99_0, version_2_9_1, version_2_9_0, version_2_8_X, version_2_8_99_1, version_2_8_99_0, version_2_8_2, version_2_8_1, version_2_8_0, version_2_7_99_1, version_2_7_99_0, version_2_10_X, version_2_10_1, version_2_10_0_RC2, version_2_10_0_RC1, version_2_10_0, loncapaMITrelate_1, language_hyphenation_merge, language_hyphenation, bz6209-base, bz6209, bz5969, bz2851, PRINT_INCOMPLETE_base, PRINT_INCOMPLETE, HEAD, GCI_3, GCI_2, GCI_1, BZ5971-printing-apage, BZ5434-fox, BZ4492-merge, BZ4492-feature_horizontal_radioresponse, BZ4492-feature_Support_horizontal_radioresponse, BZ4492-Support_horizontal_radioresponse
upgrade to mimetex version 1.7
This version will be needed in order to align formulas neatly.
noticable change is the % in the path specified in "commands".

    1: /****************************************************************************
    2:  *
    3:  * Copyright(c) 2002-2008, John Forkosh Associates, Inc. All rights reserved.
    4:  *           http://www.forkosh.com   mailto: john@forkosh.com
    5:  * --------------------------------------------------------------------------
    6:  * This file is part of mimeTeX, which is free software. You may redistribute
    7:  * and/or modify it under the terms of the GNU General Public License,
    8:  * version 3 or later, as published by the Free Software Foundation.
    9:  *      MimeTeX is distributed in the hope that it will be useful, but
   10:  * WITHOUT ANY WARRANTY, not even the implied warranty of MERCHANTABILITY.
   11:  * See the GNU General Public License for specific details.
   12:  *      By using mimeTeX, you warrant that you have read, understood and
   13:  * agreed to these terms and conditions, and that you possess the legal
   14:  * right and ability to enter into this agreement and to use mimeTeX
   15:  * in accordance with it.
   16:  *      Your mimetex.zip distribution file should contain the file COPYING,
   17:  * an ascii text copy of the GNU General Public License, version 3.
   18:  * If not, point your browser to  http://www.gnu.org/licenses/
   19:  * or write to the Free Software Foundation, Inc.,
   20:  * 59 Temple Place, Suite 330,  Boston, MA 02111-1307 USA.
   21:  * --------------------------------------------------------------------------
   22:  *
   23:  * Purpose:   o	MimeTeX, licensed under the gpl, lets you easily embed
   24:  *		LaTeX math in your html pages.  It parses a LaTeX math
   25:  *		expression and immediately emits the corresponding gif
   26:  *		image, rather than the usual TeX dvi.  And mimeTeX is an
   27:  *		entirely separate little program that doesn't use TeX or
   28:  *		its fonts in any way.  It's just one cgi that you put in
   29:  *		your site's cgi-bin/ directory, with no other dependencies.
   30:  *		     So mimeTeX is very easy to install.  And it's equally
   31:  *		easy to use.  Just place an html <img> tag in your document
   32:  *		wherever you want to see the corresponding LaTeX expression.
   33:  *		For example,
   34:  *		 <img src="../cgi-bin/mimetex.cgi?\int_{-\infty}^xe^{-t^2}dt"
   35:  *		  alt="" border=0 align=middle>
   36:  *		immediately generates the corresponding gif image on-the-fly,
   37:  *		displaying the rendered expression wherever you put that
   38:  *		<img> tag.
   39:  *		     MimeTeX doesn't need intermediate dvi-to-gif conversion,
   40:  *		and it doesn't clutter up your filesystem with separate
   41:  *		little gif files for each converted expression.
   42:  *		But image caching is available by using mimeTeX's
   43:  *		-DCACHEPATH=\"path/\" compile option (see below).
   44:  *		There's also no inherent need to repeatedly write the
   45:  *		cumbersome <img> tag illustrated above.  You can write
   46:  *		your own custom tags, or write a wrapper script around
   47:  *		mimeTeX to simplify the notation.
   48:  *		     Further discussion about mimeTeX's features and
   49:  *		usage is available on its homepage,
   50:  *		  http://www.forkosh.com/mimetex.html
   51:  *		and similarly in mimetex.html included with your mimetex.zip
   52:  *		distribution file.
   53:  *
   54:  * Functions:	===================== Raster Functions ======================
   55:  *	PART2	--- raster constructor functions ---
   56:  *		new_raster(width,height,pixsz)   allocation (and constructor)
   57:  *		new_subraster(width,height,pixsz)allocation (and constructor)
   58:  *		new_chardef()                         allocate chardef struct
   59:  *		delete_raster(rp)        deallocate raster (rp =  raster ptr)
   60:  *		delete_subraster(sp)  deallocate subraster (sp=subraster ptr)
   61:  *		delete_chardef(cp)      deallocate chardef (cp = chardef ptr)
   62:  *		--- primitive (sub)raster functions ---
   63:  *		rastcpy(rp)                           allocate new copy of rp
   64:  *		subrastcpy(sp)                        allocate new copy of sp
   65:  *		rastrot(rp)         new raster rotated right 90 degrees to rp
   66:  *		rastref(rp,axis)    new raster reflected (axis 1=horz,2=vert)
   67:  *		rastput(target,source,top,left,isopaque)  overlay src on trgt
   68:  *		rastcompose(sp1,sp2,offset2,isalign,isfree) sp2 on top of sp1
   69:  *		rastcat(sp1,sp2,isfree)                  concatanate sp1||sp2
   70:  *		rastack(sp1,sp2,base,space,iscenter,isfree)stack sp2 atop sp1
   71:  *		rastile(tiles,ntiles)      create composite raster from tiles
   72:  *		rastsmash(sp1,sp2,xmin,ymin)      calc #smash pixels sp1||sp2
   73:  *		rastsmashcheck(term)         check if term is "safe" to smash
   74:  *		--- raster "drawing" functions ---
   75:  *		accent_subraster(accent,width,height)       draw \hat\vec\etc
   76:  *		arrow_subraster(width,height,drctn,isBig)    left/right arrow
   77:  *		uparrow_subraster(width,height,drctn,isBig)     up/down arrow
   78:  *		rule_raster(rp,top,left,width,height,type)    draw rule in rp
   79:  *		line_raster(rp,row0,col0,row1,col1,thickness) draw line in rp
   80:  *		line_recurse(rp,row0,col0,row1,col1,thickness)   recurse line
   81:  *		circle_raster(rp,row0,col0,row1,col1,thickness,quads) ellipse
   82:  *		circle_recurse(rp,row0,col0,row1,col1,thickness,theta0,theta1)
   83:  *		bezier_raster(rp,r0,c0,r1,c1,rt,ct)   draw bezier recursively
   84:  *		border_raster(rp,ntop,nbot,isline,isfree)put border around rp
   85:  *		backspace_raster(rp,nback,pback,minspace,isfree)    neg space
   86:  *		--- raster (and chardef) output functions ---
   87:  *		type_raster(rp,fp)       emit ascii dump of rp on file ptr fp
   88:  *		type_bytemap(bp,grayscale,width,height,fp) dump bytemap on fp
   89:  *		xbitmap_raster(rp,fp)           emit mime xbitmap of rp on fp
   90:  *		type_pbmpgm(rp,ptype,file)     pbm or pgm image of rp to file
   91:  *		cstruct_chardef(cp,fp,col1)         emit C struct of cp on fp
   92:  *		cstruct_raster(rp,fp,col1)          emit C struct of rp on fp
   93:  *		hex_bitmap(rp,fp,col1,isstr)emit hex dump of rp->pixmap on fp
   94:  *		--- ancillary output functions ---
   95:  *		emit_string(fp,col1,string,comment) emit string and C comment
   96:  *		gftobitmap(rp)        convert .gf-like pixmap to bitmap image
   97:  *		====================== Font Functions =======================
   98:  *		--- font lookup functions ---
   99:  *		get_symdef(symbol)              return mathchardef for symbol
  100:  *		get_ligature(expr,family)  return symtable index for ligature
  101:  *		get_chardef(symdef,size)       return chardef for symdef,size
  102:  *		get_charsubraster(symdef,size)  wrap subraster around chardef
  103:  *		get_symsubraster(symbol,size)    returns subraster for symbol
  104:  *		--- ancillary font functions ---
  105:  *		get_baseline(gfdata)       determine baseline (in our coords)
  106:  *		get_delim(symbol,height,family) delim just larger than height
  107:  *		make_delim(symbol,height) construct delim exactly height size
  108:  *		================= Tokenize/Parse Functions ==================
  109:  *		texchar(expression,chartoken)  retruns next char or \sequence
  110:  *		texsubexpr(expr,subexpr,maxsubsz,left,right,isescape,isdelim)
  111:  *		texleft(expr,subexpr,maxsubsz,ldelim,rdelim)   \left...\right
  112:  *		texscripts(expression,subscript,superscript,which)get scripts
  113:  *		--- ancillary parse functions ---
  114:  *		isbrace(expression,braces,isescape)   check for leading brace
  115:  *		preamble(expression,size,subexpr)              parse preamble
  116:  *		mimeprep(expression) preprocessor converts \left( to \(, etc.
  117:  *		strchange(nfirst,from,to)   change nfirst chars of from to to
  118:  *		strreplace(string,from,to,nreplace)  change from to to in str
  119:  *		strwstr(string,substr,white,sublen)     find substr in string
  120:  *		strtexchr(string,texchr)                find texchr in string
  121:  *		findbraces(expression,command)    find opening { or closing }
  122:  *	PART3	=========== Rasterize an Expression (recursively) ===========
  123:  *		--- here's the primary entry point for all of mimeTeX ---
  124:  *		rasterize(expression,size)     parse and rasterize expression
  125:  *		--- explicitly called handlers that rasterize... ---
  126:  *		rastparen(subexpr,size,basesp)          parenthesized subexpr
  127:  *		rastlimits(expression,size,basesp)    dispatch super/sub call
  128:  *		rastscripts(expression,size,basesp) super/subscripted exprssn
  129:  *		rastdispmath(expression,size,sp)      scripts for displaymath
  130:  *		--- table-driven handlers that rasterize... ---
  131:  *		rastleft(expression,size,basesp,ildelim,arg2,arg3)\left\right
  132:  *		rastright(expression,size,basesp,ildelim,arg2,arg3) ...\right
  133:  *		rastmiddle(expression,size,basesp,arg1,arg2,arg3)     \middle
  134:  *		rastflags(expression,size,basesp,flag,value,arg3)    set flag
  135:  *		rastspace(expression,size,basesp,width,isfill,isheight)\,\:\;
  136:  *		rastnewline(expression,size,basesp,arg1,arg2,arg3)         \\
  137:  *		rastarrow(expression,size,basesp,width,height,drctn) \longarr
  138:  *		rastuparrow(expression,size,basesp,width,height,drctn)up/down
  139:  *		rastoverlay(expression,size,basesp,overlay,arg2,arg3)    \not
  140:  *		rastfrac(expression,size,basesp,isfrac,arg2,arg3) \frac \atop
  141:  *		rastackrel(expression,size,basesp,base,arg2,arg3)   \stackrel
  142:  *		rastmathfunc(expression,size,basesp,base,arg2,arg3) \lim,\etc
  143:  *		rastsqrt(expression,size,basesp,arg1,arg2,arg3)         \sqrt
  144:  *		rastaccent(expression,size,basesp,accent,isabove,isscript)
  145:  *		rastfont(expression,size,basesp,font,arg2,arg3) \cal{},\scr{}
  146:  *		rastbegin(expression,size,basesp,arg1,arg2,arg3)     \begin{}
  147:  *		rastarray(expression,size,basesp,arg1,arg2,arg3)       \array
  148:  *		rastpicture(expression,size,basesp,arg1,arg2,arg3)   \picture
  149:  *		rastline(expression,size,basesp,arg1,arg2,arg3)         \line
  150:  *		rastrule(expression,size,basesp,arg1,arg2,arg3)         \rule
  151:  *		rastcircle(expression,size,basesp,arg1,arg2,arg3)     \circle
  152:  *		rastbezier(expression,size,basesp,arg1,arg2,arg3)     \bezier
  153:  *		rastraise(expression,size,basesp,arg1,arg2,arg3)    \raisebox
  154:  *		rastrotate(expression,size,basesp,arg1,arg2,arg3)  \rotatebox
  155:  *		rastreflect(expression,size,basesp,arg1,arg2,arg3)\reflectbox
  156:  *		rastfbox(expression,size,basesp,arg1,arg2,arg3)         \fbox
  157:  *		rastinput(expression,size,basesp,arg1,arg2,arg3)       \input
  158:  *		rastcounter(expression,size,basesp,arg1,arg2,arg3)   \counter
  159:  *		rasttoday(expression,size,basesp,arg1,arg2,arg3)       \today
  160:  *		rastcalendar(expression,size,basesp,arg1,arg2,arg3) \calendar
  161:  *		rastnoop(expression,size,basesp,arg1,arg2,arg3) flush \escape
  162:  *		--- helper functions for handlers ---
  163:  *		rastopenfile(filename,mode)      opens filename[.tex] in mode
  164:  *		rasteditfilename(filename)       edit filename (for security)
  165:  *		rastreadfile(filename,islock,tag,value)   read <tag>...</tag>
  166:  *		rastwritefile(filename,tag,value,isstrict)write<tag>...</tag>
  167:  *		calendar(year,month,day)    formats one-month calendar string
  168:  *		timestamp(tzdelta,ifmt)              formats timestamp string
  169:  *		tzadjust(tzdelta,year,month,day,hour)        adjust date/time
  170:  *		daynumber(year,month,day)     #days since Monday, Jan 1, 1973
  171:  *		dbltoa(d,npts)                double to comma-separated ascii
  172:  *		=== Anti-alias completed raster (lowpass) or symbols (ss) ===
  173:  *		aalowpass(rp,bytemap,grayscale)     lowpass grayscale bytemap
  174:  *		aapnm(rp,bytemap,grayscale)       lowpass based on pnmalias.c
  175:  *		aapnmlookup(rp,bytemap,grayscale)  aapnm based on aagridnum()
  176:  *		aapatterns(rp,irow,icol,gridnum,patternum,grayscale) call 19,
  177:  *		aapattern1124(rp,irow,icol,gridnum,grayscale)antialias pattrn
  178:  *		aapattern19(rp,irow,icol,gridnum,grayscale) antialias pattern
  179:  *		aapattern20(rp,irow,icol,gridnum,grayscale) antialias pattern
  180:  *		aapattern39(rp,irow,icol,gridnum,grayscale) antialias pattern
  181:  *		aafollowline(rp,irow,icol,direction)       looks for a "turn"
  182:  *		aagridnum(rp,irow,icol)             calculates gridnum, 0-511
  183:  *		aapatternnum(gridnum)    looks up pattern#, 1-51, for gridnum
  184:  *		aalookup(gridnum)     table lookup for all possible 3x3 grids
  185:  *		aalowpasslookup(rp,bytemap,grayscale)   driver for aalookup()
  186:  *		aasupsamp(rp,aa,sf,grayscale)             or by supersampling
  187:  *		aacolormap(bytemap,nbytes,colors,colormap)make colors,colormap
  188:  *		aaweights(width,height)      builds "canonical" weight matrix
  189:  *		aawtpixel(image,ipixel,weights,rotate) weight image at ipixel
  190:  *		=== miscellaneous ===
  191:  *		mimetexsetmsg(newmsglevel,newmsgfp)    set msglevel and msgfp
  192:  *	PART1	========================== Driver ===========================
  193:  *		main(argc,argv) parses math expression and emits mime xbitmap
  194:  *		CreateGifFromEq(expression,gifFileName)  entry pt for win dll
  195:  *		isstrstr(string,snippets,iscase)  are any snippets in string?
  196:  *		ismonth(month)          is month current month ("jan"-"dec")?
  197:  *		unescape_url(url,isescape), x2c(what)   xlate %xx url-encoded
  198:  *		logger(fp,msglevel,logvars)        logs environment variables
  199:  *		emitcache(cachefile,maxage,valign,isbuffer)    emit cachefile
  200:  *		readcachefile(cachefile,buffer)    read cachefile into buffer
  201:  *		md5str(instr)                      md5 hash library functions
  202:  *		GetPixel(x,y)           callback function for gifsave library
  203:  *
  204:  * Source:	mimetex.c  (needs mimetex.h and texfonts.h to compile,
  205:  *		and also needs gifsave.c when compiled with -DAA or -DGIF)
  206:  *
  207:  * --------------------------------------------------------------------------
  208:  * Notes      o	See bottom of file for main() driver (and "friends"),
  209:  *		and compile as
  210:  *		   cc -DAA mimetex.c gifsave.c -lm -o mimetex.cgi
  211:  *		to produce an executable that emits gif images with
  212:  *		anti-aliasing (see Notes below).  You may also compile
  213:  *		   cc -DGIF mimetex.c gifsave.c -lm -o mimetex.cgi
  214:  *		to produce an executable that emits gif images without
  215:  *		anti-aliasing.  Alternatively, compile mimeTeX as
  216:  *		   cc -DXBITMAP mimetex.c -lm -o mimetex.cgi
  217:  *		to produce an executable that just emits mime xbitmaps.
  218:  *		In either case you'll need mimetex.h and texfonts.h,
  219:  *		and with -DAA or -DGIF you'll also need gifsave.c
  220:  *	      o	For gif images, the gifsave.c library by Sverre H. Huseby
  221:  *		<http://shh.thathost.com> slightly modified by me to allow
  222:  *		(a)sending output to stdout or returning it in memory,
  223:  *		and (b)specifying a transparent background color index,
  224:  *		is included with mimeTeX, and it's documented in
  225:  *		mimetex.html#gifsave .
  226:  *	      o	Optional compile-line -D defined symbols are documented
  227:  *		in mimetex.html#options .  They include (additional -D
  228:  *		switches are discussed in mimetex.html#options)...
  229:  *		-DAA
  230:  *		    Turns on gif anti-aliasing with default values
  231:  *		    (CENTERWT=32, ADJACENTWT=3, CORNERWT=1)
  232:  *		    for the following anti-aliasing parameters...
  233:  *		-DCENTERWT=n
  234:  *		-DADJACENTWT=j
  235:  *		-DCORNERWT=k
  236:  *		    MimeTeX currently provides a lowpass filtering
  237:  *		    algorithm for anti-aliasing, which is applied to the
  238:  *		    existing set of bitmap fonts.  This lowpass filter
  239:  *		    applies default weights
  240:  *				1   2   1
  241:  *				2   8   2
  242:  *				1   2   1
  243:  *		    to neighboring pixels. The defaults weights are
  244:  *		    CENTERWT=8, ADJACENTWT=2 and CORNERWT=1,
  245:  *		    which you can adjust to control anti-aliasing.
  246:  *		    Lower CENTERWT values will blur/spread out lines
  247:  *		    while higher values will tend to sharpen lines.
  248:  *		    Experimentation is recommended to determine
  249:  *		    what value works best for you.
  250:  *		-DCACHEPATH=\"path/\"
  251:  *		    This option saves each rendered image to a file
  252:  *		    in directory  path/  which mimeTeX reads rather than
  253:  *		    re-rendering the same image every time it's given
  254:  *		    the same LaTeX expression.  Sometimes mimeTeX disables
  255:  *		    caching, e.g., expressions containing \input{ } are
  256:  *		    re-rendered since the contents of the inputted file
  257:  *		    may have changed.  If compiled without -DCACHEPATH
  258:  *		    mimeTeX always re-renders expressions.  This usually
  259:  *		    isn't too cpu intensive, but if you have unusually
  260:  *		    high hit rates then image caching may be helpful.
  261:  *			The  path/  is relative to mimetex.cgi, and must
  262:  *		    be writable by it.  Files created under  path/  are
  263:  *		    named filename.gif, where filename is the 32-character
  264:  *		    MD5 hash of the LaTeX expression.
  265:  *		-DDISPLAYSIZE=n
  266:  *		    By default, operator limits like \int_a^b are rendered
  267:  *		    \textstyle at font sizes \normalsize and smaller,
  268:  *		    and rendered \displaystyle at font sizes \large and
  269:  *		    larger.  This default corresponds to -DDISPLAYSIZE=3,
  270:  *		    which you can adjust; e.g., -DDISPLAYSIZE=0 always
  271:  *		    defaults to \displaystyle, and 99 (or any large number)
  272:  *		    always defaults to \textstyle.  Note that explicit
  273:  *		    \textstyle, \displaystyle, \limits or \nolimits
  274:  *		    directives in an expression always override
  275:  *		    the DISPLAYSIZE default.
  276:  *		-NORMALSIZE=n
  277:  *		    MimeTeX currently has six font sizes numbered 0-5,
  278:  *		    and always starts in NORMALSIZE whose default value
  279:  *		    is 2.  Specify -DNORMALSIZE=3 on the compile line if
  280:  *		    you prefer mimeTeX to start in default size 3, etc.
  281:  *		-DREFERER=\"domain\"   -or-
  282:  *		-DREFERER=\"domain1,domain2,etc\"
  283:  *		    Blocks mimeTeX requests from unauthorized domains that
  284:  *		    may be using your server's mimetex.cgi without permission.
  285:  *		    If REFERER is defined, mimeTeX checks for the environment
  286:  *		    variable HTTP_REFERER and, if it exists, performs a
  287:  *		    case-insensitive test to make sure it contains 'domain'
  288:  *		    as a substring.  If given several 'domain's (second form)
  289:  *		    then HTTP_REFERER must contain either 'domain1' or
  290:  *		    'domain2', etc, as a (case-insensitive) substring.
  291:  *		    If HTTP_REFERER fails to contain a substring matching
  292:  *		    any of these domain(s), mimeTeX emits an error message
  293:  *		    image corresponding to the expression specified by
  294:  *		    the  invalid_referer_msg  string defined in main().
  295:  *		    Note: if HTTP_REFERER is not an environment variable,
  296:  *		    mimeTeX correctly generates the requested expression
  297:  *		    (i.e., no referer error).
  298:  *		-DWARNINGS=n  -or-
  299:  *		-DNOWARNINGS
  300:  *		    If an expression submitted to mimeTeX contains an
  301:  *		    unrecognzied escape sequence, e.g., "y=x+\abc+1", then
  302:  *		    mimeTeX generates a gif image containing an embedded
  303:  *		    warning in the form "y=x+[\abc?]+1".  If you want these
  304:  *		    warnings suppressed, -DWARNINGS=0 or -DNOWARNINGS tells
  305:  *		    mimeTeX to ignore unrecognized symbols, and the rendered
  306:  *		    image is "y=x++1" instead.
  307:  *		-DWHITE
  308:  *		    MimeTeX usually renders black symbols on a white
  309:  *		    background.  This option renders white symbols on
  310:  *		    a black background instead.
  311:  *	      o	See individual function entry points for further comments.
  312:  *	      o	The font information in texfonts.h was produced by multiple
  313:  *		runs of gfuntype, one run per struct (i.e., one run per font
  314:  *		family at a particular size).  See gfuntype.c, and also
  315:  *		mimetex.html#fonts, for details.
  316:  *	      o	mimetex.c contains library functions implementing a raster
  317:  *		datatype, functions to manipulate rasterized .mf fonts
  318:  *		(see gfuntype.c which rasterizes .mf fonts), functions
  319:  *		to parse LaTeX expressions, etc.  A complete list of
  320:  *		mimetex.c functions is above.  See their individual entry
  321:  *		points below for further comments.
  322:  *		   All these functions eventually belong in several
  323:  *		different modules, possibly along the lines suggested
  324:  *		by the divisions above.  But until the best decomposition
  325:  *		becomes clear, it seems better to keep mimetex.c
  326:  *		neatly together, avoiding a bad decomposition that
  327:  *		becomes permanent by default.
  328:  *	      o	The "main" reusable function is rasterize(),
  329:  *		which takes a string like "f(x)=\int_{-\infty}^xe^{-t^2}dt"
  330:  *		and returns a (sub)raster representing it as a bit or bytemap.
  331:  *		Your application can do anything it likes with this pixel map.
  332:  *		MimeTeX just outputs it, either as a mime xbitmap or as a gif.
  333:  * --------------------------------------------------------------------------
  334:  * Revision History:
  335:  * 09/18/02	J.Forkosh	Installation.
  336:  * 12/11/02	J.Forkosh	Version 1.00 released.
  337:  * 07/04/03	J.Forkosh	Version 1.01 released.
  338:  * 10/17/03	J.Forkosh	Version 1.20 released.
  339:  * 12/21/03	J.Forkosh	Version 1.30 released.
  340:  * 02/01/04	J.Forkosh	Version 1.40 released.
  341:  * 10/02/04	J.Forkosh	Version 1.50 released.
  342:  * 11/30/04	J.Forkosh	Version 1.60 released.
  343:  * 10/11/05	J.Forkosh	Version 1.64 released.
  344:  * 11/30/06	J.Forkosh	Version 1.65 released.
  345:  * 09/06/08	J.Forkosh	Version 1.70 released.
  346:  *
  347:  ****************************************************************************/
  348: 
  349: /* -------------------------------------------------------------------------
  350: header files and macros
  351: -------------------------------------------------------------------------- */
  352: /* --- standard headers --- */
  353: #include <stdio.h>
  354: #include <stdlib.h>
  355: /*#include <unistd.h>*/
  356: #include <string.h>
  357: #include <ctype.h>
  358: #include <math.h>
  359: #include <time.h>
  360: 
  361: /* --- windows-specific header info --- */
  362: #ifndef WINDOWS			/* -DWINDOWS not supplied by user */
  363:   #if defined(_WINDOWS) || defined(_WIN32) || defined(WIN32) \
  364:   ||  defined(DJGPP)		/* try to recognize windows compilers */ \
  365:   ||  defined(_USRDLL)		/* must be WINDOWS if compiling for DLL */
  366:     #define WINDOWS		/* signal windows */
  367:   #endif
  368: #endif
  369: #ifdef WINDOWS			/* Windows opens stdout in char mode, and */
  370:   #include <fcntl.h>		/* precedes every 0x0A with spurious 0x0D.*/
  371:   #include <io.h>		/* So emitcache() issues a Win _setmode() */
  372: 				/* call to put stdout in binary mode. */
  373:   #if defined(_O_BINARY) && !defined(O_BINARY)  /* only have _O_BINARY */
  374:     #define O_BINARY _O_BINARY	/* make O_BINARY available, etc... */
  375:     #define setmode  _setmode
  376:     #define fileno   _fileno
  377:   #endif
  378:   #if defined(_O_BINARY) || defined(O_BINARY)  /* setmode() now available */
  379:     #define HAVE_SETMODE	/* so we'll use setmode() */
  380:   #endif
  381:   #if defined(_MSC_VER) && defined(_DEBUG) /* MS VC++ in debug mode */
  382:     /* to show source file and line numbers where memory leaks occur... */
  383:     #define _CRTDBG_MAP_ALLOC	/* ...include this debug macro */
  384:     #include <crtdbg.h>		/* and this debug library */
  385:   #endif
  386:   #define ISWINDOWS 1
  387: #else
  388:   #define ISWINDOWS 0
  389: #endif
  390: 
  391: /* --- check for supersampling or low-pass anti-aliasing --- */
  392: #ifdef SS
  393:   #define ISSUPERSAMPLING 1
  394:   #ifndef AAALGORITHM
  395:     #define AAALGORITHM 1		/* default supersampling algorithm */
  396:   #endif
  397:   #ifndef AA				/* anti-aliasing not explicitly set */
  398:     #define AA				/* so define it ourselves */
  399:   #endif
  400:   #ifndef SSFONTS			/* need supersampling fonts */
  401:     #define SSFONTS
  402:   #endif
  403: #else
  404:   #define ISSUPERSAMPLING 0
  405:   #ifndef AAALGORITHM
  406:     #define AAALGORITHM 3 /*2*/		/* default lowpass algorithm */
  407:   #endif
  408: #endif
  409: #ifndef MAXFOLLOW
  410:   #define MAXFOLLOW 8			/* aafollowline() maxturn default */
  411: #endif
  412: 
  413: /* --- set aa (and default gif) if any anti-aliasing options specified --- */
  414: #if defined(AA) || defined(GIF) || defined(PNG) \
  415: ||  defined(CENTERWT) || defined(ADJACENTWT) || defined(CORNERWT) \
  416: ||  defined(MINADJACENT) || defined(MAXADJACENT)
  417:   #if !defined(GIF) && !defined(AA)	/* aa not explicitly specified */
  418:     #define AA				/* so define it ourselves */
  419:   #endif
  420:   #if !defined(GIF) && !defined(PNG)	/* neither gif nor png specified */
  421:     #define GIF				/* so default to gif */
  422:   #endif
  423: #endif
  424: /* --- resolve output option inconsistencies --- */
  425: #if defined(XBITMAP)			/* xbitmap supercedes gif and png */
  426:   #ifdef AA
  427:     #undef AA
  428:   #endif
  429:   #ifdef GIF
  430:     #undef GIF
  431:   #endif
  432:   #ifdef PNG
  433:     #undef PNG
  434:   #endif
  435: #endif
  436: 
  437: /* --- decide whether to compile main() --- */
  438: #if defined(XBITMAP) || defined(GIF) || defined(PNG)
  439:   #define DRIVER			/* driver will be compiled */
  440:   /* --- check whether or not to perform http_referer check --- */
  441:   #ifndef REFERER			/* all http_referer's allowed */
  442:     #define REFERER NULL
  443:   #endif
  444:   /* --- max query_string length if no http_referer supplied --- */
  445:   #ifndef NOREFMAXLEN
  446:     #define NOREFMAXLEN 9999		/* default to any length query */
  447:   #endif
  448: #else
  449:   #ifndef TEXFONTS
  450:     #define NOTEXFONTS			/* texfonts not required */
  451:   #endif
  452: #endif
  453: 
  454: /* --- application headers --- */
  455: #if !defined(NOTEXFONTS) && !defined(TEXFONTS)
  456:   #define TEXFONTS			/* to include texfonts.h */
  457: #endif
  458: #include "mimetex.h"
  459: /* --- info needed when gif image returned in memory buffer --- */
  460: #ifdef GIF				/* compiling along with gifsave.c */
  461:   extern int gifSize;
  462:   extern int maxgifSize;
  463: #else					/* or just set dummy values */
  464:   static int gifSize=0, maxgifSize=0;
  465: #endif
  466: /* --- gamma correction --- */
  467: #ifndef GAMMA
  468:   #define GAMMA 1.25 /*1.75*/ /*2.2*/
  469: #endif
  470: #ifndef REVERSEGAMMA
  471:   #define REVERSEGAMMA 0.5		/* for \reverse white-on-black */
  472: #endif
  473: /* --- opaque background (default to transparent) --- */
  474: #ifndef OPAQUE
  475:   #define ISTRANSPARENT 1
  476: #else
  477:   #define ISTRANSPARENT 0
  478: #endif
  479: /* --- internal buffer sizes --- */
  480: #if !defined(MAXEXPRSZ)
  481:   #define MAXEXPRSZ (32768-1)		/*max #bytes in input tex expression*/
  482: #endif
  483: #if !defined(MAXSUBXSZ)
  484:   #define MAXSUBXSZ (((MAXEXPRSZ+1)/2)-1)/*max #bytes in input subexpression*/
  485: #endif
  486: #if !defined(MAXTOKNSZ)
  487:   #define MAXTOKNSZ (((MAXSUBXSZ+1)/4)-1) /* max #bytes in input token */
  488: #endif
  489: #if !defined(MAXFILESZ)
  490:   #define MAXFILESZ (65536-1)		/*max #bytes in input (output) file*/
  491: #endif
  492: #if !defined(MAXLINESZ)
  493:   #define MAXLINESZ (4096-1)		/* max #chars in line from file */
  494: #endif
  495: #if !defined(MAXGIFSZ)
  496:   #define MAXGIFSZ 131072		/* max #bytes in output GIF image */
  497: #endif
  498: 
  499: /* -------------------------------------------------------------------------
  500: adjustable default values
  501: -------------------------------------------------------------------------- */
  502: /* --- anti-aliasing parameters --- */
  503: #ifndef	CENTERWT
  504:   /*#define CENTERWT 32*/		/* anti-aliasing centerwt default */
  505:   /*#define CENTERWT 10*/		/* anti-aliasing centerwt default */
  506:   #define CENTERWT 8			/* anti-aliasing centerwt default */
  507: #endif
  508: #ifndef	ADJACENTWT
  509:   /*#define ADJACENTWT 3*/		/* anti-aliasing adjacentwt default*/
  510:   #define ADJACENTWT 2			/* anti-aliasing adjacentwt default*/
  511: #endif
  512: #ifndef	CORNERWT
  513:   #define CORNERWT 1			/* anti-aliasing cornerwt default*/
  514: #endif
  515: #ifndef	MINADJACENT
  516:   #define MINADJACENT 6			/*anti-aliasing minadjacent default*/
  517: #endif
  518: #ifndef	MAXADJACENT
  519:   #define MAXADJACENT 8			/*anti-aliasing maxadjacent default*/
  520: #endif
  521: /* --- variables for anti-aliasing parameters --- */
  522: GLOBAL(int,centerwt,CENTERWT);		/*lowpass matrix center pixel wt */
  523: GLOBAL(int,adjacentwt,ADJACENTWT);	/*lowpass matrix adjacent pixel wt*/
  524: GLOBAL(int,cornerwt,CORNERWT);		/*lowpass matrix corner pixel wt */
  525: GLOBAL(int,minadjacent,MINADJACENT);	/* darken if>=adjacent pts black*/
  526: GLOBAL(int,maxadjacent,MAXADJACENT);	/* darken if<=adjacent pts black */
  527: GLOBAL(int,weightnum,1);		/* font wt, */
  528: GLOBAL(int,maxaaparams,4);		/* #entries in table */
  529: /* --- anti-aliasing parameter values by font weight --- */
  530: #define	aaparameters struct aaparameters_struct /* typedef */
  531: aaparameters
  532:   { int	centerwt;			/* lowpass matrix center   pixel wt*/
  533:     int	adjacentwt;			/* lowpass matrix adjacent pixel wt*/
  534:     int cornerwt;			/* lowpass matrix corner   pixel wt*/
  535:     int	minadjacent;			/* darken if >= adjacent pts black */
  536:     int	maxadjacent;			/* darken if <= adjacent pts black */
  537:     int fgalias,fgonly,bgalias,bgonly; } ; /* aapnm() params */
  538: STATIC aaparameters aaparams[]		/* set params by weight */
  539:   #ifdef INITVALS
  540:   =
  541:   { /* ----------------------------------------------------
  542:     centerwt adj corner minadj max  fgalias,only,bgalias,only
  543:     ------------------------------------------------------- */
  544: 	{ 64,  1,  1,    6,  8,     1,0,0,0 },	/* 0 = light */
  545: 	{ CENTERWT,ADJACENTWT,CORNERWT,MINADJACENT,MAXADJACENT,1,0,0,0 },
  546: 	{ 8,   1,  1,    5,  8,     1,0,0,0 },	/* 2 = semibold */
  547: 	{ 8,   2,  1,    4,  9,     1,0,0,0 }	/* 3 = bold */
  548:   } /* --- end-of-aaparams[] --- */
  549:   #endif
  550:   ;
  551: /* --- anti-aliasing diagnostics (to help improve algorithm) --- */
  552: STATIC int patternnumcount0[99], patternnumcount1[99], /*aalookup() counts*/
  553: 	ispatternnumcount = 1;		/* true to accumulate counts */
  554: 
  555: /* -------------------------------------------------------------------------
  556: other variables
  557: -------------------------------------------------------------------------- */
  558: /* --- black on white background (default), or white on black --- */
  559: #ifdef WHITE
  560:   #define ISBLACKONWHITE 0		/* white on black background */
  561: #else
  562:   #define ISBLACKONWHITE 1		/* black on white background */
  563: #endif
  564: /* --- colors --- */
  565: #define	BGRED   (ISBLACKONWHITE?255:0)
  566: #define	BGGREEN (ISBLACKONWHITE?255:0)
  567: #define	BGBLUE  (ISBLACKONWHITE?255:0)
  568: #ifndef	FGRED
  569:   #define FGRED   (ISBLACKONWHITE?0:255)
  570: #endif
  571: #ifndef	FGGREEN
  572:   #define FGGREEN (ISBLACKONWHITE?0:255)
  573: #endif
  574: #ifndef	FGBLUE
  575:   #define FGBLUE  (ISBLACKONWHITE?0:255)
  576: #endif
  577: /* --- "smash" margin (0 means no smashing) --- */
  578: #ifndef SMASHMARGIN
  579:   #ifdef NOSMASH
  580:     #define SMASHMARGIN 0
  581:   #else
  582:     #define SMASHMARGIN 3
  583:   #endif
  584: #endif
  585: #ifndef SMASHCHECK
  586:   #define SMASHCHECK 0
  587: #endif
  588: /* --- textwidth --- */
  589: #ifndef TEXTWIDTH
  590:   #define TEXTWIDTH (400)
  591: #endif
  592: /* --- font "combinations" --- */
  593: #define	CMSYEX (109)			/*select CMSY10, CMEX10 or STMARY10*/
  594: /* --- prefix prepended to all expressions --- */
  595: #ifndef	PREFIX
  596:   #define PREFIX "\000"			/* default no prepended prefix */
  597: #endif
  598: /* --- skip argv[]'s preceding ARGSIGNAL when parsing command-line args --- */
  599: #ifdef NOARGSIGNAL
  600:   #define ARGSIGNAL NULL
  601: #endif
  602: #ifndef	ARGSIGNAL
  603:   #define ARGSIGNAL "++"
  604: #endif
  605: /* --- security and logging (inhibit message logging, etc) --- */
  606: #ifndef	SECURITY
  607:   #define SECURITY 999			/* default highest security level */
  608: #endif
  609: #ifndef	LOGFILE
  610:   #define LOGFILE "mimetex.log"		/* default log file */
  611: #endif
  612: #ifndef	CACHELOG
  613:   #define CACHELOG "mimetex.log"	/* default caching log file */
  614: #endif
  615: #if !defined(NODUMPENVP) && !defined(DUMPENVP)
  616:   #define DUMPENVP			/* assume char *envp[] available */
  617: #endif
  618: /* --- image caching (cache images if given -DCACHEPATH=\"path\") --- */
  619: #ifndef CACHEPATH
  620:   #define ISCACHING 0			/* no caching */
  621:   #define CACHEPATH "\000"		/* same directory as mimetex.cgi */
  622: #else
  623:   #define ISCACHING 1			/* caching if -DCACHEPATH="path" */
  624: #endif
  625: /* --- \input paths (prepend prefix if given -DPATHPREFIX=\"prefix\") --- */
  626: #ifndef PATHPREFIX
  627:   #define PATHPREFIX "\000"		/* paths relative mimetex.cgi */
  628: #endif
  629: /* --- time zone delta t (in hours) --- */
  630: #ifndef TZDELTA
  631:   #define TZDELTA 0
  632: #endif
  633: /* --- treat +'s in query string as blanks? --- */
  634: #ifdef PLUSBLANK			/* + always interpreted as blank */
  635:   #define ISPLUSBLANK 1
  636: #else
  637:   #ifdef PLUSNOTBLANK			/* + never interpreted as blank */
  638:     #define ISPLUSBLANK 0
  639:   #else					/* program tries to determine */
  640:     #define ISPLUSBLANK (-1)
  641:   #endif
  642: #endif
  643: 
  644: /* -------------------------------------------------------------------------
  645: debugging and logging / error reporting
  646: -------------------------------------------------------------------------- */
  647: /* --- debugging and error reporting --- */
  648: #ifndef	MSGLEVEL
  649:   #define MSGLEVEL 1
  650: #endif
  651: #define	DBGLEVEL 9			/* debugging if msglevel>=DBGLEVEL */
  652: #define	LOGLEVEL 3			/* logging if msglevel>=LOGLEVEL */
  653: #ifndef FORMLEVEL
  654:   #define FORMLEVEL LOGLEVEL		/*msglevel if called from html form*/
  655: #endif
  656: GLOBAL(int,seclevel,SECURITY);		/* security level */
  657: GLOBAL(int,msglevel,MSGLEVEL);		/* message level for verbose/debug */
  658: STATIC	FILE *msgfp;			/* output in command-line mode */
  659: /* --- embed warnings in rendered expressions, [\xxx?] if \xxx unknown --- */
  660: #ifdef WARNINGS
  661:   #define WARNINGLEVEL WARNINGS
  662: #else
  663:   #ifdef NOWARNINGS
  664:     #define WARNINGLEVEL 0
  665:   #else
  666:     #define WARNINGLEVEL 1
  667:   #endif
  668: #endif
  669: GLOBAL(int,warninglevel,WARNINGLEVEL);	/* warning level */
  670: 
  671: /* -------------------------------------------------------------------------
  672: control flags and values
  673: -------------------------------------------------------------------------- */
  674: GLOBAL(int,recurlevel,0);		/* inc/decremented in rasterize() */
  675: GLOBAL(int,scriptlevel,0);		/* inc/decremented in rastlimits() */
  676: GLOBAL(int,isstring,0);			/*pixmap is ascii string, not raster*/
  677: GLOBAL(int,isligature,0);		/* true if ligature found */
  678: GLOBAL(char,*subexprptr,(char *)NULL);	/* ptr within expression to subexpr*/
  679: /*SHARED(int,imageformat,1);*/		/* image is 1=bitmap, 2=.gf-like */
  680: GLOBAL(int,isdisplaystyle,1);		/* displaystyle mode (forced if 2) */
  681: GLOBAL(int,ispreambledollars,0);	/* displaystyle mode set by $$...$$ */
  682: GLOBAL(int,fontnum,0);			/* cal=1,scr=2,rm=3,it=4,bb=5,bf=6 */
  683: GLOBAL(int,fontsize,NORMALSIZE);	/* current size */
  684: GLOBAL(int,displaysize,DISPLAYSIZE);	/* use \displaystyle when fontsize>=*/
  685: GLOBAL(int,shrinkfactor,3);		/* shrinkfactors[fontsize] */
  686: GLOBAL(double,unitlength,1.0);		/* #pixels per unit (may be <1.0) */
  687: /*GLOBAL(int,textwidth,TEXTWIDTH);*/	/* #pixels across line */
  688: GLOBAL(int,isnocatspace,0);		/* >0 to not add space in rastcat()*/
  689: GLOBAL(int,smashmargin,SMASHMARGIN);	/* minimum "smash" margin */
  690: GLOBAL(int,mathsmashmargin,SMASHMARGIN); /* needed for \text{if $n-m$ even}*/
  691: GLOBAL(int,issmashdelta,1);		/* true if smashmargin is a delta */
  692: GLOBAL(int,isexplicitsmash,0);		/* true if \smash explicitly given */
  693: GLOBAL(int,smashcheck,SMASHCHECK);	/* check if terms safe to smash */
  694: GLOBAL(int,isscripted,0);		/* is (lefthand) term text-scripted*/
  695: GLOBAL(int,isdelimscript,0);		/* is \right delim text-scripted */
  696: GLOBAL(int,issmashokay,0);		/*is leading char okay for smashing*/
  697: #define	BLANKSIGNAL (-991234)		/*rastsmash signal right-hand blank*/
  698: GLOBAL(int,blanksignal,BLANKSIGNAL);	/*rastsmash signal right-hand blank*/
  699: GLOBAL(int,blanksymspace,0);		/* extra (or too much) space wanted*/
  700: GLOBAL(int,istransparent,ISTRANSPARENT);/* true sets background transparent*/
  701: GLOBAL(int,fgred,FGRED);
  702:   GLOBAL(int,fggreen,FGGREEN);
  703:   GLOBAL(int,fgblue,FGBLUE);		/* fg r,g,b */
  704: GLOBAL(int,bgred,BGRED);
  705:   GLOBAL(int,bggreen,BGGREEN);
  706:   GLOBAL(int,bgblue,BGBLUE);		/* bg r,g,b */
  707: GLOBAL(double,gammacorrection,GAMMA);	/* gamma correction */
  708: GLOBAL(int,isplusblank,ISPLUSBLANK);	/*interpret +'s in query as blanks?*/
  709: GLOBAL(int,isblackonwhite,ISBLACKONWHITE); /*1=black on white,0=reverse*/
  710: GLOBAL(char,exprprefix[256],PREFIX);	/* prefix prepended to expressions */
  711: GLOBAL(int,aaalgorithm,AAALGORITHM);	/* for lp, 1=aalowpass, 2 =aapnm */
  712: GLOBAL(int,maxfollow,MAXFOLLOW);	/* aafollowline() maxturn parameter*/
  713: GLOBAL(int,fgalias,1);
  714:   GLOBAL(int,fgonly,0);
  715:   GLOBAL(int,bgalias,0);
  716:   GLOBAL(int,bgonly,0);			/* aapnm() params */
  717: GLOBAL(int,issupersampling,ISSUPERSAMPLING); /*1=supersampling 0=lowpass*/
  718: GLOBAL(int,isss,ISSUPERSAMPLING);	/* supersampling flag for main() */
  719: GLOBAL(int,*workingparam,(int *)NULL);	/* working parameter */
  720: GLOBAL(subraster,*workingbox,(subraster *)NULL); /*working subraster box*/
  721: GLOBAL(int,isreplaceleft,0);		/* true to replace leftexpression */
  722: GLOBAL(subraster,*leftexpression,(subraster *)NULL); /*rasterized so far*/
  723: GLOBAL(mathchardef,*leftsymdef,NULL);	/* mathchardef for preceding symbol*/
  724: GLOBAL(int,fraccenterline,NOVALUE);	/* baseline for punct. after \frac */
  725: /*GLOBAL(int,currentcharclass,NOVALUE);*/ /*primarily to check for PUNCTION*/
  726: GLOBAL(int,iscaching,ISCACHING);	/* true if caching images */
  727: GLOBAL(char,cachepath[256],CACHEPATH);	/* relative path to cached files */
  728: GLOBAL(int,isemitcontenttype,1);	/* true to emit mime content-type */
  729: int	iscachecontenttype = 0;		/* true to cache mime content-type */
  730: char	contenttype[2048] = "\000";	/* content-type:, etc buffer */
  731: GLOBAL(char,pathprefix[256],PATHPREFIX); /*prefix for \input,\counter paths*/
  732: /*GLOBAL(int,iswindows,ISWINDOWS);*/	/* true if compiled for ms windows */
  733: 
  734: /* -------------------------------------------------------------------------
  735: miscellaneous macros
  736: -------------------------------------------------------------------------- */
  737: #define	max2(x,y)  ((x)>(y)? (x):(y))	/* larger of 2 arguments */
  738: #define	min2(x,y)  ((x)<(y)? (x):(y))	/* smaller of 2 arguments */
  739: #define	max3(x,y,z) max2(max2(x,y),(z))	/* largest of 3 arguments */
  740: #define	min3(x,y,z) min2(min2(x,y),(z))	/* smallest of 3 arguments */
  741: #define absval(x)  ((x)>=0?(x):(-(x)))	/* absolute value */
  742: #define	iround(x)  ((int)((x)>=0?(x)+0.5:(x)-0.5)) /* round double to int */
  743: #define	dmod(x,y)  ((x)-((y)*((double)((int)((x)/(y)))))) /*x%y for doubles*/
  744: #define compress(s,c) if((s)!=NULL)	/* remove embedded c's from s */ \
  745: 	{ char *p; while((p=strchr((s),(c)))!=NULL) strcpy(p,p+1); } else
  746: #define	slower(s)  if ((s)!=NULL)	/* lowercase all chars in s */ \
  747: 	{ char *p=(s); while(*p!='\000'){*p=tolower(*p); p++;} } else
  748: /*subraster *subrastcpy();*/		/* need global module declaration */
  749: /*#define spnosmash(sp) if (sp->type==CHARASTER) sp=subrastcpy(sp); \*/
  750: /*	sp->type=blanksignal*/
  751: 
  752: /* ---
  753:  * PART2
  754:  * ------ */
  755: #if !defined(PARTS) || defined(PART2)
  756: /* ==========================================================================
  757:  * Function:	new_raster ( width, height, pixsz )
  758:  * Purpose:	Allocation and constructor for raster.
  759:  *		mallocs and initializes memory for width*height pixels,
  760:  *		and returns raster struct ptr to caller.
  761:  * --------------------------------------------------------------------------
  762:  * Arguments:	width (I)	int containing width, in bits,
  763:  *				of raster pixmap to be allocated
  764:  *		height (I)	int containing height, in bits/scans,
  765:  *				of raster pixmap to be allocated
  766:  *		pixsz (I)	int containing #bits per pixel, 1 or 8
  767:  * --------------------------------------------------------------------------
  768:  * Returns:	( raster * )	ptr to allocated and initialized
  769:  *				raster struct, or NULL for any error.
  770:  * --------------------------------------------------------------------------
  771:  * Notes:
  772:  * ======================================================================= */
  773: /* --- entry point --- */
  774: raster	*new_raster ( int width, int height, int pixsz )
  775: {
  776: /* -------------------------------------------------------------------------
  777: Allocations and Declarations
  778: -------------------------------------------------------------------------- */
  779: raster	*rp = (raster *)NULL;		/* raster ptr returned to caller */
  780: pixbyte	*pixmap = NULL;			/* raster pixel map to be malloced */
  781: int	nbytes = pixsz*bitmapsz(width,height); /* #bytes needed for pixmap */
  782: int	filler = (isstring?' ':0);	/* pixmap filler */
  783: int	delete_raster();		/* in case pixmap malloc() fails */
  784: int	npadding = (0&&issupersampling?8+256:0); /* padding bytes */
  785: /* -------------------------------------------------------------------------
  786: allocate and initialize raster struct and embedded bitmap
  787: -------------------------------------------------------------------------- */
  788: if ( msgfp!=NULL && msglevel>=9999 )
  789:   { fprintf(msgfp,"new_raster(%d,%d,%d)> entry point\n",
  790:     width,height,pixsz); fflush(msgfp); }
  791: /* --- allocate and initialize raster struct --- */
  792: rp = (raster *)malloc(sizeof(raster));	/* malloc raster struct */
  793: if ( msgfp!=NULL && msglevel>=9999 )
  794:   { fprintf(msgfp,"new_raster> rp=malloc(%d) returned (%s)\n",
  795:     sizeof(raster),(rp==NULL?"null ptr":"success")); fflush(msgfp); }
  796: if ( rp == (raster *)NULL )		/* malloc failed */
  797:   goto end_of_job;			/* return error to caller */
  798: rp->width = width;			/* store width in raster struct */
  799: rp->height = height;			/* and store height */
  800: rp->format = 1;				/* initialize as bitmap format */
  801: rp->pixsz = pixsz;			/* store #bits per pixel */
  802: rp->pixmap = (pixbyte *)NULL;		/* init bitmap as null ptr */
  803: /* --- allocate and initialize bitmap array --- */
  804: if ( msgfp!=NULL && msglevel>=9999 )
  805:   { fprintf(msgfp,"new_raster> calling pixmap=malloc(%d)\n",
  806:     nbytes); fflush(msgfp); }
  807: if ( nbytes>0 && nbytes<=pixsz*maxraster )  /* fail if width*height too big*/
  808:   pixmap = (pixbyte *)malloc(nbytes+npadding); /*bytes for width*height bits*/
  809: if ( msgfp!=NULL && msglevel>=9999 )
  810:   { fprintf(msgfp,"new_raster> pixmap=malloc(%d) returned (%s)\n",
  811:     nbytes,(pixmap==NULL?"null ptr":"success")); fflush(msgfp); }
  812: if ( pixmap == (pixbyte *)NULL )	/* malloc failed */
  813:   { delete_raster(rp);			/* so free everything */
  814:     rp = (raster *)NULL;		/* reset pointer */
  815:     goto end_of_job; }			/* and return error to caller */
  816: memset((void *)pixmap,filler,nbytes);	/* init bytes to binary 0's or ' 's*/
  817: *pixmap = (pixbyte)0;			/* and first byte alwasy 0 */
  818: rp->pixmap = pixmap;			/* store ptr to malloced memory */
  819: /* -------------------------------------------------------------------------
  820: Back to caller with address of raster struct, or NULL ptr for any error.
  821: -------------------------------------------------------------------------- */
  822: end_of_job:
  823:   if ( msgfp!=NULL && msglevel>=9999 )
  824:     { fprintf(msgfp,"new_raster(%d,%d,%d)> returning (%s)\n",
  825:       width,height,pixsz,(rp==NULL?"null ptr":"success")); fflush(msgfp); }
  826:   return ( rp );			/* back to caller with raster */
  827: } /* --- end-of-function new_raster() --- */
  828: 
  829: 
  830: /* ==========================================================================
  831:  * Function:	new_subraster ( width, height, pixsz )
  832:  * Purpose:	Allocate a new subraster along with
  833:  *		an embedded raster of width x height.
  834:  * --------------------------------------------------------------------------
  835:  * Arguments:	width (I)	int containing width of embedded raster
  836:  *		height (I)	int containing height of embedded raster
  837:  *		pixsz (I)	int containing #bits per pixel, 1 or 8
  838:  * --------------------------------------------------------------------------
  839:  * Returns:	( subraster * )	ptr to newly-allocated subraster,
  840:  *				or NULL for any error.
  841:  * --------------------------------------------------------------------------
  842:  * Notes:     o	if width or height <=0, embedded raster not allocated
  843:  * ======================================================================= */
  844: /* --- entry point --- */
  845: subraster *new_subraster ( int width, int height, int pixsz )
  846: {
  847: /* -------------------------------------------------------------------------
  848: Allocations and Declarations
  849: -------------------------------------------------------------------------- */
  850: subraster *sp=NULL;			/* subraster returned to caller */
  851: raster	*new_raster(), *rp=NULL;	/* image raster embedded in sp */
  852: int	delete_subraster();		/* in case new_raster() fails */
  853: int	size = NORMALSIZE,		/* default size */
  854: 	baseline = height-1;		/* and baseline */
  855: /* -------------------------------------------------------------------------
  856: allocate and initialize subraster struct
  857: -------------------------------------------------------------------------- */
  858: if ( msgfp!=NULL && msglevel>=9999 )
  859:   { fprintf(msgfp,"new_subraster(%d,%d,%d)> entry point\n",
  860:     width,height,pixsz); fflush(msgfp); }
  861: /* --- allocate subraster struct --- */
  862: sp = (subraster *)malloc(sizeof(subraster));  /* malloc subraster struct */
  863: if ( sp == (subraster *)NULL )		/* malloc failed */
  864:   goto end_of_job;			/* return error to caller */
  865: /* --- initialize subraster struct --- */
  866: sp->type = NOVALUE;			/* character or image raster */
  867: sp->symdef =  (mathchardef *)NULL;	/* mathchardef identifying image */
  868: sp->baseline = baseline;		/*0 if image is entirely descending*/
  869: sp->size = size;			/* font size 0-4 */
  870: sp->toprow = sp->leftcol = (-1);	/* upper-left corner of subraster */
  871: sp->image = (raster *)NULL;		/*ptr to bitmap image of subraster*/
  872: /* -------------------------------------------------------------------------
  873: allocate raster and embed it in subraster, and return to caller
  874: -------------------------------------------------------------------------- */
  875: /* --- allocate raster struct if desired --- */
  876: if ( width>0 && height>0 && pixsz>0 )	/* caller wants raster */
  877:   { if ( (rp=new_raster(width,height,pixsz)) /* allocate embedded raster */
  878:     !=   NULL )				/* if allocate succeeded */
  879:         sp->image = rp;			/* embed raster in subraster */
  880:     else				/* or if allocate failed */
  881:       { delete_subraster(sp);		/* free non-unneeded subraster */
  882: 	sp = NULL; } }			/* signal error */
  883: /* --- back to caller with new subraster or NULL --- */
  884: end_of_job:
  885:   if ( msgfp!=NULL && msglevel>=9999 )
  886:     { fprintf(msgfp,"new_subraster(%d,%d,%d)> returning (%s)\n",
  887:       width,height,pixsz,(sp==NULL?"null ptr":"success")); fflush(msgfp); }
  888:   return ( sp );
  889: } /* --- end-of-function new_subraster() --- */
  890: 
  891: 
  892: /* ==========================================================================
  893:  * Function:	new_chardef (  )
  894:  * Purpose:	Allocates and initializes a chardef struct,
  895:  *		but _not_ the embedded raster struct.
  896:  * --------------------------------------------------------------------------
  897:  * Arguments:	none
  898:  * --------------------------------------------------------------------------
  899:  * Returns:	( chardef * )	ptr to allocated and initialized
  900:  *				chardef struct, or NULL for any error.
  901:  * --------------------------------------------------------------------------
  902:  * Notes:
  903:  * ======================================================================= */
  904: /* --- entry point --- */
  905: chardef	*new_chardef (  )
  906: {
  907: /* -------------------------------------------------------------------------
  908: Allocations and Declarations
  909: -------------------------------------------------------------------------- */
  910: chardef	*cp = (chardef *)NULL;		/* chardef ptr returned to caller */
  911: /* -------------------------------------------------------------------------
  912: allocate and initialize chardef struct
  913: -------------------------------------------------------------------------- */
  914: cp = (chardef *)malloc(sizeof(chardef)); /* malloc chardef struct */
  915: if ( cp == (chardef *)NULL )		/* malloc failed */
  916:   goto end_of_job;			/* return error to caller */
  917: cp->charnum = cp->location = 0;		/* init character description */
  918: cp->toprow = cp->topleftcol = 0;	/* init upper-left corner */
  919: cp->botrow = cp->botleftcol = 0;	/* init lower-left corner */
  920: cp->image.width = cp->image.height = 0;	/* init raster dimensions */
  921: cp->image.format = 0;			/* init raster format */
  922: cp->image.pixsz = 0;			/* and #bits per pixel */
  923: cp->image.pixmap = NULL;		/* init raster pixmap as null */
  924: /* -------------------------------------------------------------------------
  925: Back to caller with address of chardef struct, or NULL ptr for any error.
  926: -------------------------------------------------------------------------- */
  927: end_of_job:
  928:   return ( cp );
  929: } /* --- end-of-function new_chardef() --- */
  930: 
  931: 
  932: /* ==========================================================================
  933:  * Function:	delete_raster ( rp )
  934:  * Purpose:	Destructor for raster.
  935:  *		Frees memory for raster bitmap and struct.
  936:  * --------------------------------------------------------------------------
  937:  * Arguments:	rp (I)		ptr to raster struct to be deleted.
  938:  * --------------------------------------------------------------------------
  939:  * Returns:	( int )		1 if completed successfully,
  940:  *				or 0 otherwise (for any error).
  941:  * --------------------------------------------------------------------------
  942:  * Notes:
  943:  * ======================================================================= */
  944: /* --- entry point --- */
  945: int	delete_raster ( raster *rp )
  946: {
  947: /* -------------------------------------------------------------------------
  948: free raster bitmap and struct
  949: -------------------------------------------------------------------------- */
  950: if ( rp != (raster *)NULL )		/* can't free null ptr */
  951:   {
  952:   if ( rp->pixmap != (pixbyte *)NULL )	/* can't free null ptr */
  953:     free((void *)rp->pixmap);		/* free pixmap within raster */
  954:   free((void *)rp);			/* lastly, free raster struct */
  955:   } /* --- end-of-if(rp!=NULL) --- */
  956: return ( 1 );				/* back to caller, 1=okay 0=failed */
  957: } /* --- end-of-function delete_raster() --- */
  958: 
  959: 
  960: /* ==========================================================================
  961:  * Function:	delete_subraster ( sp )
  962:  * Purpose:	Deallocates a subraster (and embedded raster)
  963:  * --------------------------------------------------------------------------
  964:  * Arguments:	sp (I)		ptr to subraster struct to be deleted.
  965:  * --------------------------------------------------------------------------
  966:  * Returns:	( int )		1 if completed successfully,
  967:  *				or 0 otherwise (for any error).
  968:  * --------------------------------------------------------------------------
  969:  * Notes:
  970:  * ======================================================================= */
  971: /* --- entry point --- */
  972: int	delete_subraster ( subraster *sp )
  973: {
  974: /* -------------------------------------------------------------------------
  975: free subraster struct
  976: -------------------------------------------------------------------------- */
  977: int	delete_raster();		/* to delete embedded raster */
  978: if ( sp != (subraster *)NULL )		/* can't free null ptr */
  979:   {
  980:   if ( sp->type != CHARASTER )		/* not static character data */
  981:     if ( sp->image != NULL )		/*raster allocated within subraster*/
  982:       delete_raster(sp->image);		/* so free embedded raster */
  983:   free((void *)sp);			/* and free subraster struct itself*/
  984:   } /* --- end-of-if(sp!=NULL) --- */
  985: return ( 1 );				/* back to caller, 1=okay 0=failed */
  986: } /* --- end-of-function delete_subraster() --- */
  987: 
  988: 
  989: /* ==========================================================================
  990:  * Function:	delete_chardef ( cp )
  991:  * Purpose:	Deallocates a chardef (and bitmap of embedded raster)
  992:  * --------------------------------------------------------------------------
  993:  * Arguments:	cp (I)		ptr to chardef struct to be deleted.
  994:  * --------------------------------------------------------------------------
  995:  * Returns:	( int )		1 if completed successfully,
  996:  *				or 0 otherwise (for any error).
  997:  * --------------------------------------------------------------------------
  998:  * Notes:
  999:  * ======================================================================= */
 1000: /* --- entry point --- */
 1001: int	delete_chardef ( chardef *cp )
 1002: {
 1003: /* -------------------------------------------------------------------------
 1004: free chardef struct
 1005: -------------------------------------------------------------------------- */
 1006: if ( cp != (chardef *)NULL )		/* can't free null ptr */
 1007:   {
 1008:   if ( cp->image.pixmap != NULL )	/* pixmap allocated within raster */
 1009:     free((void *)cp->image.pixmap);	/* so free embedded pixmap */
 1010:   free((void *)cp);			/* and free chardef struct itself */
 1011:   } /* --- end-of-if(cp!=NULL) --- */
 1012: /* -------------------------------------------------------------------------
 1013: Back to caller with 1=okay, 0=failed.
 1014: -------------------------------------------------------------------------- */
 1015: return ( 1 );
 1016: } /* --- end-of-function delete_chardef() --- */
 1017: 
 1018: 
 1019: /* ==========================================================================
 1020:  * Function:	rastcpy ( rp )
 1021:  * Purpose:	makes duplicate copy of rp
 1022:  * --------------------------------------------------------------------------
 1023:  * Arguments:	rp (I)		ptr to raster struct to be copied
 1024:  * --------------------------------------------------------------------------
 1025:  * Returns:	( raster * )	ptr to new copy rp,
 1026:  *				or NULL for any error.
 1027:  * --------------------------------------------------------------------------
 1028:  * Notes:     o
 1029:  * ======================================================================= */
 1030: /* --- entry point --- */
 1031: raster	*rastcpy ( raster *rp )
 1032: {
 1033: /* -------------------------------------------------------------------------
 1034: Allocations and Declarations
 1035: -------------------------------------------------------------------------- */
 1036: raster	*new_raster(), *newrp=NULL;	/*copied raster returned to caller*/
 1037: int	height= (rp==NULL?0:rp->height), /* original and copied height */
 1038: 	width = (rp==NULL?0:rp->width),	/* original and copied width */
 1039: 	pixsz = (rp==NULL?0:rp->pixsz),	/* #bits per pixel */
 1040: 	nbytes= (rp==NULL?0:(pixmapsz(rp))); /* #bytes in rp's pixmap */
 1041: /* -------------------------------------------------------------------------
 1042: allocate rotated raster and fill it
 1043: -------------------------------------------------------------------------- */
 1044: /* --- allocate copied raster with same width,height, and copy bitmap --- */
 1045: if ( rp != NULL )			/* nothing to copy if ptr null */
 1046:   if ( (newrp = new_raster(width,height,pixsz)) /*same width,height in copy*/
 1047:   !=   NULL )				/* check that allocate succeeded */
 1048:     memcpy(newrp->pixmap,rp->pixmap,nbytes); /* fill copied raster pixmap */
 1049: return ( newrp );			/* return copied raster to caller */
 1050: } /* --- end-of-function rastcpy() --- */
 1051: 
 1052: 
 1053: /* ==========================================================================
 1054:  * Function:	subrastcpy ( sp )
 1055:  * Purpose:	makes duplicate copy of sp
 1056:  * --------------------------------------------------------------------------
 1057:  * Arguments:	sp (I)		ptr to subraster struct to be copied
 1058:  * --------------------------------------------------------------------------
 1059:  * Returns:	( subraster * )	ptr to new copy sp,
 1060:  *				or NULL for any error.
 1061:  * --------------------------------------------------------------------------
 1062:  * Notes:     o
 1063:  * ======================================================================= */
 1064: /* --- entry point --- */
 1065: subraster *subrastcpy ( subraster *sp )
 1066: {
 1067: /* -------------------------------------------------------------------------
 1068: Allocations and Declarations
 1069: -------------------------------------------------------------------------- */
 1070: subraster *new_subraster(), *newsp=NULL; /* allocate new subraster */
 1071: raster	*rastcpy(), *newrp=NULL;	/* and new raster image within it */
 1072: int	delete_subraster();		/* dealloc newsp if rastcpy() fails*/
 1073: /* -------------------------------------------------------------------------
 1074: make copy, and return it to caller
 1075: -------------------------------------------------------------------------- */
 1076: if ( sp == NULL ) goto end_of_job;	/* nothing to copy */
 1077: /* --- allocate new subraster "envelope" for copy --- */
 1078: if ( (newsp=new_subraster(0,0,0))	/* allocate subraster "envelope" */
 1079: ==   NULL ) goto end_of_job;		/* and quit if we fail to allocate */
 1080: /* --- transparently copy original envelope to new one --- */
 1081: memcpy((void *)newsp,(void *)sp,sizeof(subraster)); /* copy envelope */
 1082: /* --- make a copy of the rasterized image itself, if there is one --- */
 1083: if ( sp->image != NULL )		/* there's an image embedded in sp */
 1084:   if ( (newrp = rastcpy(sp->image))	/* so copy rasterized image in sp */
 1085:   ==   NULL )				/* failed to copy successfully */
 1086:     { delete_subraster(newsp);		/* won't need newsp any more */
 1087:       newsp = NULL;			/* because we're returning error */
 1088:       goto end_of_job; }		/* back to caller with error signal*/
 1089: /* --- set new params in new envelope --- */
 1090: newsp->image = newrp;			/* new raster image we just copied */
 1091: switch ( sp->type )			/* set new raster image type */
 1092:   { case STRINGRASTER: case CHARASTER: newsp->type = STRINGRASTER; break;
 1093:     case ASCIISTRING:                  newsp->type = ASCIISTRING;  break;
 1094:     case FRACRASTER:                   newsp->type = FRACRASTER;   break;
 1095:     case BLANKSIGNAL:                  newsp->type = blanksignal;  break;
 1096:     case IMAGERASTER:  default:        newsp->type = IMAGERASTER;  break; }
 1097: /* --- return copy of sp to caller --- */
 1098: end_of_job:
 1099:   return ( newsp );			/* copy back to caller */
 1100: } /* --- end-of-function subrastcpy() --- */
 1101: 
 1102: 
 1103: /* ==========================================================================
 1104:  * Function:	rastrot ( rp )
 1105:  * Purpose:	rotates rp image 90 degrees right/clockwise
 1106:  * --------------------------------------------------------------------------
 1107:  * Arguments:	rp (I)		ptr to raster struct to be rotated
 1108:  * --------------------------------------------------------------------------
 1109:  * Returns:	( raster * )	ptr to new raster rotated relative to rp,
 1110:  *				or NULL for any error.
 1111:  * --------------------------------------------------------------------------
 1112:  * Notes:     o	An underbrace is } rotated 90 degrees clockwise,
 1113:  *		a hat is <, etc.
 1114:  * ======================================================================= */
 1115: /* --- entry point --- */
 1116: raster	*rastrot ( raster *rp )
 1117: {
 1118: /* -------------------------------------------------------------------------
 1119: Allocations and Declarations
 1120: -------------------------------------------------------------------------- */
 1121: raster	*new_raster(), *rotated=NULL;	/*rotated raster returned to caller*/
 1122: int	height = rp->height, irow,	/* original height, row index */
 1123: 	width = rp->width, icol,	/* original width, column index */
 1124: 	pixsz = rp->pixsz;		/* #bits per pixel */
 1125: /* -------------------------------------------------------------------------
 1126: allocate rotated raster and fill it
 1127: -------------------------------------------------------------------------- */
 1128: /* --- allocate rotated raster with flipped width<-->height --- */
 1129: if ( (rotated = new_raster(height,width,pixsz)) /* flip width,height */
 1130: !=   NULL )				/* check that allocation succeeded */
 1131:   /* --- fill rotated raster --- */
 1132:   for ( irow=0; irow<height; irow++ )	/* for each row of rp */
 1133:     for ( icol=0; icol<width; icol++ )	/* and each column of rp */
 1134:       {	int value = getpixel(rp,irow,icol);
 1135: 	/* setpixel(rotated,icol,irow,value); } */
 1136: 	setpixel(rotated,icol,(height-1-irow),value); }
 1137: return ( rotated );			/* return rotated raster to caller */
 1138: } /* --- end-of-function rastrot() --- */
 1139: 
 1140: 
 1141: /* ==========================================================================
 1142:  * Function:	rastref ( rp, axis )
 1143:  * Purpose:	reflects rp, horizontally about y-axis |_ becomes _| if axis=1
 1144:  *		or vertically about x-axis M becomes W if axis=2.
 1145:  * --------------------------------------------------------------------------
 1146:  * Arguments:	rp (I)		ptr to raster struct to be reflected
 1147:  *		axis (I)	int containing 1 for horizontal reflection,
 1148:  *				or 2 for vertical
 1149:  * --------------------------------------------------------------------------
 1150:  * Returns:	( raster * )	ptr to new raster reflected relative to rp,
 1151:  *				or NULL for any error.
 1152:  * --------------------------------------------------------------------------
 1153:  * Notes:     o
 1154:  * ======================================================================= */
 1155: /* --- entry point --- */
 1156: raster	*rastref ( raster *rp, int axis )
 1157: {
 1158: /* -------------------------------------------------------------------------
 1159: Allocations and Declarations
 1160: -------------------------------------------------------------------------- */
 1161: raster	*new_raster(), *reflected=NULL;	/* reflected raster back to caller */
 1162: int	height = rp->height, irow,	/* height, row index */
 1163: 	width = rp->width, icol,	/* width, column index */
 1164: 	pixsz = rp->pixsz;		/* #bits per pixel */
 1165: /* -------------------------------------------------------------------------
 1166: allocate reflected raster and fill it
 1167: -------------------------------------------------------------------------- */
 1168: /* --- allocate reflected raster with same width, height --- */
 1169: if ( axis==1 || axis==2 )		/* first validate axis arg */
 1170:  if ( (reflected = new_raster(width,height,pixsz)) /* same width, height */
 1171:  !=   NULL )				/* check that allocation succeeded */
 1172:   /* --- fill reflected raster --- */
 1173:   for ( irow=0; irow<height; irow++ )	/* for each row of rp */
 1174:     for ( icol=0; icol<width; icol++ ) { /* and each column of rp */
 1175:       int value = getpixel(rp,irow,icol);
 1176:       if ( axis == 1 ) { setpixel(reflected,irow,width-1-icol,value); }
 1177:       if ( axis == 2 ) { setpixel(reflected,height-1-irow,icol,value); } }
 1178: return ( reflected );			/*return reflected raster to caller*/
 1179: } /* --- end-of-function rastref() --- */
 1180: 
 1181: 
 1182: /* ==========================================================================
 1183:  * Function:	rastput ( target, source, top, left, isopaque )
 1184:  * Purpose:	Overlays source onto target,
 1185:  *		with the 0,0-bit of source onto the top,left-bit of target.
 1186:  * --------------------------------------------------------------------------
 1187:  * Arguments:	target (I)	ptr to target raster struct
 1188:  *		source (I)	ptr to source raster struct
 1189:  *		top (I)		int containing 0 ... target->height - 1
 1190:  *		left (I)	int containing 0 ... target->width - 1
 1191:  *		isopaque (I)	int containing false (zero) to allow
 1192:  *				original 1-bits of target to "show through"
 1193:  *				0-bits of source.
 1194:  * --------------------------------------------------------------------------
 1195:  * Returns:	( int )		1 if completed successfully,
 1196:  *				or 0 otherwise (for any error).
 1197:  * --------------------------------------------------------------------------
 1198:  * Notes:
 1199:  * ======================================================================= */
 1200: /* --- entry point --- */
 1201: int	rastput ( raster *target, raster *source,
 1202: 		int top, int left, int isopaque )
 1203: {
 1204: /* -------------------------------------------------------------------------
 1205: Allocations and Declarations
 1206: -------------------------------------------------------------------------- */
 1207: int	irow, icol,		/* indexes over source raster */
 1208: 	twidth=target->width, theight=target->height, /*target width,height*/
 1209: 	tpix, ntpix = twidth*theight; /* #pixels in target */
 1210: int	isfatal = 0,		/* true to abend on out-of-bounds error */
 1211: 	isstrict = 0/*1*/,	/* true for strict bounds check - no "wrap"*/
 1212: 	isokay = 1;		/* true if no pixels out-of-bounds */
 1213: /* -------------------------------------------------------------------------
 1214: superimpose source onto target, one bit at a time
 1215: -------------------------------------------------------------------------- */
 1216: if ( isstrict && (top<0 || left<0) )		/* args fail strict test */
 1217:  isokay = 0;					/* so just return error */
 1218: else
 1219:  for ( irow=0; irow<source->height; irow++ )	/* for each scan line */
 1220:   {
 1221:   tpix = (top+irow)*target->width + left - 1;	/*first target pixel (-1)*/
 1222:   for ( icol=0; icol<source->width; icol++ )	/* each pixel in scan line */
 1223:     {
 1224:     int svalue = getpixel(source,irow,icol);	/* source pixel value */
 1225:     ++tpix;					/* bump target pixel */
 1226:     if ( msgfp!=NULL && msglevel>=9999 )	/* debugging output */
 1227:       {	fprintf(msgfp,"rastput> tpix,ntpix=%d,%d top,irow,theight=%d,%d,%d "
 1228: 	"left,icol,twidth=%d,%d,%d\n", tpix,ntpix, top,irow,theight,
 1229: 	left,icol,twidth);  fflush(msgfp); }
 1230:     if ( tpix >= ntpix				/* bounds check failed */
 1231:     ||   (isstrict && (irow+top>=theight || icol+left>=twidth)) )
 1232:       {	isokay = 0;				/* reset okay flag */
 1233: 	if ( isfatal ) goto end_of_job;		/* abort if error is fatal */
 1234: 	else break; }				/*or just go on to next row*/
 1235:     if ( tpix >= 0 )				/* bounds check okay */
 1236:      if ( svalue!=0 || isopaque ) {		/*got dark or opaque source*/
 1237:       setpixel(target,irow+top,icol+left,svalue); }/*overlay source on targ*/
 1238:     } /* --- end-of-for(icol) --- */
 1239:   } /* --- end-of-for(irow) --- */
 1240: /* -------------------------------------------------------------------------
 1241: Back to caller with 1=okay, 0=failed.
 1242: -------------------------------------------------------------------------- */
 1243: end_of_job:
 1244:   return ( isokay /*isfatal? (tpix<ntpix? 1:0) : 1*/ );
 1245: } /* --- end-of-function rastput() --- */
 1246: 
 1247: 
 1248: /* ==========================================================================
 1249:  * Function:	rastcompose ( sp1, sp2, offset2, isalign, isfree )
 1250:  * Purpose:	Overlays sp2 on top of sp1, leaving both unchanged
 1251:  *		and returning a newly-allocated composite subraster.
 1252:  *		Frees/deletes input sp1 and/or sp2 depending on value
 1253:  *		of isfree (0=none, 1=sp1, 2=sp2, 3=both).
 1254:  * --------------------------------------------------------------------------
 1255:  * Arguments:	sp1 (I)		subraster *  to "underneath" subraster,
 1256:  *				whose baseline is preserved
 1257:  *		sp2 (I)		subraster *  to "overlaid" subraster
 1258:  *		offset2 (I)	int containing 0 or number of pixels
 1259:  *				to horizontally shift sp2 relative to sp1,
 1260:  *				either positive (right) or negative
 1261:  *		isalign (I)	int containing 1 to align baselines,
 1262:  *				or 0 to vertically center sp2 over sp1
 1263:  *		isfree (I)	int containing 1=free sp1 before return,
 1264:  *				2=free sp2, 3=free both, 0=free none.
 1265:  * --------------------------------------------------------------------------
 1266:  * Returns:	( subraster * )	pointer to constructed subraster
 1267:  *				or  NULL for any error
 1268:  * --------------------------------------------------------------------------
 1269:  * Notes:
 1270:  * ======================================================================= */
 1271: /* --- entry point --- */
 1272: subraster *rastcompose ( subraster *sp1, subraster *sp2, int offset2,
 1273: 			int isalign, int isfree )
 1274: {
 1275: /* -------------------------------------------------------------------------
 1276: Allocations and Declarations
 1277: -------------------------------------------------------------------------- */
 1278: subraster *new_subraster(), *sp=(subraster *)NULL; /* returned subraster */
 1279: raster	*rp=(raster *)NULL;		/* new composite raster in sp */
 1280: int	delete_subraster();		/* in case isfree non-zero */
 1281: int	rastput();			/*place sp1,sp2 in composite raster*/
 1282: int	base1   = sp1->baseline,	/*baseline for underlying subraster*/
 1283: 	height1 = (sp1->image)->height,	/* height for underlying subraster */
 1284: 	width1  = (sp1->image)->width,	/* width for underlying subraster */
 1285: 	pixsz1  = (sp1->image)->pixsz,	/* pixsz for underlying subraster */
 1286: 	base2   = sp2->baseline,	/*baseline for overlaid subraster */
 1287: 	height2 = (sp2->image)->height,	/* height for overlaid subraster */
 1288: 	width2  = (sp2->image)->width,	/* width for overlaid subraster */
 1289: 	pixsz2  = (sp2->image)->pixsz;	/* pixsz for overlaid subraster */
 1290: int	height=0, width=0, pixsz=0, base=0; /* overlaid composite */
 1291: /* -------------------------------------------------------------------------
 1292: Initialization
 1293: -------------------------------------------------------------------------- */
 1294: /* --- determine height, width and baseline of composite raster --- */
 1295: if ( isalign )				/* baselines of sp1,sp2 aligned */
 1296:   { height = max2(base1+1,base2+1)	/* max height above baseline */
 1297:            + max2(height1-base1-1,height2-base2-1); /*+ max descending below*/
 1298:     base   = max2(base1,base2); }	/* max space above baseline */
 1299: else					/* baselines not aligned */
 1300:   { height = max2(height1,height2);	/* max height */
 1301:     base   = base1 + (height-height1)/2; } /* baseline for sp1 */
 1302: width      = max2(width1,width2+abs(offset2)); /* max width */
 1303: pixsz      = max2(pixsz1,pixsz2);	/* bitmap,bytemap becomes bytemap */
 1304: /* -------------------------------------------------------------------------
 1305: allocate concatted composite subraster
 1306: -------------------------------------------------------------------------- */
 1307: /* --- allocate returned subraster (and then initialize it) --- */
 1308: if ( (sp=new_subraster(width,height,pixsz)) /* allocate new subraster */
 1309: ==   (subraster *)NULL ) goto end_of_job; /* failed, so quit */
 1310: /* --- initialize subraster parameters --- */
 1311: sp->type = IMAGERASTER;			/* image */
 1312: sp->baseline = base;			/* composite baseline */
 1313: sp->size = sp1->size;			/* underlying char is sp1 */
 1314: /* --- extract raster from subraster --- */
 1315: rp = sp->image;				/* raster allocated in subraster */
 1316: /* -------------------------------------------------------------------------
 1317: overlay sp1 and sp2 in new composite raster
 1318: -------------------------------------------------------------------------- */
 1319: if ( isalign )
 1320:   { rastput (rp, sp1->image, base-base1, (width-width1)/2, 1);	/*underlying*/
 1321:     rastput (rp, sp2->image, base-base2,			/*overlaid*/
 1322: 		(width-width2)/2+offset2, 0); }
 1323: else
 1324:   { rastput (rp, sp1->image, base-base1, (width-width1)/2, 1);	/*underlying*/
 1325:     rastput (rp, sp2->image, (height-height2)/2,		/*overlaid*/
 1326: 		(width-width2)/2+offset2, 0); }
 1327: /* -------------------------------------------------------------------------
 1328: free input if requested
 1329: -------------------------------------------------------------------------- */
 1330: if ( isfree > 0 )			/* caller wants input freed */
 1331:   { if ( isfree==1 || isfree>2 ) delete_subraster(sp1);	/* free sp1 */
 1332:     if ( isfree >= 2 ) delete_subraster(sp2); }		/* and/or sp2 */
 1333: /* -------------------------------------------------------------------------
 1334: Back to caller with pointer to concatted subraster or with null for error
 1335: -------------------------------------------------------------------------- */
 1336: end_of_job:
 1337:   return ( sp );			/* back with subraster or null ptr */
 1338: } /* --- end-of-function rastcompose() --- */
 1339: 
 1340: 
 1341: /* ==========================================================================
 1342:  * Function:	rastcat ( sp1, sp2, isfree )
 1343:  * Purpose:	"Concatanates" subrasters sp1||sp2, leaving both unchanged
 1344:  *		and returning a newly-allocated subraster.
 1345:  *		Frees/deletes input sp1 and/or sp2 depending on value
 1346:  *		of isfree (0=none, 1=sp1, 2=sp2, 3=both).
 1347:  * --------------------------------------------------------------------------
 1348:  * Arguments:	sp1 (I)		subraster *  to left-hand subraster
 1349:  *		sp2 (I)		subraster *  to right-hand subraster
 1350:  *		isfree (I)	int containing 1=free sp1 before return,
 1351:  *				2=free sp2, 3=free both, 0=free none.
 1352:  * --------------------------------------------------------------------------
 1353:  * Returns:	( subraster * )	pointer to constructed subraster sp1||sp2
 1354:  *				or  NULL for any error
 1355:  * --------------------------------------------------------------------------
 1356:  * Notes:
 1357:  * ======================================================================= */
 1358: /* --- entry point --- */
 1359: subraster *rastcat ( subraster *sp1, subraster *sp2, int isfree )
 1360: {
 1361: /* -------------------------------------------------------------------------
 1362: Allocations and Declarations
 1363: -------------------------------------------------------------------------- */
 1364: subraster *new_subraster(), *sp=(subraster *)NULL; /* returned subraster */
 1365: raster	*rp=(raster *)NULL;		/* new concatted raster */
 1366: int	delete_subraster();		/* in case isfree non-zero */
 1367: int	rastput();			/*place sp1,sp2 in concatted raster*/
 1368: int	type_raster();			/* debugging display */
 1369: int	base1   = sp1->baseline,	/*baseline for left-hand subraster*/
 1370: 	height1 = (sp1->image)->height,	/* height for left-hand subraster */
 1371: 	width1  = (sp1->image)->width,	/* width for left-hand subraster */
 1372: 	pixsz1  = (sp1->image)->pixsz,	/* pixsz for left-hand subraster */
 1373: 	type1   = sp1->type,		/* image type for left-hand */
 1374: 	base2   = sp2->baseline,	/*baseline for right-hand subraster*/
 1375: 	height2 = (sp2->image)->height,	/* height for right-hand subraster */
 1376: 	width2  = (sp2->image)->width,	/* width for right-hand subraster */
 1377: 	pixsz2  = (sp2->image)->pixsz,	/* pixsz for right-hand subraster */
 1378: 	type2   = sp2->type;		/* image type for right-hand */
 1379: int	height=0, width=0, pixsz=0, base=0; /*concatted sp1||sp2 composite*/
 1380: int	issmash = (smashmargin!=0?1:0),	/* true to "squash" sp1||sp2 */
 1381: 	isopaque = (issmash?0:1),	/* not oppaque if smashing */
 1382: 	rastsmash(), isblank=0, nsmash=0, /* #cols to smash */
 1383: 	oldsmashmargin = smashmargin,	/* save original smashmargin */
 1384: 	oldblanksymspace = blanksymspace, /* save original blanksymspace */
 1385: 	oldnocatspace = isnocatspace;	/* save original isnocatspace */
 1386: mathchardef *symdef1 = sp1->symdef,	/*mathchardef of last left-hand char*/
 1387: 	*symdef2 = sp2->symdef;		/* mathchardef of right-hand char */
 1388: int	class1 = (symdef1==NULL?ORDINARY:symdef1->class), /* symdef->class */
 1389: 	class2 = (symdef2==NULL?ORDINARY:symdef2->class), /* or default */
 1390: 	smash1 = (symdef1!=NULL)&&(class1==ORDINARY||class1==VARIABLE||
 1391: 		  class1==OPENING||class1==CLOSING||class1==PUNCTION),
 1392: 	smash2 = (symdef2!=NULL)&&(class2==ORDINARY||class2==VARIABLE||
 1393: 		  class2==OPENING||class2==CLOSING||class2==PUNCTION),
 1394: 	space = fontsize/2+1;		/* #cols between sp1 and sp2 */
 1395: int	isfrac = (type1 == FRACRASTER	/* sp1 is a \frac */
 1396: 		  && class2 == PUNCTION); /* and sp2 is punctuation */
 1397: /* -------------------------------------------------------------------------
 1398: Initialization
 1399: -------------------------------------------------------------------------- */
 1400: /* --- determine inter-character space from character class --- */
 1401: if ( !isstring )
 1402:   space = max2(2,(symspace[class1][class2] + fontsize-3)); /* space */
 1403: else space = 1;				/* space for ascii string */
 1404: if ( isnocatspace > 0 ) {		/* spacing explicitly turned off */
 1405:   space = 0;				/* reset space */
 1406:   isnocatspace--; }			/* and decrement isnocatspace flag */
 1407: if ( 0 && sp1->type == BLANKSIGNAL ) space=0; /*implicitly turn off spacing*/
 1408: if ( sp1->type==BLANKSIGNAL && sp2->type==BLANKSIGNAL ) /* both blank */
 1409:   space = 0;				/* no extra space between spaces */
 1410: if ( sp2->type != BLANKSIGNAL )		/* not a blank space signal */
 1411:   if ( blanksymspace != 0 ) {		/* and we have a space adjustment */
 1412:     space = max2(0,space+blanksymspace); /* adjust as much as possible */
 1413:     blanksymspace = 0; }		/* and reset adjustment */
 1414: if ( msgfp!=NULL && msglevel>=999 )	/* display space results */
 1415:   { fprintf(msgfp,"rastcat> space=%d, blanksymspace=%d, isnocatspace=%d\n",
 1416:     space,oldblanksymspace,oldnocatspace);  fflush(msgfp); }
 1417: /* --- determine smash --- */
 1418: if ( !isstring && !isfrac )		/* don't smash strings or \frac's */
 1419:  if ( issmash ) {			/* raster smash wanted */
 1420:    int	maxsmash = rastsmash(sp1,sp2),	/* calculate max smash space */
 1421: 	margin = smashmargin;		/* init margin without delta */
 1422:    if ( (1 && smash1 && smash2)		/* concatanating two chars */
 1423:    ||   (1 && type1!=IMAGERASTER && type2!=IMAGERASTER
 1424: 	   && type1!=FRACRASTER  && type2!=FRACRASTER ) )
 1425:      /*maxsmash = 0;*/			/* turn off smash */
 1426:      margin = max2(space-1,0);		/* force small smashmargin */
 1427:    else					/* adjust for delta if images */
 1428:      if ( issmashdelta )		/* smashmargin is a delta value */
 1429:        margin += fontsize;		/* add displaystyle base to margin */
 1430:    if ( maxsmash == blanksignal )	/* sp2 is intentional blank */
 1431:      isblank = 1;			/* set blank flag signal */
 1432:    else					/* see how much extra space we have*/
 1433:      if ( maxsmash > margin )		/* enough space for adjustment */
 1434:        nsmash = maxsmash-margin;	/* make adjustment */
 1435:    if ( msgfp!=NULL && msglevel>=99 )	/* display smash results */
 1436:      { fprintf(msgfp,"rastcat> maxsmash=%d, margin=%d, nsmash=%d\n",
 1437:        maxsmash,margin,nsmash);
 1438:        fprintf(msgfp,"rastcat> type1=%d,2=%d, class1=%d,2=%d\n", type1,type2,
 1439:        (symdef1==NULL?-999:class1),(symdef2==NULL?-999:class2));
 1440:        fflush(msgfp); }
 1441:    } /* --- end-of-if(issmash) --- */
 1442: /* --- determine height, width and baseline of composite raster --- */
 1443: if ( !isstring )
 1444:  { height = max2(base1+1,base2+1)	/* max height above baseline */
 1445:           + max2(height1-base1-1,height2-base2-1); /*+ max descending below*/
 1446:    width  = width1+width2 + space-nsmash; /*add widths and space-smash*/
 1447:    width  = max3(width,width1,width2); } /* don't "over-smash" composite */
 1448: else					/* ascii string */
 1449:  { height = 1;				/* default */
 1450:    width  = width1 + width2 + space - 1; } /* no need for two nulls */
 1451: pixsz  = max2(pixsz1,pixsz2);		/* bitmap||bytemap becomes bytemap */
 1452: base   = max2(base1,base2);		/* max space above baseline */
 1453: if ( msgfp!=NULL && msglevel>=9999 )	/* display components */
 1454:   { fprintf(msgfp,"rastcat> Left-hand ht,width,pixsz,base = %d,%d,%d,%d\n",
 1455:     height1,width1,pixsz1,base1);
 1456:     type_raster(sp1->image,msgfp);	/* display left-hand raster */
 1457:     fprintf(msgfp,"rastcat> Right-hand ht,width,pixsz,base = %d,%d,%d,%d\n",
 1458:     height2,width2,pixsz2,base2);
 1459:     type_raster(sp2->image,msgfp);	/* display right-hand raster */
 1460:     fprintf(msgfp,
 1461:     "rastcat> Composite ht,width,smash,pixsz,base = %d,%d,%d,%d,%d\n",
 1462:     height,width,nsmash,pixsz,base);
 1463:     fflush(msgfp); }			/* flush msgfp buffer */
 1464: /* -------------------------------------------------------------------------
 1465: allocate concatted composite subraster
 1466: -------------------------------------------------------------------------- */
 1467: /* --- allocate returned subraster (and then initialize it) --- */
 1468: if ( msgfp!=NULL && msglevel>=9999 )
 1469:   { fprintf(msgfp,"rastcat> calling new_subraster(%d,%d,%d)\n",
 1470:     width,height,pixsz); fflush(msgfp); }
 1471: if ( (sp=new_subraster(width,height,pixsz)) /* allocate new subraster */
 1472: ==   (subraster *)NULL )		/* failed */
 1473:   { if ( msgfp!=NULL && msglevel>=1 )	/* report failure */
 1474:       {	fprintf(msgfp,"rastcat> new_subraster(%d,%d,%d) failed\n",
 1475: 	width,height,pixsz); fflush(msgfp); }
 1476:     goto end_of_job; }			/* failed, so quit */
 1477: /* --- initialize subraster parameters --- */
 1478: /* sp->type = (!isstring?STRINGRASTER:ASCIISTRING); */  /*concatted string*/
 1479: if ( !isstring )
 1480:   sp->type = /*type2;*//*(type1==type2?type2:IMAGERASTER);*/
 1481: 	(type2!=CHARASTER? type2 :
 1482: 	(type1!=CHARASTER&&type1!=BLANKSIGNAL
 1483: 	 &&type1!=FRACRASTER?type1:IMAGERASTER));
 1484: else
 1485:   sp->type = ASCIISTRING;		/* concatted ascii string */
 1486: sp->symdef = symdef2;			/* rightmost char is sp2 */
 1487: sp->baseline = base;			/* composite baseline */
 1488: sp->size = sp2->size;			/* rightmost char is sp2 */
 1489: if ( isblank )				/* need to propagate blanksignal */
 1490:   sp->type = blanksignal;		/* may not be completely safe??? */
 1491: /* --- extract raster from subraster --- */
 1492: rp = sp->image;				/* raster allocated in subraster */
 1493: /* -------------------------------------------------------------------------
 1494: overlay sp1 and sp2 in new composite raster
 1495: -------------------------------------------------------------------------- */
 1496: if ( msgfp!=NULL && msglevel>=9999 )
 1497:   { fprintf(msgfp,"rastcat> calling rastput() to concatanate left||right\n");
 1498:     fflush(msgfp); }			/* flush msgfp buffer */
 1499: if ( !isstring )
 1500:  rastput (rp, sp1->image, base-base1,	/* overlay left-hand */
 1501:  max2(0,nsmash-width1), 1);		/* plus any residual smash space */
 1502: else
 1503:  memcpy(rp->pixmap,(sp1->image)->pixmap,width1-1);  /*init left string*/
 1504: if ( msgfp!=NULL && msglevel>=9999 )
 1505:   { type_raster(sp->image,msgfp);	/* display composite raster */
 1506:     fflush(msgfp); }			/* flush msgfp buffer */
 1507: if ( !isstring )
 1508:  { int	fracbase = ( isfrac?		/* baseline for punc after \frac */
 1509: 	max2(fraccenterline,base2):base ); /*adjust baseline or use original*/
 1510:    rastput (rp, sp2->image, fracbase-base2, /* overlay right-hand */
 1511:    max2(0,width1+space-nsmash), isopaque); /* minus any smashed space */
 1512:    if ( 1 && type1 == FRACRASTER	/* we're done with \frac image */
 1513:    &&   type2 != FRACRASTER )		/* unless we have \frac\frac */
 1514:      fraccenterline = NOVALUE;		/* so reset centerline signal */
 1515:    if ( fraccenterline != NOVALUE )	/* sp2 is a fraction */
 1516:      fraccenterline += (base-base2); }	/* so adjust its centerline */
 1517: else
 1518:  { strcpy((char *)(rp->pixmap)+width1-1+space,(char *)((sp2->image)->pixmap));
 1519:    ((char *)(rp->pixmap))[width1+width2+space-2] = '\000'; } /*null-term*/
 1520: if ( msgfp!=NULL && msglevel>=9999 )
 1521:   { type_raster(sp->image,msgfp);	/* display composite raster */
 1522:     fflush(msgfp); }			/* flush msgfp buffer */
 1523: /* -------------------------------------------------------------------------
 1524: free input if requested
 1525: -------------------------------------------------------------------------- */
 1526: if ( isfree > 0 )			/* caller wants input freed */
 1527:   { if ( isfree==1 || isfree>2 ) delete_subraster(sp1);	/* free sp1 */
 1528:     if ( isfree >= 2 ) delete_subraster(sp2); }		/* and/or sp2 */
 1529: /* -------------------------------------------------------------------------
 1530: Back to caller with pointer to concatted subraster or with null for error
 1531: -------------------------------------------------------------------------- */
 1532: end_of_job:
 1533:   smashmargin = oldsmashmargin;		/* reset original smashmargin */
 1534:   return ( sp );			/* back with subraster or null ptr */
 1535: } /* --- end-of-function rastcat() --- */
 1536: 
 1537: 
 1538: /* ==========================================================================
 1539:  * Function:	rastack ( sp1, sp2, base, space, iscenter, isfree )
 1540:  * Purpose:	Stack subrasters sp2 atop sp1, leaving both unchanged
 1541:  *		and returning a newly-allocated subraster,
 1542:  *		whose baseline is sp1's if base=1, or sp2's if base=2.
 1543:  *		Frees/deletes input sp1 and/or sp2 depending on value
 1544:  *		of isfree (0=none, 1=sp1, 2=sp2, 3=both).
 1545:  * --------------------------------------------------------------------------
 1546:  * Arguments:	sp1 (I)		subraster *  to lower subraster
 1547:  *		sp2 (I)		subraster *  to upper subraster
 1548:  *		base (I)	int containing 1 if sp1 is baseline,
 1549:  *				or 2 if sp2 is baseline.
 1550:  *		space (I)	int containing #rows blank space inserted
 1551:  *				between sp1's image and sp2's image.
 1552:  *		iscenter (I)	int containing 1 to center both sp1 and sp2
 1553:  *				in stacked array, 0 to left-justify both
 1554:  *		isfree (I)	int containing 1=free sp1 before return,
 1555:  *				2=free sp2, 3=free both, 0=free none.
 1556:  * --------------------------------------------------------------------------
 1557:  * Returns:	( subraster * )	pointer to constructed subraster sp2 atop sp1
 1558:  *				or  NULL for any error
 1559:  * --------------------------------------------------------------------------
 1560:  * Notes:
 1561:  * ======================================================================= */
 1562: /* --- entry point --- */
 1563: subraster *rastack ( subraster *sp1, subraster *sp2,
 1564: 			int base, int space, int iscenter, int isfree )
 1565: {
 1566: /* -------------------------------------------------------------------------
 1567: Allocations and Declarations
 1568: -------------------------------------------------------------------------- */
 1569: subraster *new_subraster(), *sp=(subraster *)NULL; /* returned subraster */
 1570: raster	*rp=(raster *)NULL;		/* new stacked raster in sp */
 1571: int	delete_subraster();		/* in case isfree non-zero */
 1572: int	rastput();			/* place sp1,sp2 in stacked raster */
 1573: int	base1   = sp1->baseline,	/* baseline for lower subraster */
 1574: 	height1 = (sp1->image)->height,	/* height for lower subraster */
 1575: 	width1  = (sp1->image)->width,	/* width for lower subraster */
 1576: 	pixsz1  = (sp1->image)->pixsz,	/* pixsz for lower subraster */
 1577: 	base2   = sp2->baseline,	/* baseline for upper subraster */
 1578: 	height2 = (sp2->image)->height,	/* height for upper subraster */
 1579: 	width2  = (sp2->image)->width,	/* width for upper subraster */
 1580: 	pixsz2  = (sp2->image)->pixsz;	/* pixsz for upper subraster */
 1581: int	height=0, width=0, pixsz=0, baseline=0;	/*for stacked sp2 atop sp1*/
 1582: mathchardef *symdef1 = sp1->symdef,	/* mathchardef of right lower char */
 1583: 	*symdef2 = sp2->symdef;		/* mathchardef of right upper char */
 1584: /* -------------------------------------------------------------------------
 1585: Initialization
 1586: -------------------------------------------------------------------------- */
 1587: /* --- determine height, width and baseline of composite raster --- */
 1588: height   = height1 + space + height2;	/* sum of heights plus space */
 1589: width    = max2(width1,width2);		/* max width is overall width */
 1590: pixsz    = max2(pixsz1,pixsz2);		/* bitmap||bytemap becomes bytemap */
 1591: baseline = (base==1? height2+space+base1 : (base==2? base2 : 0));
 1592: /* -------------------------------------------------------------------------
 1593: allocate stacked composite subraster (with embedded raster)
 1594: -------------------------------------------------------------------------- */
 1595: /* --- allocate returned subraster (and then initialize it) --- */
 1596: if ( (sp=new_subraster(width,height,pixsz)) /* allocate new subraster */
 1597: ==   (subraster *)NULL ) goto end_of_job; /* failed, so quit */
 1598: /* --- initialize subraster parameters --- */
 1599: sp->type = IMAGERASTER;			/* stacked rasters */
 1600: sp->symdef = (base==1? symdef1 : (base==2? symdef2 : NULL)); /* symdef */
 1601: sp->baseline = baseline;		/* composite baseline */
 1602: sp->size = (base==1? sp1->size : (base==2? sp2->size : NORMALSIZE)); /*size*/
 1603: /* --- extract raster from subraster --- */
 1604: rp = sp->image;				/* raster embedded in subraster */
 1605: /* -------------------------------------------------------------------------
 1606: overlay sp1 and sp2 in new composite raster
 1607: -------------------------------------------------------------------------- */
 1608: if ( iscenter == 1 )			/* center both sp1 and sp2 */
 1609:   { rastput (rp, sp2->image, 0, (width-width2)/2, 1);  /* overlay upper */
 1610:     rastput (rp, sp1->image, height2+space, (width-width1)/2, 1); } /*lower*/
 1611: else					/* left-justify both sp1 and sp2 */
 1612:   { rastput (rp, sp2->image, 0, 0, 1);  /* overlay upper */
 1613:     rastput (rp, sp1->image, height2+space, 0, 1); } /*lower*/
 1614: /* -------------------------------------------------------------------------
 1615: free input if requested
 1616: -------------------------------------------------------------------------- */
 1617: if ( isfree > 0 )			/* caller wants input freed */
 1618:   { if ( isfree==1 || isfree>2 ) delete_subraster(sp1);	/* free sp1 */
 1619:     if ( isfree>=2 ) delete_subraster(sp2); } /* and/or sp2 */
 1620: /* -------------------------------------------------------------------------
 1621: Back to caller with pointer to stacked subraster or with null for error
 1622: -------------------------------------------------------------------------- */
 1623: end_of_job:
 1624:   return ( sp );			/* back with subraster or null ptr */
 1625: } /* --- end-of-function rastack() --- */
 1626: 
 1627: 
 1628: /* ==========================================================================
 1629:  * Function:	rastile ( tiles, ntiles )
 1630:  * Purpose:	Allocate and build up a composite raster
 1631:  *		from the ntiles components/characters supplied in tiles.
 1632:  * --------------------------------------------------------------------------
 1633:  * Arguments:	tiles (I)	subraster *  to array of subraster structs
 1634:  *				describing the components and their locations
 1635:  *		ntiles (I)	int containing number of subrasters in tiles[]
 1636:  * --------------------------------------------------------------------------
 1637:  * Returns:	( raster * )	ptr to composite raster,
 1638:  *				or NULL for any error.
 1639:  * --------------------------------------------------------------------------
 1640:  * Notes:     o	The top,left corner of a raster is row=0,col=0
 1641:  *		with row# increasing as you move down,
 1642:  *		and col# increasing as you move right.
 1643:  *		Metafont numbers rows with the baseline=0,
 1644:  *		so the top row is a positive number that
 1645:  *		decreases as you move down.
 1646:  *	      o	rastile() is no longer used.
 1647:  *		It was used by an earlier rasterize() algorithm,
 1648:  *		and I've left it in place should it be needed again.
 1649:  *		But recent changes haven't been tested/exercised.
 1650:  * ======================================================================= */
 1651: /* --- entry point --- */
 1652: raster	*rastile ( subraster *tiles, int ntiles )
 1653: {
 1654: /* -------------------------------------------------------------------------
 1655: Allocations and Declarations
 1656: -------------------------------------------------------------------------- */
 1657: raster	*new_raster(), *composite=(raster *)NULL;  /*raster back to caller*/
 1658: int	width=0, height=0, pixsz=0, /*width,height,pixsz of composite raster*/
 1659: 	toprow=9999, rightcol=-999, /* extreme upper-right corner of tiles */
 1660: 	botrow=-999, leftcol=9999;  /* extreme lower-left corner of tiles */
 1661: int	itile;			/* tiles[] index */
 1662: int	rastput();		/* overlay each tile in composite raster */
 1663: /* -------------------------------------------------------------------------
 1664: run through tiles[] to determine dimensions for composite raster
 1665: -------------------------------------------------------------------------- */
 1666: /* --- determine row and column bounds of composite raster --- */
 1667: for ( itile=0; itile<ntiles; itile++ )
 1668:   {
 1669:   subraster *tile = &(tiles[itile]);		/* ptr to current tile */
 1670:   /* --- upper-left corner of composite --- */
 1671:   toprow = min2(toprow, tile->toprow);
 1672:   leftcol = min2(leftcol, tile->leftcol);
 1673:   /* --- lower-right corner of composite --- */
 1674:   botrow = max2(botrow, tile->toprow + (tile->image)->height - 1);
 1675:   rightcol = max2(rightcol, tile->leftcol + (tile->image)->width  - 1);
 1676:   /* --- pixsz of composite --- */
 1677:   pixsz = max2(pixsz,(tile->image)->pixsz);
 1678:   } /* --- end-of-for(itile) --- */
 1679: /* --- calculate width and height from bounds --- */
 1680: width  = rightcol - leftcol + 1;
 1681: height = botrow - toprow + 1;
 1682: /* --- sanity check (quit if bad dimensions) --- */
 1683: if ( width<1 || height<1 ) goto end_of_job;
 1684: /* -------------------------------------------------------------------------
 1685: allocate composite raster, and embed tiles[] within it
 1686: -------------------------------------------------------------------------- */
 1687: /* --- allocate composite raster --- */
 1688: if ( (composite=new_raster(width,height,pixsz))	/*allocate composite raster*/
 1689: ==   (raster *)NULL ) goto end_of_job;		/* and quit if failed */
 1690: /* --- embed tiles[] in composite --- */
 1691: for ( itile=0; itile<ntiles; itile++ )
 1692:   { subraster *tile = &(tiles[itile]);		/* ptr to current tile */
 1693:     rastput (composite, tile->image,		/* overlay tile image at...*/
 1694:       tile->toprow-toprow, tile->leftcol-leftcol, 1); } /*upper-left corner*/
 1695: /* -------------------------------------------------------------------------
 1696: Back to caller with composite raster (or null for any error)
 1697: -------------------------------------------------------------------------- */
 1698: end_of_job:
 1699:   return ( composite );			/* back with composite or null ptr */
 1700: } /* --- end-of-function rastile() --- */
 1701: 
 1702: 
 1703: /* ==========================================================================
 1704:  * Function:	rastsmash ( sp1, sp2 )
 1705:  * Purpose:	When concatanating sp1||sp2, calculate #pixels
 1706:  *		we can "smash sp2 left"
 1707:  * --------------------------------------------------------------------------
 1708:  * Arguments:	sp1 (I)		subraster *  to left-hand raster
 1709:  *		sp2 (I)		subraster *  to right-hand raster
 1710:  * --------------------------------------------------------------------------
 1711:  * Returns:	( int )		max #pixels we can smash sp1||sp2,
 1712:  *				or "blanksignal" if sp2 intentionally blank,
 1713:  *				or 0 for any error.
 1714:  * --------------------------------------------------------------------------
 1715:  * Notes:     o
 1716:  * ======================================================================= */
 1717: /* --- entry point --- */
 1718: int	rastsmash ( subraster *sp1, subraster *sp2 )
 1719: {
 1720: /* -------------------------------------------------------------------------
 1721: Allocations and Declarations
 1722: -------------------------------------------------------------------------- */
 1723: int	nsmash = 0;			/* #pixels to smash sp1||sp2 */
 1724: int	base1   = sp1->baseline,	/*baseline for left-hand subraster*/
 1725: 	height1 = (sp1->image)->height,	/* height for left-hand subraster */
 1726: 	width1  = (sp1->image)->width,	/* width for left-hand subraster */
 1727: 	base2   = sp2->baseline,	/*baseline for right-hand subraster*/
 1728: 	height2 = (sp2->image)->height,	/* height for right-hand subraster */
 1729: 	width2  = (sp2->image)->width;	/* width for right-hand subraster */
 1730: int	base = max2(base1,base2),	/* max ascenders - 1 above baseline*/
 1731: 	top1=base-base1, top2=base-base2, /* top irow indexes for sp1, sp2 */
 1732: 	bot1=top1+height1-1, bot2=top2+height2-1, /* bot irow indexes */
 1733: 	height = max2(bot1,bot2)+1;	/* total height */
 1734: int	irow1=0,irow2=0, icol=0;	/* row,col indexes */
 1735: int	firstcol1[1025], nfirst1=0,	/* 1st sp1 col containing set pixel*/
 1736: 	firstcol2[1025], nfirst2=0;	/* 1st sp2 col containing set pixel*/
 1737: int	smin=9999, xmin=9999,ymin=9999;	/* min separation (s=x+y) */
 1738: int	type_raster();			/* display debugging output */
 1739: /* -------------------------------------------------------------------------
 1740: find right edge of sp1 and left edge of sp2 (these will be abutting edges)
 1741: -------------------------------------------------------------------------- */
 1742: /* --- check args --- */
 1743: if ( isstring ) goto end_of_job;	/* ignore string rasters */
 1744: if ( 0 && istextmode ) goto end_of_job;	/* don't smash in text mode */
 1745: if ( height > 1023 ) goto end_of_job;	/* don't try to smash huge image */
 1746: if ( sp2->type == blanksignal )		/*blanksignal was propagated to us*/
 1747:   goto end_of_job;			/* don't smash intentional blank */
 1748: /* --- init firstcol1[], firstcol2[] --- */
 1749: for ( irow1=0; irow1<height; irow1++ )	/* for each row */
 1750:   firstcol1[irow1] = firstcol2[irow1] = blanksignal; /* signal empty rows */
 1751: /* --- set firstcol2[] indicating left edge of sp2 --- */
 1752: for ( irow2=top2; irow2<=bot2; irow2++ ) /* for each row inside sp2 */
 1753:   for ( icol=0; icol<width2; icol++ )	/* find first non-empty col in row */
 1754:     if ( getpixel(sp2->image,irow2-top2,icol) != 0 ) /* found a set pixel */
 1755:       {	firstcol2[irow2] = icol;	/* icol is #cols from left edge */
 1756: 	nfirst2++;			/* bump #rows containing set pixels*/
 1757: 	break; }			/* and go on to next row */
 1758: if ( nfirst2 < 1 )			/*right-hand sp2 is completely blank*/
 1759:   { nsmash = blanksignal;		/* signal intentional blanks */
 1760:     goto end_of_job; }			/* don't smash intentional blanks */
 1761: /* --- now check if preceding image in sp1 was an intentional blank --- */
 1762: if ( sp1->type == blanksignal )		/*blanksignal was propagated to us*/
 1763:   goto end_of_job;			/* don't smash intentional blank */
 1764: /* --- set firstcol1[] indicating right edge of sp1 --- */
 1765: for ( irow1=top1; irow1<=bot1; irow1++ ) /* for each row inside sp1 */
 1766:   for ( icol=width1-1; icol>=0; icol-- ) /* find last non-empty col in row */
 1767:     if ( getpixel(sp1->image,irow1-top1,icol) != 0 ) /* found a set pixel */
 1768:       {	firstcol1[irow1] = (width1-1)-icol; /* save #cols from right edge */
 1769: 	nfirst1++;			/* bump #rows containing set pixels*/
 1770: 	break; }			/* and go on to next row */
 1771: if ( nfirst1 < 1 )			/*left-hand sp1 is completely blank*/
 1772:   goto end_of_job;			/* don't smash intentional blanks */
 1773: /* -------------------------------------------------------------------------
 1774: find minimum separation
 1775: -------------------------------------------------------------------------- */
 1776: for ( irow2=top2; irow2<=bot2; irow2++ ) { /* check each row inside sp2 */
 1777:  int margin1, margin2=firstcol2[irow2];	/* #cols to first set pixel */
 1778:  if ( margin2 != blanksignal ) {	/* irow2 not an empty/blank row */
 1779:   for ( irow1=max2(irow2-smin,top1); ; irow1++ )
 1780:    if ( irow1 > min2(irow2+smin,bot1) ) break; /* upper bound check */
 1781:    else
 1782:     if ( (margin1=firstcol1[irow1]) != blanksignal ) { /*have non-blank row*/
 1783:      int dx=(margin1+margin2), dy=absval(irow2-irow1), ds=dx+dy; /* deltas */
 1784:      if ( ds >= smin ) continue;	/* min unchanged */
 1785:      if ( dy>smashmargin && dx<xmin && smin<9999 ) continue; /* dy alone */
 1786:      smin=ds; xmin=dx; ymin=dy;		/* set new min */
 1787:      } /* --- end-of-if(margin1!=blanksignal) --- */
 1788:   } /* --- end-of-if(margin2!=blanksignal) --- */
 1789:  if ( smin<2 ) goto end_of_job;		/* can't smash */
 1790:  } /* --- end-of-for(irow2) --- */
 1791: /*nsmash = min2(xmin,width2);*/		/* permissible smash */
 1792: nsmash = xmin;				/* permissible smash */
 1793: /* -------------------------------------------------------------------------
 1794: Back to caller with #pixels to smash sp1||sp2
 1795: -------------------------------------------------------------------------- */
 1796: end_of_job:
 1797:   /* --- debugging output --- */
 1798:   if ( msgfp!=NULL && msglevel >= 99 )	/* display for debugging */
 1799:     { fprintf(msgfp,"rastsmash> nsmash=%d, smashmargin=%d\n",
 1800:       nsmash,smashmargin);
 1801:       if ( msglevel >= 999 )		/* also display rasters */
 1802: 	{ fprintf(msgfp,"rastsmash>left-hand image...\n");
 1803: 	  if(sp1!=NULL) type_raster(sp1->image,msgfp); /* left image */
 1804: 	  fprintf(msgfp,"rastsmash>right-hand image...\n");
 1805: 	  if(sp2!=NULL) type_raster(sp2->image,msgfp); } /* right image */
 1806:       fflush(msgfp); }
 1807:   return ( nsmash );			/* back with #smash pixels */
 1808: } /* --- end-of-function rastsmash() --- */
 1809: 
 1810: 
 1811: /* ==========================================================================
 1812:  * Function:	rastsmashcheck ( term )
 1813:  * Purpose:	Check an exponent term to see if its leading symbol
 1814:  *		would make smashing dangerous
 1815:  * --------------------------------------------------------------------------
 1816:  * Arguments:	term (I)	char *  to null-terminated string
 1817:  *				containing right-hand exponent term about to
 1818:  *				be smashed against existing left-hand.
 1819:  * --------------------------------------------------------------------------
 1820:  * Returns:	( int )		1 if it's okay to smash term, or
 1821:  *				0 if smash is dangerous.
 1822:  * --------------------------------------------------------------------------
 1823:  * Notes:     o
 1824:  * ======================================================================= */
 1825: /* --- entry point --- */
 1826: int	rastsmashcheck ( char *term )
 1827: {
 1828: /* -------------------------------------------------------------------------
 1829: Allocations and Declarations
 1830: -------------------------------------------------------------------------- */
 1831: int	isokay = 0;		/* 1 to signal okay to caller */
 1832: static	char nosmashchars[64] = "-.,="; /* don't smash these leading chars */
 1833: static	char *nosmashstrs[64] = { "\\frac", NULL }; /* or leading strings */
 1834: static	char *grayspace[64] = { "\\tiny", "\\small", "\\normalsize",
 1835: 	"\\large", "\\Large", "\\LARGE", "\\huge", "\\Huge", NULL };
 1836: char	*expression = term;	/* local ptr to beginning of expression */
 1837: char	*token = NULL;  int i;	/* token = nosmashstrs[i] or grayspace[i] */
 1838: /* -------------------------------------------------------------------------
 1839: see if smash check enabled
 1840: -------------------------------------------------------------------------- */
 1841: if ( smashcheck < 1 ) {		/* no smash checking wanted */
 1842:   if ( smashcheck >= 0 )	/* -1 means check should always fail */
 1843:     isokay = 1;			/* otherwise (if 0), signal okay to smash */
 1844:   goto end_of_job; }		/* return to caller */
 1845: /* -------------------------------------------------------------------------
 1846: skip leading white and gray space
 1847: -------------------------------------------------------------------------- */
 1848: /* --- first check input --- */
 1849: if ( term == NULL )    goto end_of_job; /* no input so return 0 to caller */
 1850: if ( *term == '\000' ) goto end_of_job; /* ditto for empty string */
 1851: /* --- skip leading white space --- */
 1852: skipwhite(term);		/* skip leading white sapce */
 1853: if ( *term == '\000' ) goto end_of_job; /* nothing but white space */
 1854: /* --- skip leading gray space --- */
 1855: skipgray:
 1856:  for ( i=0; (token=grayspace[i]) != NULL; i++ ) /* check each grayspace */
 1857:   if ( strncmp(term,token,strlen(token)) == 0 ) { /* found grayspace */
 1858:    term += strlen(token);	/* skip past this grayspace token */
 1859:    if ( *term == '\000' ) {	/* nothing left so quit */
 1860:      if ( msgfp!=NULL && msglevel >= 99 ) /* display for debugging */
 1861:        fprintf(msgfp,"rastsmashcheck> only grayspace in %.32s\n",expression);
 1862:      goto end_of_job; }
 1863:    goto skipgray; }		/* restart grayspace check from beginning */
 1864: /* -------------------------------------------------------------------------
 1865: check for leading no-smash single char
 1866: -------------------------------------------------------------------------- */
 1867: /* --- don't smash if term begins with a "nosmash" char --- */
 1868: if ( (token=strchr(nosmashchars,*term)) != NULL ) {
 1869:   if ( msgfp!=NULL && msglevel >= 99 )	/* display for debugging */
 1870:     fprintf(msgfp,"rastsmashcheck> char %.1s found in %.32s\n",token,term);
 1871:   goto end_of_job; }
 1872: /* -------------------------------------------------------------------------
 1873: check for leading no-smash token
 1874: -------------------------------------------------------------------------- */
 1875: for ( i=0; (token=nosmashstrs[i]) != NULL; i++ ) /* check each nosmashstr */
 1876:  if ( strncmp(term,token,strlen(token)) == 0 ) { /* found a nosmashstr */
 1877:   if ( msgfp!=NULL && msglevel >= 99 )	/* display for debugging */
 1878:     fprintf(msgfp,"rastsmashcheck> token %s found in %.32s\n",token,term);
 1879:   goto end_of_job; }		/* so don't smash term */
 1880: /* -------------------------------------------------------------------------
 1881: back to caller
 1882: -------------------------------------------------------------------------- */
 1883: isokay = 1;			/* no problem, so signal okay to smash */
 1884: end_of_job:
 1885:   if ( msgfp!=NULL && msglevel >= 999 )	/* display for debugging */
 1886:     fprintf(msgfp,"rastsmashcheck> returning isokay=%d for \"%.32s\"\n",
 1887:     isokay,(expression==NULL?"<no input>":expression));
 1888:   return ( isokay );		/* back to caller with 1 if okay to smash */
 1889: } /* --- end-of-function rastsmashcheck() --- */
 1890: 
 1891: 
 1892: /* ==========================================================================
 1893:  * Function:	accent_subraster ( accent, width, height, pixsz )
 1894:  * Purpose:	Allocate a new subraster of width x height
 1895:  *		(or maybe different dimensions, depending on accent),
 1896:  *		and draw an accent (\hat or \vec or \etc) that fills it
 1897:  * --------------------------------------------------------------------------
 1898:  * Arguments:	accent (I)	int containing either HATACCENT or VECACCENT,
 1899:  *				etc, indicating the type of accent desired
 1900:  *		width (I)	int containing desired width of accent (#cols)
 1901:  *		height (I)	int containing desired height of accent(#rows)
 1902:  *		pixsz (I)	int containing 1 for bitmap, 8 for bytemap
 1903:  * --------------------------------------------------------------------------
 1904:  * Returns:	( subraster * )	ptr to newly-allocated subraster with accent,
 1905:  *				or NULL for any error.
 1906:  * --------------------------------------------------------------------------
 1907:  * Notes:     o	Some accents have internally-determined dimensions,
 1908:  *		and caller should check dimensions in returned subraster
 1909:  * ======================================================================= */
 1910: /* --- entry point --- */
 1911: subraster *accent_subraster (  int accent, int width, int height, int pixsz )
 1912: {
 1913: /* -------------------------------------------------------------------------
 1914: Allocations and Declarations
 1915: -------------------------------------------------------------------------- */
 1916: /* --- general info --- */
 1917: raster	*new_raster(), *rp=NULL;	/*raster containing desired accent*/
 1918: subraster *new_subraster(), *sp=NULL;	/* subraster returning accent */
 1919: int	delete_raster(), delete_subraster(); /*free allocated raster on err*/
 1920: int	line_raster(),			/* draws lines */
 1921: 	rule_raster(),			/* draw solid boxes */
 1922: 	thickness = 1;			/* line thickness */
 1923: /*int	pixval = (pixsz==1? 1 : (pixsz==8?255:(-1)));*/ /*black pixel value*/
 1924: /* --- other working info --- */
 1925: int	col0, col1,			/* cols for line */
 1926: 	row0, row1;			/* rows for line */
 1927: subraster *get_delim(), *accsp=NULL;	/*find suitable cmex10 symbol/accent*/
 1928: /* --- info for under/overbraces, tildes, etc --- */
 1929: char	brace[16];			/*"{" for over, "}" for under, etc*/
 1930: raster	*rastrot(),			/* rotate { for overbrace, etc */
 1931: 	*rastcpy();			/* may need copy of original */
 1932: subraster *arrow_subraster();		/* rightarrow for vec */
 1933: subraster *rastack();			/* stack accent atop extra space */
 1934: /* -------------------------------------------------------------------------
 1935: outer switch() traps accents that may change caller's height,width
 1936: -------------------------------------------------------------------------- */
 1937: switch ( accent )
 1938:  {
 1939:  default:
 1940:   /* -----------------------------------------------------------------------
 1941:   inner switch() first allocates fixed-size raster for accents that don't
 1942:   ------------------------------------------------------------------------ */
 1943:   if ( (rp = new_raster(width,height,pixsz)) /* allocate fixed-size raster */
 1944:   !=   NULL )				/* and if we succeeded... */
 1945:    switch ( accent )			/* ...draw requested accent in it */
 1946:     {
 1947:     /* --- unrecognized request --- */
 1948:     default: delete_raster(rp);		/* unrecognized accent requested */
 1949: 	rp = NULL;  break;		/* so free raster and signal error */
 1950:     /* --- bar request --- */
 1951:     case UNDERBARACCENT:
 1952:     case BARACCENT:
 1953: 	thickness = 1; /*height-1;*/	/* adjust thickness */
 1954: 	if ( accent == BARACCENT )	/* bar is above expression */
 1955: 	 { row0 = row1 = max2(height-3,0); /* row numbers for overbar */
 1956: 	   line_raster(rp,row0,0,row1,width-1,thickness); } /*blanks at bot*/
 1957: 	else				/* underbar is below expression */
 1958: 	 { row0 = row1 = min2(2,height-1); /* row numbers for underbar */
 1959: 	   line_raster(rp,row0,0,row1,width-1,thickness); } /*blanks at top*/
 1960: 	break;
 1961:     /* --- dot request --- */
 1962:     case DOTACCENT:
 1963: 	thickness = height-1;		/* adjust thickness */
 1964: 	/*line_raster(rp,0,width/2,1,(width/2)+1,thickness);*//*centered dot*/
 1965: 	rule_raster(rp,0,(width+1-thickness)/2,thickness,thickness,3); /*box*/
 1966: 	break;
 1967:     /* --- ddot request --- */
 1968:     case DDOTACCENT:
 1969: 	thickness = height-1;		/* adjust thickness */
 1970: 	col0 = max2((width+1)/3-(thickness/2)-1,0); /* one-third of width */
 1971: 	col1 = min2((2*width+1)/3-(thickness/2)+1,width-thickness); /*2/3rds*/
 1972: 	if ( col0+thickness >= col1 )	/* dots overlap */
 1973: 	  { col0 = max2(col0-1,0);	/* try moving left dot more left */
 1974: 	    col1 = min2(col1+1,width-thickness); } /* and right dot right */
 1975: 	if ( col0+thickness >= col1 )	/* dots _still_ overlap */
 1976: 	  thickness = max2(thickness-1,1); /* so try reducing thickness */
 1977: 	/*line_raster(rp,0,col0,1,col0+1,thickness);*//*set dot at 1st third*/
 1978: 	/*line_raster(rp,0,col1,1,col1+1,thickness);*//*and another at 2nd*/
 1979: 	rule_raster(rp,0,col0,thickness,thickness,3); /*box at 1st third*/
 1980: 	rule_raster(rp,0,col1,thickness,thickness,3); /*box at 2nd third*/
 1981: 	break;
 1982:     /* --- hat request --- */
 1983:     case HATACCENT:
 1984: 	thickness = 1; /*(width<=12? 2 : 3);*/	/* adjust thickness */
 1985: 	line_raster(rp,height-1,0,0,width/2,thickness);    /* / part of hat*/
 1986: 	line_raster(rp,0,(width-1)/2,height-1,width-1,thickness); /* \ part*/
 1987: 	break;
 1988:     /* --- sqrt request --- */
 1989:     case SQRTACCENT:
 1990: 	col1 = SQRTWIDTH(height) - 1;	/* right col of sqrt symbol */
 1991: 	col0 = (col1+2)/3;		/* midpoint col of sqrt */
 1992: 	row0 = (height+1)/2;		/* midpoint row of sqrt */
 1993: 	row1 = height-1;		/* bottom row of sqrt */
 1994: 	line_raster(rp,row0,0,row1,col0,thickness); /* descending portion */
 1995: 	line_raster(rp,row1,col0,0,col1,thickness); /* ascending portion */
 1996: 	line_raster(rp,0,col1,0,width-1,thickness); /*overbar of thickness 1*/
 1997: 	break;
 1998:     } /* --- end-of-inner-switch(accent) --- */
 1999:     break;				/* break from outer accent switch */
 2000:  /* --- underbrace, overbrace request --- */
 2001:  case UNDERBRACE:
 2002:  case OVERBRACE:
 2003:     if ( accent == UNDERBRACE ) strcpy(brace,"}"); /* start with } brace */
 2004:     if ( accent ==  OVERBRACE ) strcpy(brace,"{"); /* start with { brace */
 2005:     if ( (accsp=get_delim(brace,width,CMEX10)) /* use width for height */
 2006:     !=  NULL )				/* found desired brace */
 2007:       { rp = rastrot(accsp->image);	/* rotate 90 degrees clockwise */
 2008: 	delete_subraster(accsp); }	/* and free subraster "envelope" */
 2009:     break;
 2010:  /* --- hat request --- */
 2011:  case HATACCENT:
 2012:     if ( accent == HATACCENT ) strcpy(brace,"<"); /* start with < */
 2013:     if ( (accsp=get_delim(brace,width,CMEX10)) /* use width for height */
 2014:     !=  NULL )				/* found desired brace */
 2015:       { rp = rastrot(accsp->image);	/* rotate 90 degrees clockwise */
 2016: 	delete_subraster(accsp); }	/* and free subraster "envelope" */
 2017:     break;
 2018:  /* --- vec request --- */
 2019:  case VECACCENT:
 2020:     height = 2*(height/2) + 1;		/* force height odd */
 2021:     if ( (accsp=arrow_subraster(width,height,pixsz,1,0)) /*build rightarrow*/
 2022:     !=  NULL )				/* succeeded */
 2023: 	{ rp = accsp->image;		/* "extract" raster with bitmap */
 2024: 	  free((void *)accsp); }	/* and free subraster "envelope" */
 2025:     break;
 2026:  /* --- tilde request --- */
 2027:  case TILDEACCENT:
 2028:     accsp=(width<25? get_delim("\\sim",-width,CMSY10) :
 2029: 		     get_delim("~",-width,CMEX10)); /*width search for tilde*/
 2030:     if ( accsp !=  NULL )		/* found desired tilde */
 2031:       if ( (sp=rastack(new_subraster(1,1,pixsz),accsp,1,0,1,3))/*space below*/
 2032:       !=  NULL )			/* have tilde with space below it */
 2033: 	{ rp = sp->image;		/* "extract" raster with bitmap */
 2034: 	  free((void *)sp);		/* and free subraster "envelope" */
 2035: 	  leftsymdef = NULL; }		/* so \tilde{x}^2 works properly */
 2036:     break;
 2037:  } /* --- end-of-outer-switch(accent) --- */
 2038: /* -------------------------------------------------------------------------
 2039: if we constructed accent raster okay, embed it in a subraster and return it
 2040: -------------------------------------------------------------------------- */
 2041: /* --- if all okay, allocate subraster to contain constructed raster --- */
 2042: if ( rp != NULL ) {			/* accent raster constructed okay */
 2043:   if ( (sp=new_subraster(0,0,0))	/* allocate subraster "envelope" */
 2044:   ==   NULL )				/* and if we fail to allocate */
 2045:     delete_raster(rp);			/* free now-unneeded raster */
 2046:   else					/* subraster allocated okay */
 2047:     { /* --- init subraster parameters, embedding raster in it --- */
 2048:       sp->type = IMAGERASTER;		/* constructed image */
 2049:       sp->image = rp;			/* raster we just constructed */
 2050:       sp->size = (-1);			/* can't set font size here */
 2051:       sp->baseline = 0; }		/* can't set baseline here */
 2052:   } /* --- end-of-if(rp!=NULL) --- */
 2053: /* --- return subraster containing desired accent to caller --- */
 2054: return ( sp );				/* return accent or NULL to caller */
 2055: } /* --- end-of-function accent_subraster() --- */
 2056: 
 2057: 
 2058: /* ==========================================================================
 2059:  * Function:	arrow_subraster ( width, height, pixsz, drctn, isBig )
 2060:  * Purpose:	Allocate a raster/subraster and draw left/right arrow in it
 2061:  * --------------------------------------------------------------------------
 2062:  * Arguments:	width (I)	int containing number of cols for arrow
 2063:  *		height (I)	int containing number of rows for arrow
 2064:  *		pixsz (I)	int containing 1 for bitmap, 8 for bytemap
 2065:  *		drctn (I)	int containing +1 for right arrow,
 2066:  *				or -1 for left, 0 for leftright
 2067:  *		isBig (I)	int containing 1/true for \Long arrows,
 2068:  *				or false for \long arrows, i.e.,
 2069:  *				true for ===> or false for --->.
 2070:  * --------------------------------------------------------------------------
 2071:  * Returns:	( subraster * )	ptr to constructed left/right arrow
 2072:  *				or NULL for any error.
 2073:  * --------------------------------------------------------------------------
 2074:  * Notes:     o
 2075:  * ======================================================================= */
 2076: /* --- entry point --- */
 2077: subraster *arrow_subraster ( int width, int height, int pixsz,
 2078: 				int drctn, int isBig )
 2079: {
 2080: /* -------------------------------------------------------------------------
 2081: Allocations and Declarations
 2082: -------------------------------------------------------------------------- */
 2083: subraster *new_subraster(), *arrowsp=NULL; /* allocate arrow subraster */
 2084: int	rule_raster();			/* draw arrow line */
 2085: int	irow, midrow=height/2;		/* index, midrow is arrowhead apex */
 2086: int	icol, thickness=(height>15?2:2); /* arrowhead thickness and index */
 2087: int	pixval = (pixsz==1? 1 : (pixsz==8?255:(-1))); /* black pixel value */
 2088: int	ipix,				/* raster pixmap[] index */
 2089: 	npix = width*height;		/* #pixels malloced in pixmap[] */
 2090: /* -------------------------------------------------------------------------
 2091: allocate raster/subraster and draw arrow line
 2092: -------------------------------------------------------------------------- */
 2093: if ( height < 3 ) { height=3; midrow=1; }	/* set minimum height */
 2094: if ( (arrowsp=new_subraster(width,height,pixsz)) /* allocate empty raster */
 2095: ==   NULL ) goto end_of_job;			/* and quit if failed */
 2096: if ( !isBig )					/* single line */
 2097:   rule_raster(arrowsp->image,midrow,0,width,1,0); /*draw line across midrow*/
 2098: else
 2099:   { int	delta = (width>6? (height>15? 3: (height>7? 2 : 1)) : 1);
 2100:     rule_raster(arrowsp->image,midrow-delta,delta,width-2*delta,1,0);
 2101:     rule_raster(arrowsp->image,midrow+delta,delta,width-2*delta,1,0); }
 2102: /* -------------------------------------------------------------------------
 2103: construct arrowhead(s)
 2104: -------------------------------------------------------------------------- */
 2105: for ( irow=0; irow<height; irow++ )		/* for each row of arrow */
 2106:   {
 2107:   int	delta = abs(irow-midrow);		/*arrowhead offset for irow*/
 2108:   /* --- right arrowhead --- */
 2109:   if ( drctn >= 0 )				/* right arrowhead wanted */
 2110:     for ( icol=0; icol<thickness; icol++ )	/* for arrowhead thickness */
 2111:      { ipix = ((irow+1)*width - 1) - delta - icol; /* rightmost-delta-icol */
 2112:        if ( ipix >= 0 ) {				/* bounds check */
 2113: 	if ( pixsz == 1 )			/* have a bitmap */
 2114: 	  setlongbit((arrowsp->image)->pixmap,ipix);/*turn on arrowhead bit*/
 2115: 	else					/* should have a bytemap */
 2116: 	 if ( pixsz == 8 )			/* check pixsz for bytemap */
 2117: 	  ((arrowsp->image)->pixmap)[ipix] = pixval; } }/*set arrowhead byte*/
 2118:   /* --- left arrowhead (same as right except for ipix calculation) --- */
 2119:   if ( drctn <= 0 )				/* left arrowhead wanted */
 2120:     for ( icol=0; icol<thickness; icol++ )	/* for arrowhead thickness */
 2121:      { ipix = irow*width + delta + icol;	/* leftmost bit+delta+icol */
 2122:        if ( ipix < npix ) {			/* bounds check */
 2123: 	if ( pixsz == 1 )			/* have a bitmap */
 2124: 	  setlongbit((arrowsp->image)->pixmap,ipix);/*turn on arrowhead bit*/
 2125: 	else					/* should have a bytemap */
 2126: 	 if ( pixsz == 8 )			/* check pixsz for bytemap */
 2127: 	  ((arrowsp->image)->pixmap)[ipix] = pixval; } }/*set arrowhead byte*/
 2128:   } /* --- end-of-for(irow) --- */
 2129: end_of_job:
 2130:   return ( arrowsp );			/*back to caller with arrow or NULL*/
 2131: } /* --- end-of-function arrow_subraster() --- */
 2132: 
 2133: 
 2134: /* ==========================================================================
 2135:  * Function:	uparrow_subraster ( width, height, pixsz, drctn, isBig )
 2136:  * Purpose:	Allocate a raster/subraster and draw up/down arrow in it
 2137:  * --------------------------------------------------------------------------
 2138:  * Arguments:	width (I)	int containing number of cols for arrow
 2139:  *		height (I)	int containing number of rows for arrow
 2140:  *		pixsz (I)	int containing 1 for bitmap, 8 for bytemap
 2141:  *		drctn (I)	int containing +1 for up arrow,
 2142:  *				or -1 for down, or 0 for updown
 2143:  *		isBig (I)	int containing 1/true for \Long arrows,
 2144:  *				or false for \long arrows, i.e.,
 2145:  *				true for ===> or false for --->.
 2146:  * --------------------------------------------------------------------------
 2147:  * Returns:	( subraster * )	ptr to constructed up/down arrow
 2148:  *				or NULL for any error.
 2149:  * --------------------------------------------------------------------------
 2150:  * Notes:     o
 2151:  * ======================================================================= */
 2152: /* --- entry point --- */
 2153: subraster *uparrow_subraster ( int width, int height, int pixsz,
 2154: 					int drctn, int isBig )
 2155: {
 2156: /* -------------------------------------------------------------------------
 2157: Allocations and Declarations
 2158: -------------------------------------------------------------------------- */
 2159: subraster *new_subraster(), *arrowsp=NULL; /* allocate arrow subraster */
 2160: int	rule_raster();			/* draw arrow line */
 2161: int	icol, midcol=width/2;		/* index, midcol is arrowhead apex */
 2162: int	irow, thickness=(width>15?2:2);	/* arrowhead thickness and index */
 2163: int	pixval = (pixsz==1? 1 : (pixsz==8?255:(-1))); /* black pixel value */
 2164: int	ipix,				/* raster pixmap[] index */
 2165: 	npix = width*height;		/* #pixels malloced in pixmap[] */
 2166: /* -------------------------------------------------------------------------
 2167: allocate raster/subraster and draw arrow line
 2168: -------------------------------------------------------------------------- */
 2169: if ( width < 3 ) { width=3; midcol=1; }		/* set minimum width */
 2170: if ( (arrowsp=new_subraster(width,height,pixsz)) /* allocate empty raster */
 2171: ==   NULL ) goto end_of_job;			/* and quit if failed */
 2172: if ( !isBig )					/* single line */
 2173:   rule_raster(arrowsp->image,0,midcol,1,height,0); /*draw line down midcol*/
 2174: else
 2175:   { int	delta = (height>6? (width>15? 3: (width>7? 2 : 1)) : 1);
 2176:     rule_raster(arrowsp->image,delta,midcol-delta,1,height-2*delta,0);
 2177:     rule_raster(arrowsp->image,delta,midcol+delta,1,height-2*delta,0); }
 2178: /* -------------------------------------------------------------------------
 2179: construct arrowhead(s)
 2180: -------------------------------------------------------------------------- */
 2181: for ( icol=0; icol<width; icol++ )		/* for each col of arrow */
 2182:   {
 2183:   int	delta = abs(icol-midcol);		/*arrowhead offset for icol*/
 2184:   /* --- up arrowhead --- */
 2185:   if ( drctn >= 0 )				/* up arrowhead wanted */
 2186:     for ( irow=0; irow<thickness; irow++ )	/* for arrowhead thickness */
 2187:      { ipix = (irow+delta)*width + icol;	/* leftmost+icol */
 2188:        if ( ipix < npix ) {			/* bounds check */
 2189: 	if ( pixsz == 1 )			/* have a bitmap */
 2190: 	  setlongbit((arrowsp->image)->pixmap,ipix);/*turn on arrowhead bit*/
 2191: 	else					/* should have a bytemap */
 2192: 	 if ( pixsz == 8 )			/* check pixsz for bytemap */
 2193: 	  ((arrowsp->image)->pixmap)[ipix] = pixval; } }/*set arrowhead byte*/
 2194:   /* --- down arrowhead (same as up except for ipix calculation) --- */
 2195:   if ( drctn <= 0 )				/* down arrowhead wanted */
 2196:     for ( irow=0; irow<thickness; irow++ )	/* for arrowhead thickness */
 2197:      { ipix = (height-1-delta-irow)*width + icol; /* leftmost + icol */
 2198:        if ( ipix > 0 ) {			/* bounds check */
 2199: 	if ( pixsz == 1 )			/* have a bitmap */
 2200: 	  setlongbit((arrowsp->image)->pixmap,ipix);/*turn on arrowhead bit*/
 2201: 	else					/* should have a bytemap */
 2202: 	 if ( pixsz == 8 )			/* check pixsz for bytemap */
 2203: 	  ((arrowsp->image)->pixmap)[ipix] = pixval; } }/*set arrowhead byte*/
 2204:   } /* --- end-of-for(icol) --- */
 2205: end_of_job:
 2206:   return ( arrowsp );			/*back to caller with arrow or NULL*/
 2207: } /* --- end-of-function uparrow_subraster() --- */
 2208: 
 2209: 
 2210: /* ==========================================================================
 2211:  * Function:	rule_raster ( rp, top, left, width, height, type )
 2212:  * Purpose:	Draw a solid or dashed line (or box) in existing raster rp,
 2213:  *		starting at top,left with dimensions width,height.
 2214:  * --------------------------------------------------------------------------
 2215:  * Arguments:	rp (I)		raster *  to raster in which rule
 2216:  *				will be drawn
 2217:  *		top (I)		int containing row at which top-left corner
 2218:  *				of rule starts (0 is topmost)
 2219:  *		left (I)	int containing col at which top-left corner
 2220:  *				of rule starts (0 is leftmost)
 2221:  *		width (I)	int containing number of cols for rule
 2222:  *		height (I)	int containing number of rows for rule
 2223:  *		type (I)	int containing 0 for solid rule,
 2224:  *				1 for horizontal dashes, 2 for vertical
 2225:  *				3 for solid rule with corners removed (bevel)
 2226:  *				4 for strut (nothing drawn)
 2227:  * --------------------------------------------------------------------------
 2228:  * Returns:	( int )		1 if rule drawn okay,
 2229:  *				or 0 for any error.
 2230:  * --------------------------------------------------------------------------
 2231:  * Notes:     o	Rule line is implicitly "horizontal" or "vertical" depending
 2232:  *		on relative width,height dimensions.  It's a box if they're
 2233:  *		more or less comparable.
 2234:  * ======================================================================= */
 2235: /* --- entry point --- */
 2236: int	rule_raster ( raster *rp, int top, int left,
 2237: 		int width, int height, int type )
 2238: {
 2239: /* -------------------------------------------------------------------------
 2240: Allocations and Declarations
 2241: -------------------------------------------------------------------------- */
 2242: int	irow=0, icol=0;		/* indexes over rp raster */
 2243: int	ipix = 0,		/* raster pixmap[] index */
 2244: 	npix = rp->width * rp->height; /* #pixels malloced in rp->pixmap[] */
 2245: int	isfatal = 0;		/* true to abend on out-of-bounds error */
 2246: int	hdash=1, vdash=2,	/* type for horizontal, vertical dashes */
 2247: 	bevel=99/*3*/, strut=4;	/* type for bevel (turned off), strut */
 2248: int	dashlen=3, spacelen=2,	/* #pixels for dash followed by space */
 2249: 	isdraw=1;		/* true when drawing dash (init for solid) */
 2250: /* -------------------------------------------------------------------------
 2251: Check args
 2252: -------------------------------------------------------------------------- */
 2253: if ( rp == (raster *)NULL ) {	/* no raster arg supplied */
 2254:   if ( workingbox != (subraster *)NULL )  /* see if we have a workingbox */
 2255:     rp = workingbox->image;	/* use workingbox if possible */
 2256:   else return ( 0 ); }		/* otherwise signal error to caller */
 2257: if ( type == bevel )		/* remove corners of solid box */
 2258:   if ( width<3 || height<3 ) type=0; /* too small to remove corners */
 2259: /* -------------------------------------------------------------------------
 2260: Fill line/box
 2261: -------------------------------------------------------------------------- */
 2262: if ( width > 0 )				/* zero width implies strut*/
 2263:  for ( irow=top; irow<top+height; irow++ )	/* for each scan line */
 2264:   {
 2265:   if ( type == strut ) isdraw = 0;		/* draw nothing for strut */
 2266:   if ( type == vdash )				/*set isdraw for vert dash*/
 2267:     isdraw = (((irow-top)%(dashlen+spacelen)) < dashlen);
 2268:   ipix = irow*rp->width + left - 1;		/*first pixel preceding icol*/
 2269:   for ( icol=left; icol<left+width; icol++ )	/* each pixel in scan line */
 2270:     {
 2271:     if ( type == bevel ) {			/* remove corners of box */
 2272:       if ( (irow==top && icol==left)		/* top-left corner */
 2273:       ||   (irow==top && icol>=left+width-1)	/* top-right corner */
 2274:       ||   (irow>=top+height-1 && icol==left)	/* bottom-left corner */
 2275:       ||   (irow>=top+height-1 && icol>=left+width-1) ) /* bottom-right */
 2276: 	isdraw = 0;  else isdraw = 1; }		/*set isdraw to skip corner*/
 2277:     if ( type == hdash )			/*set isdraw for horiz dash*/
 2278:       isdraw = (((icol-left)%(dashlen+spacelen)) < dashlen);
 2279:     if ( ++ipix >= npix )			/* bounds check failed */
 2280:          if ( isfatal ) goto end_of_job;	/* abort if error is fatal */
 2281:          else break;				/*or just go on to next row*/
 2282:     else					/*ibit is within rp bounds*/
 2283:       if ( isdraw ) {				/*and we're drawing this bit*/
 2284: 	if ( rp->pixsz == 1 )			/* have a bitmap */
 2285: 	  setlongbit(rp->pixmap,ipix);		/* so turn on bit in line */
 2286: 	else					/* should have a bytemap */
 2287: 	 if ( rp->pixsz == 8 )			/* check pixsz for bytemap */
 2288: 	  ((unsigned char *)(rp->pixmap))[ipix] = 255; } /* set black byte */
 2289:     } /* --- end-of-for(icol) --- */
 2290:   } /* --- end-of-for(irow) --- */
 2291: end_of_job:
 2292:   return ( isfatal? (ipix<npix? 1:0) : 1 );
 2293: } /* --- end-of-function rule_raster() --- */
 2294: 
 2295: 
 2296: /* ==========================================================================
 2297:  * Function:	line_raster ( rp,  row0, col0,  row1, col1,  thickness )
 2298:  * Purpose:	Draw a line from row0,col0 to row1,col1 of thickness
 2299:  *		in existing raster rp.
 2300:  * --------------------------------------------------------------------------
 2301:  * Arguments:	rp (I)		raster *  to raster in which a line
 2302:  *				will be drawn
 2303:  *		row0 (I)	int containing row at which
 2304:  *				line will start (0 is topmost)
 2305:  *		col0 (I)	int containing col at which
 2306:  *				line will start (0 is leftmost)
 2307:  *		row1 (I)	int containing row at which
 2308:  *				line will end (rp->height-1 is bottom-most)
 2309:  *		col1 (I)	int containing col at which
 2310:  *				line will end (rp->width-1 is rightmost)
 2311:  *		thickness (I)	int containing number of pixels/bits
 2312:  *				thick the line will be
 2313:  * --------------------------------------------------------------------------
 2314:  * Returns:	( int )		1 if line drawn okay,
 2315:  *				or 0 for any error.
 2316:  * --------------------------------------------------------------------------
 2317:  * Notes:     o	if row0==row1, a horizontal line is drawn
 2318:  *		between col0 and col1, with row0(==row1) the top row
 2319:  *		and row0+(thickness-1) the bottom row
 2320:  *	      o	if col0==col1, a vertical bar is drawn
 2321:  *		between row0 and row1, with col0(==col1) the left col
 2322:  *		and col0+(thickness-1) the right col
 2323:  *	      o	if both the above, you get a square thickness x thickness
 2324:  *		whose top-left corner is row0,col0.
 2325:  * ======================================================================= */
 2326: /* --- entry point --- */
 2327: int	line_raster ( raster *rp, int row0, int col0,
 2328: 	int row1, int col1, int thickness )
 2329: {
 2330: /* -------------------------------------------------------------------------
 2331: Allocations and Declarations
 2332: -------------------------------------------------------------------------- */
 2333: int	irow=0, icol=0,		/* indexes over rp raster */
 2334: 	locol=col0, hicol=col1,	/* col limits at irow */
 2335: 	lorow=row0, hirow=row1;	/* row limits at icol */
 2336: int	width=rp->width, height=rp->height; /* dimensions of input raster */
 2337: int	ipix = 0,		/* raster pixmap[] index */
 2338: 	npix = width*height;	/* #pixels malloced in rp->pixmap[] */
 2339: int	isfatal = 0;		/* true to abend on out-of-bounds error */
 2340: int	isline=(row1==row0), isbar=(col1==col0); /*true if slope a=0,\infty*/
 2341: double	dy = row1-row0 /* + (row1>=row0? +1.0 : -1.0) */, /* delta-x */
 2342: 	dx = col1-col0 /* + (col1>=col0? +1.0 : -1.0) */, /* delta-y */
 2343: 	a= (isbar||isline? 0.0 : dy/dx), /* slope = tan(theta) = dy/dx */
 2344: 	xcol=0, xrow=0;		/* calculated col at irow, or row at icol */
 2345: double	ar = ASPECTRATIO,	/* aspect ratio width/height of one pixel */
 2346: 	xwidth= (isline? 0.0 :	/*#pixels per row to get sloped line thcknss*/
 2347: 		((double)thickness)*sqrt((dx*dx)+(dy*dy*ar*ar))/fabs(dy*ar)),
 2348: 	xheight = 1.0;
 2349: int	line_recurse(), isrecurse=1; /* true to draw line recursively */
 2350: /* -------------------------------------------------------------------------
 2351: Check args
 2352: -------------------------------------------------------------------------- */
 2353: if ( rp == (raster *)NULL ) {	/* no raster arg supplied */
 2354:   if ( workingbox != (subraster *)NULL )  /* see if we have a workingbox */
 2355:     rp = workingbox->image;	/* use workingbox if possible */
 2356:   else return ( 0 ); }		/* otherwise signal error to caller */
 2357: /* -------------------------------------------------------------------------
 2358: Initialization
 2359: -------------------------------------------------------------------------- */
 2360: if ( msgfp!=NULL && msglevel>=29 ) {		/* debugging */
 2361:    fprintf(msgfp,"line_raster> row,col0=%d,%d row,col1=%d,%d, thickness=%d\n"
 2362:    "\t dy,dx=%3.1f,%3.1f, a=%4.3f, xwidth=%4.3f\n",
 2363:    row0,col0, row1,col1, thickness,  dy,dx, a, xwidth); fflush(msgfp); }
 2364: /* --- check for recursive line drawing --- */
 2365: if ( isrecurse ) {		/* drawing lines recursively */
 2366:  for ( irow=0; irow<thickness; irow++ )		/* each line 1 pixel thick */
 2367:   { double xrow0=(double)row0, xcol0=(double)col0,
 2368: 	xrow1=(double)row1, xcol1=(double)col1;
 2369:     if ( isline ) xrow0 = xrow1 = (double)(row0+irow);
 2370:     else if ( isbar ) xcol0 = xcol1 = (double)(col0+irow);
 2371:     if( xrow0>(-0.001) && xcol0>(-0.001)	/*check line inside raster*/
 2372:     &&  xrow1<((double)(height-1)+0.001) && xcol1<((double)(width-1)+0.001) )
 2373:       line_recurse(rp,xrow0,xcol0,xrow1,xcol1,thickness); }
 2374:  return ( 1 ); }
 2375: /* --- set params for horizontal line or vertical bar --- */
 2376: if ( isline )					/*interpret row as top row*/
 2377:   row1 = row0 + (thickness-1);			/* set bottom row for line */
 2378: if ( 0&&isbar )					/*interpret col as left col*/
 2379:   hicol = col0 + (thickness-1);			/* set right col for bar */
 2380: /* -------------------------------------------------------------------------
 2381: draw line one row at a time
 2382: -------------------------------------------------------------------------- */
 2383: for ( irow=min2(row0,row1); irow<=max2(row0,row1); irow++ ) /*each scan line*/
 2384:   {
 2385:   if ( !isbar && !isline )			/* neither vert nor horiz */
 2386:     { xcol  = col0 + ((double)(irow-row0))/a;	/* "middle" col in irow */
 2387:       locol = max2((int)(xcol-0.5*(xwidth-1.0)),0); /* leftmost col */
 2388:       hicol = min2((int)(xcol+0.5*(xwidth-0.0)),max2(col0,col1)); } /*right*/
 2389:   if ( msgfp!=NULL && msglevel>=29 )		/* debugging */
 2390:     fprintf(msgfp,"\t irow=%d, xcol=%4.2f, lo,hicol=%d,%d\n",
 2391:     irow,xcol,locol,hicol);
 2392:   ipix = irow*rp->width + min2(locol,hicol) - 1; /*first pix preceding icol*/
 2393:   for ( icol=min2(locol,hicol); icol<=max2(locol,hicol); icol++ ) /*each pix*/
 2394:     if ( ++ipix >= npix )			/* bounds check failed */
 2395: 	if ( isfatal ) goto end_of_job;	/* abort if error is fatal */
 2396: 	else break;				/*or just go on to next row*/
 2397:     else					/* turn on pixel in line */
 2398: 	if ( rp->pixsz == 1 )			/* have a pixel bitmap */
 2399: 	  setlongbit(rp->pixmap,ipix);		/* so turn on bit in line */
 2400: 	else					/* should have a bytemap */
 2401: 	 if ( rp->pixsz == 8 )			/* check pixsz for bytemap */
 2402: 	  ((unsigned char *)(rp->pixmap))[ipix] = 255; /* set black byte */
 2403:   } /* --- end-of-for(irow) --- */
 2404: /* -------------------------------------------------------------------------
 2405: now _redraw_ line one col at a time to avoid "gaps"
 2406: -------------------------------------------------------------------------- */
 2407: if ( 1 )
 2408:  for ( icol=min2(col0,col1); icol<=max2(col0,col1); icol++ )/*each scan line*/
 2409:   {
 2410:   if ( !isbar && !isline )			/* neither vert nor horiz */
 2411:     { xrow  = row0 + ((double)(icol-col0))*a;	/* "middle" row in icol */
 2412:       lorow = max2((int)(xrow-0.5*(xheight-1.0)),0); /* topmost row */
 2413:       hirow = min2((int)(xrow+0.5*(xheight-0.0)),max2(row0,row1)); } /*bot*/
 2414:   if ( msgfp!=NULL && msglevel>=29 )		/* debugging */
 2415:     fprintf(msgfp,"\t icol=%d, xrow=%4.2f, lo,hirow=%d,%d\n",
 2416:     icol,xrow,lorow,hirow);
 2417:   ipix = irow*rp->width + min2(locol,hicol) - 1; /*first pix preceding icol*/
 2418:   for ( irow=min2(lorow,hirow); irow<=max2(lorow,hirow); irow++ ) /*each pix*/
 2419:     if ( irow<0 || irow>=rp->height
 2420:     ||   icol<0 || icol>=rp->width )		/* bounds check */
 2421:       if ( isfatal ) goto end_of_job;		/* abort if error is fatal */
 2422:       else continue;				/*or just go on to next row*/
 2423:     else
 2424:       setpixel(rp,irow,icol,255);		/* set pixel at irow,icol */
 2425:   } /* --- end-of-for(irow) --- */
 2426: /* -------------------------------------------------------------------------
 2427: Back to caller with 1=okay, 0=failed.
 2428: -------------------------------------------------------------------------- */
 2429: end_of_job:
 2430:   return ( isfatal? (ipix<npix? 1:0) : 1 );
 2431: } /* --- end-of-function line_raster() --- */
 2432: 
 2433: 
 2434: /* ==========================================================================
 2435:  * Function:	line_recurse ( rp,  row0, col0,  row1, col1,  thickness )
 2436:  * Purpose:	Draw a line from row0,col0 to row1,col1 of thickness
 2437:  *		in existing raster rp.
 2438:  * --------------------------------------------------------------------------
 2439:  * Arguments:	rp (I)		raster *  to raster in which a line
 2440:  *				will be drawn
 2441:  *		row0 (I)	double containing row at which
 2442:  *				line will start (0 is topmost)
 2443:  *		col0 (I)	double containing col at which
 2444:  *				line will start (0 is leftmost)
 2445:  *		row1 (I)	double containing row at which
 2446:  *				line will end (rp->height-1 is bottom-most)
 2447:  *		col1 (I)	double containing col at which
 2448:  *				line will end (rp->width-1 is rightmost)
 2449:  *		thickness (I)	int containing number of pixels/bits
 2450:  *				thick the line will be
 2451:  * --------------------------------------------------------------------------
 2452:  * Returns:	( int )		1 if line drawn okay,
 2453:  *				or 0 for any error.
 2454:  * --------------------------------------------------------------------------
 2455:  * Notes:     o	Recurses, drawing left- and right-halves of line
 2456:  *		until a horizontal or vertical segment is found
 2457:  * ======================================================================= */
 2458: /* --- entry point --- */
 2459: int	line_recurse ( raster *rp, double row0, double col0,
 2460: 	double row1, double col1, int thickness )
 2461: {
 2462: /* -------------------------------------------------------------------------
 2463: Allocations and Declarations
 2464: -------------------------------------------------------------------------- */
 2465: double	delrow = fabs(row1-row0),	/* 0 if line horizontal */
 2466: 	delcol = fabs(col1-col0),	/* 0 if line vertical */
 2467: 	tolerance = 0.5;		/* draw line when it goes to point */
 2468: double	midrow = 0.5*(row0+row1),	/* midpoint row */
 2469: 	midcol = 0.5*(col0+col1);	/* midpoint col */
 2470: /* -------------------------------------------------------------------------
 2471: recurse if either delta > tolerance
 2472: -------------------------------------------------------------------------- */
 2473: if ( delrow > tolerance			/* row hasn't converged */
 2474: ||   delcol > tolerance )		/* col hasn't converged */
 2475:   { line_recurse(rp,row0,col0,midrow,midcol,thickness); /* left half */
 2476:     line_recurse(rp,midrow,midcol,row1,col1,thickness); /* right half */
 2477:     return ( 1 ); }
 2478: /* -------------------------------------------------------------------------
 2479: draw converged point
 2480: -------------------------------------------------------------------------- */
 2481: setpixel(rp,iround(midrow),iround(midcol),255); /*set pixel at midrow,midcol*/
 2482: return ( 1 );
 2483: } /* --- end-of-function line_recurse() --- */
 2484: 
 2485: 
 2486: /* ==========================================================================
 2487:  * Function:	circle_raster ( rp,  row0, col0,  row1, col1,
 2488:  *		thickness, quads )
 2489:  * Purpose:	Draw quad(rant)s of an ellipse in box determined by
 2490:  *		diagonally opposite corner points (row0,col0) and
 2491:  *		(row1,col1), of thickness pixels in existing raster rp.
 2492:  * --------------------------------------------------------------------------
 2493:  * Arguments:	rp (I)		raster *  to raster in which an ellipse
 2494:  *				will be drawn
 2495:  *		row0 (I)	int containing 1st corner row bounding ellipse
 2496:  *				(0 is topmost)
 2497:  *		col0 (I)	int containing 1st corner col bounding ellipse
 2498:  *				(0 is leftmost)
 2499:  *		row1 (I)	int containing 2nd corner row bounding ellipse
 2500:  *				(rp->height-1 is bottom-most)
 2501:  *		col1 (I)	int containing 2nd corner col bounding ellipse
 2502:  *				(rp->width-1 is rightmost)
 2503:  *		thickness (I)	int containing number of pixels/bits
 2504:  *				thick the ellipse arc line will be
 2505:  *		quads (I)	char * to null-terminated string containing
 2506:  *				any subset/combination of "1234" specifying
 2507:  *				which quadrant(s) of ellipse to draw.
 2508:  *				NULL ptr draws all four quadrants;
 2509:  *				otherwise 1=upper-right quadrant,
 2510:  *				2=uper-left, 3=lower-left, 4=lower-right,
 2511:  *				i.e., counterclockwise from 1=positive quad.
 2512:  * --------------------------------------------------------------------------
 2513:  * Returns:	( int )		1 if ellipse drawn okay,
 2514:  *				or 0 for any error.
 2515:  * --------------------------------------------------------------------------
 2516:  * Notes:     o	row0==row1 or col0==col1 are errors
 2517:  *	      o	using ellipse equation x^2/a^2 + y^2/b^2 = 1
 2518:  * ======================================================================= */
 2519: /* --- entry point --- */
 2520: int	circle_raster ( raster *rp, int row0, int col0,
 2521: 	int row1, int col1, int thickness, char *quads )
 2522: {
 2523: /* -------------------------------------------------------------------------
 2524: Allocations and Declarations
 2525: -------------------------------------------------------------------------- */
 2526: /* --- lower-left and upper-right bounding points (in our coords) --- */
 2527: int	lorow = min2(row0,row1),	/* lower bounding row (top of box) */
 2528: 	locol = min2(col0,col1),	/* lower bounding col (left of box)*/
 2529: 	hirow = max2(row0,row1),	/* upper bounding row (bot of box) */
 2530: 	hicol = max2(col0,col1);	/* upper bounding col (right of box)*/
 2531: /* --- a and b ellipse params --- */
 2532: int	width = hicol-locol+1,		/* width of bounding box */
 2533: 	height= hirow-lorow+1,		/* height of bounding box */
 2534: 	islandscape = (width>=height? 1:0); /*true if ellipse lying on side*/
 2535: double	a = ((double)width)/2.0,	/* x=a when y=0 */
 2536: 	b = ((double)height)/2.0,	/* y=b when x=0 */
 2537: 	abmajor = (islandscape? a : b),	/* max2(a,b) */
 2538: 	abminor = (islandscape? b : a),	/* min2(a,b) */
 2539: 	abmajor2 = abmajor*abmajor,	/* abmajor^2 */
 2540: 	abminor2 = abminor*abminor;	/* abminor^2 */
 2541: /* --- other stuff --- */
 2542: int	imajor=0, nmajor=max2(width,height), /*index, #pixels on major axis*/
 2543: 	iminor=0, nminor=min2(width,height); /* solved index on minor axis */
 2544: int	irow, icol,			/* raster indexes at circumference */
 2545: 	rsign=1, csign=1;		/* row,col signs, both +1 in quad 1*/
 2546: double	midrow= ((double)(row0+row1))/2.0, /* center row */
 2547: 	midcol= ((double)(col0+col1))/2.0; /* center col */
 2548: double	xy, xy2,			/* major axis ellipse coord */
 2549: 	yx2, yx;			/* solved minor ellipse coord */
 2550: int	isokay = 1;			/* true if no pixels out-of-bounds */
 2551: char	*qptr=NULL, *allquads="1234";	/* quadrants if input quads==NULL */
 2552: int	circle_recurse(), isrecurse=1;	/* true to draw ellipse recursively*/
 2553: /* -------------------------------------------------------------------------
 2554: pixel-by-pixel along positive major axis, quit when it goes negative
 2555: -------------------------------------------------------------------------- */
 2556: if ( quads == NULL ) quads = allquads;	/* draw all quads, or only user's */
 2557: if ( msgfp!=NULL && msglevel>=39 )	/* debugging */
 2558:   fprintf(msgfp,"circle_raster> width,height;quads=%d,%d,%s\n",
 2559:   width,height,quads);
 2560: if ( nmajor < 1 ) isokay = 0;		/* problem with input args */
 2561: else
 2562:  {
 2563:  if ( isrecurse )			/* use recursive algorithm */
 2564:   {
 2565:   for ( qptr=quads; *qptr!='\000'; qptr++ ) /* for each character in quads */
 2566:    {
 2567:    double theta0=0.0, theta1=0.0;	/* set thetas based on quadrant */
 2568:    switch ( *qptr )			/* check for quadrant 1,2,3,4 */
 2569:     { default:				/* unrecognized, assume quadrant 1 */
 2570:       case '1': theta0=  0.0; theta1= 90.0; break;   /* first quadrant */
 2571:       case '2': theta0= 90.0; theta1=180.0; break;   /* second quadrant */
 2572:       case '3': theta0=180.0; theta1=270.0; break;   /* third quadrant */
 2573:       case '4': theta0=270.0; theta1=360.0; break; } /* fourth quadrant */
 2574:    circle_recurse(rp,row0,col0,row1,col1,thickness,theta0,theta1);
 2575:    } /* --- end-of-for(qptr) --- */
 2576:   return ( 1 );
 2577:   } /* --- end-of-if(isrecurse) --- */
 2578:  for ( imajor=(nmajor+1)/2; ; imajor-- )
 2579:   {
 2580:   /* --- xy is coord along major axis, yx is "solved" along minor axis --- */
 2581:   xy  = ((double)imajor);		/* xy = abmajor ... 0 */
 2582:   if ( xy < 0.0 ) break;		/* negative side symmetrical */
 2583:   yx2 = abminor2*(1.0 - xy*xy/abmajor2); /* "solve" ellipse equation */
 2584:   yx  = (yx2>0.0? sqrt(yx2) : 0.0);	/* take sqrt if possible */
 2585:   iminor = iround(yx);			/* nearest integer */
 2586:   /* --- set pixels for each requested quadrant --- */
 2587:   for ( qptr=quads; *qptr!='\000'; qptr++ ) /* for each character in quads */
 2588:    {
 2589:    rsign = (-1);  csign = 1;		/* init row,col in user quadrant 1 */
 2590:    switch ( *qptr )			/* check for quadrant 1,2,3,4 */
 2591:     { default: break;			/* unrecognized, assume quadrant 1 */
 2592:       case '4': rsign = 1; break;	/* row,col both pos in quadrant 4 */
 2593:       case '3': rsign = 1;		/* row pos, col neg in quadrant 3 */
 2594:       case '2': csign = (-1); break; }	/* row,col both neg in quadrant 2 */
 2595:    irow = iround(midrow + (double)rsign*(islandscape?yx:xy));
 2596:    irow = min2(hirow,max2(lorow,irow));	/* keep irow in bounds */
 2597:    icol = iround(midcol + (double)csign*(islandscape?xy:yx));
 2598:    icol = min2(hicol,max2(locol,icol));	/* keep icol in bounds */
 2599:    if ( msgfp!=NULL && msglevel>=49 )	/* debugging */
 2600:      fprintf(msgfp,"\t...imajor=%d; iminor,quad,irow,icol=%d,%c,%d,%d\n",
 2601:      imajor,iminor,*qptr,irow,icol);
 2602:    if ( irow<0 || irow>=rp->height	/* row outside raster */
 2603:    ||   icol<0 || icol>=rp->width )	/* col outside raster */
 2604:       {	isokay = 0;			/* signal out-of-bounds pixel */
 2605: 	continue; }			/* but still try remaining points */
 2606:    setpixel(rp,irow,icol,255);		/* set pixel at irow,icol */
 2607:    } /* --- end-of-for(qptr) --- */
 2608:   } /* --- end-of-for(imajor) --- */
 2609:  /* ------------------------------------------------------------------------
 2610:  now do it _again_ along minor axis to avoid "gaps"
 2611:  ------------------------------------------------------------------------- */
 2612:  if ( 1 && iminor>0 )
 2613:   for ( iminor=(nminor+1)/2; ; iminor-- )
 2614:    {
 2615:    /* --- yx is coord along minor axis, xy is "solved" along major axis --- */
 2616:    yx  = ((double)iminor);		/* yx = abminor ... 0 */
 2617:    if ( yx < 0.0 ) break;		/* negative side symmetrical */
 2618:    xy2 = abmajor2*(1.0 - yx*yx/abminor2); /* "solve" ellipse equation */
 2619:    xy  = (xy2>0.0? sqrt(xy2) : 0.0);	/* take sqrt if possible */
 2620:    imajor = iround(xy);			/* nearest integer */
 2621:    /* --- set pixels for each requested quadrant --- */
 2622:    for ( qptr=quads; *qptr!='\000'; qptr++ ) /* for each character in quads */
 2623:     {
 2624:     rsign = (-1);  csign = 1;		/* init row,col in user quadrant 1 */
 2625:     switch ( *qptr )			/* check for quadrant 1,2,3,4 */
 2626:      { default: break;			/* unrecognized, assume quadrant 1 */
 2627:        case '4': rsign = 1; break;	/* row,col both pos in quadrant 4 */
 2628:        case '3': rsign = 1;		/* row pos, col neg in quadrant 3 */
 2629:        case '2': csign = (-1); break; }	/* row,col both neg in quadrant 2 */
 2630:     irow = iround(midrow + (double)rsign*(islandscape?yx:xy));
 2631:     irow = min2(hirow,max2(lorow,irow)); /* keep irow in bounds */
 2632:     icol = iround(midcol + (double)csign*(islandscape?xy:yx));
 2633:     icol = min2(hicol,max2(locol,icol)); /* keep icol in bounds */
 2634:     if ( msgfp!=NULL && msglevel>=49 )	/* debugging */
 2635:      fprintf(msgfp,"\t...iminor=%d; imajor,quad,irow,icol=%d,%c,%d,%d\n",
 2636:      iminor,imajor,*qptr,irow,icol);
 2637:     if ( irow<0 || irow>=rp->height	/* row outside raster */
 2638:     ||   icol<0 || icol>=rp->width )	/* col outside raster */
 2639:       {	isokay = 0;			/* signal out-of-bounds pixel */
 2640: 	continue; }			/* but still try remaining points */
 2641:     setpixel(rp,irow,icol,255);		/* set pixel at irow,icol */
 2642:     } /* --- end-of-for(qptr) --- */
 2643:    } /* --- end-of-for(iminor) --- */
 2644:  } /* --- end-of-if/else(nmajor<1) --- */
 2645: return ( isokay );
 2646: } /* --- end-of-function circle_raster() --- */
 2647: 
 2648: 
 2649: /* ==========================================================================
 2650:  * Function:	circle_recurse ( rp,  row0, col0,  row1, col1,
 2651:  *		thickness, theta0, theta1 )
 2652:  * Purpose:	Recursively draws arc theta0<=theta<=theta1 of the ellipse
 2653:  *		in box determined by diagonally opposite corner points
 2654:  *		(row0,col0) and (row1,col1), of thickness pixels in raster rp.
 2655:  * --------------------------------------------------------------------------
 2656:  * Arguments:	rp (I)		raster *  to raster in which an ellipse
 2657:  *				will be drawn
 2658:  *		row0 (I)	int containing 1st corner row bounding ellipse
 2659:  *				(0 is topmost)
 2660:  *		col0 (I)	int containing 1st corner col bounding ellipse
 2661:  *				(0 is leftmost)
 2662:  *		row1 (I)	int containing 2nd corner row bounding ellipse
 2663:  *				(rp->height-1 is bottom-most)
 2664:  *		col1 (I)	int containing 2nd corner col bounding ellipse
 2665:  *				(rp->width-1 is rightmost)
 2666:  *		thickness (I)	int containing number of pixels/bits
 2667:  *				thick the ellipse arc line will be
 2668:  *		theta0 (I)	double containing first angle -360 -> +360
 2669:  *		theta1 (I)	double containing second angle -360 -> +360
 2670:  *				0=x-axis, positive moving counterclockwise
 2671:  * --------------------------------------------------------------------------
 2672:  * Returns:	( int )		1 if ellipse drawn okay,
 2673:  *				or 0 for any error.
 2674:  * --------------------------------------------------------------------------
 2675:  * Notes:     o	row0==row1 or col0==col1 are errors
 2676:  *	      o	using ellipse equation x^2/a^2 + y^2/b^2 = 1
 2677:  *		Then, with x=r*cos(theta), y=r*sin(theta), ellipse
 2678:  *		equation is r = ab/sqrt(a^2*sin^2(theta)+b^2*cos^2(theta))
 2679:  * ======================================================================= */
 2680: /* --- entry point --- */
 2681: int	circle_recurse ( raster *rp, int row0, int col0,
 2682: 	int row1, int col1, int thickness, double theta0, double theta1 )
 2683: {
 2684: /* -------------------------------------------------------------------------
 2685: Allocations and Declarations
 2686: -------------------------------------------------------------------------- */
 2687: /* --- lower-left and upper-right bounding points (in our coords) --- */
 2688: int	lorow = min2(row0,row1),	/* lower bounding row (top of box) */
 2689: 	locol = min2(col0,col1),	/* lower bounding col (left of box)*/
 2690: 	hirow = max2(row0,row1),	/* upper bounding row (bot of box) */
 2691: 	hicol = max2(col0,col1);	/* upper bounding col (right of box)*/
 2692: /* --- a and b ellipse params --- */
 2693: int	width = hicol-locol+1,		/* width of bounding box */
 2694: 	height= hirow-lorow+1;		/* height of bounding box */
 2695: double	a = ((double)width)/2.0,	/* col x=a when row y=0 */
 2696: 	b = ((double)height)/2.0,	/* row y=b when col x=0 */
 2697: 	ab=a*b, a2=a*a, b2=b*b;		/* product and squares */
 2698: /* --- arc parameters --- */
 2699: double	rads = 0.017453292,		/* radians per degree = 1/57.29578 */
 2700: 	lotheta = rads*dmod(min2(theta0,theta1),360), /* smaller angle */
 2701: 	hitheta = rads*dmod(max2(theta0,theta1),360), /* larger angle */
 2702: 	locos=cos(lotheta), losin=sin(lotheta), /* trigs for lotheta */
 2703: 	hicos=cos(hitheta), hisin=sin(hitheta), /* trigs for hitheta */
 2704: 	rlo = ab/sqrt(b2*locos*locos+a2*losin*losin), /* r for lotheta */
 2705: 	rhi = ab/sqrt(b2*hicos*hicos+a2*hisin*hisin), /* r for hitheta */
 2706: 	xlo=rlo*locos, ylo=rlo*losin,	/*col,row pixel coords for lotheta*/
 2707: 	xhi=rhi*hicos, yhi=rhi*hisin,	/*col,row pixel coords for hitheta*/
 2708: 	xdelta=fabs(xhi-xlo), ydelta=fabs(yhi-ylo), /* col,row deltas */
 2709: 	tolerance = 0.5;		/* convergence tolerance */
 2710: /* -------------------------------------------------------------------------
 2711: recurse if either delta > tolerance
 2712: -------------------------------------------------------------------------- */
 2713: if ( ydelta > tolerance			/* row hasn't converged */
 2714: ||   xdelta > tolerance )		/* col hasn't converged */
 2715:   { double midtheta = 0.5*(theta0+theta1); /* mid angle for arc */
 2716:     circle_recurse(rp,row0,col0,row1,col1,thickness,theta0,midtheta);  /*lo*/
 2717:     circle_recurse(rp,row0,col0,row1,col1,thickness,midtheta,theta1); }/*hi*/
 2718: /* -------------------------------------------------------------------------
 2719: draw converged point
 2720: -------------------------------------------------------------------------- */
 2721: else
 2722:   { double xcol=0.5*(xlo+xhi), yrow=0.5*(ylo+yhi),    /* relative to center*/
 2723: 	centerrow = 0.5*((double)(lorow+hirow)),      /* ellipse y-center */
 2724: 	centercol = 0.5*((double)(locol+hicol)),      /* ellipse x-center */
 2725: 	midrow=centerrow-yrow, midcol=centercol+xcol; /* pixel coords */
 2726:     setpixel(rp,iround(midrow),iround(midcol),255); } /* set midrow,midcol */
 2727: return ( 1 );
 2728: } /* --- end-of-function circle_recurse() --- */
 2729: 
 2730: 
 2731: /* ==========================================================================
 2732:  * Function:	bezier_raster ( rp, r0,c0, r1,c1, rt,ct )
 2733:  * Purpose:	Recursively draw bezier from r0,c0 to r1,c1
 2734:  *		(with tangent point rt,ct) in existing raster rp.
 2735:  * --------------------------------------------------------------------------
 2736:  * Arguments:	rp (I)		raster *  to raster in which a line
 2737:  *				will be drawn
 2738:  *		r0 (I)		double containing row at which
 2739:  *				bezier will start (0 is topmost)
 2740:  *		c0 (I)		double containing col at which
 2741:  *				bezier will start (0 is leftmost)
 2742:  *		r1 (I)		double containing row at which
 2743:  *				bezier will end (rp->height-1 is bottom-most)
 2744:  *		c1 (I)		double containing col at which
 2745:  *				bezier will end (rp->width-1 is rightmost)
 2746:  *		rt (I)		double containing row for tangent point
 2747:  *		ct (I)		double containing col for tangent point
 2748:  * --------------------------------------------------------------------------
 2749:  * Returns:	( int )		1 if line drawn okay,
 2750:  *				or 0 for any error.
 2751:  * --------------------------------------------------------------------------
 2752:  * Notes:     o	Recurses, drawing left- and right-halves of bezier curve
 2753:  *		until a point is found
 2754:  * ======================================================================= */
 2755: /* --- entry point --- */
 2756: int	bezier_raster ( raster *rp, double r0, double c0,
 2757: 	double r1, double c1, double rt, double ct )
 2758: {
 2759: /* -------------------------------------------------------------------------
 2760: Allocations and Declarations
 2761: -------------------------------------------------------------------------- */
 2762: double	delrow = fabs(r1-r0),		/* 0 if same row */
 2763: 	delcol = fabs(c1-c0),		/* 0 if same col */
 2764: 	tolerance = 0.5;		/* draw curve when it goes to point*/
 2765: double	midrow = 0.5*(r0+r1),		/* midpoint row */
 2766: 	midcol = 0.5*(c0+c1);		/* midpoint col */
 2767: int	irow=0, icol=0;			/* point to be drawn */
 2768: int	status = 1;			/* return status */
 2769: /* -------------------------------------------------------------------------
 2770: recurse if either delta > tolerance
 2771: -------------------------------------------------------------------------- */
 2772: if ( delrow > tolerance			/* row hasn't converged */
 2773: ||   delcol > tolerance )		/* col hasn't converged */
 2774:   { bezier_raster(rp, r0,c0,		/* left half */
 2775: 	0.5*(rt+midrow), 0.5*(ct+midcol),
 2776: 	0.5*(r0+rt), 0.5*(c0+ct) );
 2777:     bezier_raster(rp, 0.5*(rt+midrow), 0.5*(ct+midcol), /* right half */
 2778: 	r1,c1,
 2779: 	0.5*(r1+rt), 0.5*(c1+ct) );
 2780:     return ( 1 ); }
 2781: /* -------------------------------------------------------------------------
 2782: draw converged point
 2783: -------------------------------------------------------------------------- */
 2784: /* --- get integer point --- */
 2785: irow = iround(midrow);			/* row pixel coord */
 2786: icol = iround(midcol);			/* col pixel coord */
 2787: /* --- bounds check --- */
 2788: if ( irow>=0 && irow<rp->height		/* row in bounds */
 2789: &&   icol>=0 && icol<rp->width )	/* col in bounds */
 2790: 	setpixel(rp,irow,icol,255);	/* so set pixel at irow,icol*/
 2791: else	status = 0;			/* bad status if out-of-bounds */
 2792: return ( status );
 2793: } /* --- end-of-function bezier_raster() --- */
 2794: 
 2795: 
 2796: /* ==========================================================================
 2797:  * Function:	border_raster ( rp, ntop, nbot, isline, isfree )
 2798:  * Purpose:	Allocate a new raster containing a copy of input rp,
 2799:  *		along with ntop extra rows at top and nbot at bottom,
 2800:  *		and whose width is either adjusted correspondingly,
 2801:  *		or is automatically enlarged to a multiple of 8
 2802:  *		with original bitmap centered
 2803:  * --------------------------------------------------------------------------
 2804:  * Arguments:	rp (I)		raster *  to raster on which a border
 2805:  *				is to be placed
 2806:  *		ntop (I)	int containing number extra rows at top.
 2807:  *				if negative, abs(ntop) used, and same
 2808:  *				number of extra cols added at left.
 2809:  *		nbot (I)	int containing number extra rows at bottom.
 2810:  *				if negative, abs(nbot) used, and same
 2811:  *				number of extra cols added at right.
 2812:  *		isline (I)	int containing 0 to leave border pixels clear
 2813:  *				or >0 to draw a line around border of width
 2814:  *				isline.
 2815:  *		isfree (I)	int containing true to free rp before return
 2816:  * --------------------------------------------------------------------------
 2817:  * Returns:	( raster * )	ptr to bordered raster,
 2818:  *				or NULL for any error.
 2819:  * --------------------------------------------------------------------------
 2820:  * Notes:     o
 2821:  * ======================================================================= */
 2822: /* --- entry point --- */
 2823: raster	*border_raster ( raster *rp, int ntop, int nbot,
 2824: 			int isline, int isfree )
 2825: {
 2826: /* -------------------------------------------------------------------------
 2827: Allocations and Declarations
 2828: -------------------------------------------------------------------------- */
 2829: raster	*new_raster(), *bp=(raster *)NULL;  /*raster back to caller*/
 2830: int	rastput();		/* overlay rp in new bordered raster */
 2831: int	width  = (rp==NULL?0:rp->width),  /* width of raster */
 2832: 	height = (rp==NULL?0:rp->height), /* height of raster */
 2833: 	istopneg=0, isbotneg=0,		/* true if ntop or nbot negative */
 2834: 	leftmargin = 0;		/* adjust width to whole number of bytes */
 2835: int	delete_raster();		/* free input rp if isfree is true */
 2836: /* -------------------------------------------------------------------------
 2837: Initialization
 2838: -------------------------------------------------------------------------- */
 2839: if ( rp == NULL ) goto end_of_job;	/* no input raster provided */
 2840: if ( isstring || (1 && rp->height==1) )	/* explicit string signal or infer */
 2841:   { bp=rp; goto end_of_job; }		/* return ascii string unchanged */
 2842: /* --- check for negative args --- */
 2843: if ( ntop < 0 ) { ntop = -ntop; istopneg=1; } /*flip positive and set flag*/
 2844: if ( nbot < 0 ) { nbot = -nbot; isbotneg=1; } /*flip positive and set flag*/
 2845: /* --- adjust height for ntop and nbot margins --- */
 2846: height += (ntop+nbot);			/* adjust height for margins */
 2847: /* --- adjust width for left and right margins --- */
 2848: if ( istopneg || isbotneg )	/*caller wants nleft=ntop and/or nright=nbot*/
 2849:   { /* --- adjust width (and leftmargin) as requested by caller -- */
 2850:     if ( istopneg ) { width += ntop; leftmargin = ntop; }
 2851:     if ( isbotneg )   width += nbot;  }
 2852: else
 2853:   { /* --- or adjust width (and leftmargin) to whole number of bytes --- */
 2854:     leftmargin = (width%8==0? 0 : 8-(width%8)); /*makes width multiple of 8*/
 2855:     width += leftmargin;		/* width now multiple of 8 */
 2856:     leftmargin /= 2; }			/* center original raster */
 2857: /* -------------------------------------------------------------------------
 2858: allocate bordered raster, and embed rp within it
 2859: -------------------------------------------------------------------------- */
 2860: /* --- allocate bordered raster --- */
 2861: if ( (bp=new_raster(width,height,rp->pixsz))  /*allocate bordered raster*/
 2862: ==   (raster *)NULL ) goto end_of_job;	/* and quit if failed */
 2863: /* --- embed rp in it --- */
 2864: rastput(bp,rp,ntop,leftmargin,1);	/* rp embedded in bp */
 2865: /* -------------------------------------------------------------------------
 2866: draw border if requested
 2867: -------------------------------------------------------------------------- */
 2868: if ( isline )
 2869:  { int	irow, icol, nthick=isline;	/*height,width index, line thickness*/
 2870:   /* --- draw left- and right-borders --- */
 2871:   for ( irow=0; irow<height; irow++ )	/* for each row of bp */
 2872:     for ( icol=0; icol<nthick; icol++ )	/* and each pixel of thickness */
 2873:       {	setpixel(bp,irow,icol,255);	/* left border */
 2874: 	setpixel(bp,irow,width-1-icol,255); } /* right border */
 2875:   /* --- draw top- and bottom-borders --- */
 2876:   for ( icol=0; icol<width; icol++ )	/* for each col of bp */
 2877:     for ( irow=0; irow<nthick; irow++ )	/* and each pixel of thickness */
 2878:       {	setpixel(bp,irow,icol,255);	/* top border */
 2879: 	setpixel(bp,height-1-irow,icol,255); } /* bottom border */
 2880:  } /* --- end-of-if(isline) --- */
 2881: /* -------------------------------------------------------------------------
 2882: free rp if no longer needed
 2883: -------------------------------------------------------------------------- */
 2884: if ( isfree )					/*caller no longer needs rp*/
 2885:   delete_raster(rp);				/* so free it for him */
 2886: /* -------------------------------------------------------------------------
 2887: Back to caller with bordered raster (or null for any error)
 2888: -------------------------------------------------------------------------- */
 2889: end_of_job:
 2890:   return ( bp );			/* back with bordered or null ptr */
 2891: } /* --- end-of-function border_raster() --- */
 2892: 
 2893: 
 2894: /* ==========================================================================
 2895:  * Function:	backspace_raster ( rp, nback, pback, minspace, isfree )
 2896:  * Purpose:	Allocate a new raster containing a copy of input rp,
 2897:  *		but with trailing nback columns removed.
 2898:  *		If minspace>=0 then (at least) that many columns
 2899:  *		of whitespace will be left in place, regardless of nback.
 2900:  *		If minspace<0 then existing black pixels will be deleted
 2901:  *		as required.
 2902:  * --------------------------------------------------------------------------
 2903:  * Arguments:	rp (I)		raster *  to raster on which a border
 2904:  *				is to be placed
 2905:  *		nback (I)	int containing number of columns to
 2906:  *				backspace (>=0)
 2907:  *		pback (O)	ptr to int returning #pixels actually
 2908:  *				backspaced (or NULL to not use)
 2909:  *		minspace (I)	int containing number of columns
 2910:  *				of whitespace to be left in place
 2911:  *		isfree (I)	int containing true to free rp before return
 2912:  * --------------------------------------------------------------------------
 2913:  * Returns:	( raster * )	ptr to backspaced raster,
 2914:  *				or NULL for any error.
 2915:  * --------------------------------------------------------------------------
 2916:  * Notes:     o	For \! negative space, for \hspace{-10}, etc.
 2917:  * ======================================================================= */
 2918: /* --- entry point --- */
 2919: raster	*backspace_raster ( raster *rp, int nback, int *pback, int minspace,
 2920: 	int isfree )
 2921: {
 2922: /* -------------------------------------------------------------------------
 2923: Allocations and Declarations
 2924: -------------------------------------------------------------------------- */
 2925: raster	*new_raster(), *bp=(raster *)NULL;  /* raster returned to caller */
 2926: int	delete_raster();		/* free input rp if isfree is true */
 2927: int	width  = (rp==NULL?0:rp->width),  /* original width of raster */
 2928: 	height = (rp==NULL?0:rp->height), /* height of raster */
 2929: 	mback = nback,			/* nback adjusted for minspace */
 2930: 	newwidth = width,		/* adjusted width after backspace */
 2931: 	icol=0, irow=0;			/* col,row index */
 2932: if ( rp == NULL ) goto end_of_job;	/* no input given */
 2933: /* -------------------------------------------------------------------------
 2934: locate rightmost column of rp containing ink, and determine backspaced width
 2935: -------------------------------------------------------------------------- */
 2936: /* --- locate rightmost column of rp containing ink --- */
 2937: if ( minspace >= 0 )			/* only needed if given minspace */
 2938:  for ( icol=width-1; icol>=0; icol-- )	/* find first non-empty col in row */
 2939:   for ( irow=0; irow<height; irow++ )	/* for each row inside rp */
 2940:    if ( getpixel(rp,irow,icol) != 0 ) {	/* found a set pixel */
 2941:      int whitecols = (width-1) - icol;	/* #cols containing white space */
 2942:      mback = min2(nback,max2(0,whitecols-minspace)); /*leave minspace cols*/
 2943:      goto gotright; }			/* no need to look further */
 2944: /* --- determine width of new backspaced raster --- */
 2945: gotright:				/* found col with ink (or rp empty)*/
 2946:   if ( mback > width ) mback = width;	/* can't backspace before beginning*/
 2947:   newwidth = max2(1,width-mback);	/* #cols in backspaced raster */
 2948:   if ( pback != NULL ) *pback = width-newwidth; /* caller wants #pixels */
 2949: /* -------------------------------------------------------------------------
 2950: allocate new raster and fill it with leftmost cols of rp
 2951: -------------------------------------------------------------------------- */
 2952: /* --- allocate backspaced raster --- */
 2953: if ( (bp=new_raster(newwidth,height,rp->pixsz)) /*allocate backspaced raster*/
 2954: ==   (raster *)NULL ) goto end_of_job;	/* and quit if failed */
 2955: /* --- fill new raster --- */
 2956: if ( width-nback > 0 )			/* don't fill 1-pixel wide empty bp*/
 2957:  for ( icol=0; icol<newwidth; icol++ )	/* find first non-empty col in row */
 2958:   for ( irow=0; irow<height; irow++ )	/* for each row inside rp */
 2959:     { int value = getpixel(rp,irow,icol); /* original pixel at irow,icol */
 2960:       setpixel(bp,irow,icol,value); }	/* saved in backspaced raster */
 2961: /* -------------------------------------------------------------------------
 2962: Back to caller with backspaced raster (or null for any error)
 2963: -------------------------------------------------------------------------- */
 2964: end_of_job:
 2965:   if ( msgfp!=NULL && msglevel>=999 ) { fprintf(msgfp, /* diagnostics */
 2966:    "backspace_raster> nback=%d,minspace=%d,mback=%d, width:old=%d,new=%d\n",
 2967:    nback,minspace,mback,width,newwidth); fflush(msgfp); }
 2968:   if ( isfree && bp!=NULL ) delete_raster(rp); /* free original raster */
 2969:   return ( bp );			/* back with backspaced or null ptr*/
 2970: } /* --- end-of-function backspace_raster() --- */
 2971: 
 2972: 
 2973: /* ==========================================================================
 2974:  * Function:	type_raster ( rp, fp )
 2975:  * Purpose:	Emit an ascii dump representing rp, on fp.
 2976:  * --------------------------------------------------------------------------
 2977:  * Arguments:	rp (I)		ptr to raster struct for which an
 2978:  *				ascii dump is to be constructed.
 2979:  *		fp (I)		File ptr to output device (defaults to
 2980:  *				stdout if passed as NULL).
 2981:  * --------------------------------------------------------------------------
 2982:  * Returns:	( int )		1 if completed successfully,
 2983:  *				or 0 otherwise (for any error).
 2984:  * --------------------------------------------------------------------------
 2985:  * Notes:
 2986:  * ======================================================================= */
 2987: /* --- entry point --- */
 2988: int	type_raster ( raster *rp, FILE *fp )
 2989: {
 2990: /* -------------------------------------------------------------------------
 2991: Allocations and Declarations
 2992: -------------------------------------------------------------------------- */
 2993: static	int display_width = 72;		/* max columns for display */
 2994: static	char display_chars[16] =	/* display chars for bytemap */
 2995: 	{ ' ','1','2','3','4','5','6','7','8','9','A','B','C','D','E','*' };
 2996: char	scanline[133];			/* ascii image for one scan line */
 2997: int	scan_width;			/* #chars in scan (<=display_width)*/
 2998: int	irow, locol,hicol=(-1);		/* height index, width indexes */
 2999: raster	*gftobitmap(), *bitmaprp=rp;	/* convert .gf to bitmap if needed */
 3000: int	delete_raster();		/*free bitmap converted for display*/
 3001: /* --------------------------------------------------------------------------
 3002: initialization
 3003: -------------------------------------------------------------------------- */
 3004: /* --- redirect null fp --- */
 3005: if ( fp == (FILE *)NULL ) fp = stdout;	/* default fp to stdout if null */
 3006: if ( msglevel >= 999 ) { fprintf(fp,	/* debugging diagnostics */
 3007:   "type_raster> width=%d height=%d ...\n",
 3008:   rp->width,rp->height); fflush(fp); }
 3009: /* --- check for ascii string --- */
 3010: if ( isstring				/* pixmap has string, not raster */
 3011: ||   (0 && rp->height==1) )		/* infer input rp is a string */
 3012:  {
 3013:  char *string = (char *)(rp->pixmap);	/*interpret pixmap as ascii string*/
 3014:  int width = strlen(string);		/* #chars in ascii string */
 3015:  while ( width > display_width-2 )	/* too big for one line */
 3016:   { fprintf(fp,"\"%.*s\"\n",display_width-2,string); /*display leading chars*/
 3017:     string += (display_width-2);	/* bump string past displayed chars*/
 3018:     width -= (display_width-2); }	/* decrement remaining width */
 3019:  fprintf(fp,"\"%.*s\"\n",width,string);	/* display trailing chars */
 3020:  return ( 1 );
 3021:  } /* --- end-of-if(isstring) --- */
 3022: /* --------------------------------------------------------------------------
 3023: display ascii dump of bitmap image (in segments if display_width < rp->width)
 3024: -------------------------------------------------------------------------- */
 3025: if ( rp->format == 2			/* input is .gf-formatted */
 3026: ||   rp->format == 3 )
 3027:   bitmaprp = gftobitmap(rp);		/* so convert it for display */
 3028: if ( bitmaprp != NULL )			/* if we have image for display */
 3029:  while ( (locol=hicol+1) < rp->width )	/*start where prev segment left off*/
 3030:   {
 3031:   /* --- set hicol for this pass (locol set above) --- */
 3032:   hicol += display_width;		/* show as much as display allows */
 3033:   if (hicol >= rp->width) hicol = rp->width - 1; /*but not more than raster*/
 3034:   scan_width = hicol-locol+1;		/* #chars in this scan */
 3035:   if ( locol > 0 ) fprintf(fp,"----------\n"); /*separator between segments*/
 3036:   /* ------------------------------------------------------------------------
 3037:   display all scan lines for this local...hicol segment range
 3038:   ------------------------------------------------------------------------ */
 3039:   for ( irow=0; irow<rp->height; irow++ )  /* all scan lines for col range */
 3040:     {
 3041:     /* --- allocations and declarations --- */
 3042:     int	ipix,				/* pixmap[] index for this scan */
 3043: 	lopix = irow*rp->width + locol;	/*first pixmap[] pixel in this scan*/
 3044:     /* --- set chars in scanline[] based on pixels in rp->pixmap[] --- */
 3045:     for ( ipix=0; ipix<scan_width; ipix++ ) /* set each char */
 3046:       if ( bitmaprp->pixsz == 1 )	/*' '=0 or '*'=1 to display bitmap*/
 3047: 	scanline[ipix]=(getlongbit(bitmaprp->pixmap,lopix+ipix)==1? '*':'.');
 3048:       else				/* should have a bytemap */
 3049:        if ( bitmaprp->pixsz == 8 )	/* double-check pixsz for bytemap */
 3050: 	{ int pixval = (int)((bitmaprp->pixmap)[lopix+ipix]), /*byte value*/
 3051: 	  ichar = min2(15,pixval/16);	/* index for ' ', '1'...'e', '*' */
 3052: 	  scanline[ipix] = display_chars[ichar]; } /*set ' ' for 0-15, etc*/
 3053:     /* --- display completed scan line --- */
 3054:     fprintf(fp,"%.*s\n",scan_width,scanline);	
 3055:     } /* --- end-of-for(irow) --- */
 3056:   } /* --- end-of-while(hicol<rp->width) --- */
 3057: /* -------------------------------------------------------------------------
 3058: Back to caller with 1=okay, 0=failed.
 3059: -------------------------------------------------------------------------- */
 3060: if ( rp->format == 2			/* input was .gf-format */
 3061: ||   rp->format == 3 )
 3062:   if ( bitmaprp != NULL )		/* and we converted it for display */
 3063:     delete_raster(bitmaprp);		/* no longer needed, so free it */
 3064: return ( 1 );
 3065: } /* --- end-of-function type_raster() --- */
 3066: 
 3067: 
 3068: /* ==========================================================================
 3069:  * Function:	type_bytemap ( bp, grayscale, width, height, fp )
 3070:  * Purpose:	Emit an ascii dump representing bp, on fp.
 3071:  * --------------------------------------------------------------------------
 3072:  * Arguments:	bp (I)		intbyte * to bytemap for which an
 3073:  *				ascii dump is to be constructed.
 3074:  *		grayscale (I)	int containing #gray shades, 256 for 8-bit
 3075:  *		width (I)	int containing #cols in bytemap
 3076:  *		height (I)	int containing #rows in bytemap
 3077:  *		fp (I)		File ptr to output device (defaults to
 3078:  *				stdout if passed as NULL).
 3079:  * --------------------------------------------------------------------------
 3080:  * Returns:	( int )		1 if completed successfully,
 3081:  *				or 0 otherwise (for any error).
 3082:  * --------------------------------------------------------------------------
 3083:  * Notes:
 3084:  * ======================================================================= */
 3085: /* --- entry point --- */
 3086: int	type_bytemap ( intbyte *bp, int grayscale,
 3087: 			int width, int height, FILE *fp )
 3088: {
 3089: /* -------------------------------------------------------------------------
 3090: Allocations and Declarations
 3091: -------------------------------------------------------------------------- */
 3092: static	int display_width = 72;		/* max columns for display */
 3093: int	byte_width = 3,			/* cols to display byte (ff+space) */
 3094: 	maxbyte = 0;			/* if maxbyte<16, set byte_width=2 */
 3095: int	white_byte = 0,			/* show dots for white_byte's */
 3096: 	black_byte = grayscale-1;	/* show stars for black_byte's */
 3097: char	scanline[133];			/* ascii image for one scan line */
 3098: int	scan_width,			/* #chars in scan (<=display_width)*/
 3099: 	scan_cols;			/* #cols in scan (hicol-locol+1) */
 3100: int	ibyte,				/* bp[] index */
 3101: 	irow, locol,hicol=(-1);		/* height index, width indexes */
 3102: /* --------------------------------------------------------------------------
 3103: initialization
 3104: -------------------------------------------------------------------------- */
 3105: /* --- redirect null fp --- */
 3106: if ( fp == (FILE *)NULL ) fp = stdout;	/* default fp to stdout if null */
 3107: /* --- check for ascii string --- */
 3108: if ( isstring )				/* bp has ascii string, not raster */
 3109:  { width = strlen((char *)bp);		/* #chars in ascii string */
 3110:    height = 1; }			/* default */
 3111: /* --- see if we can get away with byte_width=1 --- */
 3112: for ( ibyte=0; ibyte<width*height; ibyte++ )  /* check all bytes */
 3113:   { int	byteval = (int)bp[ibyte];	/* current byte value */
 3114:     if ( byteval < black_byte )		/* if it's less than black_byte */
 3115:       maxbyte = max2(maxbyte,byteval); } /* then find max non-black value */
 3116: if ( maxbyte < 16 )			/* bytevals will fit in one column */
 3117:   byte_width = 1;			/* so reset display byte_width */
 3118: /* --------------------------------------------------------------------------
 3119: display ascii dump of bitmap image (in segments if display_width < rp->width)
 3120: -------------------------------------------------------------------------- */
 3121: while ( (locol=hicol+1) < width )	/*start where prev segment left off*/
 3122:   {
 3123:   /* --- set hicol for this pass (locol set above) --- */
 3124:   hicol += display_width/byte_width;	/* show as much as display allows */
 3125:   if (hicol >= width) hicol = width - 1; /* but not more than bytemap */
 3126:   scan_cols = hicol-locol+1;		/* #cols in this scan */
 3127:   scan_width = byte_width*scan_cols;	/* #chars in this scan */
 3128:   if ( locol>0 && !isstring ) fprintf(fp,"----------\n"); /* separator */
 3129:   /* ------------------------------------------------------------------------
 3130:   display all scan lines for this local...hicol segment range
 3131:   ------------------------------------------------------------------------ */
 3132:   for ( irow=0; irow<height; irow++ )	/* all scan lines for col range */
 3133:     {
 3134:     /* --- allocations and declarations --- */
 3135:     int  lobyte = irow*width + locol;	/* first bp[] byte in this scan */
 3136:     char scanbyte[32];			/* sprintf() buffer for byte */
 3137:     /* --- set chars in scanline[] based on bytes in bytemap bp[] --- */
 3138:     memset(scanline,' ',scan_width);	/* blank out scanline */
 3139:     for ( ibyte=0; ibyte<scan_cols; ibyte++ ) /* set chars for each col */
 3140:       {	int byteval = (int)bp[lobyte+ibyte];  /* value of current byte */
 3141: 	memset(scanbyte,'.',byte_width); /* dot-fill scanbyte */
 3142: 	if ( byteval == black_byte )	/* but if we have a black byte */
 3143: 	  memset(scanbyte,'*',byte_width); /* star-fill scanbyte instead */
 3144: 	if ( byte_width > 1 )		/* don't blank out single char */
 3145: 	  scanbyte[byte_width-1] = ' ';	/* blank-fill rightmost character */
 3146: 	if ( byteval != white_byte	/* format bytes that are non-white */
 3147: 	&&   byteval != black_byte )	/* and that are non-black */
 3148: 	  sprintf(scanbyte,"%*x ",max2(1,byte_width-1),byteval); /*hex-format*/
 3149: 	memcpy(scanline+ibyte*byte_width,scanbyte,byte_width); } /*in line*/
 3150:     /* --- display completed scan line --- */
 3151:     fprintf(fp,"%.*s\n",scan_width,scanline);	
 3152:     } /* --- end-of-for(irow) --- */
 3153:   } /* --- end-of-while(hicol<width) --- */
 3154: /* -------------------------------------------------------------------------
 3155: Back to caller with 1=okay, 0=failed.
 3156: -------------------------------------------------------------------------- */
 3157: return ( 1 );
 3158: } /* --- end-of-function type_bytemap() --- */
 3159: 
 3160: 
 3161: /* ==========================================================================
 3162:  * Function:	xbitmap_raster ( rp, fp )
 3163:  * Purpose:	Emit a mime xbitmap representing rp, on fp.
 3164:  * --------------------------------------------------------------------------
 3165:  * Arguments:	rp (I)		ptr to raster struct for which a mime
 3166:  *				xbitmap is to be constructed.
 3167:  *		fp (I)		File ptr to output device (defaults to
 3168:  *				stdout if passed as NULL).
 3169:  * --------------------------------------------------------------------------
 3170:  * Returns:	( int )		1 if completed successfully,
 3171:  *				or 0 otherwise (for any error).
 3172:  * --------------------------------------------------------------------------
 3173:  * Notes:
 3174:  * ======================================================================= */
 3175: /* --- entry point --- */
 3176: int	xbitmap_raster ( raster *rp, FILE *fp )
 3177: {
 3178: /* -------------------------------------------------------------------------
 3179: Allocations and Declarations
 3180: -------------------------------------------------------------------------- */
 3181: char	*title = "image";		/* dummy title */
 3182: int	hex_bitmap();			/* dump bitmap as hex bytes */
 3183: /* --------------------------------------------------------------------------
 3184: emit text to display mime xbitmap representation of rp->bitmap image
 3185: -------------------------------------------------------------------------- */
 3186: /* --- first redirect null fp --- */
 3187: if ( fp == (FILE *)NULL ) fp = stdout;	/* default fp to stdout if null */
 3188: /* --- check for ascii string --- */
 3189: if ( isstring )				/* pixmap has string, not raster */
 3190:  return ( 0 );				/* can't handle ascii string */
 3191: /* --- emit prologue strings and hex dump of bitmap for mime xbitmap --- */
 3192: fprintf( fp, "Content-type: image/x-xbitmap\n\n" );
 3193: fprintf( fp, "#define %s_width %d\n#define %s_height %d\n",
 3194: 	title,rp->width, title,rp->height );
 3195: fprintf( fp, "static char %s_bits[] = {\n", title );
 3196: hex_bitmap(rp,fp,0,0);			/* emit hex dump of bitmap bytes */
 3197: fprintf (fp,"};\n");			/* ending with "};" for C array */
 3198: /* -------------------------------------------------------------------------
 3199: Back to caller with 1=okay, 0=failed.
 3200: -------------------------------------------------------------------------- */
 3201: return ( 1 );
 3202: } /* --- end-of-function xbitmap_raster() --- */
 3203: 
 3204: 
 3205: /* ==========================================================================
 3206:  * Function:	type_pbmpgm ( rp, ptype, file )
 3207:  * Purpose:	Write pbm or pgm image of rp to file
 3208:  * --------------------------------------------------------------------------
 3209:  * Arguments:	rp (I)		ptr to raster struct for which
 3210:  *				a pbm/pgm file is to be written.
 3211:  *		ptype (I)	int containing 1 for pbm, 2 for pgm, or
 3212:  *				0 to determine ptype from values in rp
 3213:  *		file (I)	ptr to null-terminated char string
 3214:  *				containing name of fuke to be written
 3215:  *				(see notes below).
 3216:  * --------------------------------------------------------------------------
 3217:  * Returns:	( int )		total #bytes written,
 3218:  *				or 0 for any error.
 3219:  * --------------------------------------------------------------------------
 3220:  * Notes:     o	(a) If file==NULL, output is written to stdout;
 3221:  *		(b) if *file=='\000' then file is taken as the
 3222:  *		    address of an output buffer to which output
 3223:  *		    is written (and is followed by a terminating
 3224:  *		    '\0' which is not counted in #bytes returned);
 3225:  *		(c) otherwise file is the filename (opened and
 3226:  *		    closed internally) to which output is written,
 3227:  *		    except that any final .ext extension is replaced
 3228:  *		    by .pbm or .pgm depending on ptype.
 3229:  * ======================================================================= */
 3230: /* --- entry point --- */
 3231: int	type_pbmpgm ( raster *rp, int ptype, char *file )
 3232: {
 3233: /* -------------------------------------------------------------------------
 3234: Allocations and Declarations
 3235: -------------------------------------------------------------------------- */
 3236: int	isokay=0, nbytes=0;	/* completion flag, total #bytes written */
 3237: int	irow=0, jcol=0;		/*height(row), width(col) indexes in raster*/
 3238: int	pixmin=9999, pixmax=(-9999), /* min, max pixel value in raster */
 3239: 	ngray = 0;		/* #gray scale values */
 3240: FILE	/* *fopen(), */ *fp=NULL; /* pointer to output file (or NULL) */
 3241: char	outline[1024], outfield[256], /* output line, field */
 3242: 	cr[16] = "\n\000";	/* cr at end-of-line */
 3243: int	maxlinelen = 70;	/* maximum allowed line length */
 3244: int	pixfrac=6;		/* use (pixmax-pixmin)/pixfrac as step */
 3245: static	char
 3246: 	*suffix[] = { NULL, ".pbm", ".pgm" },	/* file.suffix[ptype] */
 3247: 	*magic[] = { NULL, "P1", "P2" },	/*identifying "magic number"*/
 3248: 	*mode[] = { NULL, "w", "w" };		/* fopen() mode[ptype] */
 3249: /* -------------------------------------------------------------------------
 3250: check input, determine grayscale,  and set up output file if necessary
 3251: -------------------------------------------------------------------------- */
 3252: /* --- check input args --- */
 3253: if ( rp == NULL ) goto end_of_job;	/* no input raster provided */
 3254: if ( ptype != 0 )			/* we'll determine ptype below */
 3255:  if ( ptype<1 || ptype>2 ) goto end_of_job; /*invalid output graphic format*/
 3256: /* --- determine largest (and smallest) value in pixmap --- */
 3257: for ( irow=0; irow<rp->height; irow++ )	/* for each row, top-to-bottom */
 3258:  for ( jcol=0; jcol<rp->width; jcol++ )	/* for each col, left-to-right */
 3259:   { int	pixval = getpixel(rp,irow,jcol);  /* value of pixel at irow,jcol */
 3260:     pixmin = min2(pixmin,pixval);	/* new minimum */
 3261:     pixmax = max2(pixmax,pixval); }	/* new maximum */
 3262: ngray = 1 + (pixmax-pixmin);		/* should be 2 for b/w bitmap */
 3263: if ( ptype == 0 )			/* caller wants us to set ptype */
 3264:   ptype = (ngray>=3?2:1);		/* use grayscale if >2 shades */
 3265: /* --- open output file if necessary --- */
 3266: if ( file == NULL ) fp = stdout;	/*null ptr signals output to stdout*/
 3267: else if ( *file != '\000' ) {		/* explicit filename provided, so...*/
 3268:   char	fname[512], *pdot=NULL;		/* file.ext, ptr to last . in fname*/
 3269:   strncpy(fname,file,255);		/* local copy of file name */
 3270:   fname[255] = '\000';			/* make sure it's null terminated */
 3271:   if ( (pdot=strrchr(fname,'.')) == NULL ) /*no extension on original name*/
 3272:     strcat(fname,suffix[ptype]);	/* so add extension */
 3273:   else					/* we already have an extension */
 3274:     strcpy(pdot,suffix[ptype]);		/* so replace original extension */
 3275:   if ( (fp = fopen(fname,mode[ptype]))	/* open output file */
 3276:   ==   (FILE *)NULL ) goto end_of_job;	/* quit if failed to open */
 3277:   } /* --- ens-of-if(*file!='\0') --- */
 3278: /* -------------------------------------------------------------------------
 3279: format and write header
 3280: -------------------------------------------------------------------------- */
 3281: /* --- format header info --- */
 3282: *outline = '\000';			/* initialize line buffer */
 3283: strcat(outline,magic[ptype]);		/* begin file with "magic number" */
 3284: strcat(outline,cr);			/* followed by cr to end line */
 3285: sprintf(outfield,"%d %d",rp->width,rp->height); /* format width and height */
 3286: strcat(outline,outfield);		/* add width and height to header */
 3287: strcat(outline,cr);			/* followed by cr to end line */
 3288: if ( ptype == 2 )			/* need max grayscale value */
 3289:   { sprintf(outfield,"%d",pixmax);	/* format maximum pixel value */
 3290:     strcat(outline,outfield);		/* add max value to header */
 3291:     strcat(outline,cr); }		/* followed by cr to end line */
 3292: /* --- write header to file or memory buffer --- */
 3293: if ( fp == NULL )			/* if we have no open file... */
 3294:   strcat(file,outline);			/* add header to caller's buffer */
 3295: else					/* or if we have an open file... */
 3296:   if ( fputs(outline,fp)		/* try writing header to open file */
 3297:   ==   EOF ) goto end_of_job;		/* return with error if failed */
 3298: nbytes += strlen(outline);		/* bump output byte count */
 3299: /* -------------------------------------------------------------------------
 3300: format and write pixels
 3301: -------------------------------------------------------------------------- */
 3302: *outline = '\000';			/* initialize line buffer */
 3303: for ( irow=0; irow<=rp->height; irow++ ) /* for each row, top-to-bottom */
 3304:  for ( jcol=0; jcol<rp->width; jcol++ )	{ /* for each col, left-to-right */
 3305:   /* --- format value at irow,jcol--- */
 3306:   *outfield = '\000';			/* init empty field */
 3307:   if ( irow < rp->height ) {		/* check row index */
 3308:     int	pixval = getpixel(rp,irow,jcol);  /* value of pixel at irow,jcol */
 3309:     if ( ptype == 1 )			/* pixval must be 1 or 0 */
 3310:       pixval = (pixval>pixmin+((pixmax-pixmin)/pixfrac)?1:0);
 3311:     sprintf(outfield,"%d ",pixval); }	/* format pixel value */
 3312:   /* --- write line if this value won't fit on it (or last line) --- */
 3313:   if ( strlen(outline)+strlen(outfield)+strlen(cr) >= maxlinelen /*won't fit*/
 3314:   ||   irow >= rp->height ) {		/* force writing last line */
 3315:     strcat(outline,cr);			/* add cr to end current line */
 3316:     if ( fp == NULL )			/* if we have no open file... */
 3317:       strcat(file,outline);		/* add header to caller's buffer */
 3318:     else				/* or if we have an open file... */
 3319:       if ( fputs(outline,fp)		/* try writing header to open file */
 3320:       ==   EOF ) goto end_of_job;	/* return with error if failed */
 3321:     nbytes += strlen(outline);		/* bump output byte count */
 3322:     *outline = '\000';			/* re-initialize line buffer */
 3323:     } /* --- end-of-if(strlen>=maxlinelen) --- */
 3324:   if ( irow >= rp->height ) break;	/* done after writing last line */
 3325:   /* --- concatanate value to line -- */
 3326:   strcat(outline,outfield);		/* concatanate value to line */
 3327:   } /* --- end-of-for(jcol,irow) --- */
 3328: isokay = 1;				/* signal successful completion */
 3329: /* -------------------------------------------------------------------------
 3330: Back to caller with total #bytes written, or 0=failed.
 3331: -------------------------------------------------------------------------- */
 3332: end_of_job:
 3333:   if ( fp != NULL			/* output written to an open file */
 3334:   &&   fp != stdout )			/* and it's not just stdout */
 3335:     fclose(fp);				/* so close file before returning */
 3336:   return ( (isokay?nbytes:0) );		/*back to caller with #bytes written*/
 3337: } /* --- end-of-function type_pbmpgm() --- */
 3338: 
 3339: 
 3340: /* ==========================================================================
 3341:  * Function:	cstruct_chardef ( cp, fp, col1 )
 3342:  * Purpose:	Emit a C struct of cp on fp, starting in col1.
 3343:  * --------------------------------------------------------------------------
 3344:  * Arguments:	cp (I)		ptr to chardef struct for which
 3345:  *				a C struct is to be generated.
 3346:  *		fp (I)		File ptr to output device (defaults to
 3347:  *				stdout if passed as NULL).
 3348:  *		col1 (I)	int containing 0...65; output lines
 3349:  *				are preceded by col1 blanks.
 3350:  * --------------------------------------------------------------------------
 3351:  * Returns:	( int )		1 if completed successfully,
 3352:  *				or 0 otherwise (for any error).
 3353:  * --------------------------------------------------------------------------
 3354:  * Notes:
 3355:  * ======================================================================= */
 3356: /* --- entry point --- */
 3357: int	cstruct_chardef ( chardef *cp, FILE *fp, int col1 )
 3358: {
 3359: /* -------------------------------------------------------------------------
 3360: Allocations and Declarations
 3361: -------------------------------------------------------------------------- */
 3362: char	field[64];		/* field within output line */
 3363: int	cstruct_raster(),	/* emit a raster */
 3364: 	emit_string();		/* emit a string and comment */
 3365: /* -------------------------------------------------------------------------
 3366: emit   charnum, location, name  /  hirow, hicol,  lorow, locol
 3367: -------------------------------------------------------------------------- */
 3368: /* --- charnum, location, name --- */
 3369: sprintf(field,"{ %3d,%5d,\n", cp->charnum,cp->location);  /*char#,location*/
 3370: emit_string ( fp, col1, field, "character number, location");
 3371: /* --- toprow, topleftcol,   botrow, botleftcol  --- */
 3372: sprintf(field,"  %3d,%2d,  %3d,%2d,\n",		/* format... */
 3373:   cp->toprow,cp->topleftcol,			/* toprow, topleftcol, */
 3374:   cp->botrow,cp->botleftcol);			/* and botrow, botleftcol */
 3375: emit_string ( fp, col1, field, "topleft row,col, and botleft row,col");
 3376: /* -------------------------------------------------------------------------
 3377: emit raster and chardef's closing brace, and then return to caller
 3378: -------------------------------------------------------------------------- */
 3379: cstruct_raster(&cp->image,fp,col1+4);		/* emit raster */
 3380: emit_string ( fp, 0, "  }", NULL);		/* emit closing brace */
 3381: return ( 1 );			/* back to caller with 1=okay, 0=failed */
 3382: } /* --- end-of-function cstruct_chardef() --- */
 3383: 
 3384: 
 3385: /* ==========================================================================
 3386:  * Function:	cstruct_raster ( rp, fp, col1 )
 3387:  * Purpose:	Emit a C struct of rp on fp, starting in col1.
 3388:  * --------------------------------------------------------------------------
 3389:  * Arguments:	rp (I)		ptr to raster struct for which
 3390:  *				a C struct is to be generated.
 3391:  *		fp (I)		File ptr to output device (defaults to
 3392:  *				stdout if passed as NULL).
 3393:  *		col1 (I)	int containing 0...65; output lines
 3394:  *				are preceded by col1 blanks.
 3395:  * --------------------------------------------------------------------------
 3396:  * Returns:	( int )		1 if completed successfully,
 3397:  *				or 0 otherwise (for any error).
 3398:  * --------------------------------------------------------------------------
 3399:  * Notes:
 3400:  * ======================================================================= */
 3401: /* --- entry point --- */
 3402: int	cstruct_raster ( raster *rp, FILE *fp, int col1 )
 3403: {
 3404: /* -------------------------------------------------------------------------
 3405: Allocations and Declarations
 3406: -------------------------------------------------------------------------- */
 3407: char	field[64];		/* field within output line */
 3408: char	typecast[64] = "(pixbyte *)"; /* type cast for pixmap string */
 3409: int	hex_bitmap();		/* to emit raster bitmap */
 3410: int	emit_string();		/* emit a string and comment */
 3411: /* -------------------------------------------------------------------------
 3412: emit width and height
 3413: -------------------------------------------------------------------------- */
 3414: sprintf(field,"{ %2d,  %3d,%2d,%2d, %s\n", /* format width,height,pixsz */
 3415: 	rp->width,rp->height,rp->format,rp->pixsz,typecast);
 3416: emit_string ( fp, col1, field, "width,ht, fmt,pixsz,map...");
 3417: /* -------------------------------------------------------------------------
 3418: emit bitmap and closing brace, and return to caller
 3419: -------------------------------------------------------------------------- */
 3420: hex_bitmap(rp,fp,col1+2,1);	/* emit bitmap */
 3421: emit_string ( fp, 0, " }", NULL); /* emit closing brace */
 3422: return ( 1 );			/* back to caller with 1=okay, 0=failed */
 3423: } /* --- end-of-function cstruct_raster() --- */
 3424: 
 3425: 
 3426: /* ==========================================================================
 3427:  * Function:	hex_bitmap ( rp, fp, col1, isstr )
 3428:  * Purpose:	Emit a hex dump of the bitmap of rp on fp, starting in col1.
 3429:  *		If isstr (is string) is true, the dump is of the form
 3430:  *			"\x01\x02\x03\x04\x05..."
 3431:  *		Otherwise, if isstr is false, the dump is of the form
 3432:  *			0x01,0x02,0x03,0x04,0x05...
 3433:  * --------------------------------------------------------------------------
 3434:  * Arguments:	rp (I)		ptr to raster struct for which
 3435:  *				a hex dump is to be constructed.
 3436:  *		fp (I)		File ptr to output device (defaults to
 3437:  *				stdout if passed as NULL).
 3438:  *		col1 (I)	int containing 0...65; output lines
 3439:  *				are preceded by col1 blanks.
 3440:  *		isstr (I)	int specifying dump format as described above
 3441:  * --------------------------------------------------------------------------
 3442:  * Returns:	( int )		1 if completed successfully,
 3443:  *				or 0 otherwise (for any error).
 3444:  * --------------------------------------------------------------------------
 3445:  * Notes:
 3446:  * ======================================================================= */
 3447: /* --- entry point --- */
 3448: int	hex_bitmap ( raster *rp, FILE *fp, int col1, int isstr )
 3449: {
 3450: /* -------------------------------------------------------------------------
 3451: Allocations and Declarations
 3452: -------------------------------------------------------------------------- */
 3453: int	ibyte,				/* pixmap[ibyte] index */
 3454: 	nbytes = pixbytes(rp);		/*#bytes in bitmap or .gf-formatted*/
 3455: char	stub[64]="                                ";/* col1 leading blanks */
 3456: int	linewidth = 64,			/* (roughly) rightmost column */
 3457: 	colwidth = (isstr? 4:5);	/* #cols required for each byte */
 3458: int	ncols = (linewidth-col1)/colwidth; /* new line after ncols bytes */
 3459: /* --------------------------------------------------------------------------
 3460: initialization
 3461: -------------------------------------------------------------------------- */
 3462: /* --- redirect null fp --- */
 3463: if ( fp == (FILE *)NULL ) fp = stdout;	/* default fp to stdout if null */
 3464: /* --- emit initial stub if wanted --- */
 3465: if ( col1 > 0 ) fprintf(fp,"%.*s",col1,stub); /* stub preceding 1st line */
 3466: /* --------------------------------------------------------------------------
 3467: emit hex dump of rp->bitmap image
 3468: -------------------------------------------------------------------------- */
 3469: if ( isstr ) fprintf(fp,"\"");		/* opening " before first line */
 3470: for ( ibyte=0; ibyte<nbytes; ibyte++ )	/* one byte at a time */
 3471:   {
 3472:   /* --- display a byte as hex char or number, depending on isstr --- */
 3473:   if ( isstr )				/* string format wanted */
 3474:     fprintf(fp,"\\x%02x",(rp->pixmap)[ibyte]);	/*print byte as hex char*/
 3475:   else					/* comma-separated format wanted */
 3476:     fprintf(fp,"0x%02x",(rp->pixmap)[ibyte]);	/*print byte as hex number*/
 3477:   /* --- add a separator and newline, etc, as necessary --- */
 3478:   if ( ibyte < nbytes-1)		/* not the last byte yet */
 3479:     {
 3480:     if ( !isstr ) fprintf(fp,",");	/* follow hex number with comma */
 3481:     if ( (ibyte+1)%ncols==0 ) {		/* need new line after every ncols */
 3482:       if ( !isstr )			/* for hex numbers format ... */
 3483: 	fprintf(fp,"\n%.*s",col1,stub);	/* ...just need newline and stub */
 3484:       else				/* for string format... */
 3485: 	fprintf(fp,"\"\n%.*s\"",col1,stub); } /*...need closing, opening "s*/
 3486:     } /* --- end-of-if(ibyte<nbytes-1) --- */
 3487:   } /* --- end-of-for(ibyte) --- */
 3488: if ( isstr ) fprintf(fp,"\"");		/* closing " after last line */
 3489: return ( 1 );				/* back with 1=okay, 0=failed */
 3490: } /* --- end-of-function hex_bitmap() --- */
 3491: 
 3492: 
 3493: /* ==========================================================================
 3494:  * Function:	emit_string ( fp, col1, string, comment )
 3495:  * Purpose:	Emit string on fp, starting in col1,
 3496:  *		and followed by right-justified comment.
 3497:  * --------------------------------------------------------------------------
 3498:  * Arguments:	fp (I)		File ptr to output device (defaults to
 3499:  *				stdout if passed as NULL).
 3500:  *		col1 (I)	int containing 0 or #blanks preceding string
 3501:  *		string (I)	char *  containing string to be emitted.
 3502:  *				If last char of string is '\n',
 3503:  *				the emitted line ends with a newline,
 3504:  *				otherwise not.
 3505:  *		comment (I)	NULL or char * containing right-justified
 3506:  *				comment (we enclose between /star and star/)
 3507:  * --------------------------------------------------------------------------
 3508:  * Returns:	( int )		1 if completed successfully,
 3509:  *				or 0 otherwise (for any error).
 3510:  * --------------------------------------------------------------------------
 3511:  * Notes:     o
 3512:  * ======================================================================= */
 3513: /* --- entry point --- */
 3514: int	emit_string ( FILE *fp, int col1, char *string, char *comment )
 3515: {
 3516: /* -------------------------------------------------------------------------
 3517: Allocations and Declarations
 3518: -------------------------------------------------------------------------- */
 3519: char	line[256];		/* construct line with caller's fields */
 3520: int	fieldlen;		/* #chars in one of caller's fields */
 3521: int	linelen = 72;		/*line length (for right-justified comment)*/
 3522: int	isnewline = 0;		/* true to emit \n at end of line */
 3523: /* --------------------------------------------------------------------------
 3524: construct line containing prolog, string, epilog, and finally comment
 3525: -------------------------------------------------------------------------- */
 3526: /* --- init line --- */
 3527: memset(line,' ',255);			/* start line with blanks */
 3528: /* --- embed string into line --- */
 3529: if ( string != NULL )			/* if caller gave us a string... */
 3530:   { fieldlen = strlen(string);		/* #cols required for string */
 3531:     if ( string[fieldlen-1] == '\n' )	/* check last char for newline */
 3532:       {	isnewline = 1;			/* got it, so set flag */
 3533: 	fieldlen--; }			/* but don't print it yet */
 3534:     memcpy(line+col1,string,fieldlen);	/* embid string starting at col1 */
 3535:     col1 += fieldlen; }			/* bump col past epilog */
 3536: /* --- embed comment into line --- */
 3537: if ( comment != NULL )			/* if caller gave us a comment... */
 3538:   { fieldlen = 6 + strlen(comment);	/* plus  /star, star/, 2 spaces */
 3539:     if ( linelen-fieldlen < col1 )	/* comment won't fit */
 3540:       fieldlen -= (col1 - (linelen-fieldlen)); /* truncate comment to fit */
 3541:     if ( fieldlen > 6 )			/* can fit all or part of comment */
 3542:       sprintf(line+linelen-fieldlen,"/%c %.*s %c/", /* so embed it in line */
 3543: 	'*', fieldlen-6,comment, '*');
 3544:     col1 = linelen; }			/* indicate line filled */
 3545: /* --- line completed --- */
 3546: line[col1] = '\000';			/* null-terminate completed line */
 3547: /* -------------------------------------------------------------------------
 3548: emit line, then back to caller with 1=okay, 0=failed.
 3549: -------------------------------------------------------------------------- */
 3550: /* --- first redirect null fp --- */
 3551: if ( fp == (FILE *)NULL ) fp = stdout;	/* default fp to stdout if null */
 3552: /* --- emit line (and optional newline) --- */
 3553: fprintf(fp,"%.*s",linelen,line);	/* no more than linelen chars */
 3554: if ( isnewline ) fprintf(fp,"\n");	/*caller wants terminating newline*/
 3555: return ( 1 );
 3556: } /* --- end-of-function emit_string() --- */
 3557: 
 3558: 
 3559: /* ==========================================================================
 3560:  * Function:	gftobitmap ( gf )
 3561:  * Purpose:	convert .gf-like pixmap to bitmap image
 3562:  * --------------------------------------------------------------------------
 3563:  * Arguments:	gf (I)		raster * to struct in .gf-format
 3564:  * --------------------------------------------------------------------------
 3565:  * Returns:	( raster * )	image-format raster * if successful,
 3566:  *				or NULL for any error.
 3567:  * --------------------------------------------------------------------------
 3568:  * Notes:     o
 3569:  * ======================================================================= */
 3570: /* --- entry point --- */
 3571: raster	*gftobitmap ( raster *gf )
 3572: {
 3573: /* -------------------------------------------------------------------------
 3574: Allocations and Declarations
 3575: -------------------------------------------------------------------------- */
 3576: raster	*new_raster(), *rp=NULL;	/* image raster retuned to caller */
 3577: int	width=0, height=0, totbits=0;	/* gf->width, gf->height, #bits */
 3578: int	format=0, icount=0, ncounts=0,	/*.gf format, count index, #counts*/
 3579: 	ibit=0, bitval=0;		/* bitmap index, bit value */
 3580: int	isrepeat = 1,			/* true to process repeat counts */
 3581: 	repeatcmds[2] = {255,15},	/*opcode for repeat/duplicate count*/
 3582: 	nrepeats=0, irepeat=0,		/* scan line repeat count,index */
 3583: 	wbits = 0;			/* count bits to width of scan line*/
 3584: /* -------------------------------------------------------------------------
 3585: initialization
 3586: -------------------------------------------------------------------------- */
 3587: /* --- check args --- */
 3588: if ( gf == NULL ) goto end_of_job;	/* input raster not provided */
 3589: format = gf->format;			/* 2 or 3 */
 3590: if ( format!=2 && format!=3 ) goto end_of_job; /* invalid raster format */
 3591: ncounts = gf->pixsz;			/*pixsz is really #counts in pixmap*/
 3592: /* --- allocate output raster with proper dimensions for bitmap --- */
 3593: width=gf->width;  height=gf->height;	/* dimensions of raster */
 3594: if ( (rp = new_raster(width,height,1))	/* allocate new raster and bitmap */
 3595: ==   NULL ) goto end_of_job;		/* quit if failed to allocate */
 3596: totbits = width*height;			/* total #bits in image */
 3597: /* -------------------------------------------------------------------------
 3598: fill bitmap
 3599: -------------------------------------------------------------------------- */
 3600: for ( icount=0,bitval=0; icount<ncounts; icount++ )
 3601:   {
 3602:   int	nbits = (int)(getbyfmt(format,gf->pixmap,icount)); /*#bits to set*/
 3603:   if ( isrepeat				/* we're proxessing repeat counts */
 3604:   &&   nbits == repeatcmds[format-2] ) { /* and repeat opcode found */
 3605:    if ( nrepeats == 0 )			/* recursive repeat is error */
 3606:     { nrepeats = (int)(getbyfmt(format,gf->pixmap,icount+1));/*repeat count*/
 3607:       nbits = (int)(getbyfmt(format,gf->pixmap,icount+2)); /*#bits to set*/
 3608:       icount += 2; }			/* bump byte/nibble count */
 3609:    else					/* some internal error occurred */
 3610:     if ( msgfp!=NULL && msglevel>=1 )	/* report error */
 3611:      fprintf(msgfp,"gftobitmap> found embedded repeat command\n"); }
 3612:   if ( 0 )
 3613:     fprintf(stdout,
 3614:     "gftobitmap> icount=%d bitval=%d nbits=%d ibit=%d totbits=%d\n",
 3615:     icount,bitval,nbits,ibit,totbits);
 3616:   for ( ; nbits>0; nbits-- )		/* count down */
 3617:     { if ( ibit >= totbits ) goto end_of_job; /* overflow check */
 3618:       for ( irepeat=0; irepeat<=nrepeats; irepeat++ )
 3619:        if ( bitval == 1 )		/* set pixel */
 3620: 	{ setlongbit(rp->pixmap,(ibit+irepeat*width)); }
 3621:        else				/* clear pixel */
 3622: 	{ unsetlongbit(rp->pixmap,(ibit+irepeat*width)); }
 3623:       if ( nrepeats > 0 ) wbits++;	/* count another repeated bit */
 3624:       ibit++; }				/* bump bit index */
 3625:   bitval = 1-bitval;			/* flip bit value */
 3626:   if ( wbits >= width ) {		/* completed repeats */
 3627:    ibit += nrepeats*width;		/*bump bit count past repeated scans*/
 3628:    if ( wbits > width )			/* out-of alignment error */
 3629:     if ( msgfp!=NULL && msglevel>=1 )	/* report error */
 3630:      fprintf(msgfp,"gftobitmap> width=%d wbits=%d\n",width,wbits);
 3631:    wbits = nrepeats = 0; }		/* reset repeat counts */
 3632:   } /* --- end-of-for(icount) --- */
 3633: end_of_job:
 3634:   return ( rp );			/* back to caller with image */
 3635: } /* --- end-of-function gftobitmap() --- */
 3636: 
 3637: 
 3638: /* ==========================================================================
 3639:  * Function:	get_symdef ( symbol )
 3640:  * Purpose:	returns mathchardef struct for symbol
 3641:  * --------------------------------------------------------------------------
 3642:  * Arguments:	symbol (I)	char *  containing symbol
 3643:  *				whose corresponding mathchardef is wanted
 3644:  * --------------------------------------------------------------------------
 3645:  * Returns:	( mathchardef * )  pointer to struct defining symbol,
 3646:  *				or NULL for any error
 3647:  * --------------------------------------------------------------------------
 3648:  * Notes:     o	Input symbol need only contain a leading substring to match,
 3649:  *		e.g., \gam passed in symbol will match \gamma in the table.
 3650:  *		If the table contains two or more possible matches,
 3651:  *		the shortest is returned, e.g., input \e will return with
 3652:  *		data for \eta rather than \epsilon.  To get \epsilon,
 3653:  *		you must pass a leading substring long enough to eliminate
 3654:  *		shorter table matches, i.e., in this case \ep
 3655:  * ======================================================================= */
 3656: /* --- entry point --- */
 3657: mathchardef *get_symdef ( char *symbol )
 3658: {
 3659: /* -------------------------------------------------------------------------
 3660: Allocations and Declarations
 3661: -------------------------------------------------------------------------- */
 3662: mathchardef *symdefs = symtable;	/* table of mathchardefs */
 3663: int	ligdef=0, get_ligature();	/* or we may have a ligature */
 3664: int	idef = 0,			/* symdefs[] index */
 3665: 	bestdef = (-9999);		/*index of shortest matching symdef*/
 3666: int	symlen = strlen(symbol),	/* length of input symbol */
 3667: 	deflen, minlen=9999;		/*length of shortest matching symdef*/
 3668: int	/*alnumsym = (symlen==1 && isalnum(*symbol)),*/ /*alphanumeric sym*/
 3669: 	alphasym = (symlen==1 && isalpha(*symbol)); /* or alpha symbol */
 3670: int	family = fontinfo[fontnum].family; /* current font family */
 3671: static	char *displaysyms[][2] = {	/*xlate to Big sym for \displaystyle*/
 3672: 	/* --- see table on page 536 in TLC2 --- */
 3673: 	{"\\int",	"\\Bigint"},
 3674: 	{"\\oint",	"\\Bigoint"},
 3675: 	{"\\sum",	"\\Bigsum"},
 3676: 	{"\\prod",	"\\Bigprod"},
 3677: 	{"\\coprod",	"\\Bigcoprod"},
 3678: 	/* --- must be 'big' when related to similar binary operators --- */
 3679: 	{"\\bigcup",	"\\Bigcup"},
 3680: 	{"\\bigsqcup",	"\\Bigsqcup"},
 3681: 	{"\\bigcap",	"\\Bigcap"},
 3682: 	/*{"\\bigsqcap", "\\sqcap"},*/	/* don't have \Bigsqcap */
 3683: 	{"\\bigodot",	"\\Bigodot"},
 3684: 	{"\\bigoplus",	"\\Bigoplus"},
 3685: 	{"\\bigominus",	"\\ominus"},
 3686: 	{"\\bigotimes",	"\\Bigotimes"},
 3687: 	{"\\bigoslash",	"\\oslash"},
 3688: 	{"\\biguplus",	"\\Biguplus"},
 3689: 	{"\\bigwedge",	"\\Bigwedge"},
 3690: 	{"\\bigvee",	"\\Bigvee"},
 3691: 	{NULL, NULL} };
 3692: /* -------------------------------------------------------------------------
 3693: First check for ligature
 3694: -------------------------------------------------------------------------- */
 3695: isligature = 0;				/* init signal for no ligature */
 3696: if ( family == CYR10 )			/*only check for cyrillic ligatures*/
 3697:  if ( (ligdef=get_ligature(subexprptr,family)) /* check for ligature */
 3698:  >=    0  )				/* found a ligature */
 3699:   { bestdef = ligdef;			/* set bestdef for ligature */
 3700:     isligature = 1;			/* signal we found a ligature */
 3701:     goto end_of_job; }			/* so just give it to caller */
 3702: /* -------------------------------------------------------------------------
 3703: If in \displaystyle mode, first xlate int to Bigint, etc.
 3704: -------------------------------------------------------------------------- */
 3705: if ( isdisplaystyle > 1 )		/* we're in \displaystyle mode */
 3706:   for ( idef=0; ; idef++ ) {		/* lookup symbol in displaysyms */
 3707:     char *fromsym = displaysyms[idef][0], /* look for this symbol */
 3708: 	 *tosym = displaysyms[idef][1];	  /* and xlate it to this symbol */
 3709:     if ( fromsym == NULL ) break;	/* end-of-table */
 3710:     if ( !strcmp(symbol,fromsym) )	/* found a match */
 3711:       {	if ( msglevel>=99 && msgfp!=NULL ) /* debugging output */
 3712: 	 { fprintf(msgfp,"get_symdef> isdisplaystyle=%d, xlated %s to %s\n",
 3713: 	   isdisplaystyle,symbol,tosym); fflush(msgfp); }
 3714: 	symbol = tosym;			/* so look up tosym instead */
 3715: 	symlen = strlen(symbol);	/* reset symbol length */
 3716: 	break; }			/* no need to search further */
 3717:     } /* --- end-of-for(idef) --- */
 3718: /* -------------------------------------------------------------------------
 3719: search symdefs[] in order for first occurrence of symbol
 3720: -------------------------------------------------------------------------- */
 3721: for ( idef=0; ;idef++ )			/* until trailer record found */
 3722:   if ( symdefs[idef].symbol == NULL ) break; /* reached end-of-table */
 3723:   else					/* check against caller's symbol */
 3724:     if ( strncmp(symbol,symdefs[idef].symbol,symlen) == 0 ) /* found match */
 3725:      if ( (fontnum==0||family==CYR10)	/* mathmode, so check every match */
 3726:      || (0 && istextmode && (!alphasym	/* text mode and not alpha symbol */
 3727: 	|| symdefs[idef].handler!=NULL))   /* or text mode and directive */
 3728:      || (symdefs[idef].family==family	/* have correct family */
 3729: 	&& symdefs[idef].handler==NULL) )  /* and not a handler collision */
 3730: #if 0
 3731:      || (fontnum==1 && symdefs[idef].family==CMR10)   /*textmode && rm text*/
 3732:      || (fontnum==2 && symdefs[idef].family==CMMI10)  /*textmode && it text*/
 3733:      || (fontnum==3 && symdefs[idef].family==BBOLD10  /*textmode && bb text*/
 3734: 	&& symdefs[idef].handler==NULL)
 3735:      || (fontnum==4 && symdefs[idef].family==CMMIB10  /*textmode && bf text*/
 3736: 	&& symdefs[idef].handler==NULL) )
 3737: #endif
 3738:       if ( (deflen=strlen(symdefs[idef].symbol)) < minlen ) /*new best match*/
 3739: 	{ bestdef = idef;		/* save index of new best match */
 3740: 	  if ( (minlen = deflen)	/* and save its len for next test */
 3741: 	  ==  symlen ) break; }		/*perfect match, so return with it*/
 3742: if ( bestdef < 0 )			/* failed to look up symbol */
 3743:   if ( fontnum != 0 )			/* we're in a restricted font mode */
 3744:     { int oldfontnum = fontnum;		/* save current font family */
 3745:       mathchardef *symdef = NULL;	/* lookup result with fontnum=0 */
 3746:       fontnum = 0;			/*try to look up symbol in any font*/
 3747:       symdef = get_symdef(symbol);	/* repeat lookup with fontnum=0 */
 3748:       fontnum = oldfontnum;		/* reset font family */
 3749:       return symdef; }			/* caller gets fontnum=0 lookup */
 3750: end_of_job:
 3751:  if ( msgfp!=NULL && msglevel>=999 )	/* debugging output */
 3752:   { fprintf(msgfp,
 3753:     "get_symdef> symbol=%s matches symtable[%d]=%s (isligature=%d)\n",
 3754:     symbol,bestdef,(bestdef<0?"NotFound":symdefs[bestdef].symbol),isligature);
 3755:     fflush(msgfp); }
 3756:  return ( (bestdef<0? NULL : &(symdefs[bestdef])) );/*NULL or best symdef[]*/
 3757: } /* --- end-of-function get_symdef() --- */
 3758: 
 3759: 
 3760: /* ==========================================================================
 3761:  * Function:	get_ligature ( expression, family )
 3762:  * Purpose:	returns symtable[] index for ligature
 3763:  * --------------------------------------------------------------------------
 3764:  * Arguments:	expression (I)	char *  containing ligature
 3765:  *				whose corresponding mathchardef is wanted
 3766:  *		family (I)	int containing NOVALUE for any family,
 3767:  *				or, e.g., CYR10 for cyrillic, etc.
 3768:  * --------------------------------------------------------------------------
 3769:  * Returns:	( int ) 	symtable[] index defining ligature,
 3770:  *				or -9999 if no ligature found or for any error
 3771:  * --------------------------------------------------------------------------
 3772:  * Notes:     o
 3773:  * ======================================================================= */
 3774: /* --- entry point --- */
 3775: int	get_ligature ( char *expression, int family )
 3776: {
 3777: /* -------------------------------------------------------------------------
 3778: Allocations and Declarations
 3779: -------------------------------------------------------------------------- */
 3780: mathchardef *symdefs = symtable;	/* table of mathchardefs */
 3781: char	*ligature = expression /*- 1*/,	/* expression ptr */
 3782: 	*symbol = NULL;			/* symdefs[idef].symbol */
 3783: int	liglen = strlen(ligature);	/* #chars remaining in expression */
 3784: int	iscyrfam = (family==CYR10);	/* true for cyrillic families */
 3785: int	idef = 0,			/* symdefs[] index */
 3786: 	bestdef = (-9999),		/*index of longest matching symdef*/
 3787: 	maxlen=(-9999);			/*length of longest matching symdef*/
 3788: /* -------------------------------------------------------------------------
 3789: search symdefs[] in order for first occurrence of symbol
 3790: -------------------------------------------------------------------------- */
 3791: if ( !isstring ) {			/* no ligatures in "string" mode */
 3792:  for ( idef=0; ;idef++ )		/* until trailer record found */
 3793:   if ( (symbol=symdefs[idef].symbol) == NULL ) break; /* end-of-table */
 3794:   else {				/* check against caller's ligature */
 3795:     int symlen = strlen(symbol);	/* #chars in symbol */
 3796:     if ( ( symlen>1 || iscyrfam )	/*ligature >1 char long or cyrillic*/
 3797:     &&   symlen <= liglen		/* and enough remaining chars */
 3798:     &&   ( *symbol!='\\' || iscyrfam )	/* not escaped or cyrillic */
 3799:     &&   symdefs[idef].handler == NULL ) /* and not a handler */
 3800:      if ( strncmp(ligature,symbol,symlen) == 0 ) /* found match */
 3801:       if ( family < 0			/* no family specifies */
 3802:       ||   symdefs[idef].family == family ) /* or have correct family */
 3803:        if ( symlen > maxlen )		/* new longest ligature */
 3804: 	{ bestdef = idef;		/* save index of new best match */
 3805: 	  maxlen = symlen; }		/* and save its len for next test */
 3806:     } /* --- end-of-if/else(symbol==NULL) --- */
 3807:  if ( msgfp!=NULL && msglevel>=999 )	/* debugging output */
 3808:   { fprintf(msgfp,"get_ligature> ligature=%.4s matches symtable[%d]=%s\n",
 3809:     ligature,bestdef,(bestdef<0?"NotFound":symdefs[bestdef].symbol));
 3810:     fflush(msgfp); }
 3811:  } /* --- end-of-if(!isstring) --- */
 3812: return ( bestdef );			/* -9999 or index of best symdef[] */
 3813: } /* --- end-of-function get_ligature --- */
 3814: 
 3815: 
 3816: /* ==========================================================================
 3817:  * Function:	get_chardef ( symdef, size )
 3818:  * Purpose:	returns chardef ptr containing data for symdef at given size
 3819:  * --------------------------------------------------------------------------
 3820:  * Arguments:	symdef (I)	mathchardef *  corresponding to symbol
 3821:  *				whose corresponding chardef is wanted
 3822:  *		size (I)	int containing 0-5 for desired size
 3823:  * --------------------------------------------------------------------------
 3824:  * Returns:	( chardef * )	pointer to struct defining symbol at size,
 3825:  *				or NULL for any error
 3826:  * --------------------------------------------------------------------------
 3827:  * Notes:     o	if size unavailable, the next-closer-to-normalsize
 3828:  *		is returned instead.
 3829:  * ======================================================================= */
 3830: /* --- entry point --- */
 3831: chardef	*get_chardef ( mathchardef *symdef, int size )
 3832: {
 3833: /* -------------------------------------------------------------------------
 3834: Allocations and Declarations
 3835: -------------------------------------------------------------------------- */
 3836: fontfamily  *fonts = fonttable;		/* table of font families */
 3837: chardef	**fontdef,			/*tables for desired font, by size*/
 3838: 	*gfdata = (chardef *)NULL;	/* chardef for symdef,size */
 3839: int	ifont;				/* fonts[] index */
 3840: int	family, charnum;		/* indexes retrieved from symdef */
 3841: int	sizeinc = 0,			/*+1 or -1 to get closer to normal*/
 3842: 	normalsize = 2;			/* this size always present */
 3843: int	isBig = 0;			/*true if symbol's 1st char is upper*/
 3844: char	*symptr = NULL;			/* look for 1st alpha of symbol */
 3845: /* -------------------------------------------------------------------------
 3846: initialization
 3847: -------------------------------------------------------------------------- */
 3848: /* --- check symdef --- */
 3849: if ( symdef == NULL ) goto end_of_job;	/* get_symdef() probably failed */
 3850: /* --- get local copy of indexes from symdef --- */
 3851: family = symdef->family;		/* font family containing symbol */
 3852: charnum = symdef->charnum;		/* char# of symbol within font */
 3853: /* --- check for supersampling --- */
 3854: if ( issupersampling )			/* check for supersampling fonts */
 3855:  if ( fonts != ssfonttable )		/* uh oh--probably internal error */
 3856:   { fonts = ssfonttable; }		/* force it */
 3857: /* --- check requested size, and set size increment --- */
 3858: if ( 0 && issupersampling )		/* set size index for supersampling */
 3859:   size = LARGESTSIZE+1;			/* index 1 past largest size */
 3860: else					/* low pass indexes 0...LARGESTSIZE */
 3861:   {
 3862:   if( size<0 ) size = 0;		/* size was definitely too small */
 3863:   if( size>LARGESTSIZE ) size = LARGESTSIZE;  /* or definitely too large */
 3864:   if( size<normalsize ) sizeinc = (+1);	/*use next larger if size too small*/
 3865:   if( size>normalsize ) sizeinc = (-1);	/*or next smaller if size too large*/
 3866:   }
 3867: /* --- check for really big symbol (1st char of symbol name uppercase) --- */
 3868: for ( symptr=symdef->symbol; *symptr!='\000'; symptr++ ) /*skip leading \'s*/
 3869:   if ( isalpha(*symptr) )		/* found leading alpha char */
 3870:     { isBig = isupper(*symptr);		/* is 1st char of name uppercase? */
 3871:       if ( !isBig			/* 1st char lowercase */
 3872:       &&   strlen(symptr) >= 4 )	/* but followed by at least 3 chars */
 3873:        isBig = !memcmp(symptr,"big\\",4) /* isBig if name starts with big\ */
 3874: 	|| !memcmp(symptr,"bigg",4);	/* or with bigg */
 3875:       break; }				/* don't check beyond 1st char */
 3876: /* -------------------------------------------------------------------------
 3877: find font family in table of fonts[]
 3878: -------------------------------------------------------------------------- */
 3879: /* --- look up font family --- */
 3880: for ( ifont=0; ;ifont++ )		/* until trailer record found */
 3881:   if ( fonts[ifont].family < 0 ) {	/* error, no such family */
 3882:     if ( msgfp!=NULL && msglevel>=99 ) { /* emit error */
 3883:      fprintf(msgfp,"get_chardef> failed to find font family %d\n",
 3884:      family); fflush(msgfp); }
 3885:     goto end_of_job; }			/* quit if can't find font family*/
 3886:   else if ( fonts[ifont].family == family ) break; /* found font family */
 3887: /* --- get local copy of table for this family by size --- */
 3888: fontdef = fonts[ifont].fontdef;		/* font by size */
 3889: /* -------------------------------------------------------------------------
 3890: get font in desired size, or closest available size, and return symbol
 3891: -------------------------------------------------------------------------- */
 3892: /* --- get font in desired size --- */
 3893: while ( 1 )				/* find size or closest available */
 3894:   if ( fontdef[size] != NULL ) break;	/* found available size */
 3895:   else					/* adjust size closer to normal */
 3896:     if ( size == NORMALSIZE		/* already normal so no more sizes,*/
 3897:     || sizeinc == 0 ) {			/* or must be supersampling */
 3898:       if ( msgfp!=NULL && msglevel>=99 ) { /* emit error */
 3899: 	fprintf(msgfp,"get_chardef> failed to find font size %d\n",
 3900: 	size); fflush(msgfp); }
 3901:       goto end_of_job; }		/* quit if can't find desired size */
 3902:     else				/*bump size 1 closer to NORMALSIZE*/
 3903:       size += sizeinc;			/* see if adjusted size available */
 3904: /* --- ptr to chardef struct --- */
 3905: gfdata = &((fontdef[size])[charnum]);	/*ptr to chardef for symbol in size*/
 3906: /* -------------------------------------------------------------------------
 3907: kludge to tweak CMEX10 (which appears to have incorrect descenders)
 3908: -------------------------------------------------------------------------- */
 3909: if ( family == CMEX10 )			/* cmex10 needs tweak */
 3910:   { int height = gfdata->toprow - gfdata->botrow + 1; /*total height of char*/
 3911:     gfdata->botrow = (isBig? (-height/3) : (-height/4));
 3912:     gfdata->toprow = gfdata->botrow + gfdata->image.height; }
 3913: /* -------------------------------------------------------------------------
 3914: return subraster containing chardef data for symbol in requested size
 3915: -------------------------------------------------------------------------- */
 3916: end_of_job:
 3917:  if ( msgfp!=NULL && msglevel>=999 )
 3918:   { if (symdef == NULL) fprintf(msgfp,"get_chardef> input symdef==NULL\n");
 3919:     else
 3920:      fprintf(msgfp,"get_chardef> requested symbol=\"%s\" size=%d  %s\n",
 3921:      symdef->symbol,size,(gfdata==NULL?"FAILED":"Succeeded"));
 3922:     fflush(msgfp); }
 3923:  return ( gfdata );			/*ptr to chardef for symbol in size*/
 3924: } /* --- end-of-function get_chardef() --- */
 3925: 
 3926: 
 3927: /* ==========================================================================
 3928:  * Function:	get_charsubraster ( symdef, size )
 3929:  * Purpose:	returns new subraster ptr containing
 3930:  *		data for symdef at given size
 3931:  * --------------------------------------------------------------------------
 3932:  * Arguments:	symdef (I)	mathchardef *  corresponding to symbol whose
 3933:  *				corresponding chardef subraster is wanted
 3934:  *		size (I)	int containing 0-5 for desired size
 3935:  * --------------------------------------------------------------------------
 3936:  * Returns:	( subraster * )	pointer to struct defining symbol at size,
 3937:  *				or NULL for any error
 3938:  * --------------------------------------------------------------------------
 3939:  * Notes:     o	just wraps a subraster envelope around get_chardef()
 3940:  * ======================================================================= */
 3941: /* --- entry point --- */
 3942: subraster *get_charsubraster ( mathchardef *symdef, int size )
 3943: {
 3944: /* -------------------------------------------------------------------------
 3945: Allocations and Declarations
 3946: -------------------------------------------------------------------------- */
 3947: chardef	*get_chardef(), *gfdata=NULL;	/* chardef struct for symdef,size */
 3948: int	get_baseline();			/* baseline of gfdata */
 3949: subraster *new_subraster(), *sp=NULL;	/* subraster containing gfdata */
 3950: raster	*bitmaprp=NULL, *gftobitmap();	/* convert .gf-format to bitmap */
 3951: int	delete_subraster();		/* in case gftobitmap() fails */
 3952: int	aasupsamp(),			/*antialias char with supersampling*/
 3953: 	grayscale=256;			/* aasupersamp() parameters */
 3954: /* -------------------------------------------------------------------------
 3955: look up chardef for symdef at size, and embed data (gfdata) in subraster
 3956: -------------------------------------------------------------------------- */
 3957: if ( (gfdata=get_chardef(symdef,size))	/* look up chardef for symdef,size */
 3958: !=   NULL )				/* and check that we found it */
 3959:  if ( (sp=new_subraster(0,0,0))		/* allocate subraster "envelope" */
 3960:  !=   NULL )				/* and check that we succeeded */
 3961:   {
 3962:   raster *image = &(gfdata->image);	/* ptr to chardef's bitmap or .gf */
 3963:   int format = image->format;		/* 1=bitmap, else .gf */
 3964:   sp->symdef = symdef;			/* replace NULL with caller's arg */
 3965:   sp->size = size;			/*replace default with caller's size*/
 3966:   sp->baseline = get_baseline(gfdata);	/* get baseline of character */
 3967:   if ( format == 1 )			/* already a bitmap */
 3968:    { sp->type = CHARASTER;		/* static char raster */
 3969:      sp->image = image; }		/* store ptr to its bitmap */
 3970:   else					/* need to convert .gf-to-bitmap */
 3971:    if ( (bitmaprp = gftobitmap(image))	/* convert */
 3972:    !=   (raster *)NULL )		/* successful */
 3973:     { sp->type = IMAGERASTER;		/* allocated raster will be freed */
 3974:       sp->image = bitmaprp; }		/* store ptr to converted bitmap */
 3975:    else					/* conversion failed */
 3976:     { delete_subraster(sp);		/* free unneeded subraster */
 3977:       sp = (subraster *)NULL;		/* signal error to caller */
 3978:       goto end_of_job; }		/* quit */
 3979:   if ( issupersampling )		/* antialias character right here */
 3980:     {
 3981:     raster *aa = NULL;			/* antialiased char raster */
 3982:     int status = aasupsamp(sp->image,&aa,shrinkfactor,grayscale);
 3983:     if ( status )			/* supersampled successfully */
 3984:       {	int baseline = sp->baseline;	/* baseline before supersampling */
 3985: 	int height = gfdata->image.height; /* #rows before supersampling */
 3986: 	sp->image = aa;			/* replace chardef with ss image */
 3987: 	if ( baseline >= height-1 )	/* baseline at bottom of char */
 3988: 	  sp->baseline = aa->height -1;	/* so keep it at bottom */
 3989: 	else				/* char has descenders */
 3990: 	  sp->baseline /= shrinkfactor;	/* rescale baseline */
 3991: 	sp->type = IMAGERASTER; }	/* character is an image raster */
 3992:     } /* --- end-of-if(issupersampling) --- */
 3993:   } /* --- end-of-if(sp!=NULL) --- */
 3994: end_of_job:
 3995:  if ( msgfp!=NULL && msglevel>=999 )
 3996:   { fprintf(msgfp,"get_charsubraster> requested symbol=\"%s\" baseline=%d"
 3997:     " %s %s\n", symdef->symbol, (sp==NULL?0:sp->baseline),
 3998:     (sp==NULL?"FAILED":"Succeeded"), (gfdata==NULL?"(gfdata=NULL)":" "));
 3999:     fflush(msgfp); }
 4000: return ( sp );				/* back to caller */
 4001: } /* --- end-of-function get_charsubraster() --- */
 4002: 
 4003: 
 4004: /* ==========================================================================
 4005:  * Function:	get_symsubraster ( symbol, size )
 4006:  * Purpose:	returns new subraster ptr containing
 4007:  *		data for symbol at given size
 4008:  * --------------------------------------------------------------------------
 4009:  * Arguments:	symbol (I)	char *  corresponding to symbol
 4010:  *				whose corresponding subraster is wanted
 4011:  *		size (I)	int containing 0-5 for desired size
 4012:  * --------------------------------------------------------------------------
 4013:  * Returns:	( subraster * )	pointer to struct defining symbol at size,
 4014:  *				or NULL for any error
 4015:  * --------------------------------------------------------------------------
 4016:  * Notes:     o	just combines get_symdef() and get_charsubraster()
 4017:  * ======================================================================= */
 4018: /* --- entry point --- */
 4019: subraster *get_symsubraster ( char *symbol, int size )
 4020: {
 4021: /* -------------------------------------------------------------------------
 4022: Allocations and Declarations
 4023: -------------------------------------------------------------------------- */
 4024: subraster *sp=NULL, *get_charsubraster(); /* subraster containing gfdata */
 4025: mathchardef *symdef=NULL, *get_symdef(); /* mathchardef lookup for symbol */
 4026: /* -------------------------------------------------------------------------
 4027: look up mathchardef for symbol
 4028: -------------------------------------------------------------------------- */
 4029: if ( symbol != NULL )			/* user supplied input symbol */
 4030:   symdef = get_symdef(symbol);		/*look up corresponding mathchardef*/
 4031: /* -------------------------------------------------------------------------
 4032: look up chardef for mathchardef and wrap a subraster structure around data
 4033: -------------------------------------------------------------------------- */
 4034: if ( symdef != NULL )			/* lookup succeeded */
 4035:   sp = get_charsubraster(symdef,size);	/* so get symbol data in subraster */
 4036: return ( sp );				/* back to caller with sp or NULL */
 4037: } /* --- end-of-function get_symsubraster() --- */
 4038: 
 4039: 
 4040: /* ==========================================================================
 4041:  * Function:	get_baseline ( gfdata )
 4042:  * Purpose:	returns baseline for a chardef struct
 4043:  * --------------------------------------------------------------------------
 4044:  * Arguments:	gfdata (I)	chardef *  containing chardef for symbol
 4045:  *				whose baseline is wanted
 4046:  * --------------------------------------------------------------------------
 4047:  * Returns:	( int )		baseline for symdef,
 4048:  *				or -1 for any error
 4049:  * --------------------------------------------------------------------------
 4050:  * Notes:     o	Unlike TeX, the top-left corners of our rasters are (0,0),
 4051:  *		with (row,col) increasing as you move down and right.
 4052:  *		Baselines are calculated with respect to this scheme,
 4053:  *		so 0 would mean the very top row is on the baseline
 4054:  *		and everything else descends below the baseline.
 4055:  * ======================================================================= */
 4056: /* --- entry point --- */
 4057: int	get_baseline ( chardef *gfdata )
 4058: {
 4059: /* -------------------------------------------------------------------------
 4060: Allocations and Declarations
 4061: -------------------------------------------------------------------------- */
 4062: int	/*toprow = gfdata->toprow,*/	/*TeX top row from .gf file info*/
 4063: 	botrow = gfdata->botrow,	/*TeX bottom row from .gf file info*/
 4064: 	height = gfdata->image.height;	/* #rows comprising symbol */
 4065: /* -------------------------------------------------------------------------
 4066: give caller baseline
 4067: -------------------------------------------------------------------------- */
 4068: return ( (height-1) + botrow );		/* note: descenders have botrow<0 */
 4069: } /* --- end-of-function get_baseline() --- */
 4070: 
 4071: 
 4072: /* ==========================================================================
 4073:  * Function:	get_delim ( char *symbol, int height, int family )
 4074:  * Purpose:	returns subraster corresponding to the samllest
 4075:  *		character containing symbol, but at least as large as height,
 4076:  *		and in caller's family (if specified).
 4077:  *		If no symbol character as large as height is available,
 4078:  *		then the largest availabale character is returned instead.
 4079:  * --------------------------------------------------------------------------
 4080:  * Arguments:	symbol (I)	char *  containing (substring of) desired
 4081:  *				symbol, e.g., if symbol="(", then any
 4082:  *				mathchardef like "(" or "\\(", etc, match.
 4083:  *		height (I)	int containing minimum acceptable height
 4084:  *				for returned character
 4085:  *		family (I)	int containing -1 to consider all families,
 4086:  *				or, e.g., CMEX10 for only that family
 4087:  * --------------------------------------------------------------------------
 4088:  * Returns:	( subraster * )	best matching character available,
 4089:  *				or NULL for any error
 4090:  * --------------------------------------------------------------------------
 4091:  * Notes:     o	If height is passed as negative, its absolute value is used
 4092:  *		but the best-fit width is searched for (rather than height)
 4093:  * ======================================================================= */
 4094: /* --- entry point --- */
 4095: subraster *get_delim ( char *symbol, int height, int family )
 4096: {
 4097: /* -------------------------------------------------------------------------
 4098: Allocations and Declarations
 4099: -------------------------------------------------------------------------- */
 4100: mathchardef *symdefs = symtable;	/* table of mathchardefs */
 4101: subraster *get_charsubraster(), *sp=(subraster *)NULL; /* best match char */
 4102: subraster *make_delim();		/* construct delim if can't find it*/
 4103: chardef	*get_chardef(), *gfdata=NULL;	/* get chardef struct for a symdef */
 4104: char	lcsymbol[256], *symptr,		/* lowercase symbol for comparison */
 4105: 	*unescsymbol = symbol;		/* unescaped symbol */
 4106: int	symlen = (symbol==NULL?0:strlen(symbol)), /* #chars in caller's sym*/
 4107: 	deflen = 0;			/* length of symdef (aka lcsymbol) */
 4108: int	idef = 0,			/* symdefs[] index */
 4109: 	bestdef = (-9999),		/* index of best fit symdef */
 4110: 	bigdef = (-9999);		/*index of biggest (in case no best)*/
 4111: int	size = 0,			/* size index 0...LARGESTSIZE */
 4112: 	bestsize = (-9999),		/* index of best fit size */
 4113: 	bigsize = (-9999);		/*index of biggest (in case no best)*/
 4114: int	defheight, bestheight=9999,	/* height of best fit symdef */
 4115: 	bigheight = (-9999);		/*height of biggest(in case no best)*/
 4116: int	iswidth = 0;			/* true if best-fit width desired */
 4117: int	isunesc = 0,			/* true if leading escape removed */
 4118: 	issq=0, isoint=0;		/* true for \sqcup,etc, \oint,etc */
 4119: int	iscurly = 0;			/* true for StMary's curly symbols */
 4120: char	*bigint="bigint", *bigoint="bigoint"; /* substitutes for int, oint */
 4121: /* -------------------------------------------------------------------------
 4122: determine if searching height or width, and search symdefs[] for best-fit
 4123: -------------------------------------------------------------------------- */
 4124: /* --- arg checks --- */
 4125: if ( symlen < 1 ) return (sp);		/* no input symbol suplied */
 4126: if ( strcmp(symbol,"e") == 0 ) return(sp); /* e causes segfault??? */
 4127: if ( strstr(symbol,"curly") != NULL ) iscurly=1; /* user wants curly delim */
 4128: /* --- ignore leading escapes for CMEX10 --- */
 4129: if ( 1 )				/* ignore leading escape */
 4130:  if ( (family==CMEX10 || family==CMSYEX) ) { /* for CMEX10 or CMSYEX */
 4131:   if ( strstr(symbol,"sq") != NULL )	/* \sq symbol requested */
 4132:      issq = 1;				/* seq \sq signal */
 4133:   if ( strstr(symbol,"oint") != NULL )	/* \oint symbol requested */
 4134:      isoint = 1;			/* seq \oint signal */
 4135:   if ( *symbol=='\\' )			/* have leading \ */
 4136:    { unescsymbol = symbol+1;		/* push past leading \ */
 4137:      if ( --symlen < 1 ) return(sp);	/* one less char */
 4138:      if ( strcmp(unescsymbol,"int") == 0 ) /* \int requested by caller */
 4139:        unescsymbol = bigint;		/* but big version looks better */
 4140:      if ( strcmp(unescsymbol,"oint") == 0 ) /* \oint requested by caller */
 4141:        unescsymbol = bigoint;		/* but big version looks better */
 4142:      symlen = strlen(unescsymbol);	/* explicitly recalculate length */
 4143:      isunesc = 1; }			/* signal leading escape removed */
 4144:   } /* --- end-of-if(family) --- */
 4145: /* --- determine whether searching for best-fit height or width --- */
 4146: if ( height < 0 )			/* negative signals width search */
 4147:   { height = (-height);			/* flip "height" positive */
 4148:     iswidth = 1; }			/* set flag for width search */
 4149: /* --- search symdefs[] for best-fit height (or width) --- */
 4150: for ( idef=0; ;idef++ )			/* until trailer record found */
 4151:  {
 4152:  char *defsym = symdefs[idef].symbol;	/* local copies */
 4153:  int  deffam  = symdefs[idef].family;
 4154:  if ( defsym == NULL ) break;		/* reached end-of-table */
 4155:  else					/* check against caller's symbol */
 4156:   if ( family<0 || deffam == family	/* if explicitly in caller's family*/
 4157:   ||  (family==CMSYEX && (deffam==CMSY10||deffam==CMEX10||deffam==STMARY10)) )
 4158:     {
 4159:     strcpy(lcsymbol,defsym);		/* local copy of symdefs[] symbol */
 4160:     if ( isunesc && *lcsymbol=='\\' )	/* ignored leading \ in symbol */
 4161:      strcpy(lcsymbol,lcsymbol+1);	/* so squeeze it out of lcsymbol too*/
 4162:     if ( 0 )				/* don't ignore case */
 4163:      for ( symptr=lcsymbol; *symptr!='\000'; symptr++ ) /*for each symbol ch*/
 4164:       if ( isalpha(*symptr) ) *symptr=tolower(*symptr); /*lowercase the char*/
 4165:     deflen = strlen(lcsymbol);		/* #chars in symbol we're checking */
 4166:     if ((symptr=strstr(lcsymbol,unescsymbol)) != NULL) /*found caller's sym*/
 4167:      if ( (isoint || strstr(lcsymbol,"oint")==NULL) /* skip unwanted "oint"*/
 4168:      &&   (issq || strstr(lcsymbol,"sq")==NULL) ) /* skip unwanted "sq" */
 4169:       if ( ( deffam == CMSY10 ?		/* CMSY10 or not CMSY10 */
 4170: 	  symptr == lcsymbol		/* caller's sym is a prefix */
 4171:           && deflen == symlen:		/* and same length */
 4172: 	  (iscurly || strstr(lcsymbol,"curly")==NULL) &&/*not unwanted curly*/
 4173: 	  (symptr == lcsymbol		/* caller's sym is a prefix */
 4174:           || symptr == lcsymbol+deflen-symlen) ) ) /* or a suffix */
 4175:        for ( size=0; size<=LARGESTSIZE; size++ ) /* check all font sizes */
 4176: 	if ( (gfdata=get_chardef(&(symdefs[idef]),size)) != NULL ) /*got one*/
 4177: 	  { defheight = gfdata->image.height;	/* height of this character */
 4178: 	    if ( iswidth )		/* width search wanted instead... */
 4179: 	      defheight = gfdata->image.width;	/* ...so substitute width */
 4180: 	    leftsymdef = &(symdefs[idef]);	/* set symbol class, etc */
 4181: 	    if ( defheight>=height && defheight<bestheight ) /*new best fit*/
 4182: 	      { bestdef=idef; bestsize=size;	/* save indexes of best fit */
 4183: 		bestheight = defheight; }	/* and save new best height */
 4184: 	    if ( defheight >= bigheight )	/* new biggest character */
 4185: 	      { bigdef=idef; bigsize=size;	/* save indexes of biggest */
 4186: 		bigheight = defheight; }	/* and save new big height */
 4187:           } /* --- end-of-if(gfdata!=NULL) --- */
 4188:     } /* --- end-of-if(family) --- */
 4189:  } /* --- end-of-for(idef) --- */
 4190: /* -------------------------------------------------------------------------
 4191: construct subraster for best fit character, and return it to caller
 4192: -------------------------------------------------------------------------- */
 4193: if ( bestdef >= 0 )			/* found a best fit for caller */
 4194:   sp = get_charsubraster(&(symdefs[bestdef]),bestsize); /* best subraster */
 4195: if ( (sp==NULL && height-bigheight>5)	/* try to construct delim */
 4196: ||   bigdef < 0 )			/* delim not in font tables */
 4197:   sp = make_delim(symbol,(iswidth?-height:height)); /* try to build delim */
 4198: if ( sp==NULL && bigdef>=0 )		/* just give biggest to caller */
 4199:   sp = get_charsubraster(&(symdefs[bigdef]),bigsize); /* biggest subraster */
 4200: if ( msgfp!=NULL && msglevel>=99 )
 4201:     fprintf(msgfp,"get_delim> symbol=%.50s, height=%d family=%d isokay=%s\n",
 4202:     (symbol==NULL?"null":symbol),height,family,(sp==NULL?"fail":"success"));
 4203: return ( sp );
 4204: } /* --- end-of-function get_delim() --- */
 4205: 
 4206: 
 4207: /* ==========================================================================
 4208:  * Function:	make_delim ( char *symbol, int height )
 4209:  * Purpose:	constructs subraster corresponding to symbol
 4210:  *		exactly as large as height,
 4211:  * --------------------------------------------------------------------------
 4212:  * Arguments:	symbol (I)	char *  containing, e.g., if symbol="("
 4213:  *				for desired delimiter
 4214:  *		height (I)	int containing height
 4215:  *				for returned character
 4216:  * --------------------------------------------------------------------------
 4217:  * Returns:	( subraster * )	constructed delimiter
 4218:  *				or NULL for any error
 4219:  * --------------------------------------------------------------------------
 4220:  * Notes:     o	If height is passed as negative, its absolute value is used
 4221:  *		and interpreted as width (rather than height)
 4222:  * ======================================================================= */
 4223: /* --- entry point --- */
 4224: subraster *make_delim ( char *symbol, int height )
 4225: {
 4226: /* -------------------------------------------------------------------------
 4227: Allocations and Declarations
 4228: -------------------------------------------------------------------------- */
 4229: subraster *sp = (subraster *)NULL,	/* subraster returned to caller */
 4230: 	*new_subraster();		/* allocate subraster */
 4231: subraster *get_symsubraster(),		/* look up delim pieces in cmex10 */
 4232: 	*symtop=NULL, *symbot=NULL, *symmid=NULL, *symbar=NULL,	/* pieces */
 4233: 	*topsym=NULL, *botsym=NULL, *midsym=NULL, *barsym=NULL,	/* +filler */
 4234: 	*rastack(), *rastcat();		/* stack pieces, concat filler */
 4235: int	isdrawparen = 0;		/*1=draw paren, 0=build from pieces*/
 4236: raster	*rasp = (raster *)NULL;		/* sp->image */
 4237: int	isokay=0, delete_subraster();	/* set true if delimiter drawn ok */
 4238: int	pixsz = 1,			/* pixels are one bit each */
 4239: 	symsize = 0;			/* size arg for get_symsubraster() */
 4240: int	thickness = 1;			/* drawn lines are one pixel thick */
 4241: int	aspectratio = 8;		/* default height/width for parens */
 4242: int	iswidth = 0,			/*true if width specified by height*/
 4243: 	width = height;			/* #pixels width (e.g., of ellipse)*/
 4244: char	*lp=NULL,  *rp=NULL,		/* check symbol for left or right */
 4245: 	*lp2=NULL, *rp2=NULL,		/* synonym for lp,rp */
 4246: 	*lp3=NULL, *rp3=NULL,		/* synonym for lp,rp */
 4247: 	*lp4=NULL, *rp4=NULL;		/* synonym for lp,rp */
 4248: int	circle_raster(),		/* ellipse for ()'s in sp->image */
 4249: 	rule_rsater(),			/* horizontal or vertical lines */
 4250: 	line_raster();			/* line between two points */
 4251: subraster *uparrow_subraster();		/* up/down arrows */
 4252: int	isprealloc = 1;			/*pre-alloc subraster, except arrow*/
 4253: int	oldsmashmargin = smashmargin,	/* save original smashmargin */
 4254: 	wasnocatspace = isnocatspace;	/* save original isnocatspace */
 4255: /* -------------------------------------------------------------------------
 4256: initialization
 4257: -------------------------------------------------------------------------- */
 4258: /* --- determine whether constructing height or width --- */
 4259: if ( height < 0 )			/* negative "height" signals width */
 4260:   { width = height = (-height);		/* flip height positive */
 4261:     iswidth = 1; }			/* set flag for width */
 4262: if ( height < 3 ) goto end_of_job;	/* too small, must be error */
 4263: /* --- set default width (or height) accordingly --- */
 4264: if ( iswidth ) height =  (width+(aspectratio+1)/2)/aspectratio;
 4265: else            width = (height+(aspectratio+1)/2)/aspectratio;
 4266: if ( strchr(symbol,'=') != NULL		/* left or right || bracket wanted */
 4267: ||   strstr(symbol,"\\|") != NULL	/* same || in standard tex notation*/
 4268: ||   strstr(symbol,"dbl") != NULL )	/* semantic bracket with ||'s */
 4269:   width = max2(width,6);		/* need space between two |'s */
 4270: if ( width < 2 ) width=2;		/* set min width */
 4271: if ( strchr(symbol,'(') != NULL		/* if left ( */
 4272: ||   strchr(symbol,')') != NULL )	/* or right ) paren wanted */
 4273:   { width = (3*width)/2;		/* adjust width */
 4274:     if ( !isdrawparen ) isprealloc=0; }	/* don't prealloc if building */
 4275: if ( strchr(symbol,'/') != NULL		/* left / */
 4276: ||   strstr(symbol,"\\\\") != NULL	/* or \\ for right \ */
 4277: ||   strstr(symbol,"backsl") != NULL )	/* or \backslash for \ */
 4278:   width = max2(height/3,5);
 4279: if ( strstr(symbol,"arrow") != NULL )	/* arrow wanted */
 4280:   { width = min2(height/3,20);		/* adjust width */
 4281:     isprealloc = 0; }			/* don't preallocate subraster */
 4282: if ( strchr(symbol,'{') != NULL		/* if left { */
 4283: ||   strchr(symbol,'}') != NULL )	/* or right } brace wanted */
 4284:   { isprealloc = 0; }			/* don't preallocate */
 4285: /* --- allocate and initialize subraster for constructed delimiter --- */
 4286: if ( isprealloc )			/* pre-allocation wanted */
 4287:  { if ( (sp=new_subraster(width,height,pixsz)) /* allocate new subraster */
 4288:    ==   NULL )  goto end_of_job;	/* quit if failed */
 4289:    /* --- initialize delimiter subraster parameters --- */
 4290:    sp->type = IMAGERASTER;		/* image */
 4291:    sp->symdef = NULL;			/* not applicable for image */
 4292:    sp->baseline = height/2 + 2;		/* is a little above center good? */
 4293:    sp->size = NORMALSIZE;		/* size (probably unneeded) */
 4294:    rasp = sp->image; }			/* pointer to image in subraster */
 4295: /* -------------------------------------------------------------------------
 4296: ( ) parens
 4297: -------------------------------------------------------------------------- */
 4298: if ( (lp=strchr(symbol,'(')) != NULL	/* left ( paren wanted */
 4299: ||   (rp=strchr(symbol,')')) != NULL )	/* right ) paren wanted */
 4300:   {
 4301:   if ( isdrawparen ) {			/* draw the paren */
 4302:    int	mywidth = min2(width,20);	/* max width for ()'s */
 4303:    circle_raster ( rasp,		/* embedded raster image */
 4304: 	0, 0,				/* row0,col0 are upper-left corner */
 4305: 	height-1, mywidth-1,		/* row1,col1 are lower-right */
 4306: 	thickness,			/* line thickness is 1 pixel */
 4307: 	(rp==NULL?"23":"41") );		/* "1234" quadrants to be drawn */
 4308:    isokay = 1; }			/* set flag */
 4309:   else {
 4310:    int	isleft = (lp!=NULL?1:0);	/* true for left, false for right */
 4311:    char	*parentop = (isleft?"\\leftparentop":"\\rightparentop"),
 4312: 	*parenbot = (isleft?"\\leftparenbot":"\\rightparenbot"),
 4313: 	*parenbar = (isleft?"\\leftparenbar":"\\rightparenbar");
 4314:    int	baseht=0, barht=0,		/* height of base=top+bot, bar */
 4315: 	ibar=0, nbars=0;		/* bar index, #bars between top&bot*/
 4316:    int	largestsize = min2(2,LARGESTSIZE), /* largest size for parens */
 4317: 	topfill=(isleft?0:0), botfill=(isleft?0:0),
 4318: 	barfill=(isleft?0:7);		/* alignment fillers */
 4319:    /* --- get pieces at largest size smaller than total height --- */
 4320:    for ( symsize=largestsize; symsize>=0; symsize-- ) /*largest to smallest*/
 4321:     {
 4322:     /* --- get pieces at current test size --- */
 4323:     isokay = 1;				/* check for all pieces */
 4324:     if ( (symtop=get_symsubraster(parentop,symsize)) == NULL ) isokay=0;
 4325:     if ( (symbot=get_symsubraster(parenbot,symsize)) == NULL ) isokay=0;
 4326:     if ( (symbar=get_symsubraster(parenbar,symsize)) == NULL ) isokay=0;
 4327:     /* --- check sum of pieces against total desired height --- */
 4328:     if ( isokay ) {			/* all pieces retrieved */
 4329:       baseht = (symtop->image)->height + (symbot->image)->height; /*top+bot*/
 4330:       barht  = (symbar->image)->height;	/* bar height */
 4331:       if ( baseht < height+5 ) break;	/* largest base that's not too big */
 4332:       if ( symsize < 1 ) break;		/* or smallest available base */
 4333:       } /* --- end-of-if(isokay) --- */
 4334:     /* --- free test pieces that were too big --- */
 4335:     if ( symtop != NULL ) delete_subraster(symtop); /* free top */
 4336:     if ( symbot != NULL ) delete_subraster(symbot); /* free bot */
 4337:     if ( symbar != NULL ) delete_subraster(symbar); /* free bar */
 4338:     isokay = 0;				/* nothing available */
 4339:     if ( symsize < 1 ) break;		/* leave isokay=0 after smallest */
 4340:     } /* --- end-of-for(symsize) --- */
 4341:    /* --- construct brace from pieces --- */
 4342:    if ( isokay ) {			/* we have the pieces */
 4343:     /* --- add alignment fillers --- */
 4344:     smashmargin=0;  isnocatspace=99;	/*turn off rastcat smashing,space*/
 4345:     topsym = (topfill>0?rastcat(new_subraster(topfill,1,1),symtop,3):symtop);
 4346:     botsym = (botfill>0?rastcat(new_subraster(botfill,1,1),symbot,3):symbot);
 4347:     barsym = (barfill>0?rastcat(new_subraster(barfill,1,1),symbar,3):symbar);
 4348:     smashmargin = oldsmashmargin;	/* reset smashmargin */
 4349:     isnocatspace = wasnocatspace;	/* reset isnocatspace */
 4350:     /* --- #bars needed between top and bot --- */
 4351:     nbars = (barht<1?0:max2(0,1+(height-baseht)/barht)); /* #bars needed */
 4352:     /* --- stack pieces --- */
 4353:     sp = topsym;			/* start with top piece */
 4354:     if ( nbars > 0 )			/* need nbars between top and bot */
 4355:       for ( ibar=1; ibar<=nbars; ibar++ ) sp = rastack(barsym,sp,1,0,0,2);
 4356:     sp = rastack(botsym,sp,1,0,0,3);	/* bottom below bars or middle */
 4357:     delete_subraster(barsym);		/* barsym no longer needed */
 4358:     } /* --- end-of-if(isokay) --- */
 4359:    } /* --- end-of-if/else(isdrawparen) --- */
 4360:   } /* --- end-of-if(left- or right-() paren wanted) --- */
 4361: /* -------------------------------------------------------------------------
 4362: { } braces
 4363: -------------------------------------------------------------------------- */
 4364: else
 4365:  if ( (lp=strchr(symbol,'{')) != NULL	/* left { brace wanted */
 4366:  ||   (rp=strchr(symbol,'}')) != NULL )	/* right } brace wanted */
 4367:   {
 4368:   int	isleft = (lp!=NULL?1:0);	/* true for left, false for right */
 4369:   char	*bracetop = (isleft?"\\leftbracetop":"\\rightbracetop"),
 4370: 	*bracebot = (isleft?"\\leftbracebot":"\\rightbracebot"),
 4371: 	*bracemid = (isleft?"\\leftbracemid":"\\rightbracemid"),
 4372: 	*bracebar = (isleft?"\\leftbracebar":"\\rightbracebar");
 4373:   int	baseht=0, barht=0,		/* height of base=top+bot+mid, bar */
 4374: 	ibar=0, nbars=0;		/* bar index, #bars above,below mid*/
 4375:   int	largestsize = min2(2,LARGESTSIZE), /* largest size for braces */
 4376: 	topfill=(isleft?4:0), botfill=(isleft?4:0),
 4377: 	midfill=(isleft?0:4), barfill=(isleft?4:4); /* alignment fillers */
 4378:   /* --- get pieces at largest size smaller than total height --- */
 4379:   for ( symsize=largestsize; symsize>=0; symsize-- ) /*largest to smallest*/
 4380:     {
 4381:     /* --- get pieces at current test size --- */
 4382:     isokay = 1;				/* check for all pieces */
 4383:     if ( (symtop=get_symsubraster(bracetop,symsize)) == NULL ) isokay=0;
 4384:     if ( (symbot=get_symsubraster(bracebot,symsize)) == NULL ) isokay=0;
 4385:     if ( (symmid=get_symsubraster(bracemid,symsize)) == NULL ) isokay=0;
 4386:     if ( (symbar=get_symsubraster(bracebar,symsize)) == NULL ) isokay=0;
 4387:     /* --- check sum of pieces against total desired height --- */
 4388:     if ( isokay ) {			/* all pieces retrieved */
 4389:       baseht = (symtop->image)->height + (symbot->image)->height
 4390: 	+ (symmid->image)->height;	/* top+bot+mid height */
 4391:       barht = (symbar->image)->height;	/* bar height */
 4392:       if ( baseht < height+5 ) break;	/* largest base that's not too big */
 4393:       if ( symsize < 1 ) break;		/* or smallest available base */
 4394:       } /* --- end-of-if(isokay) --- */
 4395:     /* --- free test pieces that were too big --- */
 4396:     if ( symtop != NULL ) delete_subraster(symtop); /* free top */
 4397:     if ( symbot != NULL ) delete_subraster(symbot); /* free bot */
 4398:     if ( symmid != NULL ) delete_subraster(symmid); /* free mid */
 4399:     if ( symbar != NULL ) delete_subraster(symbar); /* free bar */
 4400:     isokay = 0;				/* nothing available */
 4401:     if ( symsize < 1 ) break;		/* leave isokay=0 after smallest */
 4402:     } /* --- end-of-for(symsize) --- */
 4403:   /* --- construct brace from pieces --- */
 4404:   if ( isokay ) {			/* we have the pieces */
 4405:     /* --- add alignment fillers --- */
 4406:     smashmargin=0;  isnocatspace=99;	/*turn off rastcat smashing,space*/
 4407:     topsym = (topfill>0?rastcat(new_subraster(topfill,1,1),symtop,3):symtop);
 4408:     botsym = (botfill>0?rastcat(new_subraster(botfill,1,1),symbot,3):symbot);
 4409:     midsym = (midfill>0?rastcat(new_subraster(midfill,1,1),symmid,3):symmid);
 4410:     barsym = (barfill>0?rastcat(new_subraster(barfill,1,1),symbar,3):symbar);
 4411:     smashmargin = oldsmashmargin;	/* reset smashmargin */
 4412:     isnocatspace = wasnocatspace;	/* reset isnocatspace */
 4413:     /* --- #bars needed on each side of mid piece --- */
 4414:     nbars = (barht<1?0:max2(0,1+(height-baseht)/barht/2)); /*#bars per side*/
 4415:     /* --- stack pieces --- */
 4416:     sp = topsym;			/* start with top piece */
 4417:     if ( nbars > 0 )			/* need nbars above middle */
 4418:       for ( ibar=1; ibar<=nbars; ibar++ ) sp = rastack(barsym,sp,1,0,0,2);
 4419:     sp = rastack(midsym,sp,1,0,0,3);	/*mid after top or bars*/
 4420:     if ( nbars > 0 )			/* need nbars below middle */
 4421:       for ( ibar=1; ibar<=nbars; ibar++ ) sp = rastack(barsym,sp,1,0,0,2);
 4422:     sp = rastack(botsym,sp,1,0,0,3);	/* bottom below bars or middle */
 4423:     delete_subraster(barsym);		/* barsym no longer needed */
 4424:     } /* --- end-of-if(isokay) --- */
 4425:   } /* --- end-of-if(left- or right-{} brace wanted) --- */
 4426: /* -------------------------------------------------------------------------
 4427: [ ] brackets
 4428: -------------------------------------------------------------------------- */
 4429: else
 4430:  if ( (lp=strchr(symbol,'[')) != NULL	/* left [ bracket wanted */
 4431:  ||   (rp=strchr(symbol,']')) != NULL	/* right ] bracket wanted */
 4432:  ||   (lp2=strstr(symbol,"lceil")) != NULL /* left ceiling wanted */
 4433:  ||   (rp2=strstr(symbol,"rceil")) != NULL /* right ceiling wanted */
 4434:  ||   (lp3=strstr(symbol,"lfloor")) != NULL /* left floor wanted */
 4435:  ||   (rp3=strstr(symbol,"rfloor")) != NULL /* right floor wanted */
 4436:  ||   (lp4=strstr(symbol,"llbrack")) != NULL /* left semantic bracket */
 4437:  ||   (rp4=strstr(symbol,"rrbrack")) != NULL ) /* right semantic bracket */
 4438:   {
 4439:   /* --- use rule_raster ( rasp, top, left, width, height, type=0 ) --- */
 4440:   int	mywidth = min2(width,12),	/* max width for horizontal bars */
 4441: 	wthick = 1;			/* thickness of top.bottom bars */
 4442:   thickness = (height<25?1:2);		/* set lines 1 or 2 pixels thick */
 4443:   if ( lp2!=NULL || rp2!=NULL || lp3!=NULL || rp3 !=NULL ) /*ceil or floor*/
 4444:     wthick = thickness;			/* same thickness for top/bot bar */
 4445:   if ( lp3==NULL && rp3==NULL )		/* set top bar if floor not wanted */
 4446:     rule_raster(rasp, 0,0, mywidth,wthick, 0); /* top horizontal bar */
 4447:   if ( lp2==NULL && rp2==NULL )		/* set bot bar if ceil not wanted */
 4448:     rule_raster(rasp, height-wthick,0, mywidth,thickness, 0); /* bottom */
 4449:   if ( lp!=NULL || lp2!=NULL || lp3!=NULL || lp4!=NULL ) /* left bracket */
 4450:    rule_raster(rasp, 0,0, thickness,height, 0); /* left vertical bar */
 4451:   if ( lp4 != NULL )			/* 2nd left vertical bar needed */
 4452:    rule_raster(rasp, 0,thickness+1, 1,height, 0); /* 2nd left vertical bar */
 4453:   if ( rp!=NULL || rp2!=NULL || rp3!=NULL || rp4!=NULL ) /* right bracket */
 4454:    rule_raster(rasp, 0,mywidth-thickness, thickness,height, 0); /* right */
 4455:   if ( rp4 != NULL )			/* 2nd right vertical bar needed */
 4456:    rule_raster(rasp, 0,mywidth-thickness-2, 1,height, 0); /*2nd right vert*/
 4457:   isokay = 1;				/* set flag */
 4458:   } /* --- end-of-if(left- or right-[] bracket wanted) --- */
 4459: /* -------------------------------------------------------------------------
 4460: < > brackets
 4461: -------------------------------------------------------------------------- */
 4462: else
 4463:  if ( (lp=strchr(symbol,'<')) != NULL	/* left < bracket wanted */
 4464:  ||   (rp=strchr(symbol,'>')) != NULL )	/* right > bracket wanted */
 4465:   {
 4466:   /* --- use line_raster( rasp,  row0, col0,  row1, col1,  thickness ) --- */
 4467:   int	mywidth = min2(width,12),	/* max width for brackets */
 4468: 	mythick = 1;			/* all lines one pixel thick */
 4469:   thickness = (height<25?1:2);		/* set line pixel thickness */
 4470:   if ( lp != NULL )			/* left < bracket wanted */
 4471:     { line_raster(rasp,height/2,0,0,mywidth-1,mythick);
 4472:       if ( thickness>1 )
 4473: 	line_raster(rasp,height/2,1,0,mywidth-1,mythick);
 4474:       line_raster(rasp,height/2,0,height-1,mywidth-1,mythick);
 4475:       if ( thickness>1 )
 4476: 	line_raster(rasp,height/2,1,height-1,mywidth-1,mythick); }
 4477:   if ( rp != NULL )			/* right > bracket wanted */
 4478:     { line_raster(rasp,height/2,mywidth-1,0,0,mythick);
 4479:       if ( thickness>1 )
 4480: 	line_raster(rasp,height/2,mywidth-2,0,0,mythick);
 4481:       line_raster(rasp,height/2,mywidth-1,height-1,0,mythick);
 4482:       if ( thickness>1 )
 4483: 	line_raster(rasp,height/2,mywidth-2,height-1,0,mythick); }
 4484:   isokay = 1;				/* set flag */
 4485:   } /* --- end-of-if(left- or right-<> bracket wanted) --- */
 4486: /* -------------------------------------------------------------------------
 4487: / \ delimiters
 4488: -------------------------------------------------------------------------- */
 4489: else
 4490:  if ( (lp=strchr(symbol,'/')) != NULL	/* left /  wanted */
 4491:  ||   (rp=strstr(symbol,"\\\\")) != NULL /* right \ wanted */
 4492:  ||   (rp2=strstr(symbol,"backsl")) != NULL ) /* right \ wanted */
 4493:   {
 4494:   /* --- use line_raster( rasp,  row0, col0,  row1, col1,  thickness ) --- */
 4495:   int	mywidth = width;		/* max width for / \ */
 4496:   thickness = 1;			/* set line pixel thickness */
 4497:   if ( lp != NULL )			/* left / wanted */
 4498:     line_raster(rasp,0,mywidth-1,height-1,0,thickness);
 4499:   if ( rp!=NULL || rp2!=NULL )		/* right \ wanted */
 4500:     line_raster(rasp,0,0,height-1,mywidth-1,thickness);
 4501:   isokay = 1;				/* set flag */
 4502:   } /* --- end-of-if(left- or right-/\ delimiter wanted) --- */
 4503: /* -------------------------------------------------------------------------
 4504: arrow delimiters
 4505: -------------------------------------------------------------------------- */
 4506: else
 4507:  if ( strstr(symbol,"arrow") != NULL )	/* arrow delimiter wanted */
 4508:   {
 4509:   /* --- use uparrow_subraster(width,height,pixsz,drctn,isBig) --- */
 4510:   int	mywidth = width;		/* max width for / \ */
 4511:   int	isBig = (strstr(symbol,"Up")!=NULL /* isBig if we have an Up */
 4512: 		|| strstr(symbol,"Down")!=NULL); /* or a Down */
 4513:   int	drctn = +1;			/* init for uparrow */
 4514:   if ( strstr(symbol,"down")!=NULL	/* down if we have down */
 4515:   ||   strstr(symbol,"Down")!=NULL )	/* or Down */
 4516:    { drctn = (-1);			/* reset direction to down */
 4517:      if ( strstr(symbol,"up")!=NULL	/* updown if we have up or Up */
 4518:      ||   strstr(symbol,"Up")!=NULL )	/* and down or Down */
 4519:       drctn = 0; }			/* reset direction to updown */
 4520:   sp = uparrow_subraster(mywidth,height,pixsz,drctn,isBig);
 4521:   if ( sp != NULL )
 4522:    { sp->type = IMAGERASTER;		/* image */
 4523:      sp->symdef = NULL;			/* not applicable for image */
 4524:      sp->baseline = height/2 + 2;	/* is a little above center good? */
 4525:      sp->size = NORMALSIZE;		/* size (probably unneeded) */
 4526:      isokay = 1; }			/* set flag */
 4527:   } /* --- end-of-if(arrow delimiter wanted) --- */
 4528: /* -------------------------------------------------------------------------
 4529: \- for | | brackets or \= for || || brackets
 4530: -------------------------------------------------------------------------- */
 4531: else
 4532:  if ( (lp=strchr(symbol,'-')) != NULL	/* left or right | bracket wanted */
 4533:  ||  (lp2=strchr(symbol,'|')) != NULL	/* synonym for | bracket */
 4534:  ||   (rp=strchr(symbol,'=')) != NULL	/* left or right || bracket wanted */
 4535:  || (rp2=strstr(symbol,"\\|"))!= NULL )	/* || in standard tex notation */
 4536:   {
 4537:   /* --- rule_raster ( rasp, top, left, width, height, type=0 ) --- */
 4538:   int	midcol = width/2;		/* middle col, left of mid if even */
 4539:   if ( rp  != NULL			/* left or right || bracket wanted */
 4540:   ||   rp2 != NULL )			/* or || in standard tex notation */
 4541:    { thickness = (height<75?1:2);	/* each | of || 1 or 2 pixels thick*/
 4542:      rule_raster(rasp, 0,max2(0,midcol-2), thickness,height, 0); /* left */
 4543:      rule_raster(rasp, 0,min2(width,midcol+2), thickness,height, 0); }
 4544:   else					/*nb, lp2 spuriously set if rp2 set*/
 4545:    if ( lp  != NULL			/* left or right | bracket wanted */
 4546:    ||   lp2 != NULL )			/* ditto for synomym */
 4547:     { thickness = (height<75?1:2);	/* set | 1 or 2 pixels thick */
 4548:       rule_raster(rasp, 0,midcol, thickness,height, 0); } /*mid vertical bar*/
 4549:   isokay = 1;				/* set flag */
 4550:   } /* --- end-of-if(left- or right-[] bracket wanted) --- */
 4551: /* -------------------------------------------------------------------------
 4552: back to caller
 4553: -------------------------------------------------------------------------- */
 4554: end_of_job:
 4555:   if ( msgfp!=NULL && msglevel>=99 )
 4556:     fprintf(msgfp,"make_delim> symbol=%.50s, isokay=%d\n",
 4557:     (symbol==NULL?"null":symbol),isokay);
 4558:   if ( !isokay )			/* don't have requested delimiter */
 4559:     { if (sp!=NULL) delete_subraster(sp); /* so free unneeded structure */
 4560:       sp = NULL; }			/* and signal error to caller */
 4561:   return ( sp );			/*back to caller with delim or NULL*/
 4562: } /* --- end-of-function make_delim() --- */
 4563: 
 4564: 
 4565: /* ==========================================================================
 4566:  * Function:	texchar ( expression, chartoken )
 4567:  * Purpose:	scans expression, returning either its first character,
 4568:  *		or the next \sequence if that first char is \,
 4569:  *		and a pointer to the first expression char past that.
 4570:  * --------------------------------------------------------------------------
 4571:  * Arguments:	expression (I)	char * to first char of null-terminated
 4572:  *				string containing valid LaTeX expression
 4573:  *				to be scanned
 4574:  *		chartoken (O)	char * to null-terminated string returning
 4575:  *				either the first (non-whitespace) character
 4576:  *				of expression if that char isn't \, or else
 4577:  *				the \ and everything following it up to
 4578:  *				the next non-alphabetic character (but at
 4579:  *				least one char following the \ even if
 4580:  *				it's non-alpha)
 4581:  * --------------------------------------------------------------------------
 4582:  * Returns:	( char * )	ptr to the first char of expression
 4583:  *				past returned chartoken,
 4584:  *				or NULL for any parsing error.
 4585:  * --------------------------------------------------------------------------
 4586:  * Notes:     o	Does *not* skip leading whitespace, but simply
 4587:  *		returns any whitespace character as the next character.
 4588:  * ======================================================================= */
 4589: /* --- entry point --- */
 4590: char	*texchar ( char *expression, char *chartoken )
 4591: {
 4592: /* -------------------------------------------------------------------------
 4593: Allocations and Declarations
 4594: -------------------------------------------------------------------------- */
 4595: int	esclen = 0,				/*length of escape sequence*/
 4596: 	maxesclen = 128;			/* max len of esc sequence */
 4597: char	*ptoken = chartoken;			/* ptr into chartoken */
 4598: int	iprefix = 0;				/* prefix index */
 4599: static	char *prefixes[] =			/*e.g., \big followed by ( */
 4600: 	{ /* "\\left", "\\right", */
 4601: 	  "\\big",  "\\Big",  "\\bigg",  "\\Bigg",
 4602: 	  "\\bigl", "\\Bigl", "\\biggl", "\\Biggl",
 4603: 	  "\\bigr", "\\Bigr", "\\biggr", "\\Biggr", NULL };
 4604: static	char *starred[] =			/* may be followed by * */
 4605: 	{ "\\hspace",  "\\!",  NULL };
 4606: /* -------------------------------------------------------------------------
 4607: just return the next char if it's not \
 4608: -------------------------------------------------------------------------- */
 4609: /* --- error check for end-of-string --- */
 4610: *ptoken = '\000';				/* init in case of error */
 4611: if ( expression == NULL ) return(NULL);		/* nothing to scan */
 4612: if ( *expression == '\000' ) return(NULL);	/* nothing to scan */
 4613: /* --- always returning first character (either \ or some other char) --- */
 4614: *ptoken++ = *expression++;			/* here's first character */
 4615: /* --- if first char isn't \, then just return it to caller --- */
 4616: if ( !isthischar(*(expression-1),ESCAPE) )	/* not a \, so return char */
 4617:   { *ptoken = '\000';				/* add a null terminator */
 4618:     goto end_of_job; }				/* ptr past returned char */
 4619: if ( *expression == '\000' )			/* \ is very last char */
 4620:   { *chartoken = '\000';			/* flush bad trailing \ */
 4621:     return(NULL); }				/* and signal end-of-job */
 4622: /* -------------------------------------------------------------------------
 4623: we have an escape sequence, so return all alpha chars following \
 4624: -------------------------------------------------------------------------- */
 4625: /* --- accumulate chars until first non-alpha char found --- */
 4626: for ( ; isalpha(*expression); esclen++ )	/* till first non-alpha... */
 4627:   { if ( esclen < maxesclen-3 )			/* more room in chartoken */
 4628:       *ptoken++ = *expression;			/*copy alpha char, bump ptr*/
 4629:     expression++; }				/* bump expression ptr */
 4630: /* --- if we have a prefix, append next texchar, e.g., \big( --- */
 4631: *ptoken = '\000';				/* set null for compare */
 4632: for ( iprefix=0; prefixes[iprefix] != NULL; iprefix++ ) /* run thru list */
 4633:  if ( strcmp(chartoken,prefixes[iprefix]) == 0 ) /* have an exact match */
 4634:   { char nextchar[256];  int nextlen=0;		/* texchar after prefix */
 4635:     skipwhite(expression);			/* skip space after prefix*/
 4636:     expression = texchar(expression,nextchar);	/* get nextchar */
 4637:     if ( (nextlen = strlen(nextchar)) > 0 )	/* #chars in nextchar */
 4638:       { strcpy(ptoken,nextchar);		/* append nextchar */
 4639:         ptoken += strlen(nextchar);		/* point to null terminator*/
 4640:         esclen += strlen(nextchar); }		/* and bump escape length */
 4641:     break; }					/* stop checking prefixes */
 4642: /* --- every \ must be followed by at least one char, e.g., \[ --- */
 4643: if ( esclen < 1 )				/* \ followed by non-alpha */
 4644:   *ptoken++ = *expression++;			/*copy non-alpha, bump ptrs*/
 4645: *ptoken = '\000';				/* null-terminate token */
 4646: /* --- check for \hspace* or other starred commands --- */
 4647: for ( iprefix=0; starred[iprefix] != NULL; iprefix++ ) /* run thru list */
 4648:  if ( strcmp(chartoken,starred[iprefix]) == 0 )	/* have an exact match */
 4649:   if ( *expression == '*' )			/* follows by a * */
 4650:    { *ptoken++ = *expression++;			/* copy * and bump ptr */
 4651:      *ptoken = '\000';				/* null-terminate token */
 4652:      break; }					/* stop checking */
 4653: /* --- respect spaces in text mode, except first space after \escape --- */
 4654: if ( esclen >= 1 ) {				/*only for alpha \sequences*/
 4655:   if ( istextmode )				/* in \rm or \it text mode */
 4656:    if ( isthischar(*expression,WHITEDELIM) )	/* delim follows \sequence */
 4657:     expression++; }				/* so flush delim */
 4658: /* --- back to caller --- */
 4659: end_of_job:
 4660:   if ( msgfp!=NULL && msglevel>=999 )
 4661:     { fprintf(msgfp,"texchar> returning token = \"%s\"\n",chartoken);
 4662:       fflush(msgfp); }
 4663:   return ( expression );			/*ptr to 1st non-alpha char*/
 4664: } /* --- end-of-function texchar() --- */
 4665: 
 4666: 
 4667: /* ==========================================================================
 4668:  * Function:	texsubexpr (expression,subexpr,maxsubsz,
 4669:  *		left,right,isescape,isdelim)
 4670:  * Purpose:	scans expression, returning everything between a balanced
 4671:  *		left{...right} subexpression if the first non-whitespace
 4672:  *		char of expression is an (escaped or unescaped) left{,
 4673:  *		or just the next texchar() otherwise,
 4674:  *		and a pointer to the first expression char past that.
 4675:  * --------------------------------------------------------------------------
 4676:  * Arguments:	expression (I)	char * to first char of null-terminated
 4677:  *				string containing valid LaTeX expression
 4678:  *				to be scanned
 4679:  *		subexpr (O)	char * to null-terminated string returning
 4680:  *				either everything between a balanced {...}
 4681:  *				subexpression if the first char is {,
 4682:  *				or the next texchar() otherwise.
 4683:  *		maxsubsz (I)	int containing max #bytes returned
 4684:  *				in subexpr buffer (0 means unlimited)
 4685:  *		left (I)	char * specifying allowable left delimiters
 4686:  *				that begin subexpression, e.g., "{[(<"
 4687:  *		right (I)	char * specifying matching right delimiters
 4688:  *				in the same order as left, e.g., "}])>"
 4689:  *		isescape (I)	int controlling whether escaped and/or
 4690:  *				unescaped left,right are matched;
 4691:  *				see isbrace() comments below for details.
 4692:  *		isdelim (I)	int containing true (non-zero) to return
 4693:  *				the leading left and trailing right delims
 4694:  *				(if any were found) along with subexpr,
 4695:  *				or containing false=0 to return subexpr
 4696:  *				without its delimiters
 4697:  * --------------------------------------------------------------------------
 4698:  * Returns:	( char * )	ptr to the first char of expression
 4699:  *				past returned subexpr (see Notes),
 4700:  *				or NULL for any parsing error.
 4701:  * --------------------------------------------------------------------------
 4702:  * Notes:     o	If subexpr is of the form left{...right},
 4703:  *		the outer {}'s are returned as part of subexpr
 4704:  *		if isdelim is true; if isdelim is false the {}'s aren't
 4705:  *		returned.  In either case the returned pointer is
 4706:  *		*always* bumped past the closing right}, even if
 4707:  *		that closing right} isn't returned in subexpr.
 4708:  *	      o	If subexpr is not of the form left{...right},
 4709:  *		the returned pointer is on the character immediately
 4710:  *		following the last character returned in subexpr
 4711:  *	      o	\. acts as LaTeX \right. and matches any \left(
 4712:  *		And it also acts as a LaTeX \left. and matches any \right)
 4713:  * ======================================================================= */
 4714: /* --- entry point --- */
 4715: char	*texsubexpr ( char *expression, char *subexpr, int maxsubsz,
 4716: 	char *left, char *right, int isescape, int isdelim )
 4717: {
 4718: /* -------------------------------------------------------------------------
 4719: Allocations and Declarations
 4720: -------------------------------------------------------------------------- */
 4721: char	*texchar();		/*next char (or \sequence) from expression*/
 4722: char	*leftptr, leftdelim[256] = "(\000", /* left( found in expression */
 4723: 	rightdelim[256] = ")\000"; /* and matching right) */
 4724: char	*origexpression=expression, *origsubexpr=subexpr; /*original inputs*/
 4725: char	*strtexchr(), *texleft(); /* check for \left, and get it */
 4726: int	gotescape = 0,		/* true if leading char of expression is \ */
 4727: 	prevescape = 0;		/* while parsing, true if preceding char \ */
 4728: int	isbrace();		/* check for left,right braces */
 4729: int	isanyright = 1;		/* true matches any right with left, (...] */
 4730: int	isleftdot = 0;		/* true if left brace is a \. */
 4731: int	nestlevel = 1;		/* current # of nested braces */
 4732: int	subsz=0 /*,maxsubsz=MAXSUBXSZ*/; /*#chars in returned subexpr buffer*/
 4733: /* -------------------------------------------------------------------------
 4734: skip leading whitespace and just return the next char if it's not {
 4735: -------------------------------------------------------------------------- */
 4736: /* --- skip leading whitespace and error check for end-of-string --- */
 4737: *subexpr = '\000';				/* init in case of error */
 4738: if ( expression == NULL ) return(NULL);		/*can't dereference null ptr*/
 4739: skipwhite(expression);				/* leading whitespace gone */
 4740: if ( *expression == '\000' ) return(NULL);	/* nothing left to scan */
 4741: /* --- set maxsubsz --- */
 4742: if ( maxsubsz < 1 ) maxsubsz = MAXSUBXSZ-2;	/* input 0 means unlimited */
 4743: /* --- check for escape --- */
 4744: if ( isthischar(*expression,ESCAPE) )		/* expression is escaped */
 4745:   gotescape = 1;				/* so set flag accordingly */
 4746: /* --- check for \left...\right --- */
 4747: if ( gotescape )				/* begins with \ */
 4748:  if ( memcmp(expression+1,"left",4) )		/* and followed by left */
 4749:   if ( strchr(left,'l') != NULL )		/* caller wants \left's */
 4750:    if ( strtexchr(expression,"\\left") == expression ) /*expression=\left...*/
 4751:     { char *pright = texleft(expression,subexpr,maxsubsz, /* find ...\right*/
 4752: 	(isdelim?NULL:leftdelim),rightdelim);
 4753:       if ( isdelim ) strcat(subexpr,rightdelim); /* caller wants delims */
 4754:       return ( pright );			/*back to caller past \right*/
 4755:     } /* --- end-of-if(expression=="\\left") --- */
 4756: /* --- if first char isn't left{ or script, just return it to caller --- */
 4757: if ( !isbrace(expression,left,isescape) ) {	/* not a left{ */
 4758:   if ( !isthischar(*expression,SCRIPTS) )	/* and not a script */
 4759:     return ( texchar(expression,subexpr) );	/* next char to caller */
 4760:   else /* --- kludge for super/subscripts to accommodate texscripts() --- */
 4761:     { *subexpr++ = *expression;			/* signal script */
 4762:       *subexpr = '\000';			/* null-terminate subexpr */
 4763:       return ( expression ); } }		/* leave script in stream */
 4764: /* --- extract left and find matching right delimiter --- */
 4765: *leftdelim  = *(expression+gotescape);		/* the left( in expression */
 4766: if ( (gotescape && *leftdelim == '.')		/* we have a left \. */
 4767: ||   (gotescape && isanyright) )		/*or are matching any right*/
 4768:   { isleftdot = 1;				/* so just set flag */
 4769:     *leftdelim = '\000'; }			/* and reset leftdelim */
 4770: else						/* find matching \right */
 4771:   if ( (leftptr=strchr(left,*leftdelim)) != NULL ) /* ptr to that left( */
 4772:     *rightdelim = right[(int)(leftptr-left)];	/* get the matching right) */
 4773:   else						/* can't happen -- pgm bug */
 4774:     return ( NULL );				/*just signal eoj to caller*/
 4775: /* -------------------------------------------------------------------------
 4776: accumulate chars between balanced {}'s, i.e., till nestlevel returns to 0
 4777: -------------------------------------------------------------------------- */
 4778: /* --- first initialize by bumping past left{ or \{ --- */
 4779: if ( isdelim )   *subexpr++ = *expression++;	/*caller wants { in subexpr*/
 4780:   else expression++;				/* always bump past left{ */
 4781: if ( gotescape ) {				/*need to bump another char*/
 4782:   if ( isdelim ) *subexpr++ = *expression++;	/* caller wants char, too */
 4783:   else expression++; }				/* else just bump past it */
 4784: /* --- set maximum size for numerical arguments --- */
 4785: if ( 0 )					/* check turned on or off? */
 4786:  if ( !isescape && !isdelim )			/*looking for numerical arg*/
 4787:   maxsubsz = 96;				/* set max arg size */
 4788: /* --- search for matching right} --- */
 4789: while ( 1 )					/*until balanced right} */
 4790:   {
 4791:   /* --- error check for end-of-string --- */
 4792:   if ( *expression == '\000' )			/* premature end-of-string */
 4793:     { if ( 0 && (!isescape && !isdelim) )	/*looking for numerical arg,*/
 4794: 	{ expression = origexpression;		/* so end-of-string is error*/
 4795: 	  subexpr = origsubexpr; }		/* so reset all ptrs */
 4796:       if ( isdelim ) {				/* generate fake right */
 4797: 	if ( gotescape )			/* need escaped right */
 4798: 	  { *subexpr++ = '\\';			/* set escape char */
 4799: 	    *subexpr++ = '.'; }			/* and fake \right. */
 4800: 	else					/* escape not wanted */
 4801: 	    *subexpr++ = *rightdelim; }		/* so fake actual right */
 4802:       *subexpr = '\000';			/* null-terminate subexpr */
 4803:       return ( expression ); }			/* back with final token */
 4804:   /* --- check preceding char for escape --- */
 4805:   if ( isthischar(*(expression-1),ESCAPE) )	/* previous char was \ */
 4806: 	prevescape = 1-prevescape;		/* so flip escape flag */
 4807:   else	prevescape = 0;				/* or turn flag off */
 4808:   /* --- check for { and } (un/escaped as per leading left) --- */
 4809:   if ( gotescape == prevescape )		/* escaped iff leading is */
 4810:     { /* --- check for (closing) right delim and see if we're done --- */
 4811:       if ( isthischar(*expression,rightdelim)	/* found a right} */
 4812:       ||   (isleftdot && isthischar(*expression,right)) /*\left. matches all*/
 4813:       ||   (prevescape && isthischar(*expression,".")) ) /*or found \right. */
 4814:         if ( --nestlevel < 1 )			/*\right balances 1st \left*/
 4815: 	  { if ( isdelim ) 			/*caller wants } in subexpr*/
 4816: 	      *subexpr++ = *expression;		/* so end subexpr with } */
 4817: 	    else				/*check for \ before right}*/
 4818: 	      if ( prevescape )			/* have unwanted \ */
 4819: 		*(subexpr-1) = '\000';		/* so replace it with null */
 4820: 	    *subexpr = '\000';			/* null-terminate subexpr */
 4821: 	    return ( expression+1 ); }		/* back with char after } */
 4822:       /* --- check for (another) left{ --- */
 4823:       if ( isthischar(*expression,leftdelim)	/* found another left{ */
 4824:       ||   (isleftdot && isthischar(*expression,left)) ) /* any left{ */
 4825: 	nestlevel++;
 4826:     } /* --- end-of-if(gotescape==prevescape) --- */
 4827:   /* --- not done, so copy char to subexpr and continue with next char --- */
 4828:   if ( ++subsz < maxsubsz-5 )			/* more room in subexpr */
 4829:     *subexpr++ = *expression;			/* so copy char and bump ptr*/
 4830:   expression++;					/* bump expression ptr */
 4831:   } /* --- end-of-while(1) --- */
 4832: } /* --- end-of-function texsubexpr() --- */
 4833: 
 4834: 
 4835: /* ==========================================================================
 4836:  * Function:	texleft (expression,subexpr,maxsubsz,ldelim,rdelim)
 4837:  * Purpose:	scans expression, starting after opening \left,
 4838:  *		and returning ptr after matching closing \right.
 4839:  *		Everything between is returned in subexpr, if given.
 4840:  *		Likewise, if given, ldelim returns delimiter after \left
 4841:  *		and rdelim returns delimiter after \right.
 4842:  *		If ldelim is given, the returned subexpr doesn't include it.
 4843:  *		If rdelim is given, the returned pointer is after that delim.
 4844:  * --------------------------------------------------------------------------
 4845:  * Arguments:	expression (I)	char * to first char of null-terminated
 4846:  *				string immediately following opening \left
 4847:  *		subexpr (O)	char * to null-terminated string returning
 4848:  *				either everything between balanced
 4849:  *				\left ... \right.  If leftdelim given,
 4850:  *				subexpr does _not_ contain that delimiter.
 4851:  *		maxsubsz (I)	int containing max #bytes returned
 4852:  *				in subexpr buffer (0 means unlimited)
 4853:  *		ldelim (O)	char * returning delimiter following
 4854:  *				opening \left
 4855:  *		rdelim (O)	char * returning delimiter following
 4856:  *				closing \right
 4857:  * --------------------------------------------------------------------------
 4858:  * Returns:	( char * )	ptr to the first char of expression
 4859:  *				past closing \right, or past closing
 4860:  *				right delimiter if rdelim!=NULL,
 4861:  *				or NULL for any error.
 4862:  * --------------------------------------------------------------------------
 4863:  * Notes:     o
 4864:  * ======================================================================= */
 4865: /* --- entry point --- */
 4866: char	*texleft ( char *expression, char *subexpr, int maxsubsz,
 4867: 	char *ldelim, char *rdelim )
 4868: {
 4869: /* -------------------------------------------------------------------------
 4870: Allocations and Declarations
 4871: -------------------------------------------------------------------------- */
 4872: char	*texchar(),			/* get delims after \left,\right */
 4873: 	*strtexchr(), *pright=expression; /* locate matching \right */
 4874: static	char left[16]="\\left", right[16]="\\right"; /* tex delimiters */
 4875: int	sublen = 0;			/* #chars between \left...\right */
 4876: /* -------------------------------------------------------------------------
 4877: initialization
 4878: -------------------------------------------------------------------------- */
 4879: /* --- init output --- */
 4880: if ( subexpr != NULL ) *subexpr = '\000'; /* init subexpr, if given */
 4881: if ( ldelim  != NULL ) *ldelim  = '\000'; /* init ldelim,  if given */
 4882: if ( rdelim  != NULL ) *rdelim  = '\000'; /* init rdelim,  if given */
 4883: /* --- check args --- */
 4884: if ( expression == NULL ) goto end_of_job; /* no input supplied */
 4885: if ( *expression == '\000' ) goto end_of_job; /* nothing after \left */
 4886: /* --- determine left delimiter  --- */
 4887: if ( ldelim != NULL )			/* caller wants left delim */
 4888:  { skipwhite(expression);		/* interpret \left ( as \left( */
 4889:    expression = texchar(expression,ldelim); } /*delim from expression*/
 4890: /* -------------------------------------------------------------------------
 4891: locate \right balancing opening \left
 4892: -------------------------------------------------------------------------- */
 4893: /* --- first \right following \left --- */
 4894: if ( (pright=strtexchr(expression,right)) /* look for \right after \left */
 4895: !=   NULL ) {				/* found it */
 4896:  /* --- find matching \right by pushing past any nested \left's --- */
 4897:  char *pleft = expression;		/* start after first \left( */
 4898:  while ( 1 ) {				/*break when matching \right found*/
 4899:   /* -- locate next nested \left if there is one --- */
 4900:   if ( (pleft=strtexchr(pleft,left))	/* find next \left */
 4901:   ==   NULL ) break;			/*no more, so matching \right found*/
 4902:   pleft += strlen(left);		/* push ptr past \left token */
 4903:   if ( pleft >= pright ) break;		/* not nested if \left after \right*/
 4904:   /* --- have nested \left, so push forward to next \right --- */
 4905:   if ( (pright=strtexchr(pright+strlen(right),right)) /* find next \right */
 4906:   ==   NULL ) break;			/* ran out of \right's */
 4907:   } /* --- end-of-while(1) --- */
 4908:  } /* --- end-of-if(pright!=NULL) --- */
 4909: /* --- set subexpression length, push pright past \right --- */
 4910: if ( pright != (char *)NULL )		/* found matching \right */
 4911:  { sublen = (int)(pright-expression);	/* #chars between \left...\right */
 4912:    pright += strlen(right); }		/* so push pright past \right */
 4913: /* -------------------------------------------------------------------------
 4914: get rightdelim and subexpr between \left...\right
 4915: -------------------------------------------------------------------------- */
 4916: /* --- get delimiter following \right --- */
 4917: if ( rdelim != NULL ) {			/* caller wants right delim */
 4918:  if ( pright == (char *)NULL )		/* assume \right. at end of exprssn*/
 4919:   { strcpy(rdelim,".");			/* set default \right. */
 4920:     sublen = strlen(expression);	/* use entire remaining expression */
 4921:     pright = expression + sublen; }	/* and push pright to end-of-string*/
 4922:  else					/* have explicit matching \right */
 4923:   { skipwhite(pright);			/* interpret \right ) as \right) */
 4924:     pright = texchar(pright,rdelim);	/* pull delim from expression */
 4925:     if ( *rdelim == '\000' ) strcpy(rdelim,"."); } } /* or set \right. */
 4926: /* --- get subexpression between \left...\right --- */
 4927: if ( sublen > 0 )			/* have subexpr */
 4928:  if ( subexpr != NULL ) {		/* and caller wants it */
 4929:   if ( maxsubsz > 0 ) sublen = min2(sublen,maxsubsz-1); /* max buffer size */
 4930:   memcpy(subexpr,expression,sublen);	/* stuff between \left...\right */
 4931:   subexpr[sublen] = '\000'; }		/* null-terminate subexpr */
 4932: end_of_job:
 4933:   if ( msglevel>=99 && msgfp!=NULL )
 4934:     { fprintf(msgfp,"texleft> ldelim=%s, rdelim=%s, subexpr=%.128s\n",
 4935:       (ldelim==NULL?"none":ldelim),(rdelim==NULL?"none":rdelim),
 4936:       (subexpr==NULL?"none":subexpr)); fflush(msgfp); }
 4937:   return ( pright );
 4938: } /* --- end-of-function texleft --- */
 4939: 
 4940: 
 4941: /* ==========================================================================
 4942:  * Function:	texscripts ( expression, subscript, superscript, which )
 4943:  * Purpose:	scans expression, returning subscript and/or superscript
 4944:  *		if expression is of the form _x^y or ^{x}_{y},
 4945:  *		or any (valid LaTeX) permutation of the above,
 4946:  *		and a pointer to the first expression char past "scripts"
 4947:  * --------------------------------------------------------------------------
 4948:  * Arguments:	expression (I)	char * to first char of null-terminated
 4949:  *				string containing valid LaTeX expression
 4950:  *				to be scanned
 4951:  *		subscript (O)	char * to null-terminated string returning
 4952:  *				subscript (without _), if found, or "\000"
 4953:  *		superscript (O)	char * to null-terminated string returning
 4954:  *				superscript (without ^), if found, or "\000"
 4955:  *		which (I)	int containing 1 for subscript only,
 4956:  *				2 for superscript only, >=3 for either/both
 4957:  * --------------------------------------------------------------------------
 4958:  * Returns:	( char * )	ptr to the first char of expression
 4959:  *				past returned "scripts" (unchanged
 4960:  *				except for skipped whitespace if
 4961:  *				neither subscript nor superscript found),
 4962:  *				or NULL for any parsing error.
 4963:  * --------------------------------------------------------------------------
 4964:  * Notes:     o	an input expression like ^a^b_c will return superscript="b",
 4965:  *		i.e., totally ignoring all but the last "script" encountered
 4966:  * ======================================================================= */
 4967: /* --- entry point --- */
 4968: char	*texscripts ( char *expression, char *subscript,
 4969: 			char *superscript, int which )
 4970: {
 4971: /* -------------------------------------------------------------------------
 4972: Allocations and Declarations
 4973: -------------------------------------------------------------------------- */
 4974: char	*texsubexpr();		/* next subexpression from expression */
 4975: int	gotsub=0, gotsup=0;	/* check that we don't eat, e.g., x_1_2 */
 4976: /* -------------------------------------------------------------------------
 4977: init "scripts"
 4978: -------------------------------------------------------------------------- */
 4979: if ( subscript != NULL ) *subscript = '\000';	/*init in case no subscript*/
 4980: if ( superscript!=NULL ) *superscript = '\000';	/*init in case no super*/
 4981: /* -------------------------------------------------------------------------
 4982: get subscript and/or superscript from expression
 4983: -------------------------------------------------------------------------- */
 4984: while ( expression != NULL ) {
 4985:   skipwhite(expression);			/* leading whitespace gone */
 4986:   if ( *expression == '\000' ) return(expression); /* nothing left to scan */
 4987:   if ( isthischar(*expression,SUBSCRIPT)	/* found _ */
 4988:   &&   (which==1 || which>2 ) )			/* and caller wants it */
 4989:     { if ( gotsub				/* found 2nd subscript */
 4990:       ||   subscript == NULL ) break;		/* or no subscript buffer */
 4991:       gotsub = 1;				/* set subscript flag */
 4992:       expression = texsubexpr(expression+1,subscript,0,"{","}",0,0); }
 4993:   else						/* no _, check for ^ */
 4994:     if ( isthischar(*expression,SUPERSCRIPT)	/* found ^ */
 4995:     &&   which>=2  )				/* and caller wants it */
 4996:       {	if ( gotsup				/* found 2nd superscript */
 4997: 	||   superscript == NULL ) break;	/* or no superscript buffer*/
 4998: 	gotsup = 1;				/* set superscript flag */
 4999: 	expression = texsubexpr(expression+1,superscript,0,"{","}",0,0); }
 5000:     else					/* neither _ nor ^ */
 5001:       return ( expression );			/*return ptr past "scripts"*/
 5002:   } /* --- end-of-while(expression!=NULL) --- */
 5003: return ( expression );
 5004: } /* --- end-of-function texscripts() --- */
 5005: 
 5006: 
 5007: /* ==========================================================================
 5008:  * Function:	isbrace ( expression, braces, isescape )
 5009:  * Purpose:	checks leading char(s) of expression for a brace,
 5010:  *		either escaped or unescaped depending on isescape,
 5011:  *		except that { and } are always matched, if they're
 5012:  *		in braces, regardless of isescape.
 5013:  * --------------------------------------------------------------------------
 5014:  * Arguments:	expression (I)	char * to first char of null-terminated
 5015:  *				string containing a valid LaTeX expression
 5016:  *				whose leading char(s) are checked for braces
 5017:  *				that begin subexpression, e.g., "{[(<"
 5018:  *		braces (I)	char * specifying matching brace delimiters
 5019:  *				to be checked for, e.g., "{[(<" or "}])>"
 5020:  *		isescape (I)	int containing 0 to match only unescaped
 5021:  *				braces, e.g., (...) or {...}, etc,
 5022:  *				or containing 1 to match only escaped
 5023:  *				braces, e.g., \(...\) or \[...\], etc,
 5024:  *				or containing 2 to match either.
 5025:  *				But note: if {,} are in braces
 5026:  *				then they're *always* matched whether
 5027:  *				escaped or not, regardless of isescape.
 5028:  * --------------------------------------------------------------------------
 5029:  * Returns:	( int )		1 if the leading char(s) of expression
 5030:  *				is a brace, or 0 if not.
 5031:  * --------------------------------------------------------------------------
 5032:  * Notes:     o
 5033:  * ======================================================================= */
 5034: /* --- entry point --- */
 5035: int	isbrace ( char *expression, char *braces, int isescape )
 5036: {
 5037: /* -------------------------------------------------------------------------
 5038: Allocations and Declarations
 5039: -------------------------------------------------------------------------- */
 5040: int	gotescape = 0,		/* true if leading char is an escape */
 5041: 	gotbrace = 0;		/*true if first non-escape char is a brace*/
 5042: /* -------------------------------------------------------------------------
 5043: check for brace
 5044: -------------------------------------------------------------------------- */
 5045: /* --- first check for end-of-string or \= ligature --- */
 5046: if ( *expression == '\000'			/* nothing to check */
 5047: ||   isligature ) goto end_of_job;		/* have a \= ligature */
 5048: /* --- check leading char for escape --- */
 5049: if ( isthischar(*expression,ESCAPE) )		/* expression is escaped */
 5050:   { gotescape = 1;				/* so set flag accordingly */
 5051:     expression++; }				/* and bump past escape */
 5052: /* --- check (maybe next char) for brace --- */
 5053: if ( isthischar(*expression,braces) )		/* expression is braced */
 5054:   gotbrace = 1;					/* so set flag accordingly */
 5055: if ( gotescape && *expression == '.' )		/* \. matches any brace */
 5056:   gotbrace = 1;					/* set flag */
 5057: /* --- check for TeX brace { or } --- */
 5058: if ( gotbrace && isthischar(*expression,"{}") )	/*expression has TeX brace*/
 5059:   if ( isescape ) isescape = 2;			/* reset escape flag */
 5060: /* -------------------------------------------------------------------------
 5061: back to caller
 5062: -------------------------------------------------------------------------- */
 5063: end_of_job:
 5064:  if ( msglevel>=999 && msgfp!=NULL )
 5065:   { fprintf(msgfp,"isbrace> expression=%.8s, gotbrace=%d (isligature=%d)\n",
 5066:     expression,gotbrace,isligature); fflush(msgfp); }
 5067:  if ( gotbrace &&				/* found a brace */
 5068:      ( isescape==2 ||				/* escape irrelevant */
 5069:        gotescape==isescape )			/* un/escaped as requested */
 5070:    ) return ( 1 );  return ( 0 );		/* return 1,0 accordingly */
 5071: } /* --- end-of-function isbrace() --- */
 5072: 
 5073: 
 5074: /* ==========================================================================
 5075:  * Function:	preamble ( expression, size, subexpr )
 5076:  * Purpose:	parses $-terminated preamble, if present, at beginning
 5077:  *		of expression, re-setting size if necessary, and
 5078:  *		returning any other parameters besides size in subexpr.
 5079:  * --------------------------------------------------------------------------
 5080:  * Arguments:	expression (I)	char * to first char of null-terminated
 5081:  *				string containing LaTeX expression possibly
 5082:  *				preceded by $-terminated preamble
 5083:  *		size (I/O)	int *  containing 0-4 default font size,
 5084:  *				and returning size modified by first
 5085:  *				preamble parameter (or unchanged)
 5086:  *		subexpr(O)	char *  returning any remaining preamble
 5087:  *				parameters past size
 5088:  * --------------------------------------------------------------------------
 5089:  * Returns:	( char * )	ptr to first char past preamble in expression
 5090:  *				or NULL for any parsing error.
 5091:  * --------------------------------------------------------------------------
 5092:  * Notes:     o	size can be any number >=0. If preceded by + or -, it's
 5093:  *		interpreted as an increment to input size; otherwise
 5094:  *		it's interpreted as the size.
 5095:  *	      o	if subexpr is passed as NULL ptr, then returned expression
 5096:  *		ptr will have "flushed" and preamble parameters after size
 5097:  * ======================================================================= */
 5098: /* --- entry point --- */
 5099: char	*preamble ( char *expression, int *size, char *subexpr )
 5100: {
 5101: /* -------------------------------------------------------------------------
 5102: Allocations and Declarations
 5103: -------------------------------------------------------------------------- */
 5104: char	pretext[512], *prep=expression,	/*pream from expression, ptr into it*/
 5105: 	*dollar, *comma;		/* preamble delimiters */
 5106: int	prelen = 0,			/* preamble length */
 5107: 	sizevalue = 0,			/* value of size parameter */
 5108: 	isfontsize = 0,			/*true if leading fontsize present*/
 5109: 	isdelta = 0;			/*true to increment passed size arg*/
 5110: /* -------------------------------------------------------------------------
 5111: initialization
 5112: -------------------------------------------------------------------------- */
 5113: if ( subexpr != NULL )			/* caller passed us an address */
 5114:   *subexpr = '\000';			/* so init assuming no preamble */
 5115: if ( expression == NULL ) goto end_of_job; /* no input */
 5116: if ( *expression == '\000' ) goto end_of_job; /* input is an empty string */
 5117: /* -------------------------------------------------------------------------
 5118: process preamble if present
 5119: -------------------------------------------------------------------------- */
 5120: /*process_preamble:*/
 5121: if ( (dollar=strchr(expression,'$'))	/* $ signals preceding preamble */
 5122: !=   NULL ) {				/* found embedded $ */
 5123:  if ( (prelen = (int)(dollar-expression)) /*#chars in expression preceding $*/
 5124:  > 0 ) {				/* must have preamble preceding $ */
 5125:   if ( prelen < 65 ) {			/* too long for a prefix */
 5126:    memcpy(pretext,expression,prelen);	/* local copy of preamble */
 5127:    pretext[prelen] = '\000';		/* null-terminated */
 5128:    if ( strchr(pretext,*(ESCAPE))==NULL	/*shouldn't be an escape in preamble*/
 5129:    &&   strchr(pretext,'{') == NULL ) {	/*shouldn't be a left{ in preamble*/
 5130:     /* --- skip any leading whitespace  --- */
 5131:     prep = pretext;			/* start at beginning of preamble */
 5132:     skipwhite(prep);			/* skip any leading white space */
 5133:     /* --- check for embedded , or leading +/- (either signalling size) --- */
 5134:     if ( isthischar(*prep,"+-") )	/* have leading + or - */
 5135:      isdelta = 1;			/* so use size value as increment */
 5136:     comma = strchr(pretext,',');	/* , signals leading size param */
 5137:     /* --- process leading size parameter if present --- */
 5138:     if ( comma != NULL			/* size param explicitly signalled */
 5139:     ||   isdelta || isdigit(*prep) ) {	/* or inferred implicitly */
 5140:       /* --- parse size parameter and reset size accordingly --- */
 5141:       if( comma != NULL ) *comma = '\000';/*, becomes null, terminating size*/
 5142:       sizevalue = atoi(prep);		/* convert size string to integer */
 5143:       if ( size != NULL )		/* caller passed address for size */
 5144: 	*size = (isdelta? *size+sizevalue : sizevalue); /* so reset size */
 5145:       /* --- finally, set flag and shift size parameter out of preamble --- */
 5146:       isfontsize = 1;			/*set flag showing font size present*/
 5147:       if ( comma != NULL ) strcpy(pretext,comma+1);/*leading size param gone*/
 5148:      } /* --- end-of-if(comma!=NULL||etc) --- */
 5149:     /* --- copy any preamble params following size to caller's subexpr --- */
 5150:     if ( comma != NULL || !isfontsize )	/*preamb contains params past size*/
 5151:      if ( subexpr != NULL )		/* caller passed us an address */
 5152:       strcpy(subexpr,pretext);		/*so return extra params to caller*/
 5153:     /* --- finally, set prep to shift preamble out of expression --- */
 5154:     prep = expression + prelen+1;	/* set prep past $ in expression */
 5155:     } /* --- end-of-if(strchr(pretext,*ESCAPE)==NULL) --- */
 5156:    } /* --- end-of-if(prelen<65) --- */
 5157:   } /* --- end-of-if(prelen>0) --- */
 5158:  else {					/* $ is first char of expression */
 5159:   int ndollars = 0;			/* number of $...$ pairs removed */
 5160:   prep = expression;			/* start at beginning of expression*/
 5161:   while ( *prep == '$' ) {		/* remove all matching $...$'s */
 5162:    int	explen = strlen(prep)-1;	/* index of last char in expression*/
 5163:    if ( explen < 2 ) break;		/* no $...$'s left to remove */
 5164:    if ( prep[explen] != '$' ) break;	/* unmatched $ */
 5165:    prep[explen] = '\000';		/* remove trailing $ */
 5166:    prep++;				/* and remove matching leading $ */
 5167:    ndollars++;				/* count another pair removed */
 5168:    } /* --- end-of-while(*prep=='$') --- */
 5169:   ispreambledollars = ndollars;		/* set flag to fix \displaystyle */
 5170:   if ( ndollars == 1 )			/* user submitted $...$ expression */
 5171:     isdisplaystyle = 0;			/* so set \textstyle */
 5172:   if ( ndollars > 1 )			/* user submitted $$...$$ */
 5173:     isdisplaystyle = 2;			/* so set \displaystyle */
 5174:   /*goto process_preamble;*/		/*check for preamble after leading $*/
 5175:   } /* --- end-of-if/else(prelen>0) --- */
 5176:  } /* --- end-of-if(dollar!=NULL) --- */
 5177: /* -------------------------------------------------------------------------
 5178: back to caller
 5179: -------------------------------------------------------------------------- */
 5180: end_of_job:
 5181:   return ( prep );			/*expression, or ptr past preamble*/
 5182: } /* --- end-of-function preamble() --- */
 5183: 
 5184: 
 5185: /* ==========================================================================
 5186:  * Function:	mimeprep ( expression )
 5187:  * Purpose:	preprocessor for mimeTeX input, e.g.,
 5188:  *		(a) removes comments,
 5189:  *		(b) converts \left( to \( and \right) to \),
 5190:  *		(c) xlates &html; special chars to equivalent latex
 5191:  *		Should only be called once (after unescape_url())
 5192:  * --------------------------------------------------------------------------
 5193:  * Arguments:	expression (I/O) char * to first char of null-terminated
 5194:  *				string containing mimeTeX/LaTeX expression,
 5195:  *				and returning preprocessed string
 5196:  * --------------------------------------------------------------------------
 5197:  * Returns:	( char * )	ptr to input expression,
 5198:  *				or NULL for any parsing error.
 5199:  * --------------------------------------------------------------------------
 5200:  * Notes:     o
 5201:  * ======================================================================= */
 5202: /* --- entry point --- */
 5203: char	*mimeprep ( char *expression )
 5204: {
 5205: /* -------------------------------------------------------------------------
 5206: Allocations and Declarations
 5207: -------------------------------------------------------------------------- */
 5208: char	*expptr=expression,		/* ptr within expression */
 5209: 	*tokptr=NULL,			/*ptr to token found in expression*/
 5210: 	*texsubexpr(), argval[8192];	/*parse for macro args after token*/
 5211: char	*strchange();			/* change leading chars of string */
 5212: char	*strwstr();			/*use strwstr() instead of strstr()*/
 5213: char	*findbraces();			/*find left { and right } for \atop*/
 5214: int	idelim=0,			/* left- or right-index */
 5215: 	isymbol=0;			/*symbols[],rightcomment[],etc index*/
 5216: int	xlateleft = 0;			/* true to xlate \left and \right */
 5217: /* ---
 5218:  * comments
 5219:  * -------- */
 5220: char	*leftptr=NULL;			/* find leftcomment in expression */
 5221: static	char *leftcomment = "%%",	/* open comment */
 5222: 	*rightcomment[] = {"\n", "%%", NULL}; /* close comments */
 5223: /* ---
 5224:  * special long (more than 1-char) \left and \right delimiters
 5225:  * ----------------------------------------------------------- */
 5226: static	char *leftfrom[] =		/* xlate any \left suffix... */
 5227:    { "\\|",				/* \left\| */
 5228:      "\\{",				/* \left\{ */
 5229:      "\\langle",			/* \left\langle */
 5230:      NULL } ; /* --- end-of-leftfrom[] --- */
 5231: static	char *leftto[] =		/* ...to this instead */
 5232:    { "=",				/* = */
 5233:      "{",				/* { */
 5234:      "<",				/* < */
 5235:      NULL } ; /* --- end-of-leftto[] --- */
 5236: static	char *rightfrom[] =		/* xlate any \right suffix... */
 5237:    { "\\|",				/* \right\| */
 5238:      "\\}",				/* \right\} */
 5239:      "\\rangle",			/* \right\rangle */
 5240:      NULL } ; /* --- end-of-rightfrom[] --- */
 5241: static	char *rightto[] =		/* ...to this instead */
 5242:    { "=",				/* = */
 5243:      "}",				/* } */
 5244:      ">",				/* > */
 5245:      NULL } ; /* --- end-of-rightto[] --- */
 5246: /* ---
 5247:  * { \atop }-like commands
 5248:  * ----------------------- */
 5249: char	*atopsym=NULL;			/* atopcommands[isymbol] */
 5250: static	char *atopcommands[] =		/* list of {a+b\command c+d}'s */
 5251:    { "\\over",				/* plain tex for \frac */
 5252:      "\\choose",			/* binomial coefficient */
 5253:    #ifndef NOATOP			/*noatop preserves old mimeTeX rule*/
 5254:      "\\atop",
 5255:    #endif
 5256:      NULL } ; /* --- end-of-atopcommands[] --- */
 5257: static	char *atopdelims[] =		/* delims for atopcommands[] */
 5258:    { NULL, NULL,			/* \\over has no delims */
 5259:      "\\left(", "\\right)",		/* \\choose has ( ) delims*/
 5260:    #ifndef NOATOP			/*noatop preserves old mimeTeX rule*/
 5261:      NULL, NULL,			/* \\atop has no delims */
 5262:    #endif
 5263:      NULL, NULL } ; /* --- end-of-atopdelims[] --- */
 5264: /* ---
 5265:  * html special/escape chars converted to latex equivalents
 5266:  * -------------------------------------------------------- */
 5267: char	*htmlsym=NULL;			/* symbols[isymbol].html */
 5268: static	struct { char *html; char *args; char *latex; } symbols[] =
 5269:  { /* ---------------------------------------
 5270:      user-supplied newcommands
 5271:    --------------------------------------- */
 5272:  #ifdef NEWCOMMANDS			/* -DNEWCOMMANDS=\"filename.h\" */
 5273:    #include NEWCOMMANDS
 5274:  #endif
 5275:    /* ---------------------------------------
 5276:      Cyrillic termchar  mimeTeX equivalent...
 5277:    --------------------------------------- */
 5278:    { "\\\'G",	"embed\\","{\\acute{G}}" },
 5279:    { "\\\'g",	"embed\\","{\\acute{g}}" },
 5280:    { "\\\'K",	"embed\\","{\\acute{K}}" },
 5281:    { "\\\'k",	"embed\\","{\\acute{k}}" },
 5282:    { "\\u U",	"embed\\","{\\breve{U}}" },
 5283:    { "\\u u",	"embed\\","{\\breve{u}}" },
 5284:    /*{ "\\\"E",	"embed\\","{\\ddot{E}}" },*/
 5285:    /*{ "\\\"e",	"embed\\","{\\ddot{e}}" },*/
 5286:    { "\\\"I",	"embed\\","{\\ddot{\\=I}}" },
 5287:    { "\\\"\\i",	"embed\\","{\\ddot{\\=\\i}}" },
 5288:    /* ------------------------------------------
 5289:    LaTeX Macro  #args,default   template...
 5290:    ------------------------------------------ */
 5291:    { "\\lvec",	"2n",	"{#2_1,\\cdots,#2_{#1}}" },
 5292:    { "\\grave", "1",	"{\\stackrel{\\Huge\\gravesym}{#1}}" }, /* \grave */
 5293:    { "\\acute", "1",	"{\\stackrel{\\Huge\\acutesym}{#1}}" }, /* \acute */
 5294:    { "\\check", "1",	"{\\stackrel{\\Huge\\checksym}{#1}}" }, /* \check */
 5295:    { "\\breve", "1",	"{\\stackrel{\\Huge\\brevesym}{#1}}" }, /* \breve */
 5296:    { "\\buildrel","3",	"{\\stackrel{#1}{#3}}" }, /* ignore #2 = \over */
 5297:    { "\\overset", NULL,	"\\stackrel" },		/* just an alias */
 5298:    { "\\underset", "2",	"\\relstack{#2}{#1}" },	/* reverse args */
 5299:    /* ---------------------------------------
 5300:     html char termchar  LaTeX equivalent...
 5301:    --------------------------------------- */
 5302:    { "&quot",	";",	"\"" },		/* &quot; is first, &#034; */
 5303:    { "&amp",	";",	"&" },
 5304:    { "&lt",	";",	"<" },
 5305:    { "&gt",	";",	">" },
 5306:    { "&#092",	";",	"\\" },		/* backslash */
 5307:    { "&backslash",";",	"\\" },
 5308:    { "&nbsp",	";",	"~" },
 5309:    { "&iexcl",	";",	"{\\raisebox{-2}{\\rotatebox{180}{!}}}" },
 5310:    { "&brvbar",	";",	"|" },
 5311:    { "&plusmn",	";",	"\\pm" },
 5312:    { "&sup2",	";",	"{{}^2}" },
 5313:    { "&sup3",	";",	"{{}^3}" },
 5314:    { "&micro",	";",	"\\mu" },
 5315:    { "&sup1",	";",	"{{}^1}" },
 5316:    { "&frac14",	";",	"{\\frac14}" },
 5317:    { "&frac12",	";",	"{\\frac12}" },
 5318:    { "&frac34",	";",	"{\\frac34}" },
 5319:    { "&iquest",	";",	"{\\raisebox{-2}{\\rotatebox{180}{?}}}" },
 5320:    { "&Acirc",	";",	"{\\rm~\\hat~A}" },
 5321:    { "&Atilde",	";",	"{\\rm~\\tilde~A}" },
 5322:    { "&Auml",	";",	"{\\rm~\\ddot~A}" },
 5323:    { "&Aring",	";",	"{\\rm~A\\limits^{-1$o}}" },
 5324:    { "&atilde",	";",	"{\\rm~\\tilde~a}" },
 5325:    { "&yuml",	";",	"{\\rm~\\ddot~y}" },  /* &yuml; is last, &#255; */
 5326:    /* ---------------------------------------
 5327:     html tag  termchar  LaTeX equivalent...
 5328:    --------------------------------------- */
 5329:    { "<br>",	"embed\\i","\\\\" },
 5330:    { "<br/>",	"embed\\i","\\\\" },
 5331:    /* ---------------------------------------
 5332:     garbage  termchar  LaTeX equivalent...
 5333:    --------------------------------------- */
 5334:    { "< TEX >",	"embed\\i","\000" },
 5335:    { "< / TEX >","embed\\i","\000" },
 5336:    { "<br / >",	"embed\\i","\000" },
 5337:    /* ---------------------------------------
 5338:      LaTeX   termchar   mimeTeX equivalent...
 5339:    --------------------------------------- */
 5340:    { "\\AA",	NULL,	"{\\rm~A\\limits^{-1$o}}" },
 5341:    { "\\aa",	NULL,	"{\\rm~a\\limits^{-1$o}}" },
 5342:    { "\\bmod",	NULL,	"{\\hspace2{\\rm~mod}\\hspace2}" },
 5343:    { "\\vdots",	NULL,	"{\\raisebox3{\\rotatebox{90}{\\ldots}}}" },
 5344:    { "\\dots",	NULL,	"{\\cdots}" },
 5345:    { "\\cdots",	NULL,	"{\\raisebox3{\\ldots}}" },
 5346:    { "\\ldots",	NULL,	"{\\fs4.\\hspace1.\\hspace1.}" },
 5347:    { "\\ddots",	NULL,	"{\\fs4\\raisebox8.\\hspace1\\raisebox4.\\hspace1.}"},
 5348:    { "\\notin",	NULL,	"{\\not\\in}" },
 5349:    { "\\neq",	NULL,	"{\\not=}" },
 5350:    { "\\ne",	NULL,	"{\\not=}" },
 5351:    { "\\hbar",	NULL,	"{\\compose~h{{\\fs{-1}-\\atop\\vspace3}}}" },
 5352:    { "\\angle",	NULL, "{\\compose{\\hspace{3}\\lt}{\\circle(10,15;-80,80)}}"},
 5353:    { "\\textcelsius", NULL, "{\\textdegree C}"},
 5354:    { "\\textdegree", NULL, "{\\Large^{^{\\tiny\\mathbf o}}}"},
 5355:    { "\\cr",	NULL,	"\\\\" },
 5356:    { "\\iiint",	NULL,	"{\\int\\int\\int}\\limits" },
 5357:    { "\\iint",	NULL,	"{\\int\\int}\\limits" },
 5358:    { "\\Bigiint", NULL,	"{\\Bigint\\Bigint}\\limits" },
 5359:    { "\\bigsqcap",NULL,	"{\\fs{+4}\\sqcap}" },
 5360:    { "!`",	NULL,	"{\\raisebox{-2}{\\rotatebox{180}{!}}}" },
 5361:    { "?`",	NULL,	"{\\raisebox{-2}{\\rotatebox{180}{?}}}" },
 5362:    { "^\'",	"embed","\'" }, /* avoid ^^ when re-xlating \' below */
 5363:    { "\'\'\'\'","embed","^{\\fs{-1}\\prime\\prime\\prime\\prime}" },
 5364:    { "\'\'\'",	"embed","^{\\fs{-1}\\prime\\prime\\prime}" },
 5365:    { "\'\'",	"embed","^{\\fs{-1}\\prime\\prime}" },
 5366:    { "\'",	"embed","^{\\fs{-1}\\prime}" },
 5367:    { "\\rightleftharpoons",NULL,"{\\rightharpoonup\\atop\\leftharpoondown}" },
 5368:    { "\\therefore",NULL,"{\\Huge\\raisebox{-4}{.\\atop.\\,.}}" },
 5369:    { "\\LaTeX",	NULL,	"{\\rm~L\\raisebox{3}{\\fs{-1}A}\\TeX}" },
 5370:    { "\\TeX",	NULL,	"{\\rm~T\\raisebox{-3}{E}X}" },
 5371:    { "\\cyan",	NULL,	"{\\reverse\\red\\reversebg}" },
 5372:    { "\\magenta",NULL,	"{\\reverse\\green\\reversebg}" },
 5373:    { "\\yellow",NULL,	"{\\reverse\\blue\\reversebg}" },
 5374:    { "\\cancel",NULL,	"\\Not" },
 5375:    { "\\hhline",NULL,	"\\Hline" },
 5376:    { "\\Hline", NULL,	"\\hline\\,\\\\\\hline" },
 5377:    /* ---------------------------------------------------------
 5378:      "Algebra Syntax"  termchar   mimeTeX/LaTeX equivalent...
 5379:    ------------------------------------------------------------ */
 5380:    { "sqrt",	"1",	"{\\sqrt{#1}}" },
 5381:    { "sin",	"1",	"{\\sin{#1}}" },
 5382:    { "cos",	"1",	"{\\cos{#1}}" },
 5383:    { "asin",	"1",	"{\\sin^{-1}{#1}}" },
 5384:    { "acos",	"1",	"{\\cos^{-1}{#1}}" },
 5385:    { "exp",	"1",	"{{\\rm~e}^{#1}}" },
 5386:    { "det",	"1",	"{\\left|{#1}\\right|}" },
 5387:    /* ---------------------------------------
 5388:    LaTeX Constant    termchar   value...
 5389:    --------------------------------------- */
 5390:    { "\\thinspace",	NULL,	"2" },
 5391:    { "\\thinmathspace",	NULL,	"2" },
 5392:    { "\\textwidth",	NULL,	"400" },
 5393:    { NULL,	NULL,	NULL }
 5394:  } ; /* --- end-of-symbols[] --- */
 5395: /* -------------------------------------------------------------------------
 5396: first remove comments
 5397: -------------------------------------------------------------------------- */
 5398: expptr = expression;			/* start search at beginning */
 5399: while ( (leftptr=strstr(expptr,leftcomment)) != NULL ) /*found leftcomment*/
 5400:   {
 5401:   char	*rightsym=NULL;			/* rightcomment[isymbol] */
 5402:   expptr = leftptr+strlen(leftcomment);	/* start rightcomment search here */
 5403:   /* --- check for any closing rightcomment, in given precedent order --- */
 5404:   if ( *expptr != '\000' )		/*have chars after this leftcomment*/
 5405:    for(isymbol=0; (rightsym=rightcomment[isymbol]) != NULL; isymbol++)
 5406:     if ( (tokptr=strstr(expptr,rightsym)) != NULL ) /*found rightcomment*/
 5407:      { tokptr += strlen(rightsym);	/* first char after rightcomment */
 5408:        if ( *tokptr == '\000' )		/*nothing after this rightcomment*/
 5409: 	{ *leftptr = '\000';		/*so terminate expr at leftcomment*/
 5410: 	  break; }			/* and stop looking for comments */
 5411:        *leftptr = '~';			/* replace entire comment by ~ */
 5412:        strcpy(leftptr+1,tokptr);	/* and squeeze out comment */
 5413:        goto next_comment; }		/* stop looking for rightcomment */
 5414:   /* --- no rightcomment after opening leftcomment --- */
 5415:   *leftptr = '\000';			/* so terminate expression */
 5416:   /* --- resume search past squeezed-out comment --- */
 5417:   next_comment:
 5418:     if ( *leftptr == '\000' ) break;	/* reached end of expression */
 5419:     expptr = leftptr+1;			/*resume search after this comment*/
 5420:   } /* --- end-of-while(leftptr!=NULL) --- */
 5421: /* -------------------------------------------------------------------------
 5422: run thru table, converting all occurrences of each macro to its expansion
 5423: -------------------------------------------------------------------------- */
 5424: for(isymbol=0; (htmlsym=symbols[isymbol].html) != NULL; isymbol++)
 5425:   {
 5426:   int	htmllen = strlen(htmlsym);	/* length of escape, _without_ ; */
 5427:   int	isalgebra = isalpha((int)(*htmlsym)); /* leading char alphabetic */
 5428:   int	isembedded = 0,			/* true to xlate even if embedded */
 5429: 	isstrwstr = 0,			/* true to use strwstr() */
 5430: 	wstrlen = 0;			/* length of strwstr() match */
 5431:   char	*aleft="{([<|", *aright="})]>|"; /*left,right delims for alg syntax*/
 5432:   char	embedkeywd[99] = "embed",	/* keyword to signal embedded token*/
 5433: 	embedterm = '\000';		/* char immediately after embed */
 5434:   int	embedlen = strlen(embedkeywd);	/* #chars in embedkeywd */
 5435:   char	*args = symbols[isymbol].args,	/* number {}-args, optional []-arg */
 5436: 	*htmlterm = args,		/*if *args nonumeric, then html term*/
 5437: 	*latexsym = symbols[isymbol].latex; /*latex replacement for htmlsym*/
 5438:   char	abuff[8192];  int iarg,nargs=0;	/* macro expansion params */
 5439:   char	wstrwhite[99];			/* whitespace chars for strwstr() */
 5440:   if ( args != NULL )			/*we have args (or htmlterm) param*/
 5441:    if ( *args != '\000' ) {		/* and it's not an empty string */
 5442:     if ( strchr("0123456789",*args) != NULL ) /* is 1st char #args=0-9 ? */
 5443:      { htmlterm = NULL;			/* if so, then we have no htmlterm */
 5444:        *abuff = *args;  abuff[1] = '\000'; /* #args char in ascii buffer */
 5445:        nargs = atoi(abuff); }		/* interpret #args to numeric */
 5446:     else if ( strncmp(args,embedkeywd,embedlen) == 0 )/*xlate embedded token*/
 5447:      { htmlterm = NULL;			/* if so, then we have no htmlterm */
 5448:        isembedded = 1 ;			/* turn on embedded flag */
 5449:        embedterm = args[embedlen];	/* char immediately after embed */
 5450:        if (strlen(args) > embedlen+1) {	/* have embed,white for strwstr() */
 5451: 	isstrwstr = 1;			/* turn on strwtsr flag */
 5452: 	strcpy(wstrwhite,args+6); } }	/* and set its whitespace arg */
 5453:     } /* --- end-of-if(*args!='\000') --- */
 5454:   expptr = expression;			/* re-start search at beginning */
 5455:   while ( ( tokptr=(!isstrwstr?strstr(expptr,htmlsym): /* just use strtsr */
 5456:   strwstr(expptr,htmlsym,wstrwhite,&wstrlen)) ) /* or use our strwstr */
 5457:   != NULL )				/* found another sym */
 5458:     { int  toklen = (!isstrwstr?htmllen:wstrlen); /* length of matched sym */
 5459:       char termchar = *(tokptr+toklen),	/* char terminating html sequence */
 5460:            prevchar = (tokptr==expptr?' ':*(tokptr-1)); /*char preceding html*/
 5461:       int  escapelen = toklen;		/* total length of escape sequence */
 5462:       *abuff = '\000';			/* default to empty string */
 5463:       if ( latexsym != NULL )		/* table has .latex xlation */
 5464:        if ( *latexsym != '\000' )	/* and it's not an empty string */
 5465: 	strcpy(abuff,latexsym);		/* so get local copy */
 5466:       if ( htmlterm != NULL )		/* sequence may have terminator */
 5467: 	escapelen += (isthischar(termchar,htmlterm)?1:0); /*add terminator*/
 5468:       if ( !isembedded )		/* don't xlate embedded sequence */
 5469:        if ( isalpha((int)termchar) )	/*we just have prefix of longer sym*/
 5470: 	{ expptr = tokptr+toklen;	/* just resume search after prefix */
 5471: 	  continue; }			/* but don't replace it */
 5472:       if ( isembedded )			/* for embedded sequence */
 5473: 	if ( !isthischar(embedterm,ESCAPE)  /* don't xlate escaped \token */
 5474: 	&&    isthischar(prevchar,ESCAPE) ) /* and we have escaped \token */
 5475: 	  { expptr = tokptr+toklen;	/*just resume search after literal*/
 5476: 	    continue; }			/* but don't replace it */
 5477:       if ( !isthischar(*htmlsym,ESCAPE)	/* our symbol isn't escaped */
 5478:       &&   isalpha(*htmlsym)		/* and our symbol starts with alpha*/
 5479:       &&   !isthischar(*htmlsym,"&") )	/* and not an &html; special char */
 5480:        if ( tokptr != expression )	/* then if we're past beginning */
 5481: 	if ( isthischar(*(tokptr-1),ESCAPE) /*and if inline symbol escaped*/
 5482: 	||   (isalpha(*(tokptr-1))) )	/* or if suffix of longer string */
 5483: 	  { expptr = tokptr+escapelen;	/*just resume search after literal*/
 5484: 	    continue; }			/* but don't replace it */
 5485:       if ( nargs > 0 )			/*substitute #1,#2,... in latexsym*/
 5486:        {
 5487:        char *arg1ptr = tokptr+escapelen;/* nargs begin after macro literal */
 5488:        char *optarg = args+1;		/* ptr 1 char past #args digit 0-9 */
 5489:        expptr = arg1ptr;		/* ptr to beginning of next arg */
 5490:        for ( iarg=1; iarg<=nargs; iarg++ ) /* one #`iarg` arg at a time */
 5491: 	{
 5492: 	char argsignal[32] = "#1",	/* #1...#9 signals arg replacement */
 5493: 	*argsigptr = NULL;		/* ptr to argsignal in abuff[] */
 5494: 	/* --- get argument value --- */
 5495: 	*argval = '\000';		/* init arg as empty string */
 5496: 	skipwhite(expptr);		/* and skip leading white space */
 5497: 	if ( iarg==1 && *optarg!='\000'	/* check for optional [arg] */
 5498: 	&&   !isalgebra )		/* but not in "algebra syntax" */
 5499: 	 { strcpy(argval,optarg);	/* init with default value */
 5500: 	   if ( *expptr == '[' )	/* but user gave us [argval] */
 5501: 	    expptr = texsubexpr(expptr,argval,0,"[","]",0,0); } /*so get it*/
 5502: 	else				/* not optional, so get {argval} */
 5503: 	 if ( *expptr != '\000' ) {	/* check that some argval provided */
 5504: 	  if ( !isalgebra )		/* only { } delims for latex macro */
 5505: 	    expptr = texsubexpr(expptr,argval,0,"{","}",0,0); /*get {argval}*/
 5506: 	  else				/*any delim for algebra syntax macro*/
 5507: 	   { expptr = texsubexpr(expptr,argval,0,aleft,aright,0,1);
 5508: 	     if ( isthischar(*argval,aleft) ) /* have delim-enclosed arg */
 5509: 	      if ( *argval != '{' )	/* and it's not { }-enclosed */
 5510: 	       { strchange(0,argval,"\\left"); /* insert opening \left, */
 5511: 		 strchange(0,argval+strlen(argval)-1,"\\right"); } }/*\right*/
 5512: 	   } /* --- end-of-if(*expptr!='\000') --- */
 5513: 	/* --- replace #`iarg` in macro with argval --- */
 5514: 	sprintf(argsignal,"#%d",iarg);	/* #1...#9 signals argument */
 5515: 	while ( (argsigptr=strstr(argval,argsignal)) != NULL ) /* #1...#9 */
 5516: 	 strcpy(argsigptr,argsigptr+strlen(argsignal)); /*can't be in argval*/
 5517: 	while ( (argsigptr=strstr(abuff,argsignal)) != NULL ) /* #1...#9 */
 5518: 	 strchange(strlen(argsignal),argsigptr,argval); /*replaced by argval*/
 5519: 	} /* --- end-of-for(iarg) --- */
 5520:        escapelen += ((int)(expptr-arg1ptr)); /* add in length of all args */
 5521:        } /* --- end-of-if(nargs>0) --- */
 5522:       strchange(escapelen,tokptr,abuff); /*replace macro or html symbol*/
 5523:       expptr = tokptr + strlen(abuff); /*resume search after macro / html*/
 5524:     } /* --- end-of-while(tokptr!=NULL) --- */
 5525:   } /* --- end-of-for(isymbol) --- */
 5526: /* -------------------------------------------------------------------------
 5527: convert \left( to \(  and  \right) to \),  etc.
 5528: -------------------------------------------------------------------------- */
 5529: if ( xlateleft )			/* \left...\right xlation wanted */
 5530:  for ( idelim=0; idelim<2; idelim++ )	/* 0 for \left  and  1 for \right */
 5531:   {
 5532:   char	*lrstr  = (idelim==0?"\\left":"\\right"); /* \left on 1st pass */
 5533:   int	lrlen   = (idelim==0?5:6);	/* strlen() of \left or \right */
 5534:   char	*braces = (idelim==0?LEFTBRACES ".":RIGHTBRACES "."), /*([{<or)]}>*/
 5535: 	**lrfrom= (idelim==0?leftfrom:rightfrom), /* long braces like \| */
 5536: 	**lrto  = (idelim==0?leftto:rightto), /* xlated to 1-char like = */
 5537: 	*lrsym  = NULL;			/* lrfrom[isymbol] */
 5538:   expptr = expression;			/* start search at beginning */
 5539:   while ( (tokptr=strstr(expptr,lrstr)) != NULL ) /* found \left or \right */
 5540:     {
 5541:     if ( isthischar(*(tokptr+lrlen),braces) ) /* followed by a 1-char brace*/
 5542:       {	strcpy(tokptr+1,tokptr+lrlen);	/* so squeeze out "left" or "right"*/
 5543: 	expptr = tokptr+2; }		/* and resume search past brace */
 5544:     else				/* may be a "long" brace like \| */
 5545:       {
 5546:       expptr = tokptr+lrlen;		/*init to resume search past\left\rt*/
 5547:       for(isymbol=0; (lrsym=lrfrom[isymbol]) != NULL; isymbol++)
 5548: 	{ int symlen = strlen(lrsym);	/* #chars in delim, e.g., 2 for \| */
 5549: 	  if ( memcmp(tokptr+lrlen,lrsym,symlen) == 0 ) /* found long delim*/
 5550: 	    { strcpy(tokptr+1,tokptr+lrlen+symlen-1); /* squeeze out delim */
 5551: 	      *(tokptr+1) = *(lrto[isymbol]); /* last char now 1-char delim*/
 5552: 	      expptr = tokptr+2 - lrlen; /* resume search past 1-char delim*/
 5553: 	      break; }			/* no need to check more lrsym's */
 5554: 	} /* --- end-of-for(isymbol) --- */
 5555:       } /* --- end-of-if/else(isthischar()) --- */
 5556:     } /* --- end-of-while(tokptr!=NULL) --- */
 5557:   } /* --- end-of-for(idelim) --- */
 5558: /* -------------------------------------------------------------------------
 5559: run thru table, converting all {a+b\atop c+d} to \atop{a+b}{c+d}
 5560: -------------------------------------------------------------------------- */
 5561: for(isymbol=0; (atopsym=atopcommands[isymbol]) != NULL; isymbol++)
 5562:   {
 5563:   int	atoplen = strlen(atopsym);	/* #chars in \atop */
 5564:   expptr = expression;			/* re-start search at beginning */
 5565:   while ( (tokptr=strstr(expptr,atopsym)) != NULL ) /* found another atop */
 5566:     { char *leftbrace=NULL, *rightbrace=NULL; /*ptr to opening {, closing }*/
 5567:       char termchar = *(tokptr+atoplen); /* \atop followed by terminator */
 5568:       if ( msgfp!=NULL && msglevel>=999 )
 5569: 	{ fprintf(msgfp,"mimeprep> offset=%d rhs=\"%s\"\n",
 5570: 	  (int)(tokptr-expression),tokptr);
 5571: 	  fflush(msgfp); }
 5572:       if ( isalpha((int)termchar) )	/*we just have prefix of longer sym*/
 5573: 	{ expptr = tokptr+atoplen;	/* just resume search after prefix */
 5574: 	  continue; }			/* but don't process it */
 5575:       leftbrace  = findbraces(expression,tokptr);     /* find left { */
 5576:       rightbrace = findbraces(NULL,tokptr+atoplen-1); /* find right } */
 5577:       if ( leftbrace==NULL || rightbrace==NULL )
 5578: 	{ expptr += atoplen;  continue; } /* skip command if didn't find */
 5579:       else				/* we have bracketed { \atop } */
 5580: 	{
 5581: 	int  leftlen  = (int)(tokptr-leftbrace) - 1, /* #chars in left arg */
 5582: 	     rightlen = (int)(rightbrace-tokptr) - atoplen, /* and in right*/
 5583: 	     totlen   = (int)(rightbrace-leftbrace) + 1; /*tot in { \atop }*/
 5584: 	char *open=atopdelims[2*isymbol], *close=atopdelims[2*isymbol+1];
 5585: 	char arg[8192], command[8192];	/* left/right args, new \atop{}{} */
 5586: 	*command = '\000';		/* start with null string */
 5587: 	if (open!=NULL) strcat(command,open); /* add open delim if needed */
 5588: 	strcat(command,atopsym);	/* add command with \atop */
 5589: 	arg[0] = '{';			/* arg starts with { */
 5590: 	memcpy(arg+1,leftbrace+1,leftlen); /* extract left-hand arg */
 5591: 	arg[leftlen+1] = '\000';	/* and null terminate it */
 5592: 	strcat(command,arg);		/* concatanate {left-arg to \atop */
 5593: 	strcat(command,"}{");		/* close left-arg, open right-arg */
 5594: 	memcpy(arg,tokptr+atoplen,rightlen); /* right-hand arg */
 5595: 	arg[rightlen] = '}';		/* add closing } */
 5596: 	arg[rightlen+1] = '\000';	/* and null terminate it */
 5597: 	if ( isthischar(*arg,WHITEMATH) ) /* 1st char was mandatory space */
 5598: 	  strcpy(arg,arg+1);		/* so squeeze it out */
 5599: 	strcat(command,arg);		/* concatanate right-arg} */
 5600: 	if (close!=NULL) strcat(command,close); /* add close delim if needed*/
 5601: 	strchange(totlen-2,leftbrace+1,command); /* {\atop} --> {\atop{}{}} */
 5602: 	expptr = leftbrace+strlen(command); /*resume search past \atop{}{}*/
 5603: 	}
 5604:     } /* --- end-of-while(tokptr!=NULL) --- */
 5605:   } /* --- end-of-for(isymbol) --- */
 5606: /* -------------------------------------------------------------------------
 5607: back to caller with preprocessed expression
 5608: -------------------------------------------------------------------------- */
 5609: if ( msgfp!=NULL && msglevel>=99 )	/* display preprocessed expression */
 5610:   { fprintf(msgfp,"mimeprep> expression=\"\"%s\"\"\n",expression);
 5611:     fflush(msgfp); }
 5612: return ( expression );
 5613: } /* --- end-of-function mimeprep() --- */
 5614: 
 5615: 
 5616: /* ==========================================================================
 5617:  * Function:	strchange ( int nfirst, char *from, char *to )
 5618:  * Purpose:	Changes the nfirst leading chars of `from` to `to`.
 5619:  *		For example, to change char x[99]="12345678" to "123ABC5678"
 5620:  *		call strchange(1,x+3,"ABC")
 5621:  * --------------------------------------------------------------------------
 5622:  * Arguments:	nfirst (I)	int containing #leading chars of `from`
 5623:  *				that will be replace by `to`
 5624:  *		from (I/O)	char * to null-terminated string whose nfirst
 5625:  *				leading chars will be replaced by `to`
 5626:  *		to (I)		char * to null-terminated string that will
 5627:  *				replace the nfirst leading chars of `from`
 5628:  * --------------------------------------------------------------------------
 5629:  * Returns:	( char * )	ptr to first char of input `from`
 5630:  *				or NULL for any error.
 5631:  * --------------------------------------------------------------------------
 5632:  * Notes:     o	If strlen(to)>nfirst, from must have memory past its null
 5633:  *		(i.e., we don't do a realloc)
 5634:  * ======================================================================= */
 5635: /* --- entry point --- */
 5636: char	*strchange ( int nfirst, char *from, char *to )
 5637: {
 5638: /* -------------------------------------------------------------------------
 5639: Allocations and Declarations
 5640: -------------------------------------------------------------------------- */
 5641: int	tolen = (to==NULL?0:strlen(to)), /* #chars in replacement string */
 5642: 	nshift = abs(tolen-nfirst);	/*need to shift from left or right*/
 5643: /* -------------------------------------------------------------------------
 5644: shift from left or right to accommodate replacement of its nfirst chars by to
 5645: -------------------------------------------------------------------------- */
 5646: if ( tolen < nfirst )			/* shift left is easy */
 5647:   strcpy(from,from+nshift);		/* because memory doesn't overlap */
 5648: if ( tolen > nfirst )			/* need more room at start of from */
 5649:   { char *pfrom = from+strlen(from);	/* ptr to null terminating from */
 5650:     for ( ; pfrom>=from; pfrom-- )	/* shift all chars including null */
 5651:       *(pfrom+nshift) = *pfrom; }	/* shift chars nshift places right */
 5652: /* -------------------------------------------------------------------------
 5653: from has exactly the right number of free leading chars, so just put to there
 5654: -------------------------------------------------------------------------- */
 5655: if ( tolen != 0 )			/* make sure to not empty or null */
 5656:   memcpy(from,to,tolen);		/* chars moved into place */
 5657: return ( from );			/* changed string back to caller */
 5658: } /* --- end-of-function strchange() --- */
 5659: 
 5660: 
 5661: /* ==========================================================================
 5662:  * Function:	strreplace (char *string, char *from, char *to, int nreplace)
 5663:  * Purpose:	Changes the first nreplace occurrences of 'from' to 'to'
 5664:  *		in string, or all occurrences if nreplace=0.
 5665:  * --------------------------------------------------------------------------
 5666:  * Arguments:	string (I/0)	char * to null-terminated string in which
 5667:  *				occurrence of 'from' will be replaced by 'to'
 5668:  *		from (I)	char * to null-terminated string
 5669:  *				to be replaced by 'to'
 5670:  *		to (I)		char * to null-terminated string that will
 5671:  *				replace 'from'
 5672:  *		nreplace (I)	int containing (maximum) number of
 5673:  *				replacements, or 0 to replace all.
 5674:  * --------------------------------------------------------------------------
 5675:  * Returns:	( int )		number of replacements performed,
 5676:  *				or 0 for no replacements or -1 for any error.
 5677:  * --------------------------------------------------------------------------
 5678:  * Notes:     o
 5679:  * ======================================================================= */
 5680: /* --- entry point --- */
 5681: int	strreplace ( char *string, char *from, char *to, int nreplace )
 5682: {
 5683: /* -------------------------------------------------------------------------
 5684: Allocations and Declarations
 5685: -------------------------------------------------------------------------- */
 5686: int	fromlen = (from==NULL?0:strlen(from)), /* #chars to be replaced */
 5687: 	tolen = (to==NULL?0:strlen(to)); /* #chars in replacement string */
 5688: char	*pfrom = (char *)NULL,		/*ptr to 1st char of from in string*/
 5689: 	*pstring = string,		/*ptr past previously replaced from*/
 5690: 	*strchange();			/* change 'from' to 'to' */
 5691: int	nreps = 0;			/* #replacements returned to caller*/
 5692: /* -------------------------------------------------------------------------
 5693: repace occurrences of 'from' in string to 'to'
 5694: -------------------------------------------------------------------------- */
 5695: if ( string == (char *)NULL		/* no input string */
 5696: ||   (fromlen<1 && nreplace<=0) )	/* replacing empty string forever */
 5697:   nreps = (-1);				/* so signal error */
 5698: else					/* args okay */
 5699:   while (nreplace<1 || nreps<nreplace)	/* up to #replacements requested */
 5700:     {
 5701:     if ( fromlen > 0 )			/* have 'from' string */
 5702:       pfrom = strstr(pstring,from);	/*ptr to 1st char of from in string*/
 5703:     else  pfrom = pstring;		/*or empty from at start of string*/
 5704:     if ( pfrom == (char *)NULL ) break;	/*no more from's, so back to caller*/
 5705:     if ( strchange(fromlen,pfrom,to)	/* leading 'from' changed to 'to' */
 5706:     ==   (char *)NULL ) { nreps=(-1); break; } /* signal error to caller */
 5707:     nreps++;				/* count another replacement */
 5708:     pstring = pfrom+tolen;		/* pick up search after 'to' */
 5709:     if ( *pstring == '\000' ) break;	/* but quit at end of string */
 5710:     } /* --- end-of-while() --- */
 5711: return ( nreps );			/* #replacements back to caller */
 5712: } /* --- end-of-function strreplace() --- */
 5713: 
 5714: 
 5715: /* ==========================================================================
 5716:  * Function:	strwstr (char *string, char *substr, char *white, int *sublen)
 5717:  * Purpose:	Find first substr in string, but wherever substr contains
 5718:  *		a whitespace char (in white), string may contain any number
 5719:  *		(including 0) of whitespace chars. If white contains I or i,
 5720:  *		then match is case-insensitive (and I,i _not_ whitespace).
 5721:  * --------------------------------------------------------------------------
 5722:  * Arguments:	string (I)	char * to null-terminated string in which
 5723:  *				first occurrence of substr will be found
 5724:  *		substr (I)	char * to null-terminated string containing
 5725:  *				"template" that will be searched for
 5726:  *		white (I)	char * to null-terminated string containing
 5727:  *				whitespace chars.  If NULL or empty, then
 5728:  *				"~ \t\n\r\f\v" (WHITEMATH in mimetex.h) used.
 5729:  *				If white contains I or i, then match is
 5730:  *				case-insensitive (and I,i _not_ considered
 5731:  *				whitespace).
 5732:  *		sublen (O)	address of int returning "length" of substr
 5733:  *				found in string (which may be longer or
 5734:  *				shorter than substr itself).
 5735:  * --------------------------------------------------------------------------
 5736:  * Returns:	( char * )	ptr to first char of substr in string
 5737:  *				or NULL if not found or for any error.
 5738:  * --------------------------------------------------------------------------
 5739:  * Notes:     o	Wherever a single whitespace char appears in substr,
 5740:  *		the corresponding position in string may contain any
 5741:  *		number (including 0) of whitespace chars, e.g.,
 5742:  *		string="abc   def" and string="abcdef" both match
 5743:  *		substr="c d" at offset 2 of string.
 5744:  *	      o	If substr="c  d" (two spaces between c and d),
 5745:  *		then string must have at least one space, so now "abcdef"
 5746:  *		doesn't match.  In general, the minimum number of spaces
 5747:  *		in string is the number of spaces in substr minus 1
 5748:  *		(so 1 space in substr permits 0 spaces in string).
 5749:  *	      o	Embedded spaces are counted in sublen, e.g.,
 5750:  *		string="c   d" (three spaces) matches substr="c d"
 5751:  *		with sublen=5 returned.  But string="ab   c   d" will
 5752:  *		also match substr="  c d" returning sublen=5 and
 5753:  *		a ptr to the "c".  That is, the mandatory preceding
 5754:  *		space is _not_ counted as part of the match.
 5755:  *		But all the embedded space is counted.
 5756:  *		(An inconsistent bug/feature is that mandatory
 5757:  *		terminating space is counted.)
 5758:  *	      o	Moreover, string="c   d" matches substr="  c d", i.e.,
 5759:  *		the very beginning of a string is assumed to be preceded
 5760:  *		by "virtual blanks".
 5761:  * ======================================================================= */
 5762: /* --- entry point --- */
 5763: char	*strwstr ( char *string, char *substr, char *white, int *sublen )
 5764: {
 5765: /* -------------------------------------------------------------------------
 5766: Allocations and Declarations
 5767: -------------------------------------------------------------------------- */
 5768: char	*psubstr=substr, *pstring=string,/*ptr to current char in substr,str*/
 5769: 	*pfound = (char *)NULL;		/*ptr to found substr back to caller*/
 5770: char	*pwhite=NULL, whitespace[256];	/* callers white whithout i,I */
 5771: int	iscase = (white==NULL?1:	/* case-sensitive if i,I in white */
 5772: 	strchr(white,'i')==NULL && strchr(white,'I')==NULL);
 5773: int	foundlen = 0;			/* length of substr found in string*/
 5774: int	nstrwhite=0, nsubwhite=0,	/* #leading white chars in str,sub */
 5775: 	nminwhite=0;			/* #mandatory leading white in str */
 5776: int	nstrchars=0, nsubchars=0,	/* #non-white chars to be matched */
 5777: 	isncmp=0;			/*strncmp() or strncasecmp() result*/
 5778: /* -------------------------------------------------------------------------
 5779: Initialization
 5780: -------------------------------------------------------------------------- */
 5781: /* --- set up whitespace --- */
 5782: strcpy(whitespace,WHITEMATH);		/*default if no user input for white*/
 5783: if ( white != NULL )			/*user provided ptr to white string*/
 5784:  if ( *white != '\000' ) {		/*and it's not just an empty string*/
 5785:    strcpy(whitespace,white);		/* so use caller's white spaces */
 5786:    while ( (pwhite=strchr(whitespace,'i')) != NULL ) /* have an embedded i */
 5787:      strcpy(pwhite,pwhite+1);		/* so squeeze it out */
 5788:    while ( (pwhite=strchr(whitespace,'I')) != NULL ) /* have an embedded I */
 5789:      strcpy(pwhite,pwhite+1);		/* so squeeze it out */
 5790:    if ( *whitespace == '\000' )		/* caller's white just had i,I */
 5791:      strcpy(whitespace,WHITEMATH); }	/* so revert back to default */
 5792: /* -------------------------------------------------------------------------
 5793: Find first occurrence of substr in string
 5794: -------------------------------------------------------------------------- */
 5795: if ( string != NULL )			/* caller passed us a string ptr */
 5796:  while ( *pstring != '\000' ) {		/* break when string exhausted */
 5797:   char	*pstrptr = pstring;		/* (re)start at next char in string*/
 5798:   int	leadingwhite = 0;		/* leading whitespace */
 5799:   psubstr = substr;			/* start at beginning of substr */
 5800:   foundlen = 0;				/* reset length of found substr */
 5801:   if ( substr != NULL )			/* caller passed us a substr ptr */
 5802:    while ( *psubstr != '\000' ) {	/*see if pstring begins with substr*/
 5803:     /* --- check for end-of-string before finding match --- */
 5804:     if ( *pstrptr == '\000' )		/* end-of-string without a match */
 5805:       goto nextstrchar;			/* keep trying with next char */
 5806:     /* --- actual amount of whitespace in string and substr --- */
 5807:     nsubwhite = strspn(psubstr,whitespace); /* #leading white chars in sub */
 5808:     nstrwhite = strspn(pstrptr,whitespace); /* #leading white chars in str */
 5809:     nminwhite = max2(0,nsubwhite-1);	/* #mandatory leading white in str */
 5810:     /* --- check for mandatory leading whitespace in string --- */
 5811:     if ( pstrptr != string )		/*not mandatory at start of string*/
 5812:       if ( nstrwhite < nminwhite )	/* too little leading white space */
 5813: 	goto nextstrchar;		/* keep trying with next char */
 5814:     /* ---hold on to #whitespace chars in string preceding substr match--- */
 5815:     if ( pstrptr == pstring )		/* whitespace at start of substr */
 5816:       leadingwhite = nstrwhite;		/* save it as leadingwhite */
 5817:     /* --- check for optional whitespace --- */
 5818:     if ( psubstr != substr )		/* always okay at start of substr */
 5819:       if ( nstrwhite>0 && nsubwhite<1 )	/* too much leading white space */
 5820: 	goto nextstrchar;		/* keep trying with next char */
 5821:     /* --- skip any leading whitespace in substr and string --- */
 5822:     psubstr += nsubwhite;		/* push past leading sub whitespace*/
 5823:     pstrptr += nstrwhite;		/* push past leading str whitespace*/
 5824:     /* --- now get non-whitespace chars that we have to match --- */
 5825:     nsubchars = strcspn(psubstr,whitespace); /* #non-white chars in sub */
 5826:     nstrchars = strcspn(pstrptr,whitespace); /* #non-white chars in str */
 5827:     if ( nstrchars < nsubchars )	/* too few chars for match */
 5828:       goto nextstrchar;			/* keep trying with next char */
 5829:     /* --- see if next nsubchars are a match --- */
 5830:     isncmp = (iscase? strncmp(pstrptr,psubstr,nsubchars): /*case sensitive*/
 5831: 		strncasecmp(pstrptr,psubstr,nsubchars)); /*case insensitive*/
 5832:     if ( isncmp != 0 )			/* no match */
 5833:       goto nextstrchar;			/* keep trying with next char */
 5834:     /* --- push past matched chars --- */
 5835:     psubstr += nsubchars;  pstrptr += nsubchars;  /*nsubchars were matched*/
 5836:     } /* --- end-of-while(*psubstr!='\000') --- */
 5837:   pfound = pstring + leadingwhite;	/* found match starting at pstring */
 5838:   foundlen = (int)(pstrptr-pfound);	/* consisting of this many chars */
 5839:   goto end_of_job;			/* back to caller */
 5840:   /* ---failed to find substr, continue trying with next char in string--- */
 5841:   nextstrchar:				/* continue outer loop */
 5842:     pstring++;				/* bump to next char in string */
 5843:   } /* --- end-of-while(*pstring!='\000') --- */
 5844: /* -------------------------------------------------------------------------
 5845: Back to caller with ptr to first occurrence of substr in string
 5846: -------------------------------------------------------------------------- */
 5847: end_of_job:
 5848:   if ( msglevel>=999 && msgfp!=NULL) {	/* debugging/diagnostic output */
 5849:     fprintf(msgfp,"strwstr> str=\"%.72s\" sub=\"%s\" found at offset %d\n",
 5850:     string,substr,(pfound==NULL?(-1):(int)(pfound-string))); fflush(msgfp); }
 5851:   if ( sublen != NULL )			/*caller wants length of found substr*/
 5852:     *sublen = foundlen;			/* give it to him along with ptr */
 5853:   return ( pfound );			/*ptr to first found substr, or NULL*/
 5854: } /* --- end-of-function strwstr() --- */
 5855: 
 5856: 
 5857: /* ==========================================================================
 5858:  * Function:	strtexchr ( char *string, char *texchr )
 5859:  * Purpose:	Find first texchr in string, but texchr must be followed
 5860:  *		by non-alpha
 5861:  * --------------------------------------------------------------------------
 5862:  * Arguments:	string (I)	char * to null-terminated string in which
 5863:  *				first occurrence of delim will be found
 5864:  *		texchr (I)	char * to null-terminated string that
 5865:  *				will be searched for
 5866:  * --------------------------------------------------------------------------
 5867:  * Returns:	( char * )	ptr to first char of texchr in string
 5868:  *				or NULL if not found or for any error.
 5869:  * --------------------------------------------------------------------------
 5870:  * Notes:     o	texchr should contain its leading \, e.g., "\\left"
 5871:  * ======================================================================= */
 5872: /* --- entry point --- */
 5873: char	*strtexchr ( char *string, char *texchr )
 5874: {
 5875: /* -------------------------------------------------------------------------
 5876: Allocations and Declarations
 5877: -------------------------------------------------------------------------- */
 5878: char	delim, *ptexchr=(char *)NULL;	/* ptr returned to caller*/
 5879: char	*pstring = string;		/* start or continue up search here*/
 5880: int	texchrlen = (texchr==NULL?0:strlen(texchr)); /* #chars in texchr */
 5881: /* -------------------------------------------------------------------------
 5882: locate texchr in string
 5883: -------------------------------------------------------------------------- */
 5884: if ( string != (char *)NULL		/* check that we got input string */
 5885: &&   texchrlen > 0 ) {			/* and a texchr to search for */
 5886:  while ( (ptexchr=strstr(pstring,texchr)) /* look for texchr in string */
 5887:  != (char *)NULL )			/* found it */
 5888:   if ( (delim = ptexchr[texchrlen])	/* char immediately after texchr */
 5889:   ==   '\000' ) break;			/* texchr at very end of string */
 5890:   else					/* if there are chars after texchr */
 5891:    if ( isalpha(delim)			/*texchr is prefix of longer symbol*/
 5892:    ||   0 )				/* other tests to be determined */
 5893:     pstring = ptexchr + texchrlen;	/* continue search after texchr */
 5894:    else					/* passed all tests */
 5895:     break; }				/*so return ptr to texchr to caller*/
 5896: return ( ptexchr );			/* ptr to texchar back to caller */
 5897: } /* --- end-of-function strtexchr() --- */
 5898: 
 5899: 
 5900: /* ==========================================================================
 5901:  * Function:	findbraces ( char *expression, char *command )
 5902:  * Purpose:	If expression!=NULL, finds opening left { preceding command;
 5903:  *		if expression==NULL, finds closing right } after command.
 5904:  *		For example, to parse out {a+b\over c+d} call findbraces()
 5905:  *		twice.
 5906:  * --------------------------------------------------------------------------
 5907:  * Arguments:	expression (I)	NULL to find closing right } after command,
 5908:  *				or char * to null-terminated string to find
 5909:  *				left opening { preceding command.
 5910:  *		command (I)	char * to null-terminated string whose
 5911:  *				first character is usually the \ of \command
 5912:  * --------------------------------------------------------------------------
 5913:  * Returns:	( char * )	ptr to either opening { or closing },
 5914:  *				or NULL for any error.
 5915:  * --------------------------------------------------------------------------
 5916:  * Notes:     o
 5917:  * ======================================================================= */
 5918: /* --- entry point --- */
 5919: char	*findbraces ( char *expression, char *command )
 5920: {
 5921: /* -------------------------------------------------------------------------
 5922: Allocations and Declarations
 5923: -------------------------------------------------------------------------- */
 5924: int	isopen = (expression==NULL?0:1); /* true to find left opening { */
 5925: char	*left="{", *right="}",		/* delims bracketing {x\command y} */
 5926: 	*delim = (isopen?left:right),	/* delim we want,  { if isopen */
 5927: 	*match = (isopen?right:left),	/* matching delim, } if isopen */
 5928: 	*brace = NULL;			/* ptr to delim returned to caller */
 5929: int	inc = (isopen?-1:+1);		/* pointer increment */
 5930: int	level = 1;			/* nesting level, for {{}\command} */
 5931: char	*ptr = command;			/* start search here */
 5932: int	setbrace = 1;			/* true to set {}'s if none found */
 5933: /* -------------------------------------------------------------------------
 5934: search for left opening { before command, or right closing } after command
 5935: -------------------------------------------------------------------------- */
 5936: while ( 1 )				/* search for brace, or until end */
 5937:   {
 5938:   /* --- next char to check for delim --- */
 5939:   ptr += inc;				/* bump ptr left or right */
 5940:   /* --- check for beginning or end of expression --- */
 5941:   if ( isopen )				/* going left, check for beginning */
 5942:        { if ( ptr < expression ) break;	} /* went before start of string */
 5943:   else { if ( *ptr == '\000' ) break; }	/* went past end of string */
 5944:   /* --- don't check this char if it's escaped --- */
 5945:   if ( !isopen || ptr>expression )	/* very first char can't be escaped*/
 5946:     if ( isthischar(*(ptr-1),ESCAPE) )	/* escape char precedes current */
 5947:       continue;				/* so don't check this char */
 5948:   /* --- check for delim --- */
 5949:   if ( isthischar(*ptr,delim) )		/* found delim */
 5950:     if ( --level == 0 )			/* and it's not "internally" nested*/
 5951:       {	brace = ptr;			/* set ptr to brace */
 5952: 	goto end_of_job; }		/* and return it to caller */
 5953:   /* --- check for matching delim --- */
 5954:   if ( isthischar(*ptr,match) )		/* found matching delim */
 5955:     level++;				/* so bump nesting level */
 5956:   } /* --- end-of-while(1) --- */
 5957: end_of_job:
 5958:   if ( brace == (char *)NULL )		/* open{ or close} not found */
 5959:     if ( setbrace )			/* want to force one at start/end? */
 5960:       brace = ptr;			/* { before expressn, } after cmmnd*/
 5961:   return ( brace );			/*back to caller with delim or NULL*/
 5962: } /* --- end-of-function findbraces() --- */
 5963: #endif /* PART2 */
 5964: 
 5965: /* ---
 5966:  * PART3
 5967:  * ------ */
 5968: #if !defined(PARTS) || defined(PART3)
 5969: /* ==========================================================================
 5970:  * Function:	rasterize ( expression, size )
 5971:  * Purpose:	returns subraster corresponding to (a valid LaTeX) expression
 5972:  *		at font size
 5973:  * --------------------------------------------------------------------------
 5974:  * Arguments:	expression (I)	char * to first char of null-terminated
 5975:  *				string containing valid LaTeX expression
 5976:  *				to be rasterized
 5977:  *		size (I)	int containing 0-4 default font size
 5978:  * --------------------------------------------------------------------------
 5979:  * Returns:	( subraster * )	ptr to subraster corresponding to expression,
 5980:  *				or NULL for any parsing error.
 5981:  * --------------------------------------------------------------------------
 5982:  * Notes:     o	This is mimeTeX's "main" reusable entry point.  Easy to use:
 5983:  *		just call it with a LaTeX expression, and get back a bitmap
 5984:  *		of that expression.  Then do what you want with the bitmap.
 5985:  * ======================================================================= */
 5986: /* --- entry point --- */
 5987: subraster *rasterize ( char *expression, int size )
 5988: {
 5989: /* -------------------------------------------------------------------------
 5990: Allocations and Declarations
 5991: -------------------------------------------------------------------------- */
 5992: char	*preamble(), pretext[512];	/* process preamble, if present */
 5993: char	chartoken[MAXSUBXSZ+1], *texsubexpr(), /*get subexpression from expr*/
 5994: 	*subexpr = chartoken;		/* token may be parenthesized expr */
 5995: int	isbrace();			/* check subexpr for braces */
 5996: mathchardef *symdef, *get_symdef();	/*get mathchardef struct for symbol*/
 5997: int	ligdef, get_ligature();		/*get symtable[] index for ligature*/
 5998: int	natoms=0;			/* #atoms/tokens processed so far */
 5999: int	type_raster();			/* display debugging output */
 6000: subraster *rasterize(),			/* recurse */
 6001: 	*rastparen(),			/* handle parenthesized subexpr's */
 6002: 	*rastlimits();			/* handle sub/superscripted expr's */
 6003: subraster *rastcat(),			/* concatanate atom subrasters */
 6004: 	*subrastcpy(),			/* copy final result if a charaster*/
 6005: 	*new_subraster();		/* new subraster for isstring mode */
 6006: subraster *get_charsubraster(),		/* character subraster */
 6007: 	*sp=NULL, *prevsp=NULL,		/* raster for current, prev char */
 6008: 	*expraster = (subraster *)NULL;	/* raster returned to caller */
 6009: int	delete_subraster();		/* free everything before returning*/
 6010: int	family = fontinfo[fontnum].family; /* current font family */
 6011: int	isleftscript = 0,		/* true if left-hand term scripted */
 6012: 	wasscripted = 0,		/* true if preceding token scripted*/
 6013: 	wasdelimscript = 0;		/* true if preceding delim scripted*/
 6014: /*int	pixsz = 1;*/			/*default #bits per pixel, 1=bitmap*/
 6015: /* --- global values saved/restored at each recursive iteration --- */
 6016: int	wasstring = isstring,		/* initial isstring mode flag */
 6017: 	wasdisplaystyle = isdisplaystyle, /*initial displaystyle mode flag*/
 6018: 	oldfontnum = fontnum,		/* initial font family */
 6019: 	oldfontsize = fontsize,		/* initial fontsize */
 6020: 	olddisplaysize = displaysize,	/* initial \displaystyle size */
 6021: 	oldshrinkfactor = shrinkfactor,	/* initial shrinkfactor */
 6022: 	oldsmashmargin = smashmargin,	/* initial smashmargin */
 6023: 	oldissmashdelta = issmashdelta, /* initial issmashdelta */
 6024: 	oldisexplicitsmash = isexplicitsmash, /* initial isexplicitsmash */
 6025: 	oldisscripted = isscripted,	/* initial isscripted */
 6026: 	*oldworkingparam = workingparam; /* initial working parameter */
 6027: subraster *oldworkingbox = workingbox,	/* initial working box */
 6028: 	*oldleftexpression = leftexpression; /*left half rasterized so far*/
 6029: double	oldunitlength = unitlength;	/* initial unitlength */
 6030: mathchardef *oldleftsymdef = leftsymdef; /* init oldleftsymdef */
 6031: /* -------------------------------------------------------------------------
 6032: initialization
 6033: -------------------------------------------------------------------------- */
 6034: recurlevel++;				/* wind up one more recursion level*/
 6035: leftexpression = NULL;			/* no leading left half yet */
 6036: isreplaceleft = 0;			/* reset replaceleft flag */
 6037: if(1)fraccenterline = NOVALUE;		/* reset \frac baseline signal */
 6038: /* shrinkfactor = shrinkfactors[max2(0,min2(size,LARGESTSIZE))];*/ /*set sf*/
 6039: shrinkfactor = shrinkfactors[max2(0,min2(size,16))]; /* have 17 sf's */
 6040: if ( msgfp!=NULL && msglevel >= 9 ) {	/*display expression for debugging*/
 6041:  fprintf(msgfp,
 6042:  "rasterize> recursion#%d, size=%d,\n\texpression=\"%s\"\n",
 6043:  recurlevel,size,(expression==NULL?"<null>":expression)); fflush(msgfp); }
 6044: if ( expression == NULL ) goto end_of_job; /* nothing given to do */
 6045: /* -------------------------------------------------------------------------
 6046: preocess optional $-terminated preamble preceding expression
 6047: -------------------------------------------------------------------------- */
 6048: expression = preamble(expression,&size,pretext); /* size may be modified */
 6049: if ( *expression == '\000' ) goto end_of_job; /* nothing left to do */
 6050: fontsize = size;			/* start at requested size */
 6051: if ( isdisplaystyle == 1 )		/* displaystyle enabled but not set*/
 6052:  if ( !ispreambledollars )		/* style fixed by $$...$$'s */
 6053:   isdisplaystyle = (fontsize>=displaysize? 2:1); /*force at large fontsize*/
 6054: /* -------------------------------------------------------------------------
 6055: build up raster one character (or subexpression) at a time
 6056: -------------------------------------------------------------------------- */
 6057: while ( 1 )
 6058:   {
 6059:   /* --- kludge for \= cyrillic ligature --- */
 6060:   isligature = 0;			/* no ligature found yet */
 6061:   family = fontinfo[fontnum].family;	/* current font family */
 6062:   if ( family == CYR10 )		/* may have cyrillic \= ligature */
 6063:    if ( (ligdef = get_ligature(expression,family)) /*check for any ligature*/
 6064:    >=    0 )				/* got some ligature */
 6065:     if ( memcmp(symtable[ligdef].symbol,"\\=",2) == 0 ) /* starts with \= */
 6066:      isligature = 1;			/* signal \= ligature */
 6067:   /* --- get next character/token or subexpression --- */
 6068:   subexprptr = expression;		/* ptr within expression to subexpr*/
 6069:   expression = texsubexpr(expression,chartoken,0,LEFTBRACES,RIGHTBRACES,1,1);
 6070:   subexpr = chartoken;			/* "local" copy of chartoken ptr */
 6071:   leftsymdef = NULL;			/* no character identified yet */
 6072:   sp = NULL;				/* no subraster yet */
 6073:   size = fontsize;			/* in case reset by \tiny, etc */
 6074:   /*isleftscript = isdelimscript;*/	/*was preceding term scripted delim*/
 6075:   wasscripted = isscripted;		/* true if preceding token scripted*/
 6076:   wasdelimscript = isdelimscript;	/* preceding \right delim scripted */
 6077:   if(1)isscripted = 0;			/* no subscripted expression yet */
 6078:   isdelimscript = 0;			/* reset \right delim scripted flag*/
 6079:   /* --- debugging output --- */
 6080:   if ( msgfp!=NULL && msglevel >= 9 ) {	/* display chartoken for debugging */
 6081:    fprintf(msgfp,
 6082:    "rasterize> recursion#%d,atom#%d=\"%s\" (isligature=%d,isleftscript=%d)\n",
 6083:    recurlevel,natoms+1,chartoken,isligature,isleftscript); fflush(msgfp); }
 6084:   if ( expression == NULL		/* no more tokens */
 6085:   &&   *subexpr == '\000' ) break;	/* and this token empty */
 6086:   if ( *subexpr == '\000' ) break;	/* enough if just this token empty */
 6087:   /* --- check for parenthesized subexpression --- */
 6088:   if ( isbrace(subexpr,LEFTBRACES,1) )	/* got parenthesized subexpression */
 6089:     { if ( (sp=rastparen(&subexpr,size,prevsp)) /* rasterize subexpression */
 6090:       ==   NULL )  continue; }		/* flush it if failed to rasterize */
 6091:   else /* --- single-character atomic token --- */
 6092:    if ( !isthischar(*subexpr,SCRIPTS) )	/* scripts handled below */
 6093:     {
 6094:     /* --- first check for opening $ in \text{ if $n-m$ even} --- */
 6095:     if ( istextmode			/* we're in \text mode */
 6096:     &&   *subexpr=='$' && subexpr[1]=='\000' ) { /* and have an opening $ */
 6097:      char *endptr=NULL, mathexpr[MAXSUBXSZ+1]; /* $expression$ in \text{ }*/
 6098:      int  exprlen = 0;			/* length of $expression$ */
 6099:      int  textfontnum = fontnum;	/* current text font number */
 6100:      /*if ( (endptr=strrchr(expression,'$')) != NULL )*/ /*ptr to closing $*/
 6101:      if ( (endptr=strchr(expression,'$')) != NULL ) /* ptr to closing $ */
 6102:        exprlen = (int)(endptr-expression); /* #chars preceding closing $ */
 6103:      else {				/* no closing $ found */
 6104:        exprlen = strlen(expression);	/* just assume entire expression */
 6105:        endptr = expression + (exprlen-1); } /*and push expression to '\000'*/
 6106:      exprlen = min2(exprlen,MAXSUBXSZ);	/* don't overflow mathexpr[] */
 6107:      if ( exprlen > 0 ) {		/* have something between $$ */
 6108:        memcpy(mathexpr,expression,exprlen); /*local copy of math expression*/
 6109:        mathexpr[exprlen] = '\000';	/* null-terminate it */
 6110:        fontnum = 0;			/* set math mode */
 6111:        sp = rasterize(mathexpr,size);	/* and rasterize $expression$ */
 6112:        fontnum = textfontnum; }		/* set back to text mode */
 6113:      expression = endptr+1;		/* push expression past closing $ */
 6114:      } /* --- end-of-if(istextmode&&*subexpr=='$') --- */
 6115:     else
 6116:      /* --- otherwise, look up mathchardef for atomic token in table --- */
 6117:      if ( (leftsymdef=symdef=get_symdef(chartoken)) /*mathchardef for token*/
 6118:      ==  NULL )				/* lookup failed */
 6119:       { char literal[512] = "[?]";	/*display for unrecognized literal*/
 6120:         int  oldfontnum = fontnum;	/* error display in default mode */
 6121:         if ( msgfp!=NULL && msglevel >= 29 ) /* display unrecognized symbol*/
 6122: 	 { fprintf(msgfp,"rasterize> get_symdef() failed for \"%s\"\n",
 6123: 	   chartoken); fflush(msgfp); }
 6124:         sp = (subraster *)NULL;		/* init to signal failure */
 6125:         if ( warninglevel < 1 ) continue; /* warnings not wanted */
 6126:         fontnum = 0;			/* reset from \mathbb, etc */
 6127:         if ( isthischar(*chartoken,ESCAPE) ) /* we got unrecognized \escape*/
 6128: 	 { /* --- so display literal {\rm~[\backslash~chartoken?]} ---  */
 6129: 	   strcpy(literal,"{\\rm~[\\backslash~"); /* init token */
 6130: 	   strcat(literal,chartoken+1);	/* add chars following leading \ */
 6131: 	   strcat(literal,"?]}"); }	/* add closing brace */
 6132:         sp = rasterize(literal,size-1);	/* rasterize literal token */
 6133:         fontnum = oldfontnum;		/* reset font family */
 6134:         if ( sp == (subraster *)NULL ) continue; }/*flush if rasterize fails*/
 6135:      else /* --- check if we have special handler to process this token --- */
 6136:       if ( symdef->handler != NULL )	/* have a handler for this token */
 6137:        { int arg1=symdef->charnum, arg2=symdef->family, arg3=symdef->class;
 6138:          if ( (sp = (subraster *)	/* returned void* is subraster* */
 6139: 	 (*(symdef->handler))(&expression,size,prevsp,arg1,arg2,arg3))==NULL)
 6140: 	   continue; }			/* flush token if handler failed */
 6141:       else /* --- no handler, so just get subraster for this character --- */
 6142:        if ( !isstring )			/* rasterizing */
 6143: 	{ if ( isligature )		/* found a ligature */
 6144: 	   expression = subexprptr + strlen(symdef->symbol); /*push past it*/
 6145: 	  if ( (sp=get_charsubraster(symdef,size)) /* get subraster */
 6146: 	  ==  NULL )  continue; }	/* flush token if failed */
 6147:        else				/* constructing ascii string */
 6148: 	{ char *symbol = symdef->symbol; /* symbol for ascii string */
 6149: 	  int symlen = (symbol!=NULL?strlen(symbol):0); /*#chars in symbol*/
 6150: 	  if ( symlen < 1 ) continue;	/* no symbol for ascii string */
 6151: 	  if ( (sp=new_subraster(symlen+1,1,8)) /* subraster for symbol */
 6152: 	  ==  NULL )  continue;		/* flush token if malloc failed */
 6153: 	  sp->type = ASCIISTRING;	/* set subraster type */
 6154: 	  sp->symdef = symdef;		/* and set symbol definition */
 6155: 	  sp->baseline = 1;		/* default (should be unused) */
 6156: 	  strcpy((char *)((sp->image)->pixmap),symbol); /* copy symbol */
 6157: 	  /*((char *)((sp->image)->pixmap))[symlen] = '\000';*/ } /*null*/
 6158:     } /* --- end-of-if(!isthischar(*subexpr,SCRIPTS)) --- */
 6159:   /* --- handle any super/subscripts following symbol or subexpression --- */
 6160:   sp = rastlimits(&expression,size,sp);
 6161:   isleftscript = (wasscripted||wasdelimscript?1:0);/*preceding term scripted*/
 6162:   /* --- debugging output --- */
 6163:   if ( msgfp!=NULL && msglevel >= 9 ) {	/* display raster for debugging */
 6164:    fprintf(msgfp,"rasterize> recursion#%d,atom#%d%s\n",
 6165:    recurlevel,natoms+1,(sp==NULL?" = <null>":"..."));
 6166:    if ( msglevel >= 9 ) fprintf(msgfp,
 6167:     "  isleftscript=%d is/wasscripted=%d,%d is/wasdelimscript=%d,%d\n",
 6168:     isleftscript,isscripted,wasscripted,isdelimscript,wasdelimscript);
 6169:    if ( msglevel >= 99 )
 6170:     if(sp!=NULL) type_raster(sp->image,msgfp); /* display raster */
 6171:    fflush(msgfp); }			/* flush msgfp buffer */
 6172:   /* --- accumulate atom or parenthesized subexpression --- */
 6173:   if ( natoms < 1			/* nothing previous to concat */
 6174:   ||   expraster == NULL		/* or previous was complete error */
 6175:   ||   isreplaceleft )			/* or we're replacing previous */
 6176:     { if ( 1 && expraster!=NULL )	/* probably replacing left */
 6177: 	delete_subraster(expraster);	/* so first free original left */
 6178:       expraster = subrastcpy(sp);	/* copy static CHARASTER or left */
 6179:       isreplaceleft = 0; }		/* reset replacement flag */
 6180:   else					/*we've already built up atoms so...*/
 6181:    if ( sp != NULL ) {			/* ...if we have a new term */
 6182:     int prevsmashmargin = smashmargin;	/* save current smash margin */
 6183:     if ( isleftscript ) {		/* don't smash against scripts */
 6184:      isdelimscript = 0;			/* reset \right delim scripted flag*/
 6185:      if ( !isexplicitsmash ) smashmargin = 0; } /* signal no smash wanted */
 6186:     expraster = rastcat(expraster,sp,1); /* concat new term, free previous */
 6187:     smashmargin = prevsmashmargin; }	/* restore current smash margin */
 6188:   delete_subraster(prevsp);		/* free prev (if not a CHARASTER) */
 6189:   prevsp = sp;				/* current becomes previous */
 6190:   leftexpression = expraster;		/* left half rasterized so far */
 6191:   /* --- bump count --- */
 6192:   natoms++;				/* bump #atoms count */
 6193:   } /* --- end-of-while(expression!=NULL) --- */
 6194: /* -------------------------------------------------------------------------
 6195: back to caller with rasterized expression
 6196: -------------------------------------------------------------------------- */
 6197: end_of_job:
 6198:   delete_subraster(prevsp);		/* free last (if not a CHARASTER) */
 6199:   /* --- debugging output --- */
 6200:   if ( msgfp!=NULL && msglevel >= 999 )	/* display raster for debugging */
 6201:     { fprintf(msgfp,"rasterize> Final recursion level=%d, atom#%d...\n",
 6202:       recurlevel,natoms);
 6203:       if ( expraster != (subraster *)NULL ) /* i.e., if natoms>0 */
 6204: 	type_raster(expraster->image,msgfp); /* display completed raster */
 6205:       fflush(msgfp); }			/* flush msgfp buffer */
 6206:   /* --- set final raster buffer --- */
 6207:   if ( 1 && expraster != (subraster *)NULL ) /* have an expression */
 6208:     { int type = expraster->type;	/* type of constructed image */
 6209:       if ( type != FRACRASTER )		/* leave \frac alone */
 6210: 	expraster->type = IMAGERASTER;	/* set type to constructed image */
 6211:       if ( istextmode )			/* but in text mode */
 6212:         expraster->type = blanksignal;	/* set type to avoid smash */
 6213:       expraster->size = fontsize; }	/* set original input font size */
 6214:   /* --- restore flags/values to original saved values --- */
 6215:   isstring = wasstring;			/* string mode reset */
 6216:   isdisplaystyle = wasdisplaystyle;	/* displaystyle mode reset */
 6217:   fontnum = oldfontnum;			/* font family reset */
 6218:   fontsize = oldfontsize;		/* fontsize reset */
 6219:   displaysize = olddisplaysize;		/* \displaystyle size reset */
 6220:   shrinkfactor = oldshrinkfactor;	/* shrinkfactor reset */
 6221:   smashmargin = oldsmashmargin;		/* smashmargin reset */
 6222:   issmashdelta = oldissmashdelta;	/* issmashdelta reset */
 6223:   isexplicitsmash = oldisexplicitsmash;	/* isexplicitsmash reset */
 6224:   isscripted = oldisscripted;		/* isscripted reset */
 6225:   workingparam = oldworkingparam;	/* working parameter reset */
 6226:   workingbox = oldworkingbox;		/* working box reset */
 6227:   leftexpression = oldleftexpression;	/* leftexpression reset */
 6228:   leftsymdef = oldleftsymdef;		/* leftsymdef reset */
 6229:   unitlength = oldunitlength;		/* unitlength reset */
 6230:   recurlevel--;				/* unwind one recursion level */
 6231:   /* --- return final subraster to caller --- */
 6232:   return ( expraster );
 6233: } /* --- end-of-function rasterize() --- */
 6234: 
 6235: 
 6236: /* ==========================================================================
 6237:  * Function:	rastparen ( subexpr, size, basesp )
 6238:  * Purpose:	parentheses handler, returns a subraster corresponding to
 6239:  *		parenthesized subexpression at font size
 6240:  * --------------------------------------------------------------------------
 6241:  * Arguments:	subexpr (I)	char **  to first char of null-terminated
 6242:  *				string beginning with a LEFTBRACES
 6243:  *				to be rasterized
 6244:  *		size (I)	int containing 0-5 default font size
 6245:  *		basesp (I)	subraster *  to character (or subexpression)
 6246:  *				immediately preceding leading left{
 6247:  *				(unused, but passed for consistency)
 6248:  * --------------------------------------------------------------------------
 6249:  * Returns:	( subraster * )	ptr to subraster corresponding to subexpr,
 6250:  *				or NULL for any parsing error
 6251:  * --------------------------------------------------------------------------
 6252:  * Notes:     o	This "handler" isn't in the mathchardef symbol table,
 6253:  *		but is called directly from rasterize(), as necessary.
 6254:  *	      o	Though subexpr is returned unchanged, it's passed as char **
 6255:  *		for consistency with other handlers.  Ditto, basesp is unused
 6256:  *		but passed for consistency
 6257:  * ======================================================================= */
 6258: /* --- entry point --- */
 6259: subraster *rastparen ( char **subexpr, int size, subraster *basesp )
 6260: {
 6261: /* -------------------------------------------------------------------------
 6262: Allocations and Declarations
 6263: -------------------------------------------------------------------------- */
 6264: char	*expression = *subexpr;		/* dereference subexpr to get char* */
 6265: int	explen = strlen(expression);	/* total #chars, including parens */
 6266: int	isescape = 0,			/* true if parens \escaped */
 6267: 	isrightdot = 0,			/* true if right paren is \right. */
 6268: 	isleftdot = 0;			/* true if left paren is \left. */
 6269: char	left[32], right[32];		/* parens enclosing expresion */
 6270: char	noparens[MAXSUBXSZ+1];		/* get subexpr without parens */
 6271: subraster *rasterize(), *sp=NULL;	/* rasterize what's between ()'s */
 6272: int	isheight = 1;			/*true=full height, false=baseline*/
 6273: int	height,				/* height of rasterized noparens[] */
 6274: 	baseline;			/* and its baseline */
 6275: int	family = /*CMSYEX*/ CMEX10;	/* family for paren chars */
 6276: subraster *get_delim(), *lp=NULL, *rp=NULL; /* left and right paren chars */
 6277: subraster *rastcat();			/* concatanate subrasters */
 6278: int	delete_subraster();		/*in case of error after allocation*/
 6279: /* -------------------------------------------------------------------------
 6280: rasterize "interior" of expression, i.e., without enclosing parens
 6281: -------------------------------------------------------------------------- */
 6282: /* --- first see if enclosing parens are \escaped --- */
 6283: if ( isthischar(*expression,ESCAPE) )	/* expression begins with \escape */
 6284:   isescape = 1;				/* so set flag accordingly */
 6285: /* --- get expression *without* enclosing parens --- */
 6286: strcpy(noparens,expression);		/* get local copy of expression */
 6287: noparens[explen-(1+isescape)] = '\000';	/* null-terminate before right} */
 6288: strcpy(noparens,noparens+(1+isescape));	/* and then squeeze out left{ */
 6289: /* --- rasterize it --- */
 6290: if ( (sp = rasterize(noparens,size))	/*rasterize "interior" of expression*/
 6291: ==   NULL ) goto end_of_job;		/* quit if failed */
 6292: /* --- no need to add parentheses for unescaped { --- */
 6293: if ( !isescape && isthischar(*expression,"{") ) /* don't add parentheses */
 6294:   goto end_of_job;			/* just return sp to caller */
 6295: /* -------------------------------------------------------------------------
 6296: obtain paren characters to enclose noparens[] raster with
 6297: -------------------------------------------------------------------------- */
 6298: /* --- first get left and right parens from expression --- */
 6299: memset(left,0,16);  memset(right,0,16);	/* init parens with nulls */
 6300: left[0] = *(expression+isescape);	/* left{ is 1st or 2nd char */
 6301: right[0] = *(expression+explen-1);	/* right} is always last char */
 6302: isleftdot  = (isescape && isthischar(*left,".")); /* true if \left. */
 6303: isrightdot = (isescape && isthischar(*right,".")); /* true if \right. */
 6304: /* --- need height of noparens[] raster as minimum parens height --- */
 6305: height = (sp->image)->height;		/* height of noparens[] raster */
 6306: baseline = sp->baseline;		/* baseline of noparens[] raster */
 6307: if ( !isheight ) height = baseline+1;	/* parens only enclose baseline up */
 6308: /* --- get best-fit parentheses characters --- */
 6309: if ( !isleftdot )			/* if not \left. */
 6310:   lp = get_delim(left,height+1,family);	/* get left paren char */
 6311: if ( !isrightdot )			/* and if not \right. */
 6312:   rp = get_delim(right,height+1,family); /* get right paren char */
 6313: if ( (lp==NULL && !isleftdot)		/* check that we got left( */
 6314: ||   (rp==NULL && !isrightdot) )	/* and right) if needed */
 6315:   { delete_subraster(sp);		/* if failed, free subraster */
 6316:     if ( lp != NULL ) free ((void *)lp);/*free left-paren subraster envelope*/
 6317:     if ( rp != NULL ) free ((void *)rp);/*and right-paren subraster envelope*/
 6318:     sp = (subraster *)NULL;		/* signal error to caller */
 6319:     goto end_of_job; }			/* and quit */
 6320: /* -------------------------------------------------------------------------
 6321: set paren baselines to center on noparens[] raster, and concat components
 6322: -------------------------------------------------------------------------- */
 6323: /* --- set baselines to center paren chars on raster --- */
 6324: if ( lp != NULL )			/* ignore for \left. */
 6325:   lp->baseline = baseline + ((lp->image)->height - height)/2;
 6326: if ( rp != NULL )			/* ignore for \right. */
 6327:   rp->baseline = baseline + ((rp->image)->height - height)/2;
 6328: /* --- concat lp||sp||rp to obtain final result --- */
 6329: if ( lp != NULL )			/* ignore \left. */
 6330:   sp = rastcat(lp,sp,3);		/* concat lp||sp and free sp,lp */
 6331: if ( sp != NULL )			/* succeeded or ignored \left. */
 6332:   if ( rp != NULL )			/* ignore \right. */
 6333:     sp = rastcat(sp,rp,3);		/* concat sp||rp and free sp,rp */
 6334: /* --- back to caller --- */
 6335: end_of_job:
 6336:   return ( sp );
 6337: } /* --- end-of-function rastparen() --- */
 6338: 
 6339: 
 6340: /* ==========================================================================
 6341:  * Function:	rastlimits ( expression, size, basesp )
 6342:  * Purpose:	\limits, \nolimts, _ and ^ handler,
 6343:  *		dispatches call to rastscripts() or to rastdispmath()
 6344:  *		as necessary, to handle sub/superscripts following symbol
 6345:  * --------------------------------------------------------------------------
 6346:  * Arguments:	expression (I)	char **  to first char of null-terminated
 6347:  *				LaTeX expression (unused/unchanged)
 6348:  *		size (I)	int containing base font size (not used,
 6349:  *				just stored in subraster)
 6350:  *		basesp (I)	subraster *  to current character (or
 6351:  *				subexpression) immediately preceding script
 6352:  *				indicator
 6353:  * --------------------------------------------------------------------------
 6354:  * Returns:	( subraster * )	ptr to subraster returned by rastscripts()
 6355:  *				or rastdispmath(), or NULL for any error
 6356:  * --------------------------------------------------------------------------
 6357:  * Notes:     o
 6358:  * ======================================================================= */
 6359: /* --- entry point --- */
 6360: subraster *rastlimits ( char **expression, int size, subraster *basesp )
 6361: {
 6362: /* -------------------------------------------------------------------------
 6363: Allocations and Declarations
 6364: -------------------------------------------------------------------------- */
 6365: subraster *rastscripts(), *rastdispmath(), /*one of these will do the work*/
 6366: 	*rastcat(),			/* may need to concat scripts */
 6367: 	*rasterize(),			/* may need to construct dummy base*/
 6368: 	*scriptsp = basesp,		/* and this will become the result */
 6369: 	*dummybase = basesp;		/* for {}_i construct a dummy base */
 6370: int	isdisplay = (-1);		/* set 1 for displaystyle, else 0 */
 6371: int	oldsmashmargin = smashmargin;	/* save original smashmargin */
 6372: int	type_raster();			/* display debugging output */
 6373: int	delete_subraster();		/* free dummybase, if necessary */
 6374: int	rastsmashcheck();		/* check if okay to smash scripts */
 6375: /* --- to check for \limits or \nolimits preceding scripts --- */
 6376: char	*texchar(), *exprptr=*expression, limtoken[255]; /*check for \limits*/
 6377: int	toklen=0;			/* strlen(limtoken) */
 6378: mathchardef *tokdef, *get_symdef();	/* mathchardef struct for limtoken */
 6379: int	class=(leftsymdef==NULL?NOVALUE:leftsymdef->class); /*base sym class*/
 6380: /* -------------------------------------------------------------------------
 6381: determine whether or not to use displaymath
 6382: -------------------------------------------------------------------------- */
 6383: scriptlevel++;				/* first, increment subscript level*/
 6384: *limtoken = '\000';			/* no token yet */
 6385: isscripted = 0;				/* signal term not (text) scripted */
 6386: if ( msgfp!=NULL && msglevel>=999 )
 6387:  { fprintf(msgfp,"rastlimits> scriptlevel#%d exprptr=%.48s\n",
 6388:    scriptlevel,(exprptr==NULL?"null":exprptr));  fflush(msgfp); }
 6389: if ( isstring ) goto end_of_job;	/* no scripts for ascii string */
 6390: /* --- check for \limits or \nolimits --- */
 6391: skipwhite(exprptr);			/* skip white space before \limits */
 6392: if ( exprptr != NULL )			/* expression ptr supplied */
 6393:  if ( *exprptr != '\000' )		/* something in expression */
 6394:   exprptr = texchar(exprptr,limtoken);	/* retrieve next token */
 6395: if ( *limtoken != '\000' )		/* have token */
 6396:  if ( (toklen=strlen(limtoken)) >= 3 )	/* which may be \[no]limits */
 6397:   if ( memcmp("\\limits",limtoken,toklen) == 0     /* may be \limits */
 6398:   ||   memcmp("\\nolimits",limtoken,toklen) == 0 ) /* or may be \nolimits */
 6399:    if ( (tokdef= get_symdef(limtoken))	/* look up token to be sure */
 6400:    !=   NULL ) {			/* found token in table */
 6401:     if ( strcmp("\\limits",tokdef->symbol) == 0 )  /* found \limits */
 6402:       isdisplay = 1;			/* so explicitly set displaymath */
 6403:     else				/* wasn't \limits */
 6404:       if ( strcmp("\\nolimits",tokdef->symbol) == 0 ) /* found \nolimits */
 6405: 	isdisplay = 0; }		/* so explicitly reset displaymath */
 6406: /* --- see if we found \[no]limits --- */
 6407: if ( isdisplay != (-1) )		/* explicit directive found */
 6408:   *expression = exprptr;		/* so bump expression past it */
 6409: else					/* noexplicit directive */
 6410:   { isdisplay = 0;			/* init displaymath flag off */
 6411:     if ( isdisplaystyle ) {		/* we're in displaystyle math mode */
 6412:       if ( isdisplaystyle >= 5 )	/* and mode irrevocably forced true */
 6413: 	{ if ( class!=OPENING && class!=CLOSING ) /*don't force ('s and )'s*/
 6414: 	    isdisplay = 1; }		/* set flag if mode forced true */
 6415:       else
 6416:        if ( isdisplaystyle >= 2 )	/*or mode forced conditionally true*/
 6417: 	{ if ( class!=VARIABLE && class!=ORDINARY /*don't force characters*/
 6418: 	  &&   class!=OPENING  && class!=CLOSING  /*don't force ('s and )'s*/
 6419: 	  &&   class!=BINARYOP		/* don't force binary operators */
 6420: 	  &&   class!=NOVALUE )		/* finally, don't force "images" */
 6421: 	    isdisplay = 1; }		/* set flag if mode forced true */
 6422:        else				/* determine mode from base symbol */
 6423: 	if ( class == DISPOPER )	/* it's a displaystyle operator */
 6424: 	  isdisplay = 1; } }		/* so set flag */
 6425: /* -------------------------------------------------------------------------
 6426: dispatch call to create sub/superscripts
 6427: -------------------------------------------------------------------------- */
 6428: if ( isdisplay )			/* scripts above/below base symbol */
 6429:   scriptsp = rastdispmath(expression,size,basesp); /* everything all done */
 6430: else {					/* scripts alongside base symbol */
 6431:   if ( dummybase == NULL )		/* no base symbol preceding scripts*/
 6432:     dummybase = rasterize("\\rule0{10}",size); /*guess a typical base symbol*/
 6433:   issmashokay = 1;			/*haven't found a no-smash char yet*/
 6434:   if((scriptsp=rastscripts(expression,size,dummybase)) == NULL) /*no scripts*/
 6435:     scriptsp = basesp;			/* so just return unscripted symbol*/
 6436:   else {				/* symbols followed by scripts */
 6437:     isscripted = 1;			/*signal current term text-scripted*/
 6438:     if ( basesp != NULL )		/* have base symbol */
 6439:      { /*if(0)smashmargin = 0;*/	/*don't smash script (doesn't work)*/
 6440:        /*scriptsp = rastcat(basesp,scriptsp,2);*//*concat scripts to base sym*/
 6441:        /* --- smash (or just concat) script raster against base symbol --- */
 6442:        if ( !issmashokay )		/* don't smash leading - */
 6443:          if ( !isexplicitsmash ) scriptsp->type = blanksignal; /*don't smash*/
 6444:        scriptsp = rastcat(basesp,scriptsp,3); /*concat scripts to base sym*/
 6445:        if(1) scriptsp->type = IMAGERASTER; /* flip type of composite object */
 6446:        /* --- smash (or just concat) scripted term to stuff to its left --- */
 6447:        issmashokay = 1;			/* okay to smash base expression */
 6448:        if ( 0 && smashcheck > 1 )	/* smashcheck=2 to check base */
 6449:          /* note -- we _don't_ have base expression available to check */
 6450:          issmashokay = rastsmashcheck(*expression); /*check if okay to smash*/
 6451:        if ( !issmashokay )		/* don't smash leading - */
 6452:          if ( !isexplicitsmash ) scriptsp->type = blanksignal; /*don't smash*/
 6453:        scriptsp->size = size; } } }	/* and set font size */
 6454: end_of_job:
 6455:   smashmargin = oldsmashmargin;		/* reset original smashmargin */
 6456:   if ( dummybase != basesp ) delete_subraster(dummybase); /*free work area*/
 6457:   if ( msgfp!=NULL && msglevel>=99 )
 6458:     { fprintf(msgfp,"rastlimits> scriptlevel#%d returning %s\n",
 6459: 	scriptlevel,(scriptsp==NULL?"null":"..."));
 6460:       if ( scriptsp != NULL )		/* have a constructed raster */
 6461: 	type_raster(scriptsp->image,msgfp); /*display constructed raster*/
 6462:       fflush(msgfp); }
 6463:   scriptlevel--;			/*lastly, decrement subscript level*/
 6464:   return ( scriptsp );
 6465: } /* --- end-of-function rastlimits() --- */
 6466: 
 6467: 
 6468: /* ==========================================================================
 6469:  * Function:	rastscripts ( expression, size, basesp )
 6470:  * Purpose:	super/subscript handler, returns subraster for the leading
 6471:  *		scripts in expression, whose base symbol is at font size
 6472:  * --------------------------------------------------------------------------
 6473:  * Arguments:	expression (I/O) char **  to first char of null-terminated
 6474:  *				string beginning with a super/subscript,
 6475:  *				and returning ptr immediately following
 6476:  *				last script character processed.
 6477:  *		size (I)	int containing 0-4 default font size
 6478:  *		basesp (I)	subraster *  to character (or subexpression)
 6479:  *				immediately preceding leading script
 6480:  *				(scripts will be placed relative to base)
 6481:  * --------------------------------------------------------------------------
 6482:  * Returns:	( subraster * )	ptr to subraster corresponding to scripts,
 6483:  *				or NULL for any parsing error
 6484:  * --------------------------------------------------------------------------
 6485:  * Notes:     o	This "handler" isn't in the mathchardef symbol table,
 6486:  *		but is called directly from rasterize(), as necessary.
 6487:  * ======================================================================= */
 6488: /* --- entry point --- */
 6489: subraster *rastscripts ( char **expression, int size, subraster *basesp )
 6490: {
 6491: /* -------------------------------------------------------------------------
 6492: Allocations and Declarations
 6493: -------------------------------------------------------------------------- */
 6494: char	*texscripts(),			/* parse expression for scripts */
 6495: 	subscript[512], supscript[512];	/* scripts parsed from expression */
 6496: subraster *rasterize(), *subsp=NULL, *supsp=NULL; /* rasterize scripts */
 6497: subraster *new_subraster(), *sp=NULL,	/* super- over subscript subraster */
 6498: 	*rastack();			/*sets scripts in displaymath mode*/
 6499: raster	*rp=NULL;			/* image raster embedded in sp */
 6500: int	height=0, width=0,  baseline=0,	/* height,width,baseline of sp */
 6501: 	subht=0,  subwidth=0,  subln=0,	/* height,width,baseline of sub */
 6502: 	supht=0,  supwidth=0,  supln=0,	/* height,width,baseline of sup */
 6503: 	baseht=0, baseln=0;		/* height,baseline of base */
 6504: int	bdescend=0, sdescend=0;		/* descender of base, subscript */
 6505: int	issub=0, issup=0, isboth=0,	/* true if we have sub,sup,both */
 6506: 	isbase=0;			/* true if we have base symbol */
 6507: int	szval = min2(max2(size,0),LARGESTSIZE), /* 0...LARGESTSIZE */
 6508: 	vbetween = 2,			/* vertical space between scripts */
 6509: 	vabove   = szval+1,		/*sup's top/bot above base's top/bot*/
 6510: 	vbelow   = szval+1,		/*sub's top/bot below base's top/bot*/
 6511: 	vbottom  = szval+1;		/*sup's bot above (sub's below) bsln*/
 6512: /*int	istweak = 1;*/			/* true to tweak script positioning */
 6513: int	rastput();			/*put scripts in constructed raster*/
 6514: int	delete_subraster();		/* free work areas */
 6515: int	rastsmashcheck();		/* check if okay to smash scripts */
 6516: int	pixsz = 1;			/*default #bits per pixel, 1=bitmap*/
 6517: /* -------------------------------------------------------------------------
 6518: Obtain subscript and/or superscript expressions, and rasterize them/it
 6519: -------------------------------------------------------------------------- */
 6520: /* --- parse for sub,superscript(s), and bump expression past it(them) --- */
 6521: if ( expression == NULL ) goto end_of_job; /* no *ptr given */
 6522: if ( *expression == NULL ) goto end_of_job; /* no expression given */
 6523: if ( *(*expression) == '\000' ) goto end_of_job; /* nothing in expression */
 6524: *expression = texscripts(*expression,subscript,supscript,3);
 6525: /* --- rasterize scripts --- */
 6526: if ( *subscript != '\000' )		/* have a subscript */
 6527:   subsp = rasterize(subscript,size-1);	/* so rasterize it at size-1 */
 6528: if ( *supscript != '\000' )		/* have a superscript */
 6529:   supsp = rasterize(supscript,size-1);	/* so rasterize it at size-1 */
 6530: /* --- set flags for convenience --- */
 6531: issub  = (subsp != (subraster *)NULL);	/* true if we have subscript */
 6532: issup  = (supsp != (subraster *)NULL);	/* true if we have superscript */
 6533: isboth = (issub && issup);		/* true if we have both */
 6534: if (!issub && !issup) goto end_of_job;	/* quit if we have neither */
 6535: /* --- check for leading no-smash chars (if enabled) --- */
 6536: issmashokay = 0;			/* default, don't smash scripts */
 6537: if ( smashcheck > 0 ) {			/* smash checking wanted */
 6538:  issmashokay = 1;			/*haven't found a no-smash char yet*/
 6539:  if ( issub )				/* got a subscript */
 6540:   issmashokay = rastsmashcheck(subscript); /* check if okay to smash */
 6541:  if ( issmashokay )			/* clean sub, so check sup */
 6542:   if ( issup )				/* got a superscript */
 6543:    issmashokay = rastsmashcheck(supscript); /* check if okay to smash */
 6544:  } /* --- end-of-if(smashcheck>0) --- */
 6545: /* -------------------------------------------------------------------------
 6546: get height, width, baseline of scripts,  and height, baseline of base symbol
 6547: -------------------------------------------------------------------------- */
 6548: /* --- get height and width of components --- */
 6549: if ( issub )				/* we have a subscript */
 6550:   { subht    = (subsp->image)->height;	/* so get its height */
 6551:     subwidth = (subsp->image)->width;	/* and width */
 6552:     subln    =  subsp->baseline; }	/* and baseline */
 6553: if ( issup )				/* we have a superscript */
 6554:   { supht    = (supsp->image)->height;	/* so get its height */
 6555:     supwidth = (supsp->image)->width;	/* and width */
 6556:     supln    =  supsp->baseline; }	/* and baseline */
 6557: /* --- get height and baseline of base, and descender of base and sub --- */
 6558: if ( basesp == (subraster *)NULL )	/* no base symbol for scripts */
 6559:   basesp = leftexpression;		/* try using left side thus far */
 6560: if ( basesp != (subraster *)NULL )	/* we have base symbol for scripts */
 6561:   { baseht   = (basesp->image)->height;	/* height of base symbol */
 6562:     baseln   =  basesp->baseline;	/* and its baseline */
 6563:     bdescend =  baseht-(baseln+1);	/* and base symbol descender */
 6564:     sdescend =  bdescend + vbelow;	/*sub must descend by at least this*/
 6565:     if ( baseht > 0 ) isbase = 1; }	/* set flag */
 6566: /* -------------------------------------------------------------------------
 6567: determine width of constructed raster
 6568: -------------------------------------------------------------------------- */
 6569: width = max2(subwidth,supwidth);	/*widest component is overall width*/
 6570: /* -------------------------------------------------------------------------
 6571: determine height and baseline of constructed raster
 6572: -------------------------------------------------------------------------- */
 6573: /* --- both super/subscript --- */
 6574: if ( isboth )				/*we have subscript and superscript*/
 6575:   { height = max2(subht+vbetween+supht,	/* script heights + space bewteen */
 6576: 		vbelow+baseht+vabove);	/*sub below base bot, sup above top*/
 6577:     baseline = baseln + (height-baseht)/2; } /*center scripts on base symbol*/
 6578: /* --- superscript only --- */
 6579: if ( !issub )				/* we only have a superscript */
 6580:   { height = max3(baseln+1+vabove,	/* sup's top above base symbol top */
 6581: 		supht+vbottom,		/* sup's bot above baseln */
 6582: 		supht+vabove-bdescend);	/* sup's bot above base symbol bot */
 6583:     baseline = height-1; }		/*sup's baseline at bottom of raster*/
 6584: /* --- subscript only --- */
 6585: if ( !issup ) {				/* we only have a subscript */
 6586:   if ( subht > sdescend )		/*sub can descend below base bot...*/
 6587:     { height = subht;			/* ...without extra space on top */
 6588:       baseline = height-(sdescend+1);	/* sub's bot below base symbol bot */
 6589:       baseline = min2(baseline,max2(baseln-vbelow,0)); }/*top below base top*/
 6590:   else					/* sub's top will be below baseln */
 6591:     { height = sdescend+1;		/* sub's bot below base symbol bot */
 6592:       baseline = 0; } }			/* sub's baseline at top of raster */
 6593: /* -------------------------------------------------------------------------
 6594: construct raster with superscript over subscript
 6595: -------------------------------------------------------------------------- */
 6596: /* --- allocate subraster containing constructed raster --- */
 6597: if ( (sp=new_subraster(width,height,pixsz)) /*allocate subraster and raster*/
 6598: ==   NULL )				/* and if we fail to allocate */
 6599:   goto end_of_job;			/* quit */
 6600: /* --- initialize subraster parameters --- */
 6601: sp->type  = IMAGERASTER;		/* set type as constructed image */
 6602: sp->size  = size;			/* set given size */
 6603: sp->baseline = baseline;		/* composite scripts baseline */
 6604: rp = sp->image;				/* raster embedded in subraster */
 6605: /* --- place super/subscripts in new raster --- */
 6606: if ( issup )				/* we have a superscript */
 6607:  rastput(rp,supsp->image,0,0,1);	/* it goes in upper-left corner */
 6608: if ( issub )				/* we have a subscript */
 6609:  rastput(rp,subsp->image,height-subht,0,1); /*in lower-left corner*/
 6610: /* -------------------------------------------------------------------------
 6611: free unneeded component subrasters and return final result to caller
 6612: -------------------------------------------------------------------------- */
 6613: end_of_job:
 6614:   if ( issub ) delete_subraster(subsp);	/* free unneeded subscript */
 6615:   if ( issup ) delete_subraster(supsp);	/* and superscript */
 6616:   return ( sp );
 6617: } /* --- end-of-function rastscripts() --- */
 6618: 
 6619: 
 6620: /* ==========================================================================
 6621:  * Function:	rastdispmath ( expression, size, sp )
 6622:  * Purpose:	displaymath handler, returns sp along with
 6623:  *		its immediately following super/subscripts
 6624:  * --------------------------------------------------------------------------
 6625:  * Arguments:	expression (I/O) char **  to first char of null-terminated
 6626:  *				string immediately following sp to be
 6627:  *				rasterized along with its super/subscripts,
 6628:  *				and returning ptr immediately following last
 6629:  *				character processed.
 6630:  *		size (I)	int containing 0-4 default font size
 6631:  *		sp (I)		subraster *  to display math operator
 6632:  *				to which super/subscripts will be added
 6633:  * --------------------------------------------------------------------------
 6634:  * Returns:	( subraster * )	ptr to subraster corresponding to sp
 6635:  *				plus its scripts, or NULL for any error
 6636:  * --------------------------------------------------------------------------
 6637:  * Notes:     o	sp returned unchanged if no super/subscript(s) follow it.
 6638:  * ======================================================================= */
 6639: /* --- entry point --- */
 6640: subraster *rastdispmath ( char **expression, int size, subraster *sp )
 6641: {
 6642: /* -------------------------------------------------------------------------
 6643: Allocations and Declarations
 6644: -------------------------------------------------------------------------- */
 6645: char	*texscripts(),			/* parse expression for scripts */
 6646: 	subscript[512], supscript[512];	/* scripts parsed from expression */
 6647: int	issub=0, issup=0;		/* true if we have sub,sup */
 6648: subraster *rasterize(), *subsp=NULL, *supsp=NULL, /* rasterize scripts */
 6649: 	*rastack(),			/* stack operator with scripts */
 6650: 	*new_subraster();		/* for dummy base sp, if needed */
 6651: int	vspace = 1;			/* vertical space between scripts */
 6652: /* -------------------------------------------------------------------------
 6653: Obtain subscript and/or superscript expressions, and rasterize them/it
 6654: -------------------------------------------------------------------------- */
 6655: /* --- parse for sub,superscript(s), and bump expression past it(them) --- */
 6656: if ( expression == NULL ) goto end_of_job; /* no *ptr given */
 6657: if ( *expression == NULL ) goto end_of_job; /* no expression given */
 6658: if ( *(*expression) == '\000' ) goto end_of_job; /* nothing in expression */
 6659: *expression = texscripts(*expression,subscript,supscript,3);
 6660: /* --- rasterize scripts --- */
 6661: if ( *subscript != '\000' )		/* have a subscript */
 6662:   subsp = rasterize(subscript,size-1);	/* so rasterize it at size-1 */
 6663: if ( *supscript != '\000' )		/* have a superscript */
 6664:   supsp = rasterize(supscript,size-1);	/* so rasterize it at size-1 */
 6665: /* --- set flags for convenience --- */
 6666: issub  = (subsp != (subraster *)NULL);	/* true if we have subscript */
 6667: issup  = (supsp != (subraster *)NULL);	/* true if we have superscript */
 6668: if (!issub && !issup) goto end_of_job;	/*return operator alone if neither*/
 6669: /* -------------------------------------------------------------------------
 6670: stack operator and its script(s)
 6671: -------------------------------------------------------------------------- */
 6672: /* --- stack superscript atop operator --- */
 6673: if ( issup ) {				/* we have a superscript */
 6674:  if ( sp == NULL )			/* but no base expression */
 6675:   sp = supsp;				/* so just use superscript */
 6676:  else					/* have base and superscript */
 6677:   if ( (sp=rastack(sp,supsp,1,vspace,1,3)) /* stack supsp atop base sp */
 6678:   ==   NULL ) goto end_of_job; }	/* and quit if failed */
 6679: /* --- stack operator+superscript atop subscript --- */
 6680: if ( issub ) {				/* we have a subscript */
 6681:  if ( sp == NULL )			/* but no base expression */
 6682:   sp = subsp;				/* so just use subscript */
 6683:  else					/* have base and subscript */
 6684:   if ( (sp=rastack(subsp,sp,2,vspace,1,3)) /* stack sp atop base subsp */
 6685:   ==   NULL ) goto end_of_job; }	/* and quit if failed */
 6686: sp->type = IMAGERASTER;			/* flip type of composite object */
 6687: sp->size = size;			/* and set font size */
 6688: /* -------------------------------------------------------------------------
 6689: free unneeded component subrasters and return final result to caller
 6690: -------------------------------------------------------------------------- */
 6691: end_of_job:
 6692:   return ( sp );
 6693: } /* --- end-of-function rastdispmath() --- */
 6694: 
 6695: 
 6696: /* ==========================================================================
 6697:  * Function:	rastleft ( expression, size, basesp, ildelim, arg2, arg3 )
 6698:  * Purpose:	\left...\right handler, returns a subraster corresponding to
 6699:  *		delimited subexpression at font size
 6700:  * --------------------------------------------------------------------------
 6701:  * Arguments:	expression (I)	char **  to first char of null-terminated
 6702:  *				string beginning with a \left
 6703:  *				to be rasterized
 6704:  *		size (I)	int containing 0-5 default font size
 6705:  *		basesp (I)	subraster *  to character (or subexpression)
 6706:  *				immediately preceding leading left{
 6707:  *				(unused, but passed for consistency)
 6708:  *		ildelim (I)	int containing ldelims[] index of
 6709:  *				left delimiter
 6710:  *		arg2 (I)	int unused
 6711:  *		arg3 (I)	int unused
 6712:  * --------------------------------------------------------------------------
 6713:  * Returns:	( subraster * )	ptr to subraster corresponding to subexpr,
 6714:  *				or NULL for any parsing error
 6715:  * --------------------------------------------------------------------------
 6716:  * Notes:     o
 6717:  * ======================================================================= */
 6718: /* --- entry point --- */
 6719: subraster *rastleft ( char **expression, int size, subraster *basesp,
 6720: 			int ildelim, int arg2, int arg3 )
 6721: {
 6722: /* -------------------------------------------------------------------------
 6723: Allocations and Declarations
 6724: -------------------------------------------------------------------------- */
 6725: subraster *rasterize(), *sp=NULL;	/*rasterize between \left...\right*/
 6726: subraster *get_delim(), *lp=NULL, *rp=NULL; /* left and right delim chars */
 6727: subraster *rastlimits();		/*handle sub/super scripts on lp,rp*/
 6728: subraster *rastcat();			/* concat lp||sp||rp subrasters */
 6729: int	family=CMSYEX,			/* get_delim() family */
 6730: 	height=0, rheight=0,		/* subexpr, right delim height */
 6731: 	margin=(size+1),		/* delim height margin over subexpr*/
 6732: 	opmargin=(5);			/* extra margin for \int,\sum,\etc */
 6733: char	/* *texleft(),*/ subexpr[MAXSUBXSZ+1];/*chars between \left...\right*/
 6734: char	*texchar(),			/* get delims after \left,\right */
 6735: 	ldelim[256]=".", rdelim[256]="."; /* delims following \left,\right */
 6736: char	*strtexchr(), *pleft, *pright;	/*locate \right matching our \left*/
 6737: int	isleftdot=0, isrightdot=0;	/* true if \left. or \right. */
 6738: int	isleftscript=0, isrightscript=0; /* true if delims are scripted */
 6739: int	sublen=0;			/* strlen(subexpr) */
 6740: int	idelim=0;			/* 1=left,2=right */
 6741: /* int	gotldelim = 0; */		/* true if ildelim given by caller */
 6742: int	delete_subraster();		/* free subraster if rastleft fails*/
 6743: int	wasdisplaystyle = isdisplaystyle; /* save current displaystyle */
 6744: int	istextleft=0, istextright=0;	/* true for non-displaystyle delims*/
 6745: /* --- recognized delimiters --- */
 6746: static	char left[16]="\\left", right[16]="\\right"; /* tex delimiters */
 6747: static	char *ldelims[] = {
 6748:    "unused", ".",			/* 1   for \left., \right. */
 6749: 	"(", ")",			/* 2,3 for \left(, \right) */
 6750: 	"\\{","\\}",			/* 4,5 for \left\{, \right\} */
 6751: 	"[", "]",			/* 6,7 for \left[, \right] */
 6752: 	"<", ">",			/* 8,9 for \left<, \right> */
 6753: 	"|", "\\|",			/* 10,11 for \left,\right |,\|*/
 6754: 	NULL };
 6755: /* --- recognized operator delimiters --- */
 6756: static	char *opdelims[] = {		/* operator delims from cmex10 */
 6757:      "int",	  "sum",	"prod",
 6758:      "cup",	  "cap",	"dot",
 6759:      "plus",	  "times",	"wedge",
 6760:      "vee",
 6761:      NULL }; /* --- end-of-opdelims[] --- */
 6762: /* --- delimiter xlation --- */
 6763: static	char *xfrom[] =			/* xlate any delim suffix... */
 6764:    { "\\|",				/* \| */
 6765:      "\\{",				/* \{ */
 6766:      "\\}",				/* \} */
 6767:      "\\lbrace",			/* \lbrace */
 6768:      "\\rbrace",			/* \rbrace */
 6769:      "\\langle",			/* \langle */
 6770:      "\\rangle",			/* \rangle */
 6771:      NULL } ; /* --- end-of-xfrom[] --- */
 6772: static	char *xto[] =			/* ...to this instead */
 6773:    { "=",				/* \| to = */
 6774:      "{",				/* \{ to { */
 6775:      "}",				/* \} to } */
 6776:      "{",				/* \lbrace to { */
 6777:      "}",				/* \rbrace to } */
 6778:      "<",				/* \langle to < */
 6779:      ">",				/* \rangle to > */
 6780:      NULL } ; /* --- end-of-xto[] --- */
 6781: /* --- non-displaystyle delimiters --- */
 6782: static	char *textdelims[] =		/* these delims _aren't_ display */
 6783:    { "|", "=",
 6784:      "(", ")",
 6785:      "[", "]",
 6786:      "<", ">",
 6787:      "{", "}",
 6788:      "dbl",				/* \lbrackdbl and \rbrackdbl */
 6789:      NULL } ; /* --- end-of-textdelims[] --- */
 6790: /* -------------------------------------------------------------------------
 6791: initialization
 6792: -------------------------------------------------------------------------- */
 6793: /* --- check args --- */
 6794: if ( *(*expression) == '\000' ) goto end_of_job; /* nothing after \left */
 6795: /* --- determine left delimiter, and set default \right. delimiter --- */
 6796: if ( ildelim!=NOVALUE && ildelim>=1 )	/* called with explicit left delim */
 6797:  { strcpy(ldelim,ldelims[ildelim]);	/* so just get a local copy */
 6798:    /* gotldelim = 1; */ }		/* and set flag that we got it */
 6799: else					/* trapped \left without delim */
 6800:  { skipwhite(*expression);		/* interpret \left ( as \left( */
 6801:    if ( *(*expression) == '\000' )	/* end-of-string after \left */
 6802:       goto end_of_job;			/* so return NULL */
 6803:    *expression = texchar(*expression,ldelim); /*pull delim from expression*/
 6804:    if ( *expression == NULL		/* probably invalid end-of-string */
 6805:    ||   *ldelim == '\000' ) goto end_of_job; } /* no delimiter */
 6806: strcpy(rdelim,".");			/* init default \right. delim */
 6807: /* -------------------------------------------------------------------------
 6808: locate \right balancing our opening \left
 6809: -------------------------------------------------------------------------- */
 6810: /* --- first \right following \left --- */
 6811: if ( (pright=strtexchr(*expression,right)) /* look for \right after \left */
 6812: !=   NULL ) {				/* found it */
 6813:  /* --- find matching \right by pushing past any nested \left's --- */
 6814:  pleft = *expression;			/* start after first \left( */
 6815:  while ( 1 ) {				/*break when matching \right found*/
 6816:   /* -- locate next nested \left if there is one --- */
 6817:   if ( (pleft=strtexchr(pleft,left))	/* find next \left */
 6818:   ==   NULL ) break;			/*no more, so matching \right found*/
 6819:   pleft += strlen(left);		/* push ptr past \left token */
 6820:   if ( pleft >= pright ) break;		/* not nested if \left after \right*/
 6821:   /* --- have nested \left, so push forward to next \right --- */
 6822:   if ( (pright=strtexchr(pright+strlen(right),right)) /* find next \right */
 6823:   ==   NULL ) break;			/* ran out of \right's */
 6824:   } /* --- end-of-while(1) --- */
 6825:  } /* --- end-of-if(pright!=NULL) --- */
 6826: /* -------------------------------------------------------------------------
 6827: push past \left(_a^b sub/superscripts, if present
 6828: -------------------------------------------------------------------------- */
 6829: pleft = *expression;			/*reset pleft after opening \left( */
 6830: if ( (lp=rastlimits(expression,size,lp)) /*dummy call push expression past b*/
 6831: !=   NULL )				/* found actual _a^b scripts, too */
 6832:   { delete_subraster(lp);		/* but we don't need them */
 6833:     lp = NULL; }			/* reset pointer, too */
 6834: /* -------------------------------------------------------------------------
 6835: get \right delimiter and subexpression between \left...\right, xlate delims
 6836: -------------------------------------------------------------------------- */
 6837: /* --- get delimiter following \right --- */
 6838: if ( pright == (char *)NULL ) {		/* assume \right. at end of exprssn*/
 6839:   strcpy(rdelim,".");			/* set default \right. */
 6840:   sublen = strlen(*expression);		/* use entire remaining expression */
 6841:   memcpy(subexpr,*expression,sublen);	/* copy all remaining chars */
 6842:   *expression += sublen; }		/* and push expression to its null */
 6843: else {					/* have explicit matching \right */
 6844:   sublen = (int)(pright-(*expression));	/* #chars between \left...\right */
 6845:   memcpy(subexpr,*expression,sublen);	/* copy chars preceding \right */
 6846:   *expression = pright+strlen(right);	/* push expression past \right */
 6847:   skipwhite(*expression);		/* interpret \right ) as \right) */
 6848:   *expression = texchar(*expression,rdelim); /*pull delim from expression*/
 6849:   if ( *rdelim == '\000' ) strcpy(rdelim,"."); } /* \right. if no rdelim */
 6850: /* --- get subexpression between \left...\right --- */
 6851: if ( sublen < 1 ) goto end_of_job;	/* nothing between delimiters */
 6852: subexpr[sublen] = '\000';		/* and null-terminate it */
 6853: /* --- adjust margin for expressions containing \middle's --- */
 6854: if ( strtexchr(subexpr,"\\middle") != NULL ) /* have enclosed \middle's */
 6855:   margin = 1;				/* so don't "overwhelm" them */
 6856: /* --- check for operator delimiter --- */
 6857: for ( idelim=0; opdelims[idelim]!=NULL; idelim++ )
 6858:   if ( strstr(ldelim,opdelims[idelim]) != NULL ) /* found operator */
 6859:     { margin += opmargin;		/* extra height for operator */
 6860:       if ( *ldelim == '\\' )		/* have leading escape */
 6861: 	strcpy(ldelim,ldelim+1);	/* squeeze it out */
 6862:       break; }				/* no need to check rest of table */
 6863: /* --- xlate delimiters and check for textstyle --- */
 6864: for ( idelim=1; idelim<=2; idelim++ ) {	/* 1=left, 2=right */
 6865:   char	*lrdelim  = (idelim==1? ldelim:rdelim); /* ldelim or rdelim */
 6866:   int	ix;  char *xdelim;		/* xfrom[] and xto[] index, delim */
 6867:   for( ix=0; (xdelim=xfrom[ix]) != NULL; ix++ )
 6868:     if ( strcmp(lrdelim,xdelim) == 0 )	/* found delim to xlate */
 6869:       {	strcpy(lrdelim,xto[ix]);	/* replace with corresponding xto[]*/
 6870: 	break; }			/* no need to check further */
 6871:   for( ix=0; (xdelim=textdelims[ix]) != NULL; ix++ )
 6872:     if ( strstr(lrdelim,xdelim) != 0 )	/* found textstyle delim */
 6873:       {	if ( idelim == 1 )		/* if it's the \left one */
 6874: 	  istextleft = 1;		/* set left textstyle flag */
 6875: 	else istextright = 1;		/* else set right textstyle flag */
 6876: 	break; }			/* no need to check further */
 6877:   } /* --- end-of-for(idelim) --- */
 6878: /* --- debugging --- */
 6879: if ( msgfp!=NULL && msglevel>=99 )
 6880:   fprintf(msgfp,"rastleft> left=\"%s\" right=\"%s\" subexpr=\"%s\"\n",
 6881:   ldelim,rdelim,subexpr);
 6882: /* -------------------------------------------------------------------------
 6883: rasterize subexpression
 6884: -------------------------------------------------------------------------- */
 6885: /* --- rasterize subexpression --- */
 6886: if ( (sp = rasterize(subexpr,size))	/* rasterize chars between delims */
 6887: ==   NULL ) goto end_of_job;		/* quit if failed */
 6888: height = (sp->image)->height;		/* height of subexpr raster */
 6889: rheight = height+margin;		/*default rheight as subexpr height*/
 6890: /* -------------------------------------------------------------------------
 6891: rasterize delimiters, reset baselines, and add  sub/superscripts if present
 6892: -------------------------------------------------------------------------- */
 6893: /* --- check for dot delimiter --- */
 6894: isleftdot  = (strchr(ldelim,'.')!=NULL); /* true if \left. */
 6895: isrightdot = (strchr(rdelim,'.')!=NULL); /* true if \right. */
 6896: /* --- get rasters for best-fit delim characters, add sub/superscripts --- */
 6897: isdisplaystyle = (istextleft?0:9);	/* force \displaystyle */
 6898: if ( !isleftdot )			/* if not \left. */
 6899:  { /* --- first get requested \left delimiter --- */
 6900:    lp = get_delim(ldelim,rheight,family); /* get \left delim char */
 6901:    /* --- reset lp delim baseline to center delim on subexpr raster --- */
 6902:    if ( lp != NULL )			/* if get_delim() succeeded */
 6903:     { int lheight = (lp->image)->height; /* actual height of left delim */
 6904:       lp->baseline = sp->baseline + (lheight - height)/2;
 6905:       if ( lheight > rheight )		/* got bigger delim than requested */
 6906: 	rheight = lheight-1; }		/* make sure right delim matches */
 6907:    /* --- then add on any sub/superscripts attached to \left( --- */
 6908:    lp = rastlimits(&pleft,size,lp);	/*\left(_a^b and push pleft past b*/
 6909:    isleftscript = isscripted; }		/* check if left delim scripted */
 6910: isdisplaystyle = (istextright?0:9);	/* force \displaystyle */
 6911: if ( !isrightdot )			/* and if not \right. */
 6912:  { /* --- first get requested \right delimiter --- */
 6913:    rp = get_delim(rdelim,rheight,family); /* get \right delim char */
 6914:    /* --- reset rp delim baseline to center delim on subexpr raster --- */
 6915:    if ( rp != NULL )			/* if get_delim() succeeded */
 6916:      rp->baseline = sp->baseline + ((rp->image)->height - height)/2;
 6917:    /* --- then add on any sub/superscripts attached to \right) --- */
 6918:    rp = rastlimits(expression,size,rp);	/*\right)_c^d, expression past d*/
 6919:    isrightscript = isscripted; }	/* check if right delim scripted */
 6920: isdisplaystyle = wasdisplaystyle;	/* original \displystyle default */
 6921: /* --- check that we got delimiters --- */
 6922: if ( 0 )
 6923:  if ( (lp==NULL && !isleftdot)		/* check that we got left( */
 6924:  ||   (rp==NULL && !isrightdot) )	/* and right) if needed */
 6925:   { if ( lp != NULL ) free ((void *)lp); /* free \left-delim subraster */
 6926:     if ( rp != NULL ) free ((void *)rp); /* and \right-delim subraster */
 6927:     if (0) { delete_subraster(sp);	/* if failed, free subraster */
 6928:              sp = (subraster *)NULL; }	/* signal error to caller */
 6929:     goto end_of_job; }			/* and quit */
 6930: /* -------------------------------------------------------------------------
 6931: concat  lp || sp || rp  components
 6932: -------------------------------------------------------------------------- */
 6933: /* --- concat lp||sp||rp to obtain final result --- */
 6934: if ( lp != NULL )			/* ignore \left. */
 6935:   sp = rastcat(lp,sp,3);		/* concat lp||sp and free sp,lp */
 6936: if ( sp != NULL )			/* succeeded or ignored \left. */
 6937:   if ( rp != NULL )			/* ignore \right. */
 6938:     sp = rastcat(sp,rp,3);		/* concat sp||rp and free sp,rp */
 6939: /* --- back to caller --- */
 6940: end_of_job:
 6941:   isdelimscript = isrightscript;	/* signal if right delim scripted */
 6942:   return ( sp );
 6943: } /* --- end-of-function rastleft() --- */
 6944: 
 6945: 
 6946: /* ==========================================================================
 6947:  * Function:	rastright ( expression, size, basesp, ildelim, arg2, arg3 )
 6948:  * Purpose:	...\right handler, intercepts an unexpected/unbalanced \right
 6949:  * --------------------------------------------------------------------------
 6950:  * Arguments:	expression (I)	char **  to first char of null-terminated
 6951:  *				string beginning with a \right
 6952:  *				to be rasterized
 6953:  *		size (I)	int containing 0-5 default font size
 6954:  *		basesp (I)	subraster *  to character (or subexpression)
 6955:  *				immediately preceding leading left{
 6956:  *				(unused, but passed for consistency)
 6957:  *		ildelim (I)	int containing rdelims[] index of
 6958:  *				right delimiter
 6959:  *		arg2 (I)	int unused
 6960:  *		arg3 (I)	int unused
 6961:  * --------------------------------------------------------------------------
 6962:  * Returns:	( subraster * )	ptr to subraster corresponding to subexpr,
 6963:  *				or NULL for any parsing error
 6964:  * --------------------------------------------------------------------------
 6965:  * Notes:     o
 6966:  * ======================================================================= */
 6967: /* --- entry point --- */
 6968: subraster *rastright ( char **expression, int size, subraster *basesp,
 6969: 			int ildelim, int arg2, int arg3 )
 6970: {
 6971: /* -------------------------------------------------------------------------
 6972: Allocations and Declarations
 6973: -------------------------------------------------------------------------- */
 6974: subraster /* *rasterize(),*/ *sp=NULL;	/*rasterize \right subexpr's*/
 6975:   if ( sp != NULL )			/* returning entire expression */
 6976:     {
 6977:       isreplaceleft = 1;		/* set flag to replace left half*/
 6978:     }
 6979: return ( sp );
 6980: } /* --- end-of-function rastright() --- */
 6981: 
 6982: 
 6983: /* ==========================================================================
 6984:  * Function:	rastmiddle ( expression, size, basesp,  arg1, arg2, arg3 )
 6985:  * Purpose:	\middle handler, returns subraster corresponding to
 6986:  *		entire expression with \middle delimiter(s) sized to fit.
 6987:  * --------------------------------------------------------------------------
 6988:  * Arguments:	expression (I/O) char **  to first char of null-terminated
 6989:  *				string immediately following \middle to be
 6990:  *				rasterized, and returning ptr immediately
 6991:  *				to terminating null.
 6992:  *		size (I)	int containing 0-5 default font size
 6993:  *		basesp (I)	subraster *  to character (or subexpression)
 6994:  *				immediately preceding \middle
 6995:  *				(unused, but passed for consistency)
 6996:  *		arg1 (I)	int unused
 6997:  *		arg2 (I)	int unused
 6998:  *		arg3 (I)	int unused
 6999:  * --------------------------------------------------------------------------
 7000:  * Returns:	( subraster * )	ptr to subraster corresponding to expression,
 7001:  *				or NULL for any parsing error
 7002:  *				(expression ptr unchanged if error occurs)
 7003:  * --------------------------------------------------------------------------
 7004:  * Notes:     o
 7005:  * ======================================================================= */
 7006: /* --- entry point --- */
 7007: subraster *rastmiddle ( char **expression, int size, subraster *basesp,
 7008: 			int arg1, int arg2, int arg3 )
 7009: {
 7010: /* -------------------------------------------------------------------------
 7011: Allocations and Declarations
 7012: -------------------------------------------------------------------------- */
 7013: subraster *rasterize(), *sp=NULL, *subsp[32]; /*rasterize \middle subexpr's*/
 7014: char	*exprptr = *expression,		/* local copy of ptr to expression */
 7015: 	*texchar(), delim[32][132],	/* delimiters following \middle's */
 7016: 	*strtexchr(),			/* locate \middle's */
 7017: 	subexpr[MAXSUBXSZ+1], *subptr=NULL;/*subexpression between \middle's*/
 7018: int	height=0, habove=0, hbelow=0;	/* height, above & below baseline */
 7019: int	idelim, ndelims=0,		/* \middle count (max 32) */
 7020: 	family = CMSYEX;		/* delims from CMSY10 or CMEX10 */
 7021: subraster *subrastcpy(),		/* copy subraster */
 7022: 	*rastcat(),			/* concatanate subraster */
 7023: 	*get_delim();			/* get rasterized delimiter */
 7024: int	delete_subraster();		/* free work area subsp[]'s at eoj */
 7025: /* -------------------------------------------------------------------------
 7026: initialization
 7027: -------------------------------------------------------------------------- */
 7028: subsp[0] = leftexpression;		/* expressn preceding 1st \middle */
 7029: subsp[1] = NULL;			/* set first null */
 7030: /* -------------------------------------------------------------------------
 7031: accumulate subrasters between consecutive \middle\delim...\middle\delim...'s
 7032: -------------------------------------------------------------------------- */
 7033: while ( ndelims < 30 )			/* max of 31 \middle's */
 7034:   {
 7035:   /* --- maintain max height above,below baseline --- */
 7036:   if ( subsp[ndelims] != NULL )		/*exprssn preceding current \middle*/
 7037:    { int baseline = (subsp[ndelims])->baseline;  /* #rows above baseline */
 7038:      height = ((subsp[ndelims])->image)->height; /* tot #rows (height) */
 7039:      habove = max2(habove,baseline);	/* max #rows above baseline */
 7040:      hbelow = max2(hbelow,height-baseline); } /* max #rows below baseline */
 7041:   /* --- get delimter after \middle --- */
 7042:   skipwhite(exprptr);			/*skip space betwn \middle & \delim*/
 7043:   exprptr = texchar(exprptr,delim[ndelims]); /* \delim after \middle */
 7044:   if ( *(delim[ndelims]) == '\000' )	/* \middle at end-of-expression */
 7045:     break;				/* ignore it and consider job done */
 7046:   ndelims++;				/* count another \middle\delim */
 7047:   /* --- get subexpression between \delim and next \middle --- */
 7048:   subsp[ndelims] = NULL;		/* no subexpresion yet */
 7049:   if ( *exprptr == '\000' )		/* end-of-expression after \delim */
 7050:     break;				/* so we have all subexpressions */
 7051:   if ( (subptr = strtexchr(exprptr,"\\middle")) /* find next \middle */
 7052:   ==   NULL )				/* no more \middle's */
 7053:    { strncpy(subexpr,exprptr,MAXSUBXSZ); /*get entire remaining expression*/
 7054:      subexpr[MAXSUBXSZ] = '\000';	/* make sure it's null-terminated */
 7055:      exprptr += strlen(exprptr); }	/* push exprptr to terminating '\0'*/
 7056:   else					/* have another \middle */
 7057:    { int sublen = (int)(subptr-exprptr); /* #chars between \delim...\middle*/
 7058:      memcpy(subexpr,exprptr,min2(sublen,MAXSUBXSZ)); /* get subexpression */
 7059:      subexpr[min2(sublen,MAXSUBXSZ)] = '\000'; /* and null-terminate it */
 7060:      exprptr += (sublen+strlen("\\middle")); } /* push exprptr past \middle*/
 7061:   /* --- rasterize subexpression --- */
 7062:   subsp[ndelims] = rasterize(subexpr,size); /* rasterize subexpresion */
 7063:   } /* --- end-of-while(1) --- */
 7064: /* -------------------------------------------------------------------------
 7065: construct \middle\delim's and concatanate them between subexpressions
 7066: -------------------------------------------------------------------------- */
 7067: if ( ndelims < 1			/* no delims */
 7068: ||   (height=habove+hbelow) < 1 )	/* or no subexpressions? */
 7069:   goto end_of_job;			/* just flush \middle directive */
 7070: for ( idelim=0; idelim<=ndelims; idelim++ )
 7071:   {
 7072:   /* --- first add on subexpression preceding delim --- */
 7073:   if ( subsp[idelim] != NULL ) {	/* have subexpr preceding delim */
 7074:     if ( sp == NULL )			/* this is first piece */
 7075:      { sp = subsp[idelim];		/* so just use it */
 7076:        if ( idelim == 0 ) sp = subrastcpy(sp); } /* or copy leftexpression */
 7077:     else sp = rastcat(sp,subsp[idelim],(idelim>0?3:1)); } /* or concat it */
 7078:   /* --- now construct delimiter --- */
 7079:   if ( *(delim[idelim]) != '\000' )	/* have delimter */
 7080:    { subraster *delimsp = get_delim(delim[idelim],height,family);
 7081:      if ( delimsp != NULL )		/* rasterized delim */
 7082:       {	delimsp->baseline = habove;	/* set baseline */
 7083: 	if ( sp == NULL )		/* this is first piece */
 7084: 	  sp = delimsp;			/* so just use it */
 7085: 	else sp = rastcat(sp,delimsp,3); } } /*or concat to existing pieces*/
 7086:   } /* --- end-of-for(idelim) --- */
 7087: /* --- back to caller --- */
 7088: end_of_job:
 7089:   if ( 0 ) /* now handled above */
 7090:     for ( idelim=1; idelim<=ndelims; idelim++ ) /* free subsp[]'s (not 0) */
 7091:      if ( subsp[idelim] != NULL )	/* have allocated subraster */
 7092:       delete_subraster(subsp[idelim]);	/* so free it */
 7093:   if ( sp != NULL )			/* returning entire expression */
 7094:     { int newht = (sp->image)->height;	/* height of returned subraster */
 7095:       sp->baseline = min2(newht-1,newht/2+5); /* guess new baseline */
 7096:       isreplaceleft = 1;		/* set flag to replace left half*/
 7097:       *expression += strlen(*expression); } /* and push to terminating null*/
 7098:   return ( sp );
 7099: } /* --- end-of-function rastmiddle() --- */
 7100: 
 7101: 
 7102: /* ==========================================================================
 7103:  * Function:	rastflags ( expression, size, basesp,  flag, value, arg3 )
 7104:  * Purpose:	sets an internal flag, e.g., for \rm, or sets an internal
 7105:  *		value, e.g., for \unitlength=<value>, and returns NULL
 7106:  *		so nothing is displayed
 7107:  * --------------------------------------------------------------------------
 7108:  * Arguments:	expression (I)	char **  to first char of null-terminated
 7109:  *				LaTeX expression (unused/unchanged)
 7110:  *		size (I)	int containing base font size (not used,
 7111:  *				just stored in subraster)
 7112:  *		basesp (I)	subraster *  to character (or subexpression)
 7113:  *				immediately preceding "flags" directive
 7114:  *				(unused but passed for consistency)
 7115:  *		flag (I)	int containing #define'd symbol specifying
 7116:  *				internal flag to be set
 7117:  *		value (I)	int containing new value of flag
 7118:  *		arg3 (I)	int unused
 7119:  * --------------------------------------------------------------------------
 7120:  * Returns:	( subraster * )	NULL so nothing is displayed
 7121:  * --------------------------------------------------------------------------
 7122:  * Notes:     o
 7123:  * ======================================================================= */
 7124: /* --- entry point --- */
 7125: subraster *rastflags ( char **expression, int size, subraster *basesp,
 7126: 			int flag, int value, int arg3 )
 7127: {
 7128: /* -------------------------------------------------------------------------
 7129: Allocations and Declarations
 7130: -------------------------------------------------------------------------- */
 7131: char	*texsubexpr(),			/* parse expression for... */
 7132: 	valuearg[1024]="NOVALUE";	/* value from expression, if needed */
 7133: int	argvalue=NOVALUE,		/* atoi(valuearg) */
 7134: 	isdelta=0,			/* true if + or - precedes valuearg */
 7135: 	valuelen=0;			/* strlen(valuearg) */
 7136: double	dblvalue=(-99.), strtod();	/*convert ascii {valuearg} to double*/
 7137: static	int displaystylelevel = (-99);	/* \displaystyle set at recurlevel */
 7138: /* -------------------------------------------------------------------------
 7139: set flag or value
 7140: -------------------------------------------------------------------------- */
 7141: switch ( flag )
 7142:   {
 7143:   default: break;			/* unrecognized flag */
 7144:   case ISFONTFAM:
 7145:     if ( isthischar((*(*expression)),WHITEMATH) ) /* \rm followed by white */
 7146:       (*expression)++;			/* skip leading ~ after \rm */
 7147:     fontnum = value;			/* set font family */
 7148:     break;
 7149:   case ISSTRING: isstring=value; break;	/* set string/image mode */
 7150:   case ISDISPLAYSTYLE:			/* set \displaystyle mode */
 7151:     displaystylelevel = recurlevel;	/* \displaystyle set at recurlevel */
 7152:     isdisplaystyle=value; break;
 7153:   case ISOPAQUE:  istransparent=value; break; /* set transparent/opaque */
 7154:   case ISREVERSE:			/* reverse video */
 7155:     if ( value==1 || value==NOVALUE )
 7156:       {	fgred=255-fgred; fggreen=255-fggreen; fgblue=255-fgblue; }
 7157:     if ( value==2 || value==NOVALUE )
 7158:       {	bgred=255-bgred; bggreen=255-bggreen; bgblue=255-bgblue; }
 7159:     if ( value==2 || value==NOVALUE )
 7160:       isblackonwhite = !isblackonwhite;
 7161:     if ( gammacorrection > 0.0001 )	/* have gamma correction */
 7162:       gammacorrection = REVERSEGAMMA;	/* use reverse video gamma instead */
 7163:     break;
 7164:   case ISSUPER:				/* set supersampling/lowpass flag */
 7165:     #ifndef SSFONTS			/* don't have ss fonts loaded */
 7166:       value = 0;			/* so force lowpass */
 7167:     #endif
 7168:     isss = issupersampling = value;
 7169:     fonttable = (issupersampling?ssfonttable:aafonttable); /* set fonts */
 7170:     break;
 7171:   case ISFONTSIZE:			/* set fontsize */
 7172:   case ISDISPLAYSIZE:			/* set displaysize */
 7173:   case ISCONTENTTYPE:			/*enable/disable content-type lines*/
 7174:   case ISSHRINK:			/* set shrinkfactor */
 7175:   case ISAAALGORITHM:			/* set anti-aliasing algorithm */
 7176:   case ISWEIGHT:			/* set font weight */
 7177:   case ISCENTERWT:			/* set lowpass center pixel weight */
 7178:   case ISADJACENTWT:			/* set lowpass adjacent weight */
 7179:   case ISCORNERWT:			/* set lowpass corner weight */
 7180:   case ISCOLOR:				/* set red(1),green(2),blue(3) */
 7181:   case ISSMASH:				/* set (minimum) "smash" margin */
 7182:   case ISGAMMA:				/* set gamma correction */
 7183:     if ( value != NOVALUE )		/* passed a fixed value to be set */
 7184:       {	argvalue = value;		/* set given fixed int value */
 7185: 	dblvalue = (double)value; }	/* or maybe interpreted as double */
 7186:     else				/* get value from expression */
 7187:       {	*expression = texsubexpr(*expression,valuearg,1023,"{","}",0,0);
 7188: 	if ( *valuearg != '\000' )	/* guard against empty string */
 7189: 	 if ( !isalpha(*valuearg) )	/* and against alpha string args */
 7190: 	  if ( !isthischar(*valuearg,"?") ) /*leading ? is query for value*/
 7191: 	   { isdelta = isthischar(*valuearg,"+-"); /* leading + or - */
 7192: 	     if ( memcmp(valuearg,"--",2) == 0 ) /* leading -- signals...*/
 7193: 	       { isdelta=0; strcpy(valuearg,valuearg+1); } /* ...not delta */
 7194: 	     switch ( flag ) {		/* convert to double or int */
 7195: 	      default: argvalue = atoi(valuearg); break; /* convert to int */
 7196: 	      case ISGAMMA:
 7197: 		dblvalue = strtod(valuearg,NULL); break; } /* or to double */
 7198: 	   } /* --- end-of-if(*valuearg!='?') --- */
 7199:       } /* --- end-of-if(value==NOVALUE) --- */
 7200:     switch ( flag )
 7201:       {
 7202:       default: break;
 7203:       case ISCOLOR:			/* set color */
 7204: 	slower(valuearg);		/* convert arg to lower case */
 7205: 	if ( argvalue==1 || strstr(valuearg,"red") )
 7206: 	  { fggreen = fgblue = (isblackonwhite?0:255);
 7207: 	    fgred = (isblackonwhite?255:0); }
 7208: 	if ( argvalue==2 || strstr(valuearg,"green") )
 7209: 	  { fgred = fgblue = (isblackonwhite?0:255);
 7210: 	    fggreen = (isblackonwhite?255:0); }
 7211: 	if ( argvalue==3 || strstr(valuearg,"blue") )
 7212: 	  { fgred = fggreen = (isblackonwhite?0:255);
 7213: 	    fgblue = (isblackonwhite?255:0); }
 7214: 	if ( argvalue==0 || strstr(valuearg,"black") )
 7215: 	    fgred = fggreen = fgblue = (isblackonwhite?0:255);
 7216: 	if ( argvalue==7 || strstr(valuearg,"white") )
 7217: 	    fgred = fggreen = fgblue = (isblackonwhite?255:0);
 7218: 	break;
 7219:       case ISFONTSIZE:			/* set fontsize */
 7220: 	if ( argvalue != NOVALUE )	/* got a value */
 7221: 	  { int largestsize = (issupersampling?16:LARGESTSIZE);
 7222: 	    fontsize = (isdelta? fontsize+argvalue : argvalue);
 7223: 	    fontsize = max2(0,min2(fontsize,largestsize));
 7224: 	    shrinkfactor = shrinkfactors[fontsize];
 7225: 	    if ( isdisplaystyle == 1	/* displaystyle enabled but not set*/
 7226: 	    ||  (1 && isdisplaystyle==2) /* displaystyle enabled and set */
 7227: 	    ||  (0 && isdisplaystyle==0) )/*\textstyle disabled displaystyle*/
 7228: 	     if ( displaystylelevel != recurlevel ) /*respect \displaystyle*/
 7229: 	      if ( !ispreambledollars )	{ /* respect $$...$$'s */
 7230: 	       if ( fontsize >= displaysize )
 7231: 		isdisplaystyle = 2;	/* forced */
 7232: 	       else isdisplaystyle = 1; }
 7233: 	    /*displaystylelevel = (-99);*/ } /* reset \displaystyle level */
 7234: 	else				/* embed font size in expression */
 7235: 	  { sprintf(valuearg,"%d",fontsize); /* convert size */
 7236: 	    valuelen = strlen(valuearg); /* ought to be 1 */
 7237: 	    if ( *expression != '\000' ) /* ill-formed expression */
 7238: 	     { *expression = (char *)(*expression-valuelen); /*back up buff*/
 7239: 	       memcpy(*expression,valuearg,valuelen); } } /*and put in size*/
 7240: 	break;
 7241:       case ISDISPLAYSIZE:		/* set displaysize */
 7242: 	if ( argvalue != NOVALUE )	/* got a value */
 7243: 	    displaysize = (isdelta? displaysize+argvalue : argvalue);
 7244: 	break;
 7245:       case ISCONTENTTYPE:		/*enable/disable content-type lines*/
 7246: 	if ( argvalue != NOVALUE )	/* got a value */
 7247: 	    isemitcontenttype = (argvalue>0?1:0);
 7248: 	break;
 7249:       case ISSMASH:			/* set (minimum) "smash" margin */
 7250: 	if ( argvalue != NOVALUE )	/* got a value */
 7251: 	  { smashmargin = argvalue;	/* set value */
 7252: 	    if ( arg3 != NOVALUE ) isdelta=arg3; /* hard-coded isdelta */
 7253: 	    issmashdelta = (isdelta?1:0); } /* and set delta flag */
 7254: 	smashmargin = max2((isdelta?-5:0),min2(smashmargin,32)); /*sanity*/
 7255: 	isexplicitsmash = 1;		/* signal explicit \smash directive*/
 7256: 	break;
 7257:       case ISSHRINK:			/* set shrinkfactor */
 7258: 	if ( argvalue != NOVALUE )	/* got a value */
 7259: 	  shrinkfactor = (isdelta? shrinkfactor+argvalue : argvalue);
 7260: 	shrinkfactor = max2(1,min2(shrinkfactor,27)); /* sanity check */
 7261: 	break;
 7262:       case ISAAALGORITHM:		/* set anti-aliasing algorithm */
 7263: 	if ( argvalue != NOVALUE ) {	/* got a value */
 7264: 	  if ( argvalue >= 0 ) {	/* non-negative to set algorithm */
 7265: 	      aaalgorithm = argvalue;	/* set algorithm number */
 7266: 	    aaalgorithm = max2(0,min2(aaalgorithm,4)); } /* bounds check */
 7267: 	  else maxfollow = abs(argvalue); } /* or maxfollow=abs(negative#) */
 7268: 	break;
 7269:       case ISWEIGHT:			/* set font weight number */
 7270: 	value =	(argvalue==NOVALUE? NOVALUE : /* don't have a value */
 7271: 		(isdelta? weightnum+argvalue : argvalue));
 7272: 	if ( value>=0 && value<maxaaparams ) /* in range */
 7273: 	  { weightnum   = value;	/* reset weightnum index */
 7274: 	    minadjacent = aaparams[weightnum].minadjacent;
 7275: 	    maxadjacent = aaparams[weightnum].maxadjacent;
 7276: 	    cornerwt    = aaparams[weightnum].cornerwt;
 7277: 	    adjacentwt  = aaparams[weightnum].adjacentwt;
 7278: 	    centerwt    = aaparams[weightnum].centerwt;
 7279: 	    fgalias     = aaparams[weightnum].fgalias;
 7280: 	    fgonly      = aaparams[weightnum].fgonly;
 7281: 	    bgalias     = aaparams[weightnum].bgalias;
 7282: 	    bgonly      = aaparams[weightnum].bgonly; }
 7283: 	break;
 7284:       case ISCENTERWT:			/* set lowpass center pixel weight */
 7285: 	if ( argvalue != NOVALUE )	/* got a value */
 7286: 	  centerwt = argvalue;		/* set lowpass center weight */
 7287: 	break;
 7288:       case ISADJACENTWT:		/* set lowpass adjacent weight */
 7289: 	if ( argvalue != NOVALUE )	/* got a value */
 7290: 	  adjacentwt = argvalue;	/* set lowpass adjacent weight */
 7291: 	break;
 7292:       case ISCORNERWT:			/* set lowpass corner weight */
 7293: 	if ( argvalue != NOVALUE )	/* got a value */
 7294: 	  cornerwt = argvalue;		/* set lowpass corner weight */
 7295: 	break;
 7296:       case ISGAMMA:			/* set gamma correction */
 7297: 	if ( dblvalue >= 0.0 )		/* got a value */
 7298: 	  gammacorrection = dblvalue;	/* set gamma correction */
 7299: 	break;
 7300:       } /* --- end-of-switch() --- */
 7301:     break;
 7302:   case PNMPARAMS:			/*set fgalias,fgonly,bgalias,bgonly*/
 7303:     *expression = texsubexpr(*expression,valuearg,1023,"{","}",0,0);
 7304:     valuelen = strlen(valuearg);	/* ought to be 1-4 */
 7305:     if ( valuelen>0 && isthischar(toupper(valuearg[0]),"TY1") ) fgalias=1;
 7306:     if ( valuelen>0 && isthischar(toupper(valuearg[0]),"FN0") ) fgalias=0;
 7307:     if ( valuelen>1 && isthischar(toupper(valuearg[1]),"TY1") ) fgonly =1;
 7308:     if ( valuelen>1 && isthischar(toupper(valuearg[1]),"FN0") ) fgonly =0;
 7309:     if ( valuelen>2 && isthischar(toupper(valuearg[2]),"TY1") ) bgalias=1;
 7310:     if ( valuelen>2 && isthischar(toupper(valuearg[2]),"FN0") ) bgalias=0;
 7311:     if ( valuelen>3 && isthischar(toupper(valuearg[3]),"TY1") ) bgonly =1;
 7312:     if ( valuelen>3 && isthischar(toupper(valuearg[3]),"FN0") ) bgonly =0;
 7313:     break;
 7314:   case UNITLENGTH:
 7315:     if ( value != NOVALUE )		/* passed a fixed value to be set */
 7316: 	unitlength = (double)(value);	/* set given fixed value */
 7317:     else				/* get value from expression */
 7318:       {	*expression = texsubexpr(*expression,valuearg,1023,"{","}",0,0);
 7319: 	if ( *valuearg != '\000' )	/* guard against empty string */
 7320: 	  unitlength = strtod(valuearg,NULL); } /* convert to double */
 7321:     break;
 7322:   } /* --- end-of-switch(flag) --- */
 7323: return ( NULL );			/*just set value, nothing to display*/
 7324: } /* --- end-of-function rastflags() --- */
 7325: 
 7326: 
 7327: /* ==========================================================================
 7328:  * Function:	rastspace(expression, size, basesp,  width, isfill, isheight)
 7329:  * Purpose:	returns a blank/space subraster width wide,
 7330:  *		with baseline and height corresponding to basep
 7331:  * --------------------------------------------------------------------------
 7332:  * Arguments:	expression (I)	char **  to first char of null-terminated
 7333:  *				LaTeX expression (unused/unchanged)
 7334:  *		size (I)	int containing base font size (not used,
 7335:  *				just stored in subraster)
 7336:  *		basesp (I)	subraster *  to character (or subexpression)
 7337:  *				immediately preceding space, whose baseline
 7338:  *				and height params are transferred to space
 7339:  *		width (I)	int containing #bits/pixels for space width
 7340:  *		isfill (I)	int containing true to \hfill complete
 7341:  *				expression out to width
 7342:  *				(Kludge: isfill=99 signals \hspace*
 7343:  *				for negative space)
 7344:  *		isheight (I)	int containing true (but not NOVALUE)
 7345:  *				to treat width arg as height
 7346:  * --------------------------------------------------------------------------
 7347:  * Returns:	( subraster * )	ptr to empty/blank subraster
 7348:  *				or NULL for any error
 7349:  * --------------------------------------------------------------------------
 7350:  * Notes:     o
 7351:  * ======================================================================= */
 7352: /* --- entry point --- */
 7353: subraster *rastspace ( char **expression, int size, subraster *basesp,
 7354: 			int width, int isfill, int isheight )
 7355: {
 7356: /* -------------------------------------------------------------------------
 7357: Allocations and Declarations
 7358: -------------------------------------------------------------------------- */
 7359: subraster *new_subraster(), *spacesp=NULL; /* subraster for space */
 7360: raster	*bp=NULL, *backspace_raster();	/* for negative space */
 7361: int	delete_subraster();		/* if fail, free unneeded subraster*/
 7362: int	baseht=1, baseln=0;		/* height,baseline of base symbol */
 7363: int	pixsz = 1;			/*default #bits per pixel, 1=bitmap*/
 7364: int	isstar=0, minspace=0;		/* defaults for negative hspace */
 7365: char	*texsubexpr(), widtharg[256];	/* parse for optional {width} */
 7366: subraster *rasterize(), *rightsp=NULL;	/*rasterize right half of expression*/
 7367: subraster *rastcat();			/* cat rightsp after \hfill */
 7368: /* -------------------------------------------------------------------------
 7369: initialization
 7370: -------------------------------------------------------------------------- */
 7371: if ( isfill > 1 ) { isstar=1; isfill=0; } /* large fill signals \hspace* */
 7372: if ( isfill == NOVALUE ) isfill=0;	/* novalue means false */
 7373: if ( isheight == NOVALUE ) isheight=0;	/* novalue means false */
 7374: minspace = (isstar?(-1):0);		/* reset default minspace */
 7375: /* -------------------------------------------------------------------------
 7376: determine width if not given (e.g., \hspace{width}, \hfill{width})
 7377: -------------------------------------------------------------------------- */
 7378: if ( width == 0 ) {			/* width specified in expression */
 7379:   double dwidth;  int widthval;		/* test {width} before using it */
 7380:   int minwidth = (isfill||isheight?1:-600); /* \hspace allows negative */
 7381:   /* --- check if optional [minspace] given for negative \hspace --- */
 7382:   if ( *(*expression) == '[' ) {	/* [minspace] if leading char is [ */
 7383:     /* ---parse [minspace], bump expression past it, interpret as double--- */
 7384:     *expression = texsubexpr(*expression,widtharg,127,"[","]",0,0);
 7385:     if ( *widtharg != '\000' )		/* got [minspace] */
 7386:       minspace = iround(unitlength*strtod(widtharg,NULL)); /* in pixels */
 7387:     } /* --- end-of-if(*(*expression)=='[') --- */
 7388:   width = 1;				/* set default width */
 7389:   *expression = texsubexpr(*expression,widtharg,255,"{","}",0,0);
 7390:   dwidth = unitlength*strtod(widtharg,NULL); /* scaled width value */
 7391:   widthval =				/* convert {width} to integer */
 7392: 		(int)( dwidth + (dwidth>=0.0?0.5:(-0.5)) );
 7393:   if ( widthval>=minwidth && widthval<=600 ) /* sanity check */
 7394:     width = widthval;			/* replace deafault width */
 7395:   } /* --- end-of-if(width==0) --- */
 7396: /* -------------------------------------------------------------------------
 7397: first check for negative space
 7398: -------------------------------------------------------------------------- */
 7399: if ( width < 0 ) {			/* have negative hspace */
 7400:  if ( leftexpression != (subraster *)NULL ) /* can't backspace */
 7401:   if ( (spacesp=new_subraster(0,0,0))	/* get new subraster for backspace */
 7402:   !=   NULL ) {				/* and if we succeed... */
 7403:    int nback=(-width), pback;		/*#pixels wanted,actually backspaced*/
 7404:    if ( (bp=backspace_raster(leftexpression->image,nback,&pback,minspace,0))
 7405:    !=    NULL ) {			/* and if backspace succeeds... */
 7406:      spacesp->image = bp;		/* save backspaced image */
 7407:      /*spacesp->type = leftexpression->type;*/ /* copy original type */
 7408:      spacesp->type = blanksignal;	/* need to propagate blanks */
 7409:      spacesp->size = leftexpression->size; /* copy original font size */
 7410:      spacesp->baseline = leftexpression->baseline; /* and baseline */
 7411:      blanksymspace += -(nback-pback);	/* wanted more than we got */
 7412:      isreplaceleft = 1; }		/*signal to replace entire expressn*/
 7413:    else {				/* backspace failed */
 7414:      delete_subraster(spacesp);		/* free unneeded envelope */
 7415:      spacesp = (subraster *)NULL; } }	/* and signal failure */
 7416:  goto end_of_job;
 7417:  } /* --- end-of-if(width<0) --- */
 7418: /* -------------------------------------------------------------------------
 7419: see if width is "absolute" or fill width
 7420: -------------------------------------------------------------------------- */
 7421: if ( isfill				/* called as \hfill{} */
 7422: &&   !isheight )			/* parameter conflict */
 7423:  { if ( leftexpression != NULL )	/* if we have left half */
 7424:     width -= (leftexpression->image)->width; /*reduce left width from total*/
 7425:    if ( (rightsp=rasterize(*expression,size)) /* rasterize right half */
 7426:    != NULL )				/* succeeded */
 7427:     width -= (rightsp->image)->width; } /* reduce right width from total */
 7428: /* -------------------------------------------------------------------------
 7429: construct blank subraster, and return it to caller
 7430: -------------------------------------------------------------------------- */
 7431: /* --- get parameters from base symbol --- */
 7432: if ( basesp != (subraster *)NULL )	/* we have base symbol for space */
 7433:   { baseht = (basesp->image)->height; 	/* height of base symbol */
 7434:     baseln =  basesp->baseline; }	/* and its baseline */
 7435: /* --- flip params for height --- */
 7436: if ( isheight )				/* width is actually height */
 7437:   { baseht = width;			/* use given width as height */
 7438:     width = 1; }			/* and set default width */
 7439: /* --- generate and init space subraster --- */
 7440: if ( width > 0 )			/*make sure we have positive width*/
 7441:  if ( (spacesp=new_subraster(width,baseht,pixsz)) /*generate space subraster*/
 7442:  !=   NULL )				/* and if we succeed... */
 7443:   { /* --- ...re-init subraster parameters --- */
 7444:     spacesp->size = size;		/*propagate base font size forward*/
 7445:     if(1)spacesp->type = blanksignal;	/* need to propagate blanks (???) */
 7446:     spacesp->baseline = baseln; }	/* ditto baseline */
 7447: /* -------------------------------------------------------------------------
 7448: concat right half if \hfill-ing
 7449: -------------------------------------------------------------------------- */
 7450: if ( rightsp != NULL )			/* we have a right half after fill */
 7451:   { spacesp = (spacesp==NULL? rightsp:	/* no space, so just use right half*/
 7452: 	rastcat(spacesp,rightsp,3));	/* or cat right half after space */
 7453:     spacesp->type = blanksignal;	/* need to propagate blanks */
 7454:     *expression += strlen((*expression)); } /* push expression to its null */
 7455: end_of_job:
 7456:   return ( spacesp );
 7457: } /* --- end-of-function rastspace() --- */
 7458: 
 7459: 
 7460: /* ==========================================================================
 7461:  * Function:	rastnewline ( expression, size, basesp,  arg1, arg2, arg3 )
 7462:  * Purpose:	\\ handler, returns subraster corresponding to
 7463:  *		left-hand expression preceding \\ above right-hand expression
 7464:  * --------------------------------------------------------------------------
 7465:  * Arguments:	expression (I/O) char **  to first char of null-terminated
 7466:  *				string immediately following \\ to be
 7467:  *				rasterized, and returning ptr immediately
 7468:  *				to terminating null.
 7469:  *		size (I)	int containing 0-5 default font size
 7470:  *		basesp (I)	subraster *  to character (or subexpression)
 7471:  *				immediately preceding \\
 7472:  *				(unused, but passed for consistency)
 7473:  *		arg1 (I)	int unused
 7474:  *		arg2 (I)	int unused
 7475:  *		arg3 (I)	int unused
 7476:  * --------------------------------------------------------------------------
 7477:  * Returns:	( subraster * )	ptr to subraster corresponding to expression,
 7478:  *				or NULL for any parsing error
 7479:  *				(expression ptr unchanged if error occurs)
 7480:  * --------------------------------------------------------------------------
 7481:  * Notes:     o
 7482:  * ======================================================================= */
 7483: /* --- entry point --- */
 7484: subraster *rastnewline ( char **expression, int size, subraster *basesp,
 7485: 			int arg1, int arg2, int arg3 )
 7486: {
 7487: /* -------------------------------------------------------------------------
 7488: Allocations and Declarations
 7489: -------------------------------------------------------------------------- */
 7490: subraster *rastack(), *newlsp=NULL;	/* subraster for both lines */
 7491: subraster *rasterize(), *rightsp=NULL;	/*rasterize right half of expression*/
 7492: char	*texsubexpr(), spacexpr[129]/*, *xptr=spacexpr*/; /*for \\[vspace]*/
 7493: double	strtod();			/* convert ascii param to double */
 7494: int	vspace = size+2;		/* #pixels between lines */
 7495: /* -------------------------------------------------------------------------
 7496: obtain optional [vspace] argument immediately following \\ command
 7497: -------------------------------------------------------------------------- */
 7498: /* --- check if [vspace] given --- */
 7499: if ( *(*expression) == '[' )		/*have [vspace] if leading char is [*/
 7500:   {
 7501:   /* ---parse [vspace] and bump expression past it, interpret as double--- */
 7502:   *expression = texsubexpr(*expression,spacexpr,127,"[","]",0,0);
 7503:   if ( *spacexpr == '\000' ) goto end_of_job; /* couldn't get [vspace] */
 7504:   vspace = iround(unitlength*strtod(spacexpr,NULL)); /* vspace in pixels */
 7505:   } /* --- end-of-if(*(*expression)=='[') --- */
 7506: if ( leftexpression == NULL ) goto end_of_job; /* nothing preceding \\ */
 7507: /* -------------------------------------------------------------------------
 7508: rasterize right half of expression and stack left half above it
 7509: -------------------------------------------------------------------------- */
 7510: /* --- rasterize right half --- */
 7511: if ( (rightsp=rasterize(*expression,size)) /* rasterize right half */
 7512: == NULL ) goto end_of_job;		/* quit if failed */
 7513: /* --- stack left half above it --- */
 7514: /*newlsp = rastack(rightsp,leftexpression,1,vspace,0,3);*//*right under left*/
 7515: newlsp = rastack(rightsp,leftexpression,1,vspace,0,1); /*right under left*/
 7516: /* --- back to caller --- */
 7517: end_of_job:
 7518:   if ( newlsp != NULL )			/* returning entire expression */
 7519:     { int newht = (newlsp->image)->height; /* height of returned subraster */
 7520:       newlsp->baseline = min2(newht-1,newht/2+5); /* guess new baseline */
 7521:       isreplaceleft = 1;		/* so set flag to replace left half*/
 7522:       *expression += strlen(*expression); } /* and push to terminating null*/
 7523:   return ( newlsp );			/* 1st line over 2nd, or null=error*/
 7524: } /* --- end-of-function rastnewline() --- */
 7525: 
 7526: 
 7527: /* ==========================================================================
 7528:  * Function:	rastarrow ( expression, size, basesp,  drctn, isBig, arg3 )
 7529:  * Purpose:	returns left/right arrow subraster (e.g., for \longrightarrow)
 7530:  * --------------------------------------------------------------------------
 7531:  * Arguments:	expression (I)	char **  to first char of null-terminated
 7532:  *				LaTeX expression (unused/unchanged)
 7533:  *		size (I)	int containing base font size (not used,
 7534:  *				just stored in subraster)
 7535:  *		basesp (I)	subraster *  to character (or subexpression)
 7536:  *				immediately preceding space, whose baseline
 7537:  *				and height params are transferred to space
 7538:  *		drctn (I)	int containing +1 for right, -1 for left,
 7539:  *				or 0 for leftright
 7540:  *		isBig (I)	int containing 0 for ---> or 1 for ===>
 7541:  *		arg3 (I)	int unused
 7542:  * --------------------------------------------------------------------------
 7543:  * Returns:	( subraster * )	ptr to left/right arrow subraster
 7544:  *				or NULL for any error
 7545:  * --------------------------------------------------------------------------
 7546:  * Notes:     o	An optional argument [width] may *immediately* follow
 7547:  *		the \longxxx to explicitly set the arrow's width in pixels.
 7548:  *		For example, \longrightarrow calculates a default width
 7549:  *		(as usual in LaTeX), whereas \longrightarrow[50] explicitly
 7550:  *		draws a 50-pixel long arrow.  This can be used, e.g.,
 7551:  *		to draw commutative diagrams in conjunction with
 7552:  *		\array (and maybe with \stackrel and/or \relstack, too).
 7553:  *	      o	In case you really want to render, say, [f]---->[g], just
 7554:  *		use an intervening space, i.e., [f]\longrightarrow~[g].
 7555:  *		In text mode use two spaces {\rm~[f]\longrightarrow~~[g]}.
 7556:  * ======================================================================= */
 7557: /* --- entry point --- */
 7558: subraster *rastarrow ( char **expression, int size, subraster *basesp,
 7559: 			int drctn, int isBig, int arg3 )
 7560: {
 7561: /* -------------------------------------------------------------------------
 7562: Allocations and Declarations
 7563: -------------------------------------------------------------------------- */
 7564: subraster *arrow_subraster(), *arrowsp=NULL; /* subraster for arrow */
 7565: char	*texsubexpr(), widtharg[256];	/* parse for optional [width] */
 7566: char	*texscripts(), sub[1024],super[1024]; /* and _^limits after [width]*/
 7567: subraster *rasterize(), *subsp=NULL,*supsp=NULL; /*rasterize limits*/
 7568: subraster *new_subraster(), *rastack(), *spacesp=NULL; /*space below arrow*/
 7569: int	delete_subraster();		/*free work areas in case of error*/
 7570: double	strtod();			/* convert ascii [width] to value */
 7571: int	width = 10 + 8*size,  height;	/* width, height for \longxxxarrow */
 7572: int	islimits = 1;			/*true to handle limits internally*/
 7573: int	limsize = size-1;		/* font size for limits */
 7574: int	vspace = 1;			/* #empty rows below arrow */
 7575: int	pixsz = 1;			/*default #bits per pixel, 1=bitmap*/
 7576: /* -------------------------------------------------------------------------
 7577: construct longleft/rightarrow subraster, with limits, and return it to caller
 7578: -------------------------------------------------------------------------- */
 7579: /* --- check for optional width arg and replace default width --- */
 7580: if ( *(*expression) == '[' )		/*check for []-enclosed optional arg*/
 7581:   { int widthval;			/* test [width] before using it */
 7582:     *expression = texsubexpr(*expression,widtharg,255,"[","]",0,0);
 7583:     widthval =				/* convert [width] to integer */
 7584: 		(int)((unitlength*strtod(widtharg,NULL))+0.5);
 7585:     if ( widthval>=2 && widthval<=600 )	/* sanity check */
 7586:       width = widthval; }		/* replace deafault width */
 7587: /* --- now parse for limits, and bump expression past it(them) --- */
 7588: if ( islimits )				/* handling limits internally */
 7589:   { *expression = texscripts(*expression,sub,super,3); /* parse for limits */
 7590:     if ( *sub != '\000' )		/*have a subscript following arrow*/
 7591:       subsp = rasterize(sub,limsize);	/* so try to rasterize subscript */
 7592:     if ( *super != '\000' )		/*have superscript following arrow*/
 7593:       supsp = rasterize(super,limsize); } /*so try to rasterize superscript*/
 7594: /* --- set height based on width --- */
 7595: height = min2(17,max2(9,(width+2)/6));	/* height based on width */
 7596: height = 1 + (height/2)*2;		/* always force odd height */
 7597: /* --- generate arrow subraster --- */
 7598: if ( (arrowsp=arrow_subraster(width,height,pixsz,drctn,isBig)) /*build arrow*/
 7599: ==   NULL ) goto end_of_job;		/* and quit if we failed */
 7600: /* --- add space below arrow --- */
 7601: if ( vspace > 0 )			/* if we have space below arrow */
 7602:   if ( (spacesp=new_subraster(width,vspace,pixsz)) /*allocate required space*/
 7603:   !=   NULL )				/* and if we succeeded */
 7604:     if ( (arrowsp = rastack(spacesp,arrowsp,2,0,1,3)) /* space below arrow */
 7605:     ==   NULL ) goto end_of_job;	/* and quit if we failed */
 7606: /* --- init arrow subraster parameters --- */
 7607: arrowsp->size = size;			/*propagate base font size forward*/
 7608: arrowsp->baseline = height+vspace-1;	/* set baseline at bottom of arrow */
 7609: /* --- add limits above/below arrow, as necessary --- */
 7610: if ( subsp != NULL )			/* stack subscript below arrow */
 7611:   if ( (arrowsp = rastack(subsp,arrowsp,2,0,1,3)) /* subscript below arrow */
 7612:   ==   NULL ) goto end_of_job;		/* quit if failed */
 7613: if ( supsp != NULL )			/* stack superscript above arrow */
 7614:   if ( (arrowsp = rastack(arrowsp,supsp,1,vspace,1,3)) /*supsc above arrow*/
 7615:   ==   NULL ) goto end_of_job;		/* quit if failed */
 7616: /* --- return arrow (or NULL) to caller --- */
 7617: end_of_job:
 7618:   return ( arrowsp );
 7619: } /* --- end-of-function rastarrow() --- */
 7620: 
 7621: 
 7622: /* ==========================================================================
 7623:  * Function:	rastuparrow ( expression, size, basesp,  drctn, isBig, arg3 )
 7624:  * Purpose:	returns an up/down arrow subraster (e.g., for \longuparrow)
 7625:  * --------------------------------------------------------------------------
 7626:  * Arguments:	expression (I)	char **  to first char of null-terminated
 7627:  *				LaTeX expression (unused/unchanged)
 7628:  *		size (I)	int containing base font size (not used,
 7629:  *				just stored in subraster)
 7630:  *		basesp (I)	subraster *  to character (or subexpression)
 7631:  *				immediately preceding space, whose baseline
 7632:  *				and height params are transferred to space
 7633:  *		drctn (I)	int containing +1 for up, -1 for down,
 7634:  *				or 0 for updown
 7635:  *		isBig (I)	int containing 0 for ---> or 1 for ===>
 7636:  *		arg3 (I)	int unused
 7637:  * --------------------------------------------------------------------------
 7638:  * Returns:	( subraster * )	ptr to up/down arrow subraster
 7639:  *				or NULL for any error
 7640:  * --------------------------------------------------------------------------
 7641:  * Notes:     o	An optional argument [height] may *immediately* follow
 7642:  *		the \longxxx to explicitly set the arrow's height in pixels.
 7643:  *		For example, \longuparrow calculates a default height
 7644:  *		(as usual in LaTeX), whereas \longuparrow[25] explicitly
 7645:  *		draws a 25-pixel high arrow.  This can be used, e.g.,
 7646:  *		to draw commutative diagrams in conjunction with
 7647:  *		\array (and maybe with \stackrel and/or \relstack, too).
 7648:  *	      o	In case you really want to render, say, [f]---->[g], just
 7649:  *		use an intervening space, i.e., [f]\longuparrow~[g].
 7650:  *		In text use two spaces {\rm~[f]\longuparrow~~[g]}.
 7651:  * ======================================================================= */
 7652: /* --- entry point --- */
 7653: subraster *rastuparrow ( char **expression, int size, subraster *basesp,
 7654: 			int drctn, int isBig, int arg3 )
 7655: {
 7656: /* -------------------------------------------------------------------------
 7657: Allocations and Declarations
 7658: -------------------------------------------------------------------------- */
 7659: subraster *uparrow_subraster(), *arrowsp=NULL; /* subraster for arrow */
 7660: char	*texsubexpr(), heightarg[256];	/* parse for optional [height] */
 7661: char	*texscripts(), sub[1024],super[1024]; /* and _^limits after [width]*/
 7662: subraster *rasterize(), *subsp=NULL,*supsp=NULL; /*rasterize limits*/
 7663: subraster *rastcat();			/* cat superscript left, sub right */
 7664: double	strtod();			/* convert ascii [height] to value */
 7665: int	height = 8 + 2*size,  width;	/* height, width for \longxxxarrow */
 7666: int	islimits = 1;			/*true to handle limits internally*/
 7667: int	limsize = size-1;		/* font size for limits */
 7668: int	pixsz = 1;			/*default #bits per pixel, 1=bitmap*/
 7669: /* -------------------------------------------------------------------------
 7670: construct blank subraster, and return it to caller
 7671: -------------------------------------------------------------------------- */
 7672: /* --- check for optional height arg and replace default height --- */
 7673: if ( *(*expression) == '[' )		/*check for []-enclosed optional arg*/
 7674:   { int heightval;			/* test height before using it */
 7675:     *expression = texsubexpr(*expression,heightarg,255,"[","]",0,0);
 7676:     heightval =				/* convert [height] to integer */
 7677: 		(int)((unitlength*strtod(heightarg,NULL))+0.5);
 7678:     if ( heightval>=2 && heightval<=600 ) /* sanity check */
 7679:       height = heightval; }		/* replace deafault height */
 7680: /* --- now parse for limits, and bump expression past it(them) --- */
 7681: if ( islimits )				/* handling limits internally */
 7682:   { *expression = texscripts(*expression,sub,super,3); /* parse for limits */
 7683:     if ( *sub != '\000' )		/*have a subscript following arrow*/
 7684:       subsp = rasterize(sub,limsize);	/* so try to rasterize subscript */
 7685:     if ( *super != '\000' )		/*have superscript following arrow*/
 7686:       supsp = rasterize(super,limsize); } /*so try to rasterize superscript*/
 7687: /* --- set width based on height --- */
 7688: width = min2(17,max2(9,(height+2)/4));	/* width based on height */
 7689: width = 1 + (width/2)*2;		/* always force odd width */
 7690: /* --- generate arrow subraster --- */
 7691: if ( (arrowsp=uparrow_subraster(width,height,pixsz,drctn,isBig)) /*build arr*/
 7692: ==   NULL ) goto end_of_job;		/* and quit if we failed */
 7693: /* --- init arrow subraster parameters --- */
 7694: arrowsp->size = size;			/*propagate base font size forward*/
 7695: arrowsp->baseline = height-1;		/* set baseline at bottom of arrow */
 7696: /* --- add limits above/below arrow, as necessary --- */
 7697: if ( supsp != NULL )			/* cat superscript to left of arrow*/
 7698:   { int	supht = (supsp->image)->height,	/* superscript height */
 7699: 	deltab = (1+abs(height-supht))/2; /* baseline difference to center */
 7700:   supsp->baseline = supht-1;		/* force script baseline to bottom */
 7701:   if ( supht <= height )		/* arrow usually taller than script*/
 7702: 	arrowsp->baseline -= deltab;	/* so bottom of script goes here */
 7703:   else	supsp->baseline -= deltab;	/* else bottom of arrow goes here */
 7704:   if ( (arrowsp = rastcat(supsp,arrowsp,3)) /* superscript left of arrow */
 7705:     ==   NULL ) goto end_of_job; }	/* quit if failed */
 7706: if ( subsp != NULL )			/* cat subscript to right of arrow */
 7707:   { int	subht = (subsp->image)->height,	/* subscript height */
 7708: 	deltab = (1+abs(height-subht))/2; /* baseline difference to center */
 7709:   arrowsp->baseline = height-1;		/* reset arrow baseline to bottom */
 7710:   subsp->baseline = subht-1;		/* force script baseline to bottom */
 7711:   if ( subht <= height )		/* arrow usually taller than script*/
 7712: 	arrowsp->baseline -= deltab;	/* so bottom of script goes here */
 7713:   else	subsp->baseline -= deltab;	/* else bottom of arrow goes here */
 7714:   if ( (arrowsp = rastcat(arrowsp,subsp,3)) /* subscript right of arrow */
 7715:     ==   NULL ) goto end_of_job; }	/* quit if failed */
 7716: /* --- return arrow (or NULL) to caller --- */
 7717: end_of_job:
 7718:   arrowsp->baseline = height-1;		/* reset arrow baseline to bottom */
 7719:   return ( arrowsp );
 7720: } /* --- end-of-function rastuparrow() --- */
 7721: 
 7722: 
 7723: /* ==========================================================================
 7724:  * Function:	rastoverlay (expression, size, basesp, overlay, offset2, arg3)
 7725:  * Purpose:	overlays one raster on another
 7726:  * --------------------------------------------------------------------------
 7727:  * Arguments:	expression (I/O) char **  to first char of null-terminated
 7728:  *				string immediately following overlay \cmd to
 7729:  *				be rasterized, and returning ptr immediately
 7730:  *				following last character processed.
 7731:  *		size (I)	int containing 0-5 default font size
 7732:  *		basesp (I)	subraster *  to character (or subexpression)
 7733:  *				immediately preceding overlay \cmd
 7734:  *				(unused, but passed for consistency)
 7735:  *		overlay (I)	int containing 1 to overlay / (e.g., \not)
 7736:  *				or NOVALUE to pick up 2nd arg from expression
 7737:  *		offset2 (I)	int containing #pixels to horizontally offset
 7738:  *				overlay relative to underlying symbol,
 7739:  *				positive(right) or negative or 0,
 7740:  *				or NOVALUE to pick up optional [offset] arg
 7741:  *		arg3 (I)	int unused
 7742:  * --------------------------------------------------------------------------
 7743:  * Returns:	( subraster * )	ptr to subraster corresponding to composite,
 7744:  *				or NULL for any parsing error
 7745:  * --------------------------------------------------------------------------
 7746:  * Notes:     o
 7747:  * ======================================================================= */
 7748: /* --- entry point --- */
 7749: subraster *rastoverlay ( char **expression, int size, subraster *basesp,
 7750: 			int overlay, int offset2, int arg3 )
 7751: {
 7752: /* -------------------------------------------------------------------------
 7753: Allocations and Declarations
 7754: -------------------------------------------------------------------------- */
 7755: char	*texsubexpr(),			/*parse expression for base,overlay*/
 7756: 	expr1[512], expr2[512];		/* base, overlay */
 7757: subraster *rasterize(), *sp1=NULL, *sp2=NULL, /*rasterize 1=base, 2=overlay*/
 7758: 	*new_subraster();		/*explicitly alloc sp2 if necessary*/
 7759: subraster *rastcompose(), *overlaysp=NULL; /*subraster for composite overlay*/
 7760: int	line_raster();			/* draw diagonal for \Not */
 7761: /* -------------------------------------------------------------------------
 7762: Obtain base, and maybe overlay, and rasterize them
 7763: -------------------------------------------------------------------------- */
 7764: /* --- check for optional offset2 arg  --- */
 7765: if ( offset2 == NOVALUE )		/* only if not explicitly specified*/
 7766:  if ( *(*expression) == '[' )		/*check for []-enclosed optional arg*/
 7767:   { int offsetval;			/* test before using it */
 7768:     *expression = texsubexpr(*expression,expr2,511,"[","]",0,0);
 7769:     offsetval = (int)(strtod(expr2,NULL)+0.5); /* convert [offset2] to int */
 7770:     if ( abs(offsetval) <= 25 )		/* sanity check */
 7771:       offset2 = offsetval; }		/* replace deafault */
 7772: if ( offset2 == NOVALUE ) offset2 = 0;	/* novalue means no offset */
 7773: /* --- parse for base, bump expression past it, and rasterize it --- */
 7774: *expression = texsubexpr(*expression,expr1,511,"{","}",0,0);
 7775: if ( *expr1 == '\000' ) goto end_of_job; /* nothing to overlay, so quit */
 7776: if ( (sp1=rasterize(expr1,size))	/* rasterize base expression */
 7777: ==   NULL ) goto end_of_job;		/* quit if failed to rasterize */
 7778: overlaysp = sp1;			/*in case we return with no overlay*/
 7779: /* --- get overlay expression, and rasterize it --- */
 7780: if ( overlay == NOVALUE )		/* get overlay from input stream */
 7781:   { *expression = texsubexpr(*expression,expr2,511,"{","}",0,0);
 7782:     if ( *expr2 != '\000' )		/* have an overlay */
 7783:       sp2 = rasterize(expr2,size); }	/* so rasterize overlay expression */
 7784: else					/* specific overlay */
 7785:   switch ( overlay )
 7786:     {
 7787:     default: break;
 7788:     case 1:				/* e.g., \not overlays slash */
 7789:       sp2 = rasterize("/",size+1);	/* rasterize overlay expression */
 7790:       offset2 = max2(1,size-3);		/* push / right a bit */
 7791:       offset2 = 0;
 7792:       break;
 7793:     case 2:				/* e.g., \Not draws diagonal */
 7794:       sp2 = NULL;			/* no overlay required */
 7795:       if ( overlaysp != NULL )		/* check that we have raster */
 7796: 	{ raster *rp = overlaysp->image; /* raster to be \Not-ed */
 7797: 	  int width=rp->width, height=rp->height; /* raster dimensions */
 7798: 	  if ( 0 )			/* diagonal within bounding box */
 7799: 	   line_raster(rp,0,width-1,height-1,0,1); /* just draw diagonal */
 7800: 	  else				/* construct "wide" diagonal */
 7801: 	   { int margin=3;		/* desired extra margin width */
 7802: 	     sp2 = new_subraster(width+margin,height+margin,1); /*alloc it*/
 7803: 	     if ( sp2 != NULL )		/* allocated successfully */
 7804: 	      line_raster(sp2->image,0,width+margin-1,height+margin-1,0,1);}}
 7805:       break;
 7806:     case 3:				/* e.g., \sout for strikeout */
 7807:       sp2 = NULL;			/* no overlay required */
 7808:       if ( overlaysp != NULL )		/* check that we have raster */
 7809: 	{ raster *rp = overlaysp->image; /* raster to be \Not-ed */
 7810: 	  int width=rp->width, height=rp->height; /* raster dimensions */
 7811: 	  int baseline = overlaysp->baseline; /* we'll ignore descenders */
 7812: 	  int midrow = max2(0,min2(height-1,offset2+((baseline+1)/2)));
 7813: 	  if ( 1 )			/* strikeout within bounding box */
 7814: 	    line_raster(rp,midrow,0,midrow,width-1,1); } /*draw strikeout*/
 7815:       break;
 7816:     } /* --- end-of-switch(overlay) --- */
 7817: if ( sp2 == NULL ) goto end_of_job;	/*return sp1 if failed to rasterize*/
 7818: /* -------------------------------------------------------------------------
 7819: construct composite overlay
 7820: -------------------------------------------------------------------------- */
 7821: overlaysp = rastcompose(sp1,sp2,offset2,0,3);
 7822: end_of_job:
 7823:   return ( overlaysp );
 7824: } /* --- end-of-function rastoverlay() --- */
 7825: 
 7826: 
 7827: /* ==========================================================================
 7828:  * Function:	rastfrac ( expression, size, basesp,  isfrac, arg2, arg3 )
 7829:  * Purpose:	\frac,\atop handler, returns a subraster corresponding to
 7830:  *		expression (immediately following \frac,\atop) at font size
 7831:  * --------------------------------------------------------------------------
 7832:  * Arguments:	expression (I/O) char **  to first char of null-terminated
 7833:  *				string immediately following \frac to be
 7834:  *				rasterized, and returning ptr immediately
 7835:  *				following last character processed.
 7836:  *		size (I)	int containing 0-5 default font size
 7837:  *		basesp (I)	subraster *  to character (or subexpression)
 7838:  *				immediately preceding \frac
 7839:  *				(unused, but passed for consistency)
 7840:  *		isfrac (I)	int containing true to draw horizontal line
 7841:  *				between numerator and denominator,
 7842:  *				or false not to draw it (for \atop).
 7843:  *		arg2 (I)	int unused
 7844:  *		arg3 (I)	int unused
 7845:  * --------------------------------------------------------------------------
 7846:  * Returns:	( subraster * )	ptr to subraster corresponding to fraction,
 7847:  *				or NULL for any parsing error
 7848:  * --------------------------------------------------------------------------
 7849:  * Notes:     o
 7850:  * ======================================================================= */
 7851: /* --- entry point --- */
 7852: subraster *rastfrac ( char **expression, int size, subraster *basesp,
 7853: 			int isfrac, int arg2, int arg3 )
 7854: {
 7855: /* -------------------------------------------------------------------------
 7856: Allocations and Declarations
 7857: -------------------------------------------------------------------------- */
 7858: char	*texsubexpr(),			/*parse expression for numer,denom*/
 7859: 	numer[MAXSUBXSZ+1], denom[MAXSUBXSZ+1]; /* parsed numer, denom */
 7860: subraster *rasterize(), *numsp=NULL, *densp=NULL; /*rasterize numer, denom*/
 7861: subraster *rastack(), *fracsp=NULL;	/* subraster for numer/denom */
 7862: subraster *new_subraster()/*, *spacesp=NULL*/; /* space for num or den */
 7863: int	width=0,			/* width of constructed raster */
 7864: 	numheight=0;			/* height of numerator */
 7865: int	baseht=0, baseln=0;		/* height,baseline of base symbol */
 7866: /*int	istweak = 1;*/			/*true to tweak baseline alignment*/
 7867: int	rule_raster(),			/* draw horizontal line for frac */
 7868: 	lineheight = 1;			/* thickness of fraction line */
 7869: int	vspace = (size>2?2:1);		/*vertical space between components*/
 7870: int	delete_subraster();		/*free work areas in case of error*/
 7871: int	type_raster();			/* display debugging output */
 7872: /* -------------------------------------------------------------------------
 7873: Obtain numerator and denominator, and rasterize them
 7874: -------------------------------------------------------------------------- */
 7875: /* --- parse for numerator,denominator and bump expression past them --- */
 7876: *expression = texsubexpr(*expression,numer,0,"{","}",0,0);
 7877: *expression = texsubexpr(*expression,denom,0,"{","}",0,0);
 7878: if ( *numer=='\000' && *denom=='\000' )	/* missing both components of frac */
 7879:   goto end_of_job;			/* nothing to do, so quit */
 7880: /* --- rasterize numerator, denominator --- */
 7881: if ( *numer != '\000' )			/* have a numerator */
 7882:  if ( (numsp = rasterize(numer,size-1))	/* so rasterize numer at size-1 */
 7883:  ==   NULL ) goto end_of_job;		/* and quit if failed */
 7884: if ( *denom != '\000' )			/* have a denominator */
 7885:  if ( (densp = rasterize(denom,size-1))	/* so rasterize denom at size-1 */
 7886:  ==   NULL )				/* failed */
 7887:   { if ( numsp != NULL )		/* already rasterized numerator */
 7888:       delete_subraster(numsp);		/* so free now-unneeded numerator */
 7889:     goto end_of_job; }			/* and quit */
 7890: /* --- if one componenet missing, use a blank space for it --- */
 7891: if ( numsp == NULL )			/* no numerator given */
 7892:   numsp = rasterize("[?]",size-1);	/* missing numerator */
 7893: if ( densp == NULL )			/* no denominator given */
 7894:   densp = rasterize("[?]",size-1);	/* missing denominator */
 7895: /* --- check that we got both components --- */
 7896: if ( numsp==NULL || densp==NULL )	/* some problem */
 7897:   { delete_subraster(numsp);		/*delete numerator (if it existed)*/
 7898:     delete_subraster(densp);		/*delete denominator (if it existed)*/
 7899:     goto end_of_job; }			/* and quit */
 7900: /* --- get height of numerator (to determine where line belongs) --- */
 7901: numheight = (numsp->image)->height;	/* get numerator's height */
 7902: /* -------------------------------------------------------------------------
 7903: construct raster with numerator stacked over denominator
 7904: -------------------------------------------------------------------------- */
 7905: /* --- construct raster with numer/denom --- */
 7906: if ( (fracsp = rastack(densp,numsp,0,2*vspace+lineheight,1,3))/*numer/denom*/
 7907: ==  NULL )				/* failed to construct numer/denom */
 7908:   { delete_subraster(numsp);		/* so free now-unneeded numerator */
 7909:     delete_subraster(densp);		/* and now-unneeded denominator */
 7910:     goto end_of_job; }			/* and then quit */
 7911: /* --- determine width of constructed raster --- */
 7912: width = (fracsp->image)->width;		/*just get width of embedded image*/
 7913: /* --- initialize subraster parameters --- */
 7914: fracsp->size = size;			/* propagate font size forward */
 7915: fracsp->baseline = (numheight+vspace+lineheight)+(size+2);/*default baseline*/
 7916: fracsp->type = FRACRASTER;		/* signal \frac image */
 7917: if ( basesp != (subraster *)NULL )	/* we have base symbol for frac */
 7918:   { baseht = (basesp->image)->height; 	/* height of base symbol */
 7919:     baseln =  basesp->baseline;		/* and its baseline */
 7920:   } /* --- end-of-if(basesp!=NULL) --- */
 7921: /* -------------------------------------------------------------------------
 7922: draw horizontal line between numerator and denominator
 7923: -------------------------------------------------------------------------- */
 7924: fraccenterline = numheight+vspace;	/* signal that we have a \frac */
 7925: if ( isfrac )				/*line for \frac, but not for \atop*/
 7926:   rule_raster(fracsp->image,fraccenterline,0,width,lineheight,0);
 7927: /* -------------------------------------------------------------------------
 7928: return final result to caller
 7929: -------------------------------------------------------------------------- */
 7930: end_of_job:
 7931:   if ( msgfp!=NULL && msglevel>=99 )
 7932:     { fprintf(msgfp,"rastfrac> returning %s\n",(fracsp==NULL?"null":"..."));
 7933:       if ( fracsp != NULL )		/* have a constructed raster */
 7934: 	type_raster(fracsp->image,msgfp); } /* display constructed raster */
 7935:   return ( fracsp );
 7936: } /* --- end-of-function rastfrac() --- */
 7937: 
 7938: 
 7939: /* ==========================================================================
 7940:  * Function:	rastackrel ( expression, size, basesp,  base, arg2, arg3 )
 7941:  * Purpose:	\stackrel handler, returns a subraster corresponding to
 7942:  *		stacked relation
 7943:  * --------------------------------------------------------------------------
 7944:  * Arguments:	expression (I/O) char **  to first char of null-terminated
 7945:  *				string immediately following \stackrel to be
 7946:  *				rasterized, and returning ptr immediately
 7947:  *				following last character processed.
 7948:  *		size (I)	int containing 0-4 default font size
 7949:  *		basesp (I)	subraster *  to character (or subexpression)
 7950:  *				immediately preceding \stackrel
 7951:  *				(unused, but passed for consistency)
 7952:  *		base (I)	int containing 1 if upper/first subexpression
 7953:  *				is base relation, or 2 if lower/second is
 7954:  *		arg2 (I)	int unused
 7955:  *		arg3 (I)	int unused
 7956:  * --------------------------------------------------------------------------
 7957:  * Returns:	( subraster * )	ptr to subraster corresponding to stacked
 7958:  *				relation, or NULL for any parsing error
 7959:  * --------------------------------------------------------------------------
 7960:  * Notes:     o
 7961:  * ======================================================================= */
 7962: /* --- entry point --- */
 7963: subraster *rastackrel ( char **expression, int size, subraster *basesp,
 7964: 			int base, int arg2, int arg3 )
 7965: {
 7966: /* -------------------------------------------------------------------------
 7967: Allocations and Declarations
 7968: -------------------------------------------------------------------------- */
 7969: char	*texsubexpr(),			/*parse expression for upper,lower*/
 7970: 	upper[MAXSUBXSZ+1], lower[MAXSUBXSZ+1];	/* parsed upper, lower */
 7971: subraster *rasterize(), *upsp=NULL, *lowsp=NULL; /* rasterize upper, lower */
 7972: subraster *rastack(), *relsp=NULL;	/* subraster for upper/lower */
 7973: int	upsize  = (base==1? size:size-1), /* font size for upper component */
 7974: 	lowsize = (base==2? size:size-1); /* font size for lower component */
 7975: int	vspace = 1;			/*vertical space between components*/
 7976: int	delete_subraster();		/*free work areas in case of error*/
 7977: /* -------------------------------------------------------------------------
 7978: Obtain numerator and denominator, and rasterize them
 7979: -------------------------------------------------------------------------- */
 7980: /* --- parse for numerator,denominator and bump expression past them --- */
 7981: *expression = texsubexpr(*expression,upper,0,"{","}",0,0);
 7982: *expression = texsubexpr(*expression,lower,0,"{","}",0,0);
 7983: if ( *upper=='\000' || *lower=='\000' )	/* missing either component */
 7984:   goto end_of_job;			/* nothing to do, so quit */
 7985: /* --- rasterize upper, lower --- */
 7986: if ( *upper != '\000' )			/* have upper component */
 7987:  if ( (upsp = rasterize(upper,upsize))	/* so rasterize upper component */
 7988:  ==   NULL ) goto end_of_job;		/* and quit if failed */
 7989: if ( *lower != '\000' )			/* have lower component */
 7990:  if ( (lowsp = rasterize(lower,lowsize)) /* so rasterize lower component */
 7991:  ==   NULL )				/* failed */
 7992:   { if ( upsp != NULL )			/* already rasterized upper */
 7993:       delete_subraster(upsp);		/* so free now-unneeded upper */
 7994:     goto end_of_job; }			/* and quit */
 7995: /* -------------------------------------------------------------------------
 7996: construct stacked relation raster
 7997: -------------------------------------------------------------------------- */
 7998: /* --- construct stacked relation --- */
 7999: if ( (relsp = rastack(lowsp,upsp,3-base,vspace,1,3)) /* stacked relation */
 8000: ==   NULL ) goto end_of_job;		/* quit if failed */
 8001: /* --- initialize subraster parameters --- */
 8002: relsp->size = size;			/* propagate font size forward */
 8003: /* -------------------------------------------------------------------------
 8004: return final result to caller
 8005: -------------------------------------------------------------------------- */
 8006: end_of_job:
 8007:   return ( relsp );
 8008: } /* --- end-of-function rastackrel() --- */
 8009: 
 8010: 
 8011: /* ==========================================================================
 8012:  * Function:	rastmathfunc ( expression, size, basesp,  base, arg2, arg3 )
 8013:  * Purpose:	\log, \lim, etc handler, returns a subraster corresponding
 8014:  *		to math functions
 8015:  * --------------------------------------------------------------------------
 8016:  * Arguments:	expression (I/O) char **  to first char of null-terminated
 8017:  *				string immediately following \mathfunc to be
 8018:  *				rasterized, and returning ptr immediately
 8019:  *				following last character processed.
 8020:  *		size (I)	int containing 0-4 default font size
 8021:  *		basesp (I)	subraster *  to character (or subexpression)
 8022:  *				immediately preceding \mathfunc
 8023:  *				(unused, but passed for consistency)
 8024:  *		mathfunc (I)	int containing 1=arccos, 2=arcsin, etc.
 8025:  *		islimits (I)	int containing 1 if function may have
 8026:  *				limits underneath, e.g., \lim_{n\to\infty}
 8027:  *		arg3 (I)	int unused
 8028:  * --------------------------------------------------------------------------
 8029:  * Returns:	( subraster * )	ptr to subraster corresponding to mathfunc,
 8030:  *				or NULL for any parsing error
 8031:  * --------------------------------------------------------------------------
 8032:  * Notes:     o
 8033:  * ======================================================================= */
 8034: /* --- entry point --- */
 8035: subraster *rastmathfunc ( char **expression, int size, subraster *basesp,
 8036: 			int mathfunc, int islimits, int arg3 )
 8037: {
 8038: /* -------------------------------------------------------------------------
 8039: Allocations and Declarations
 8040: -------------------------------------------------------------------------- */
 8041: char	*texscripts(),			/* parse expression for _limits */
 8042: 	func[MAXTOKNSZ+1], limits[MAXSUBXSZ+1]; /*func as {\rm func}, limits*/
 8043: char	*texsubexpr(),			/* parse expression for arg */
 8044: 	funcarg[MAXTOKNSZ+1];		/* optional func arg */
 8045: subraster *rasterize(), *funcsp=NULL, *limsp=NULL; /*rasterize func,limits*/
 8046: subraster *rastack(), *mathfuncsp=NULL;	/* subraster for mathfunc/limits */
 8047: int	limsize = size-1;		/* font size for limits */
 8048: int	vspace = 1;			/*vertical space between components*/
 8049: int	delete_subraster();		/*free work areas in case of error*/
 8050: /* --- table of function names by mathfunc number --- */
 8051: static	int  numnames = 34;		/* number of names in table */
 8052: static	char *funcnames[] = {
 8053: 	"error",			/*  0 index is illegal/error bucket*/
 8054: 	"arccos",  "arcsin",  "arctan",	/*  1 -  3 */
 8055: 	"arg",     "cos",     "cosh",	/*  4 -  6 */
 8056: 	"cot",     "coth",    "csc",	/*  7 -  9 */
 8057: 	"deg",     "det",     "dim",	/* 10 - 12 */
 8058: 	"exp",     "gcd",     "hom",	/* 13 - 15 */
 8059: 	"inf",     "ker",     "lg",	/* 16 - 18 */
 8060: 	"lim",     "liminf",  "limsup",	/* 19 - 21 */
 8061: 	"ln",      "log",     "max",	/* 22 - 24 */
 8062: 	"min",     "Pr",      "sec",	/* 25 - 27 */
 8063: 	"sin",     "sinh",    "sup",	/* 28 - 30 */
 8064: 	"tan",     "tanh",		/* 31 - 32 */
 8065: 	/* --- extra mimetex funcnames --- */
 8066: 	"tr",				/* 33 */
 8067: 	"pmod"				/* 34 */
 8068: 	} ;
 8069: /* -------------------------------------------------------------------------
 8070: set up and rasterize function name in \rm
 8071: -------------------------------------------------------------------------- */
 8072: if ( mathfunc<0 || mathfunc>numnames ) mathfunc=0; /* check index bounds */
 8073: switch ( mathfunc )			/* check for special processing */
 8074:   {
 8075:   default:				/* no special processing */
 8076:     strcpy(func,"{\\rm~");		/* init string with {\rm~ */
 8077:     strcat(func,funcnames[mathfunc]);	/* concat function name */
 8078:     strcat(func,"}");			/* and add terminating } */
 8079:     break;
 8080:   case 34:				/* \pmod{x} --> (mod x) */
 8081:     /* --- parse for \pmod{arg} argument --- */
 8082:     *expression = texsubexpr(*expression,funcarg,2047,"{","}",0,0);
 8083:     strcpy(func,"{\\({\\rm~mod}");	/* init with {\left({\rm~mod} */
 8084:     strcat(func,"\\hspace2");		/* concat space */
 8085:     strcat(func,funcarg);		/* and \pmodargument */
 8086:     strcat(func,"\\)}");		/* and add terminating \right)} */
 8087:     break;
 8088:   } /* --- end-of-switch(mathfunc) --- */
 8089: if ( (funcsp = rasterize(func,size))	/* rasterize function name */
 8090: ==   NULL ) goto end_of_job;		/* and quit if failed */
 8091: mathfuncsp = funcsp;			/* just return funcsp if no limits */
 8092: if ( !islimits ) goto end_of_job;	/* treat any subscript normally */
 8093: /* -------------------------------------------------------------------------
 8094: Obtain limits, if permitted and if provided, and rasterize them
 8095: -------------------------------------------------------------------------- */
 8096: /* --- parse for subscript limits, and bump expression past it(them) --- */
 8097: *expression = texscripts(*expression,limits,limits,1);
 8098: if ( *limits=='\000') goto end_of_job;	/* no limits, nothing to do, quit */
 8099: /* --- rasterize limits --- */
 8100: if ( (limsp = rasterize(limits,limsize)) /* rasterize limits */
 8101: ==   NULL ) goto end_of_job;		/* and quit if failed */
 8102: /* -------------------------------------------------------------------------
 8103: construct func atop limits
 8104: -------------------------------------------------------------------------- */
 8105: /* --- construct func atop limits --- */
 8106: if ( (mathfuncsp = rastack(limsp,funcsp,2,vspace,1,3)) /* func atop limits */
 8107: ==   NULL ) goto end_of_job;		/* quit if failed */
 8108: /* --- initialize subraster parameters --- */
 8109: mathfuncsp->size = size;		/* propagate font size forward */
 8110: /* -------------------------------------------------------------------------
 8111: return final result to caller
 8112: -------------------------------------------------------------------------- */
 8113: end_of_job:
 8114:   return ( mathfuncsp );
 8115: } /* --- end-of-function rastmathfunc() --- */
 8116: 
 8117: 
 8118: /* ==========================================================================
 8119:  * Function:	rastsqrt ( expression, size, basesp,  arg1, arg2, arg3 )
 8120:  * Purpose:	\sqrt handler, returns a subraster corresponding to
 8121:  *		expression (immediately following \sqrt) at font size
 8122:  * --------------------------------------------------------------------------
 8123:  * Arguments:	expression (I/O) char **  to first char of null-terminated
 8124:  *				string immediately following \sqrt to be
 8125:  *				rasterized, and returning ptr immediately
 8126:  *				following last character processed.
 8127:  *		size (I)	int containing 0-4 default font size
 8128:  *		basesp (I)	subraster *  to character (or subexpression)
 8129:  *				immediately preceding \accent
 8130:  *				(unused, but passed for consistency)
 8131:  *		arg1 (I)	int unused
 8132:  *		arg2 (I)	int unused
 8133:  *		arg3 (I)	int unused
 8134:  * --------------------------------------------------------------------------
 8135:  * Returns:	( subraster * )	ptr to subraster corresponding to expression,
 8136:  *				or NULL for any parsing error
 8137:  *				(expression ptr unchanged if error occurs)
 8138:  * --------------------------------------------------------------------------
 8139:  * Notes:     o
 8140:  * ======================================================================= */
 8141: /* --- entry point --- */
 8142: subraster *rastsqrt ( char **expression, int size, subraster *basesp,
 8143: 			int arg1, int arg2, int arg3 )
 8144: {
 8145: /* -------------------------------------------------------------------------
 8146: Allocations and Declarations
 8147: -------------------------------------------------------------------------- */
 8148: char	*texsubexpr(), subexpr[MAXSUBXSZ+1], /*parse subexpr to be sqrt-ed*/
 8149: 	rootarg[MAXSUBXSZ+1];		/* optional \sqrt[rootarg]{...} */
 8150: subraster *rasterize(), *subsp=NULL;	/* rasterize subexpr */
 8151: subraster *accent_subraster(), *sqrtsp=NULL, /* subraster with the sqrt */
 8152: 	*new_subraster(), *rootsp=NULL;	/* optionally preceded by [rootarg]*/
 8153: int	sqrtheight=0, sqrtwidth=0, surdwidth=0,	/* height,width of sqrt */
 8154: 	rootheight=0, rootwidth=0,	/* height,width of rootarg raster */
 8155: 	subheight=0, subwidth=0, pixsz=0; /* height,width,pixsz of subexpr */
 8156: int	rastput();			/* put subexpr in constructed sqrt */
 8157: int	overspace = 2;			/*space between subexpr and overbar*/
 8158: int	delete_subraster();		/* free work areas */
 8159: /* -------------------------------------------------------------------------
 8160: Obtain subexpression to be sqrt-ed, and rasterize it
 8161: -------------------------------------------------------------------------- */
 8162: /* --- first check for optional \sqrt[rootarg]{...} --- */
 8163: if ( *(*expression) == '[' )		/*check for []-enclosed optional arg*/
 8164:   { *expression = texsubexpr(*expression,rootarg,0,"[","]",0,0);
 8165:     if ( *rootarg != '\000' )		/* got rootarg */
 8166:      if ( (rootsp=rasterize(rootarg,size-1)) /*rasterize it at smaller size*/
 8167:      != NULL )				/* rasterized successfully */
 8168:       {	rootheight = (rootsp->image)->height;  /* get height of rootarg */
 8169: 	rootwidth  = (rootsp->image)->width; } /* and its width */
 8170:   } /* --- end-of-if(**expression=='[') --- */
 8171: /* --- parse for subexpr to be sqrt-ed, and bump expression past it --- */
 8172: *expression = texsubexpr(*expression,subexpr,0,"{","}",0,0);
 8173: if ( *subexpr == '\000' )		/* couldn't get subexpression */
 8174:   goto end_of_job;			/* nothing to do, so quit */
 8175: /* --- rasterize subexpression to be accented --- */
 8176: if ( (subsp = rasterize(subexpr,size))	/*rasterize subexpr at original size*/
 8177: ==   NULL ) goto end_of_job;		/* quit if failed */
 8178: /* -------------------------------------------------------------------------
 8179: determine height and width of sqrt raster to be constructed
 8180: -------------------------------------------------------------------------- */
 8181: /* --- first get height and width of subexpr --- */
 8182: subheight = (subsp->image)->height;	/* height of subexpr */
 8183: subwidth  = (subsp->image)->width;	/* and its width */
 8184: pixsz     = (subsp->image)->pixsz;	/* pixsz remains constant */
 8185: /* --- determine height and width of sqrt to contain subexpr --- */
 8186: sqrtheight = subheight + overspace;	/* subexpr + blank line + overbar */
 8187: surdwidth  = SQRTWIDTH(sqrtheight);	/* width of surd */
 8188: sqrtwidth  = subwidth + surdwidth + 1;	/* total width */
 8189: /* -------------------------------------------------------------------------
 8190: construct sqrt (with room to move in subexpr) and embed subexpr in it
 8191: -------------------------------------------------------------------------- */
 8192: /* --- construct sqrt --- */
 8193: if ( (sqrtsp=accent_subraster(SQRTACCENT,sqrtwidth,sqrtheight,pixsz))
 8194: ==   NULL ) goto end_of_job;		/* quit if failed to build sqrt */
 8195: /* --- embed subexpr in sqrt at lower-right corner--- */
 8196: rastput(sqrtsp->image,subsp->image,overspace,sqrtwidth-subwidth,1);
 8197: sqrtsp->baseline = subsp->baseline + overspace; /* adjust baseline */
 8198: /* --- "embed" rootarg at upper-left --- */
 8199: if ( rootsp != NULL )			/*have optional \sqrt[rootarg]{...}*/
 8200:   {
 8201:   /* --- allocate full raster to contain sqrtsp and rootsp --- */
 8202:   int fullwidth = sqrtwidth +rootwidth - min2(rootwidth,max2(0,surdwidth-4)),
 8203:       fullheight= sqrtheight+rootheight- min2(rootheight,3+size);
 8204:   subraster *fullsp = new_subraster(fullwidth,fullheight,pixsz);
 8205:   if ( fullsp != NULL )			/* allocated successfully */
 8206:     { /* --- embed sqrtsp exactly at lower-right corner --- */
 8207:       rastput(fullsp->image,sqrtsp->image, /* exactly at lower-right corner*/
 8208: 	fullheight-sqrtheight,fullwidth-sqrtwidth,1);
 8209:       /* --- embed rootsp near upper-left, nestled above leading surd --- */
 8210:       rastput(fullsp->image,rootsp->image,
 8211: 	0,max2(0,surdwidth-rootwidth-2-size),0);
 8212:       /* --- replace sqrtsp with fullsp --- */
 8213:       delete_subraster(sqrtsp);		/* free original sqrtsp */
 8214:       sqrtsp = fullsp;			/* and repoint it to fullsp instead*/
 8215:       sqrtsp->baseline = fullheight - (subheight - subsp->baseline); }
 8216:   } /* --- end-of-if(rootsp!=NULL) --- */
 8217: /* --- initialize subraster parameters --- */
 8218: sqrtsp->size = size;			/* propagate font size forward */
 8219: /* -------------------------------------------------------------------------
 8220: free unneeded component subrasters and return final result to caller
 8221: -------------------------------------------------------------------------- */
 8222: end_of_job:
 8223:   if ( subsp != NULL ) delete_subraster(subsp); /* free unneeded subexpr */
 8224:   return ( sqrtsp );
 8225: } /* --- end-of-function rastsqrt() --- */
 8226: 
 8227: 
 8228: /* ==========================================================================
 8229:  * Function:	rastaccent (expression,size,basesp,accent,isabove,isscript)
 8230:  * Purpose:	\hat, \vec, \etc handler, returns a subraster corresponding
 8231:  *		to expression (immediately following \accent) at font size
 8232:  * --------------------------------------------------------------------------
 8233:  * Arguments:	expression (I/O) char **  to first char of null-terminated
 8234:  *				string immediately following \accent to be
 8235:  *				rasterized, and returning ptr immediately
 8236:  *				following last character processed.
 8237:  *		size (I)	int containing 0-4 default font size
 8238:  *		basesp (I)	subraster *  to character (or subexpression)
 8239:  *				immediately preceding \accent
 8240:  *				(unused, but passed for consistency)
 8241:  *		accent (I)	int containing HATACCENT or VECACCENT, etc,
 8242:  *				between numerator and denominator,
 8243:  *				or false not to draw it (for \over).
 8244:  *		isabove (I)	int containing true if accent is above
 8245:  *				expression to be accented, or false
 8246:  *				if accent is below (e.g., underbrace)
 8247:  *		isscript (I)	int containing true if sub/superscripts
 8248:  *				allowed (for under/overbrace), or 0 if not.
 8249:  * --------------------------------------------------------------------------
 8250:  * Returns:	( subraster * )	ptr to subraster corresponding to expression,
 8251:  *				or NULL for any parsing error
 8252:  *				(expression ptr unchanged if error occurs)
 8253:  * --------------------------------------------------------------------------
 8254:  * Notes:     o	Also handles \overbrace{}^{} and \underbrace{}_{} by way
 8255:  *		of isabove and isscript args.
 8256:  * ======================================================================= */
 8257: /* --- entry point --- */
 8258: subraster *rastaccent ( char **expression, int size, subraster *basesp,
 8259: 			int accent, int isabove, int isscript )
 8260: {
 8261: /* -------------------------------------------------------------------------
 8262: Allocations and Declarations
 8263: -------------------------------------------------------------------------- */
 8264: char	*texsubexpr(), subexpr[MAXSUBXSZ+1]; /*parse subexpr to be accented*/
 8265: char	*texscripts(), *script=NULL,	/* \under,overbrace allow scripts */
 8266: 	subscript[MAXTOKNSZ+1], supscript[MAXTOKNSZ+1];	/* parsed scripts */
 8267: subraster *rasterize(), *subsp=NULL, *scrsp=NULL; /*rasterize subexpr,script*/
 8268: subraster *rastack(), *accsubsp=NULL;	/* stack accent, subexpr, script */
 8269: subraster *accent_subraster(), *accsp=NULL; /*raster for the accent itself*/
 8270: int	accheight=0, accwidth=0,	/* height, width of accent */
 8271: 	subheight=0, subwidth=0, pixsz=0; /* height,width,pixsz of subexpr */
 8272: int	delete_subraster();		/*free work areas in case of error*/
 8273: int	vspace = 0;			/*vertical space between accent,sub*/
 8274: /* -------------------------------------------------------------------------
 8275: Obtain subexpression to be accented, and rasterize it
 8276: -------------------------------------------------------------------------- */
 8277: /* --- parse for subexpr to be accented, and bump expression past it --- */
 8278: *expression = texsubexpr(*expression,subexpr,0,"{","}",0,0);
 8279: if ( *subexpr=='\000' )			/* couldn't get subexpression */
 8280:   goto end_of_job;			/* nothing to do, so quit */
 8281: /* --- rasterize subexpression to be accented --- */
 8282: if ( (subsp = rasterize(subexpr,size))	/*rasterize subexpr at original size*/
 8283: ==   NULL ) goto end_of_job;		/* quit if failed */
 8284: /* -------------------------------------------------------------------------
 8285: determine desired accent width and height
 8286: -------------------------------------------------------------------------- */
 8287: /* --- first get height and width of subexpr --- */
 8288: subheight = (subsp->image)->height;	/* height of subexpr */
 8289: subwidth  = (subsp->image)->width;	/* and its width is overall width */
 8290: pixsz     = (subsp->image)->pixsz;	/* original pixsz remains constant */
 8291: /* --- determine desired width, height of accent --- */
 8292: accwidth = subwidth;			/* same width as subexpr */
 8293: accheight = 4;				/* default for bars */
 8294: switch ( accent )
 8295:   { default: break;			/* default okay */
 8296:   case DOTACCENT: case DDOTACCENT:
 8297:     accheight = (size<4? 3:4);		/* default for dots */
 8298:     break;
 8299:   case VECACCENT:
 8300:     vspace = 1;				/* set 1-pixel vertical space */
 8301:   case HATACCENT:
 8302:     accheight = 7;			/* default */
 8303:     if ( subwidth < 10 ) accheight = 5;	/* unless small width */
 8304:       else if ( subwidth > 25 ) accheight = 9; /* or large */
 8305:     break;
 8306:   } /* --- end-of-switch(accent) --- */
 8307: accheight = min2(accheight,subheight);	/*never higher than accented subexpr*/
 8308: /* -------------------------------------------------------------------------
 8309: construct accent, and construct subraster with accent over (or under) subexpr
 8310: -------------------------------------------------------------------------- */
 8311: /* --- first construct accent --- */
 8312: if ( (accsp = accent_subraster(accent,accwidth,accheight,pixsz)) /* accent */
 8313: ==   NULL ) goto end_of_job;		/* quit if failed to build accent */
 8314: /* --- now stack accent above (or below) subexpr, and free both args --- */
 8315: accsubsp = (isabove? rastack(subsp,accsp,1,vspace,1,3)/*accent above subexpr*/
 8316:            : rastack(accsp,subsp,2,vspace,1,3));      /*accent below subexpr*/
 8317: if ( accsubsp == NULL )			/* failed to stack accent */
 8318:   { delete_subraster(subsp);		/* free unneeded subsp */
 8319:     delete_subraster(accsp);		/* and unneeded accsp */
 8320:     goto end_of_job; }			/* and quit */
 8321: /* -------------------------------------------------------------------------
 8322: look for super/subscript (annotation for over/underbrace)
 8323: -------------------------------------------------------------------------- */
 8324: /* --- first check whether accent permits accompanying annotations --- */
 8325: if ( !isscript ) goto end_of_job;	/* no annotations for this accent */
 8326: /* --- now get scripts if there actually are any --- */
 8327: *expression = texscripts(*expression,subscript,supscript,(isabove?2:1));
 8328: script = (isabove? supscript : subscript); /*select above^ or below_ script*/
 8329: if ( *script == '\000' ) goto end_of_job; /* no accompanying script */
 8330: /* --- rasterize script annotation at size-2 --- */
 8331: if ( (scrsp = rasterize(script,size-2)) /* rasterize script at size-2 */
 8332: ==   NULL ) goto end_of_job;		/* quit if failed */
 8333: /* --- stack annotation above (or below) accent, and free both args --- */
 8334: accsubsp = (isabove? rastack(accsubsp,scrsp,1,0,1,3) /* accent above base */
 8335:            : rastack(scrsp,accsubsp,2,0,1,3));       /* accent below base */
 8336: /* -------------------------------------------------------------------------
 8337: return final result to caller
 8338: -------------------------------------------------------------------------- */
 8339: end_of_job:
 8340:   if ( accsubsp != NULL )		/* initialize subraster parameters */
 8341:     accsubsp->size = size;		/* propagate font size forward */
 8342:   return ( accsubsp );
 8343: } /* --- end-of-function rastaccent() --- */
 8344: 
 8345: 
 8346: /* ==========================================================================
 8347:  * Function:	rastfont (expression,size,basesp,ifontnum,arg2,arg3)
 8348:  * Purpose:	\cal{}, \scr{}, \etc handler, returns subraster corresponding
 8349:  *		to char(s) within {}'s rendered at size
 8350:  * --------------------------------------------------------------------------
 8351:  * Arguments:	expression (I/O) char **  to first char of null-terminated
 8352:  *				string immediately following \font to be
 8353:  *				rasterized, and returning ptr immediately
 8354:  *				following last character processed.
 8355:  *		size (I)	int containing 0-5 default font size
 8356:  *		basesp (I)	subraster *  to character (or subexpression)
 8357:  *				immediately preceding \accent
 8358:  *				(unused, but passed for consistency)
 8359:  *		ifontnum (I)	int containing 1 for \cal{}, 2 for \scr{}
 8360:  *		arg2 (I)	int unused
 8361:  *		arg3 (I)	int unused
 8362:  * --------------------------------------------------------------------------
 8363:  * Returns:	( subraster * )	ptr to subraster corresponding to chars
 8364:  *				between {}'s, or NULL for any parsing error
 8365:  * --------------------------------------------------------------------------
 8366:  * Notes:     o
 8367:  * ======================================================================= */
 8368: /* --- entry point --- */
 8369: subraster *rastfont ( char **expression, int size, subraster *basesp,
 8370: 			int ifontnum, int arg2, int arg3 )
 8371: {
 8372: /* -------------------------------------------------------------------------
 8373: Allocations and Declarations
 8374: -------------------------------------------------------------------------- */
 8375: char	*texsubexpr(), fontchars[MAXSUBXSZ+1], /* chars to render in font */
 8376: 	subexpr[MAXSUBXSZ+1];		/* turn \cal{AB} into \calA\calB */
 8377: char	*pfchars=fontchars, fchar='\0';	/* run thru fontchars one at a time*/
 8378: char	*name = NULL;			/* fontinfo[ifontnum].name */
 8379: int	family = 0,			/* fontinfo[ifontnum].family */
 8380: 	istext = 0,			/* fontinfo[ifontnum].istext */
 8381: 	class = 0;			/* fontinfo[ifontnum].class */
 8382: subraster *rasterize(), *fontsp=NULL,	/* rasterize chars in font */
 8383: 	*rastflags();			/* or just set flag to switch font */
 8384: int	oldsmashmargin = smashmargin;	/* turn off smash in text mode */
 8385: #if 0
 8386: /* --- fonts recognized by rastfont --- */
 8387: static	int  nfonts = 6;		/* legal font #'s are 1...nfonts */
 8388: static	struct {char *name; int class;}
 8389:   fonts[] =
 8390:     { /* --- name  class 1=upper,2=alpha,3=alnum,4=lower,5=digit,9=all --- */
 8391: 	{ "\\math",	0 },
 8392: 	{ "\\mathcal",	1 },		/*(1) calligraphic, uppercase */
 8393: 	{ "\\mathscr",	1 },		/*(2) rsfs/script, uppercase */
 8394: 	{ "\\textrm",	-1 },		/*(3) \rm,\text{abc} --> {\rm~abc} */
 8395: 	{ "\\textit",	-1 },		/*(4) \it,\textit{abc}-->{\it~abc} */
 8396: 	{ "\\mathbb",	-1 },		/*(5) \bb,\mathbb{abc}-->{\bb~abc} */
 8397: 	{ "\\mathbf",	-1 },		/*(6) \bf,\mathbf{abc}-->{\bf~abc} */
 8398: 	{ "\\mathrm",   -1 },		/*(7) \mathrm */
 8399: 	{ "\\cyr",      -1 },		/*(8) \cyr */
 8400: 	{ NULL,		0 }
 8401:     } ; /* --- end-of-fonts[] --- */
 8402: #endif
 8403: /* -------------------------------------------------------------------------
 8404: first get font name and class to determine type of conversion desired
 8405: -------------------------------------------------------------------------- */
 8406: if (ifontnum<=0 || ifontnum>nfontinfo) ifontnum=0; /*math if out-of-bounds*/
 8407: name   = fontinfo[ifontnum].name;	/* font name */
 8408: family = fontinfo[ifontnum].family;	/* font family */
 8409: istext = fontinfo[ifontnum].istext;	/*true in text mode (respect space)*/
 8410: class  = fontinfo[ifontnum].class;	/* font class */
 8411: if ( istext )				/* text (respect blanks) */
 8412:  { mathsmashmargin = smashmargin;	/* needed for \text{if $n-m$ even} */
 8413:    smashmargin = 0; }			/* don't smash internal blanks */
 8414: /* -------------------------------------------------------------------------
 8415: now convert \font{abc} --> {\font~abc}, or convert ABC to \calA\calB\calC
 8416: -------------------------------------------------------------------------- */
 8417: if ( 1 || class<0 )			/* not character-by-character */
 8418:  { 
 8419:  /* ---
 8420:  if \font not immediately followed by { then it has no arg, so just set flag
 8421:  ------------------------------------------------------------------------ */
 8422:  if ( *(*expression) != '{' )		/* no \font arg, so just set flag */
 8423:     {
 8424:     if ( msgfp!=NULL && msglevel>=99 )
 8425:      fprintf(msgfp,"rastfont> \\%s rastflags() for font#%d\n",name,ifontnum);
 8426:     fontsp = rastflags(expression,size,basesp,ISFONTFAM,ifontnum,arg3);
 8427:     goto end_of_job;
 8428:     } /* --- end-of-if(*(*expression)!='{') --- */
 8429:  /* ---
 8430:  convert \font{abc} --> {\font~abc}
 8431:  ---------------------------------- */
 8432:  /* --- parse for {fontchars} arg, and bump expression past it --- */
 8433:  *expression = texsubexpr(*expression,fontchars,0,"{","}",0,0);
 8434:  if ( msgfp!=NULL && msglevel>=99 )
 8435:   fprintf(msgfp,"rastfont> \\%s fontchars=\"%s\"\n",name,fontchars);
 8436:  /* --- convert all fontchars at the same time --- */
 8437:  strcpy(subexpr,"{");			/* start off with opening { */
 8438:  strcat(subexpr,name);			/* followed by font name */
 8439:  strcat(subexpr,"~");			/* followed by whitespace */
 8440:  strcat(subexpr,fontchars);		/* followed by all the chars */
 8441:  strcat(subexpr,"}");			/* terminate with closing } */
 8442:  } /* --- end-of-if(class<0) --- */
 8443: else					/* character-by-character */
 8444:  {
 8445:  /* ---
 8446:  convert ABC to \calA\calB\calC
 8447:  ------------------------------ */
 8448:  int	isprevchar=0;			/* true if prev char converted */
 8449:  /* --- parse for {fontchars} arg, and bump expression past it --- */
 8450:  *expression = texsubexpr(*expression,fontchars,0,"{","}",0,0);
 8451:  if ( msgfp!=NULL && msglevel>=99 )
 8452:   fprintf(msgfp,"rastfont> \\%s fontchars=\"%s\"\n",name,fontchars);
 8453:  /* --- convert fontchars one at a time --- */
 8454:  strcpy(subexpr,"{\\rm~");		/* start off with opening {\rm */
 8455:  strcpy(subexpr,"{");			/* nope, just start off with { */
 8456:  for ( pfchars=fontchars; (fchar= *pfchars)!='\000'; pfchars++ )
 8457:   {
 8458:   if ( isthischar(fchar,WHITEMATH) )	/* some whitespace */
 8459:     { if ( 0 || istext )		/* and we're in a text mode font */
 8460: 	strcat(subexpr,"\\;"); }	/* so respect whitespace */
 8461:   else					/* char to be displayed in font */
 8462:     { int exprlen = 0;			/* #chars in subexpr before fchar */
 8463:       int isinclass = 0;		/* set true if fchar in font class */
 8464:       /* --- class: 1=upper, 2=alpha, 3=alnum, 4=lower, 5=digit, 9=all --- */
 8465:       switch ( class )			/* check if fchar is in font class */
 8466: 	{ default: break;		/* no chars in unrecognized class */
 8467: 	  case 1: if ( isupper((int)fchar) ) isinclass=1; break;
 8468: 	  case 2: if ( isalpha((int)fchar) ) isinclass=1; break;
 8469: 	  case 3: if ( isalnum((int)fchar) ) isinclass=1; break;
 8470: 	  case 4: if ( islower((int)fchar) ) isinclass=1; break;
 8471: 	  case 5: if ( isdigit((int)fchar) ) isinclass=1; break;
 8472: 	  case 9: isinclass=1; break; }
 8473:       if ( isinclass )			/* convert current char to \font */
 8474: 	{ strcat(subexpr,name);		/* by prefixing it with font name */
 8475: 	  isprevchar = 1; }		/* and set flag to signal separator*/
 8476:       else				/* current char not in \font */
 8477: 	{ if ( isprevchar )		/* extra separator only after \font*/
 8478: 	   if ( isalpha(fchar) )	/* separator only before alpha */
 8479: 	    strcat(subexpr,"~");	/* need separator after \font */
 8480: 	  isprevchar = 0; }		/* reset flag for next char */
 8481:       exprlen = strlen(subexpr);	/* #chars so far */
 8482:       subexpr[exprlen] = fchar;		/*fchar immediately after \fontname*/
 8483:       subexpr[exprlen+1] = '\000'; }	/* replace terminating '\0' */
 8484:   } /* --- end-of-for(pfchars) --- */
 8485:  strcat(subexpr,"}");			/* add closing } */
 8486:  } /* --- end-of-if/else(class<0) --- */
 8487: /* -------------------------------------------------------------------------
 8488: rasterize subexpression containing chars to be rendered at font
 8489: -------------------------------------------------------------------------- */
 8490: if ( msgfp!=NULL && msglevel>=99 )
 8491:   fprintf(msgfp,"rastfont> subexpr=\"%s\"\n",subexpr);
 8492: if ( (fontsp = rasterize(subexpr,size))	/* rasterize chars in font */
 8493: ==   NULL ) goto end_of_job;		/* and quit if failed */
 8494: /* -------------------------------------------------------------------------
 8495: back to caller with chars rendered in font
 8496: -------------------------------------------------------------------------- */
 8497: end_of_job:
 8498:   smashmargin = oldsmashmargin;		/* restore smash */
 8499:   mathsmashmargin = SMASHMARGIN;	/* this one probably not necessary */
 8500:   if ( istext && fontsp!=NULL )		/* raster contains text mode font */
 8501:     fontsp->type = blanksignal;		/* signal nosmash */
 8502:   return ( fontsp );			/* chars rendered in font */
 8503: } /* --- end-of-function rastfont() --- */
 8504: 
 8505: 
 8506: /* ==========================================================================
 8507:  * Function:	rastbegin ( expression, size, basesp, arg1, arg2, arg3 )
 8508:  * Purpose:	\begin{}...\end{}  handler, returns a subraster corresponding
 8509:  *		to array expression within environment, i.e., rewrites
 8510:  *		\begin{}...\end{} as mimeTeX equivalent, and rasterizes that.
 8511:  * --------------------------------------------------------------------------
 8512:  * Arguments:	expression (I/O) char **  to first char of null-terminated
 8513:  *				string immediately following \begin to be
 8514:  *				rasterized, and returning ptr immediately
 8515:  *				following last character processed.
 8516:  *		size (I)	int containing 0-4 default font size
 8517:  *		basesp (I)	subraster *  to character (or subexpression)
 8518:  *				immediately preceding \begin
 8519:  *				(unused, but passed for consistency)
 8520:  *		arg1 (I)	int unused
 8521:  *		arg2 (I)	int unused
 8522:  *		arg3 (I)	int unused
 8523:  * --------------------------------------------------------------------------
 8524:  * Returns:	( subraster * )	ptr to subraster corresponding to array
 8525:  *				expression, or NULL for any parsing error
 8526:  * --------------------------------------------------------------------------
 8527:  * Notes:     o
 8528:  * ======================================================================= */
 8529: /* --- entry point --- */
 8530: subraster *rastbegin ( char **expression, int size, subraster *basesp,
 8531: 			int arg1, int arg2, int arg3 )
 8532: {
 8533: /* -------------------------------------------------------------------------
 8534: Allocations and Declarations
 8535: -------------------------------------------------------------------------- */
 8536: char	*texsubexpr(), subexpr[MAXSUBXSZ+1], /* \begin{} environment params*/
 8537: 	*exprptr=NULL,*begptr=NULL,*endptr=NULL,*braceptr=NULL; /* ptrs */
 8538: char	*begtoken="\\begin{", *endtoken="\\end{"; /*tokens we're looking for*/
 8539: int	strreplace();			/* replace substring in string */
 8540: char	*strchange();			/*\begin...\end --> {\begin...\end}*/
 8541: char	*delims = (char *)NULL;		/* mdelims[ienviron] */
 8542: subraster *rasterize(), *sp=NULL;	/* rasterize environment */
 8543: int	ienviron = 0;			/* environs[] index */
 8544: int	nbegins = 0;			/* #\begins nested beneath this one*/
 8545: int	envlen=0, sublen=0;		/* #chars in environ, subexpr */
 8546: static	int blevel = 0;			/* \begin...\end nesting level */
 8547: static	char *mdelims[] = { NULL, NULL, NULL, NULL,
 8548: 	"()","[]","{}","||","==",	/* for pbBvVmatrix */
 8549: 	NULL, NULL, NULL, NULL, "{.", NULL, NULL, NULL, NULL, NULL, NULL,
 8550: 	NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL };
 8551: static	char *environs[] = {		/* types of environments we process*/
 8552: 	"eqnarray",			/* 0 eqnarray environment */
 8553: 	"array",			/* 1 array environment */
 8554: 	"matrix",			/* 2 array environment */
 8555: 	"tabular",			/* 3 array environment */
 8556: 	"pmatrix",			/* 4 ( ) */
 8557: 	"bmatrix",			/* 5 [ ] */
 8558: 	"Bmatrix",			/* 6 { } */
 8559: 	"vmatrix",			/* 7 | | */
 8560: 	"Vmatrix",			/* 8 || || */
 8561: 	"gather",			/* 9 gather environment */
 8562: 	"align",			/* 10 align environment */
 8563: 	"verbatim",			/* 11 verbatim environment */
 8564: 	"picture",			/* 12 picture environment */
 8565: 	"cases",			/* 13 cases environment */
 8566: 	"equation",			/* 14 for \begin{equation} */
 8567: 	NULL };				/* trailer */
 8568: /* -------------------------------------------------------------------------
 8569: determine type of environment we're beginning
 8570: -------------------------------------------------------------------------- */
 8571: /* --- first bump nesting level --- */
 8572: blevel++;				/* count \begin...\begin...'s */
 8573: /* --- \begin must be followed by {type_of_environment} --- */
 8574: exprptr = texsubexpr(*expression,subexpr,0,"{","}",0,0);
 8575: if ( *subexpr == '\000' ) goto end_of_job; /* no environment given */
 8576: while ( (delims=strchr(subexpr,'*')) != NULL ) /* have environment* */
 8577:   strcpy(delims,delims+1);		/* treat it as environment */
 8578: /* --- look up environment in our table --- */
 8579: for ( ienviron=0; ;ienviron++ )		/* search table till NULL */
 8580:   if ( environs[ienviron] == NULL )	/* found NULL before match */
 8581:     goto end_of_job;			/* so quit */
 8582:   else					/* see if we have an exact match */
 8583:     if ( memcmp(environs[ienviron],subexpr,strlen(subexpr)) == 0 ) /*match*/
 8584:       break;				/* leave loop with ienviron index */
 8585: /* --- accumulate any additional params for this environment --- */
 8586: *subexpr = '\000';			/* reset subexpr to empty string */
 8587: delims = mdelims[ienviron];		/* mdelims[] string for ienviron */
 8588: if ( delims != NULL )			/* add appropriate opening delim */
 8589:   { strcpy(subexpr,"\\");		/* start with \ for (,[,{,|,= */
 8590:     strcat(subexpr,delims);		/* then add opening delim */
 8591:     subexpr[2] = '\000'; }		/* remove extraneous closing delim */
 8592: switch ( ienviron )
 8593:   {
 8594:   default: goto end_of_job;		/* environ not implemented yet */
 8595:   case 0:				/* \begin{eqnarray} */
 8596:     strcpy(subexpr,"\\array{rcl$");	/* set default rcl for eqnarray */
 8597:     break;
 8598:   case 1:  case 2:  case 3:		/* \begin{array} followed by {lcr} */
 8599:     strcpy(subexpr,"\\array{");		/*start with mimeTeX \array{ command*/
 8600:     skipwhite(exprptr);			/* bump to next non-white char */
 8601:     if ( *exprptr == '{' )		/* assume we have {lcr} argument */
 8602:       {	exprptr = texsubexpr(exprptr,subexpr+7,0,"{","}",0,0); /*add on lcr*/
 8603: 	if ( *(subexpr+7) == '\000' ) goto end_of_job; /* quit if no lcr */
 8604: 	strcat(subexpr,"$"); }		/* add terminating $ to lcr */
 8605:     break;
 8606:   case 4:  case 5:  case 6:		/* \begin{pmatrix} or b,B,v,Vmatrix */
 8607:   case 7:  case 8:
 8608:     strcat(subexpr,"\\array{");		/*start with mimeTeX \array{ command*/
 8609:     break;
 8610:   case 9:				/* gather */
 8611:     strcat(subexpr,"\\array{c$");	/* center equations */
 8612:     break;
 8613:   case 10:				/* align */
 8614:     strcat(subexpr,"\\array{rclrclrclrclrclrcl$"); /* a&=b & c&=d & etc */
 8615:     break;
 8616:   case 11:				/* verbatim */
 8617:     strcat(subexpr,"{\\rm ");		/* {\rm ...} */
 8618:     /*strcat(subexpr,"\\\\{\\rm ");*/	/* \\{\rm } doesn't work in context */
 8619:     break;
 8620:   case 12:				/* picture */
 8621:     strcat(subexpr,"\\picture");	/* picture environment */
 8622:     skipwhite(exprptr);			/* bump to next non-white char */
 8623:     if ( *exprptr == '(' )		/*assume we have (width,height) arg*/
 8624:       {	exprptr = texsubexpr(exprptr,subexpr+8,0,"(",")",0,1); /*add on arg*/
 8625: 	if ( *(subexpr+8) == '\000' ) goto end_of_job; } /* quit if no arg */
 8626:     strcat(subexpr,"{");		/* opening {  after (width,height) */
 8627:     break;
 8628:   case 13:				/* cases */
 8629:     strcat(subexpr,"\\array{ll$");	/* a&b \\ c&d etc */
 8630:     break;
 8631:   case 14:				/* \begin{equation} */
 8632:     strcat(subexpr,"{");		/* just enclose expression in {}'s */
 8633:     break;
 8634:   } /* --- end-of-switch(ienviron) --- */
 8635: /* -------------------------------------------------------------------------
 8636: locate matching \end{...}
 8637: -------------------------------------------------------------------------- */
 8638: /* --- first \end following \begin --- */
 8639: if ( (endptr=strstr(exprptr,endtoken))	/* find 1st \end following \begin */
 8640: ==   NULL ) goto end_of_job;		/* and quit if no \end found */
 8641: /* --- find matching endptr by pushing past any nested \begin's --- */
 8642: begptr = exprptr;			/* start after first \begin{...} */
 8643: while ( 1 )				/*break when we find matching \end*/
 8644:   {
 8645:   /* --- first, set ptr to closing } terminating current \end{...} --- */
 8646:   if ( (braceptr=strchr(endptr+1,'}'))	/* find 1st } following \end{ */
 8647:   ==   NULL ) goto end_of_job;		/* and quit if no } found */
 8648:   /* -- locate next nested \begin --- */
 8649:   if ( (begptr=strstr(begptr,begtoken))	/* find next \begin{...} */
 8650:   ==   NULL ) break;			/*no more, so we have matching \end*/
 8651:   begptr += strlen(begtoken);		/* push ptr past token */
 8652:   if ( begptr >= endptr ) break;	/* past endptr, so not nested */
 8653:   /* --- have nested \begin, so push forward to next \end --- */
 8654:   nbegins++;				/* count another nested \begin */
 8655:   if ( (endptr=strstr(endptr+strlen(endtoken),endtoken)) /* find next \end */
 8656:   ==   NULL ) goto end_of_job;		/* and quit if none found */
 8657:   } /* --- end-of-while(1) --- */
 8658: /* --- push expression past closing } of \end{} --- */
 8659: *expression = braceptr+1;		/* resume processing after } */
 8660: /* -------------------------------------------------------------------------
 8661: add on everything (i.e., the ...'s) between \begin{}[{}] ... \end{}
 8662: -------------------------------------------------------------------------- */
 8663: /* --- add on everything, completing subexpr for \begin{}...\end{} --- */
 8664: sublen = strlen(subexpr);		/* #chars in "preamble" */
 8665: envlen = (int)(endptr-exprptr);		/* #chars between \begin{}{}...\end */
 8666: memcpy(subexpr+sublen,exprptr,envlen);	/*concatanate environ after subexpr*/
 8667: subexpr[sublen+envlen] = '\000';	/* and null-terminate */
 8668: if ( 2 > 1 )				/* always... */
 8669:   strcat(subexpr,"}");			/* ...followed by terminating } */
 8670: /* --- add terminating \right), etc, if necessary --- */
 8671: if ( delims != (char *)NULL )		/* need closing delim */
 8672:  { strcat(subexpr,"\\");		/* start with \ for ),],},|,= */
 8673:    strcat(subexpr,delims+1); }		/* add appropriate closing delim */
 8674: /* -------------------------------------------------------------------------
 8675: change nested \begin...\end to {\begin...\end} so \array{} can handle them
 8676: -------------------------------------------------------------------------- */
 8677: if ( nbegins > 0 )			/* have nested begins */
 8678:  if ( blevel < 2 )			/* only need to do this once */
 8679:   {
 8680:   begptr = subexpr;			/* start at beginning of subexpr */
 8681:   while( (begptr=strstr(begptr,begtoken)) != NULL ) /* have \begin{...} */
 8682:     { strchange(0,begptr,"{");		/* \begin --> {\begin */
 8683:       begptr += strlen(begtoken); }	/* continue past {\begin */
 8684:   endptr = subexpr;			/* start at beginning of subexpr */
 8685:   while( (endptr=strstr(endptr,endtoken)) != NULL ) /* have \end{...} */
 8686:     if ( (braceptr=strchr(endptr+1,'}')) /* find 1st } following \end{ */
 8687:     ==   NULL ) goto end_of_job;	/* and quit if no } found */
 8688:     else				/* found terminating } */
 8689:      { strchange(0,braceptr,"}");	/* \end{...} --> \end{...}} */
 8690:        endptr = braceptr+1; }		/* continue past \end{...} */
 8691:   } /* --- end-of-if(nbegins>0) --- */
 8692: /* -------------------------------------------------------------------------
 8693: post process as necessary
 8694: -------------------------------------------------------------------------- */
 8695: switch ( ienviron )
 8696:   {
 8697:   default: break;			/* no post-processing required */
 8698:   case 10:				/* align */
 8699:     strreplace(subexpr,"&=","#*@*#=",0); /* tag all &='s */
 8700:     strreplace(subexpr,"&<","#*@*#<",0); /* tag all &<'s */
 8701:     strreplace(subexpr,"&\\lt","#*@*#<",0); /* tag all &\lt's */
 8702:     strreplace(subexpr,"&\\leq","#*@*#\\leq",0); /* tag all &\leq's */
 8703:     strreplace(subexpr,"&>","#*@*#>",0); /* tag all &>'s */
 8704:     strreplace(subexpr,"&\\gt","#*@*#>",0); /* tag all &\gt's */
 8705:     strreplace(subexpr,"&\\geq","#*@*#\\geq",0); /* tag all &\geq's */
 8706:     if ( nbegins < 1 )			/* don't modify nested arrays */
 8707:       strreplace(subexpr,"&","\\hspace{10}&\\hspace{10}",0); /* add space */
 8708:     strreplace(subexpr,"#*@*#=","& = &",0); /*restore and xlate tagged &='s*/
 8709:     strreplace(subexpr,"#*@*#<","& \\lt &",0); /*restore, xlate tagged &<'s*/
 8710:     strreplace(subexpr,"#*@*#\\leq","& \\leq &",0); /*xlate tagged &\leq's*/
 8711:     strreplace(subexpr,"#*@*#>","& \\gt &",0); /*restore, xlate tagged &>'s*/
 8712:     strreplace(subexpr,"#*@*#\\geq","& \\geq &",0); /*xlate tagged &\geq's*/
 8713:     break;
 8714:   case 11:				/* verbatim */
 8715:     strreplace(subexpr,"\n","\\\\",0);	/* xlate \n newline to latex \\ */
 8716:     /*strcat(subexpr,"\\\\");*/		/* add final latex \\ newline */
 8717:     break;
 8718:   case 12:				/* picture */
 8719:     strreplace(subexpr,"\\put "," ",0);	/*remove \put's (not really needed)*/
 8720:     strreplace(subexpr,"\\put(","(",0);	/*remove \put's (not really needed)*/
 8721:     strreplace(subexpr,"\\oval","\\circle",0); /* actually an ellipse */
 8722:     break;
 8723:   } /* --- end-of-switch(ienviron) --- */
 8724: /* -------------------------------------------------------------------------
 8725: return rasterized mimeTeX equivalent of \begin{}...\end{} environment
 8726: -------------------------------------------------------------------------- */
 8727: /* --- debugging output --- */
 8728: if ( msgfp!=NULL && msglevel>=99 )
 8729:   fprintf(msgfp,"rastbegin> subexpr=%s\n",subexpr);
 8730: /* --- rasterize mimeTeX equivalent of \begin{}...\end{} environment --- */
 8731: sp = rasterize(subexpr,size);		/* rasterize subexpr */
 8732: end_of_job:
 8733:   blevel--;				/* decrement \begin nesting level */
 8734:   return ( sp );			/* back to caller with sp or NULL */
 8735: } /* --- end-of-function rastbegin() --- */
 8736: 
 8737: 
 8738: /* ==========================================================================
 8739:  * Function:	rastarray ( expression, size, basesp, arg1, arg2, arg3 )
 8740:  * Purpose:	\array handler, returns a subraster corresponding to array
 8741:  *		expression (immediately following \array) at font size
 8742:  * --------------------------------------------------------------------------
 8743:  * Arguments:	expression (I/O) char **  to first char of null-terminated
 8744:  *				string immediately following \array to be
 8745:  *				rasterized, and returning ptr immediately
 8746:  *				following last character processed.
 8747:  *		size (I)	int containing 0-4 default font size
 8748:  *		basesp (I)	subraster *  to character (or subexpression)
 8749:  *				immediately preceding \array
 8750:  *				(unused, but passed for consistency)
 8751:  *		arg1 (I)	int unused
 8752:  *		arg2 (I)	int unused
 8753:  *		arg3 (I)	int unused
 8754:  * --------------------------------------------------------------------------
 8755:  * Returns:	( subraster * )	ptr to subraster corresponding to array
 8756:  *				expression, or NULL for any parsing error
 8757:  * --------------------------------------------------------------------------
 8758:  * Notes:     o	Summary of syntax...
 8759:  *			\array{3,lcrBC$a&b&c\\d&e&f\\etc}
 8760:  *	      o	The 3,lcrBC$ part is an optional "preamble".  The lcr means
 8761:  *		what you think, i.e., "horizontal" left,center,right
 8762:  *		justification down corresponding column.  The new BC means
 8763:  *		"vertical" baseline,center justification across corresponding
 8764:  *		row.  The leading 3 specifies the font size 0-4 to be used.
 8765:  *		You may also specify +1,-1,+2,-2, etc, which is used as an
 8766:  *		increment to the current font size, e.g., -1,lcr$ uses
 8767:  *		one font size smaller than current.  Without a leading
 8768:  *		+ or -, the font size is "absolute".
 8769:  *	      o	The preamble can also be just lcrBC$ without a leading
 8770:  *		size-part, or just 3$ without a trailing lcrBC-part.
 8771:  *		The default size is whatever is current, and the
 8772:  *		default justification is c(entered) and B(aseline).
 8773:  * ======================================================================= */
 8774: /* --- entry point --- */
 8775: subraster *rastarray ( char **expression, int size, subraster *basesp,
 8776: 			int arg1, int arg2, int arg3 )
 8777: {
 8778: /* -------------------------------------------------------------------------
 8779: Allocations and Declarations
 8780: -------------------------------------------------------------------------- */
 8781: char	*texsubexpr(), subexpr[MAXSUBXSZ+1], *exprptr, /*parse array subexpr*/
 8782: 	 subtok[MAXTOKNSZ+1], *subptr=subtok, /* &,\\ inside { } not a delim*/
 8783: 	 token[MAXTOKNSZ+1],  *tokptr=token, /* subexpr token to rasterize */
 8784: 	*preamble(),   *preptr=token;	/*process optional size,lcr preamble*/
 8785: char	*coldelim="&", *rowdelim="\\";	/* need escaped rowdelim */
 8786: int	maxarraysz = 64;		/* max #rows, cols */
 8787: int	justify[65]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* -1,0,+1 = l,c,r */
 8788: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
 8789: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
 8790: 	  hline[65]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* hline above row? */
 8791: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
 8792: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
 8793: 	  vline[65]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /*vline left of col?*/
 8794: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
 8795: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
 8796:        colwidth[65]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /*widest tokn in col*/
 8797: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
 8798: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
 8799:       rowheight[65]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* "highest" in row */
 8800: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
 8801: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
 8802:      fixcolsize[65]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /*1=fixed col width*/
 8803: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
 8804: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
 8805:      fixrowsize[65]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /*1=fixed row height*/
 8806: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
 8807: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
 8808:       rowbaseln[65]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* baseline for row */
 8809: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
 8810: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
 8811:       rowcenter[65]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /*true = vcenter row*/
 8812: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
 8813: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
 8814: static int /* --- propagate global values across arrays --- */
 8815:        gjustify[65]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* -1,0,+1 = l,c,r */
 8816: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
 8817: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
 8818:       gcolwidth[65]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /*widest tokn in col*/
 8819: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
 8820: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
 8821:      growheight[65]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* "highest" in row */
 8822: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
 8823: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
 8824:     gfixcolsize[65]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /*1=fixed col width*/
 8825: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
 8826: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
 8827:     gfixrowsize[65]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /*1=fixed row height*/
 8828: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
 8829: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
 8830:      growcenter[65]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /*true = vcenter row*/
 8831: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
 8832: 	               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
 8833: int	rowglobal=0, colglobal=0,	/* true to set global values */
 8834: 	rowpropagate=0, colpropagate=0;	/* true if propagating values */
 8835: int	irow,nrows=0, icol,ncols[65],	/*#rows in array, #cols in each row*/
 8836: 	maxcols=0;			/* max# cols in any single row */
 8837: int	itoken, ntokens=0,		/* index, total #tokens in array */
 8838: 	subtoklen=0,			/* strlen of {...} subtoken */
 8839: 	istokwhite=1,			/* true if token all whitespace */
 8840: 	nnonwhite=0;			/* #non-white tokens */
 8841: int	isescape=0,wasescape=0,		/* current,prev chars escape? */
 8842: 	ischarescaped=0,		/* is current char escaped? */
 8843: 	nescapes=0;			/* #consecutive escapes */
 8844: subraster *rasterize(), *toksp[1025],	/* rasterize tokens */
 8845: 	*new_subraster(), *arraysp=NULL; /* subraster for entire array */
 8846: raster	*arrayrp=NULL;			/* raster for entire array */
 8847: int	delete_subraster();		/* free toksp[] workspace at eoj */
 8848: int	rowspace=2, colspace=4,		/* blank space between rows, cols */
 8849: 	hspace=1, vspace=1;		/*space to accommodate hline,vline*/
 8850: int	width=0, height=0,		/* width,height of array */
 8851: 	leftcol=0, toprow=0;		/*upper-left corner for cell in it*/
 8852: int	rastput();			/* embed tokens/cells in array */
 8853: int	rule_raster();			/* draw hlines and vlines in array */
 8854: char	*hlchar="\\hline", *hdchar="\\hdash"; /* token signals hline */
 8855: char	*texchar(), hltoken[1025];	/* extract \hline from token */
 8856: int	ishonly=0, hltoklen, minhltoklen=3; /*flag, token must be \hl or \hd*/
 8857: int	isnewrow=1;			/* true for new row */
 8858: int	pixsz = 1;			/*default #bits per pixel, 1=bitmap*/
 8859: /* -------------------------------------------------------------------------
 8860: Macros to determine extra raster space required for vline/hline
 8861: -------------------------------------------------------------------------- */
 8862: #define	vlinespace(icol) \
 8863: 	( vline[icol] == 0?  0 :	/* no vline so no space needed */   \
 8864: 	  ( icol<1 || icol>=maxcols? vspace+(colspace+1)/2 : vspace ) )
 8865: #define	hlinespace(irow) \
 8866: 	( hline[irow] == 0?  0 :	/* no hline so no space needed */   \
 8867: 	  ( irow<1 || irow>=nrows? hspace+(rowspace+1)/2 : hspace ) )
 8868: /* -------------------------------------------------------------------------
 8869: Obtain array subexpression
 8870: -------------------------------------------------------------------------- */
 8871: /* --- parse for array subexpression, and bump expression past it --- */
 8872: subexpr[1] = *subexpr = ' ';		/* set two leading blanks */
 8873: *expression = texsubexpr(*expression,subexpr+2,0,"{","}",0,0);
 8874: if ( msglevel>=29 && msgfp!=NULL )	/* debugging, display array */
 8875:   fprintf(msgfp,"rastarray> %.256s\n",subexpr+2);
 8876: if ( *(subexpr+2)=='\000' )		/* couldn't get subexpression */
 8877:   goto end_of_job;			/* nothing to do, so quit */
 8878: /* -------------------------------------------------------------------------
 8879: process optional size,lcr preamble if present
 8880: -------------------------------------------------------------------------- */
 8881: /* --- reset size, get lcr's, and push exprptr past preamble --- */
 8882: exprptr = preamble(subexpr+2,&size,preptr); /* reset size and get lcr's */
 8883: /* --- init with global values --- */
 8884: for(icol=0; icol<=maxarraysz; icol++) {	/* propagate global values... */
 8885:   justify[icol] = gjustify[icol];	/* -1,0,+1 = l,c,r */
 8886:   colwidth[icol] = gcolwidth[icol];	/* column width */
 8887:   rowheight[icol] = growheight[icol];	/* row height */
 8888:   fixcolsize[icol] = gfixcolsize[icol];	/* 1=fixed col width */
 8889:   fixrowsize[icol] = gfixrowsize[icol];	/* 1=fixed row height */
 8890:   rowcenter[icol] = growcenter[icol]; }	/* true = vcenter row */
 8891: /* --- process lcr's, etc in preamble --- */
 8892: itoken = 0;				/* debugging flag */
 8893: if ( msglevel>=29 && msgfp!=NULL )	/* debugging, display preamble */
 8894:  if ( *preptr != '\000' )		/* if we have one */
 8895:   fprintf(msgfp,"rastarray> preamble= \"%.256s\"\nrastarray> preamble: ",
 8896:   preptr);
 8897: irow = icol = 0;			/* init lcr counts */
 8898: while (  *preptr != '\000' )		/* check preamble text for lcr */
 8899:   {
 8900:   char	prepchar = *preptr;		/* current preamble character */
 8901:   int	prepcase = (islower(prepchar)?1:(isupper(prepchar)?2:0)); /*1,2,or 0*/
 8902:   if ( irow<maxarraysz && icol<maxarraysz )
 8903:    switch ( /*tolower*/(prepchar) )
 8904:     {  default: break;			/* just flush unrecognized chars */
 8905:       case 'l': justify[icol] = (-1);		/*left-justify this column*/
 8906: 		if (colglobal) gjustify[irow] = justify[irow]; break;
 8907:       case 'c': justify[icol] = (0);		/* center this column */
 8908: 		if (colglobal) gjustify[irow] = justify[irow]; break;
 8909:       case 'r': justify[icol] = (+1);		/* right-justify this col */
 8910: 		if (colglobal) gjustify[irow] = justify[irow]; break;
 8911:       case '|': vline[icol] += 1;   break;	/* solid vline left of col */
 8912:       case '.': vline[icol] = (-1); break;	/*dashed vline left of col */
 8913:       case 'b': prepchar='B'; prepcase=2;	/* alias for B */
 8914:       case 'B': break;				/* baseline-justify row */
 8915:       case 'v': prepchar='C'; prepcase=2;	/* alias for C */
 8916:       case 'C': rowcenter[irow] = 1;		/* vertically center row */
 8917: 		if (rowglobal) growcenter[irow] = rowcenter[irow]; break;
 8918:       case 'g': colglobal=1; prepcase=0; break;	/* set global col values */
 8919:       case 'G': rowglobal=1; prepcase=0; break;	/* set global row values */
 8920:       case '#': colglobal=rowglobal=1; break; }	/* set global col,row vals */
 8921:   if ( msglevel>=29 && msgfp!=NULL )	/* debugging */
 8922:     fprintf(msgfp," %c[%d]",prepchar,
 8923:     (prepcase==1?icol+1:(prepcase==2?irow+1:0)));
 8924:   preptr++;				/* check next char for lcr */
 8925:   itoken++;				/* #lcr's processed (debugging only)*/
 8926:   /* --- check for number or +number specifying colwidth or rowheight --- */
 8927:   if ( prepcase != 0 )			/* only check upper,lowercase */
 8928:    {
 8929:    int	ispropagate = (*preptr=='+'?1:0); /* leading + propagates width/ht */
 8930:    if ( ispropagate ) {			/* set row or col propagation */
 8931:      if ( prepcase == 1 ) colpropagate = 1; /* propagating col values */
 8932:      else if ( prepcase == 2 ) rowpropagate = 1; } /*propagating row values*/
 8933:    if ( !colpropagate && prepcase == 1 )
 8934:       {	colwidth[icol] = 0;		/* reset colwidth */
 8935: 	fixcolsize[icol] = 0; }		/* reset width flag */
 8936:    if ( !rowpropagate && prepcase == 2 )
 8937:       {	rowheight[irow] = 0;		/* reset row height */
 8938: 	fixrowsize[irow] = 0; }		/* reset height flag */
 8939:    if ( ispropagate ) preptr++;		/* bump past leading + */
 8940:    if ( isdigit(*preptr) )		/* digit follows character */
 8941:      { char *endptr = NULL;		/* preptr set to 1st char after num*/
 8942:        int size = (int)(strtol(preptr,&endptr,10)); /* interpret number */
 8943:        char *whchars="?wh";		/* debugging width/height labels */
 8944:        preptr = endptr;			/* skip over all digits */
 8945:        if ( size==0 || (size>=3&&size<=500) ) { /* sanity check */
 8946: 	int index;			/* icol,irow...maxarraysz index */
 8947: 	if ( prepcase == 1 )		/* lowercase signifies colwidth */
 8948: 	 for(index=icol; index<=maxarraysz; index++) { /*propagate col size*/
 8949: 	  colwidth[index] = size;	/* set colwidth to fixed size */
 8950: 	  fixcolsize[index] = (size>0?1:0); /* set fixed width flag */
 8951: 	  justify[index] = justify[icol]; /* and propagate justification */
 8952: 	  if ( colglobal ) {		/* set global values */
 8953: 	    gcolwidth[index] = colwidth[index]; /* set global col width */
 8954: 	    gfixcolsize[index] = fixcolsize[index]; /*set global width flag*/
 8955: 	    gjustify[index] = justify[icol]; } /* set global col justify */
 8956: 	  if ( !ispropagate ) break; }	/* don't propagate */
 8957: 	else				/* uppercase signifies rowheight */
 8958: 	 for(index=irow; index<=maxarraysz; index++) { /*propagate row size*/
 8959: 	  rowheight[index] = size;	/* set rowheight to size */
 8960: 	  fixrowsize[index] = (size>0?1:0); /* set fixed height flag */
 8961: 	  rowcenter[index] = rowcenter[irow]; /* and propagate row center */
 8962: 	  if ( rowglobal ) {		/* set global values */
 8963: 	    growheight[index] = rowheight[index]; /* set global row height */
 8964: 	    gfixrowsize[index] = fixrowsize[index]; /*set global height flag*/
 8965: 	    growcenter[index] = rowcenter[irow]; } /*set global row center*/
 8966: 	  if ( !ispropagate ) break; }	/* don't propagate */
 8967:         } /* --- end-of-if(size>=3&&size<=500) --- */
 8968:        if ( msglevel>=29 && msgfp!=NULL ) /* debugging */
 8969: 	 fprintf(msgfp,":%c=%d/fix#%d",whchars[prepcase],
 8970: 	 (prepcase==1?colwidth[icol]:rowheight[irow]),
 8971: 	 (prepcase==1?fixcolsize[icol]:fixrowsize[irow]));
 8972:      } /* --- end-of-if(isdigit()) --- */
 8973:    } /* --- end-of-if(prepcase!=0) --- */
 8974:   if ( prepcase == 1 ) icol++;		/* bump col if lowercase lcr */
 8975:     else if ( prepcase == 2 ) irow++;	/* bump row if uppercase BC */
 8976:   } /* --- end-of-while(*preptr!='\000') --- */
 8977: if ( msglevel>=29 && msgfp!=NULL )	/* debugging, emit final newline */
 8978:  if ( itoken > 0 )			/* if we have preamble */
 8979:   fprintf(msgfp,"\n");
 8980: /* -------------------------------------------------------------------------
 8981: tokenize and rasterize components  a & b \\ c & d \\ etc  of subexpr
 8982: -------------------------------------------------------------------------- */
 8983: /* --- rasterize tokens one at a time, and maintain row,col counts --- */
 8984: ncols[nrows] = 0;			/* no tokens/cols in top row yet */
 8985: while ( 1 )				/* scan chars till end */
 8986:   {
 8987:   /* --- local control flags --- */
 8988:   int	iseox = (*exprptr == '\000'),	/* null signals end-of-expression */
 8989: 	iseor = iseox,			/* \\ or eox signals end-of-row */
 8990: 	iseoc = iseor;			/* & or eor signals end-of-col */
 8991:   /* --- check for escapes --- */
 8992:   isescape = isthischar(*exprptr,ESCAPE); /* is current char escape? */
 8993:   wasescape= (!isnewrow&&isthischar(*(exprptr-1),ESCAPE)); /*prev char esc?*/
 8994:   nescapes = (wasescape?nescapes+1:0);	/* # preceding consecutive escapes */
 8995:   ischarescaped = (nescapes%2==0?0:1);	/* is current char escaped? */
 8996:   /* -----------------------------------------------------------------------
 8997:   check for {...} subexpression starting from where we are now
 8998:   ------------------------------------------------------------------------ */
 8999:   if ( *exprptr == '{'			/* start of {...} subexpression */
 9000:   &&   !ischarescaped )			/* if not escaped \{ */
 9001:     {
 9002:     subptr = texsubexpr(exprptr,subtok,4095,"{","}",1,1); /*entire subexpr*/
 9003:     subtoklen = strlen(subtok);		/* #chars in {...} */
 9004:     memcpy(tokptr,exprptr,subtoklen);	/* copy {...} to accumulated token */
 9005:     tokptr  += subtoklen;		/* bump tokptr to end of token */
 9006:     exprptr += subtoklen;		/* and bump exprptr past {...} */
 9007:     istokwhite = 0;			/* signal non-empty token */
 9008:     continue;				/* continue with char after {...} */
 9009:     } /* --- end-of-if(*exprptr=='{') --- */
 9010:   /* -----------------------------------------------------------------------
 9011:   check for end-of-row(\\) and/or end-of-col(&)
 9012:   ------------------------------------------------------------------------ */
 9013:   /* --- check for (escaped) end-of-row delimiter --- */
 9014:   if ( isescape && !ischarescaped )	/* current char is escaped */
 9015:     if ( isthischar(*(exprptr+1),rowdelim) /* next char is rowdelim */
 9016:     ||   *(exprptr+1) == '\000' )	/* or a pathological null */
 9017:       {	iseor = 1;			/* so set end-of-row flag */
 9018: 	wasescape=isescape=nescapes = 0; } /* reset flags for new row */
 9019:   /* --- check for end-of-col delimiter --- */
 9020:   if (iseor				/* end-of-row signals end-of-col */
 9021:   ||  (!ischarescaped&&isthischar(*exprptr,coldelim))) /*or unescaped coldel*/
 9022:       iseoc = 1;			/* so set end-of-col flag */
 9023:   /* -----------------------------------------------------------------------
 9024:   rasterize completed token
 9025:   ------------------------------------------------------------------------ */
 9026:   if ( iseoc )				/* we have a completed token */
 9027:     {
 9028:     *tokptr = '\000';			/* first, null-terminate token */
 9029:     /* --- check first token in row for \hline or \hdash --- */
 9030:     ishonly = 0;			/*init for token not only an \hline*/
 9031:     if ( ncols[nrows] == 0 )		/*\hline must be first token in row*/
 9032:       {
 9033:       tokptr=token; skipwhite(tokptr);	/* skip whitespace after // */
 9034:       tokptr = texchar(tokptr,hltoken);	/* extract first char from token */
 9035:       hltoklen = strlen(hltoken);	/* length of first char */
 9036:       if ( hltoklen >= minhltoklen ) {	/*token must be at least \hl or \hd*/
 9037: 	if ( memcmp(hlchar,hltoken,hltoklen) == 0 ) /* we have an \hline */
 9038: 	   hline[nrows] += 1;		/* bump \hline count for row */
 9039: 	else if ( memcmp(hdchar,hltoken,hltoklen) == 0 ) /*we have an \hdash*/
 9040: 	   hline[nrows] = (-1); }	/* set \hdash flag for row */
 9041:       if ( hline[nrows] != 0 )		/* \hline or \hdash prefixes token */
 9042: 	{ skipwhite(tokptr);		/* flush whitespace after \hline */
 9043: 	  if ( *tokptr == '\000'	/* end-of-expression after \hline */
 9044: 	  ||   isthischar(*tokptr,coldelim) ) /* or unescaped coldelim */
 9045: 	    { istokwhite = 1;		/* so token contains \hline only */
 9046: 	      if ( iseox ) ishonly = 1; } /* ignore entire row at eox */
 9047: 	  else				/* token contains more than \hline */
 9048: 	    strcpy(token,tokptr); }	/* so flush \hline from token */
 9049:       } /* --- end-of-if(ncols[nrows]==0) --- */
 9050:     /* --- rasterize completed token --- */
 9051:     toksp[ntokens] = (istokwhite? NULL : /* don't rasterize empty token */
 9052:       rasterize(token,size));		/* rasterize non-empty token */
 9053:     if ( toksp[ntokens] != NULL )	/* have a rasterized token */
 9054:       nnonwhite++;			/* bump rasterized token count */
 9055:     /* --- maintain colwidth[], rowheight[] max, and rowbaseln[] --- */
 9056:     if ( toksp[ntokens] != NULL )	/* we have a rasterized token */
 9057:       {
 9058:       /* --- update max token "height" in current row, and baseline --- */
 9059:       int twidth = ((toksp[ntokens])->image)->width,  /* width of token */
 9060: 	theight = ((toksp[ntokens])->image)->height, /* height of token */
 9061: 	tbaseln =  (toksp[ntokens])->baseline, /* baseline of token */
 9062: 	rheight = rowheight[nrows],	/* current max height for row */
 9063: 	rbaseln = rowbaseln[nrows];	/* current baseline for max height */
 9064:       if ( 0 || fixrowsize[nrows]==0 )	/* rowheight not fixed */
 9065:        rowheight[nrows] = /*max2( rheight,*/( /* current (max) rowheight */
 9066: 	max2(rbaseln+1,tbaseln+1)	/* max height above baseline */
 9067: 	+ max2(rheight-rbaseln-1,theight-tbaseln-1) ); /* plus max below */
 9068:       rowbaseln[nrows] = max2(rbaseln,tbaseln); /*max space above baseline*/
 9069:       /* --- update max token width in current column --- */
 9070:       icol = ncols[nrows];		/* current column index */
 9071:       if ( 0 || fixcolsize[icol]==0 )	/* colwidth not fixed */
 9072:        colwidth[icol] = max2(colwidth[icol],twidth); /*widest token in col*/
 9073:       } /* --- end-of-if(toksp[]!=NULL) --- */
 9074:     /* --- bump counters --- */
 9075:     if ( !ishonly )			/* don't count only an \hline */
 9076:       {	ntokens++;			/* bump total token count */
 9077: 	ncols[nrows] += 1; }		/* and bump #cols in current row */
 9078:     /* --- get ready for next token --- */
 9079:     tokptr = token;			/* reset ptr for next token */
 9080:     istokwhite = 1;			/* next token starts all white */
 9081:     } /* --- end-of-if(iseoc) --- */
 9082:   /* -----------------------------------------------------------------------
 9083:   bump row as necessary
 9084:   ------------------------------------------------------------------------ */
 9085:   if ( iseor )				/* we have a completed row */
 9086:     {
 9087:     maxcols = max2(maxcols,ncols[nrows]); /* max# cols in array */
 9088:     if ( ncols[nrows]>0 || hline[nrows]==0 ) /*ignore row with only \hline*/
 9089:       nrows++;				/* bump row count */
 9090:     ncols[nrows] = 0;			/* no cols in this row yet */
 9091:     if ( !iseox )			/* don't have a null yet */
 9092:       {	exprptr++;			/* bump past extra \ in \\ delim */
 9093: 	iseox = (*exprptr == '\000'); }	/* recheck for pathological \null */
 9094:     isnewrow = 1;			/* signal start of new row */
 9095:     } /* --- end-of-if(iseor) --- */
 9096:   else
 9097:     isnewrow = 0;			/* no longer first col of new row */
 9098:   /* -----------------------------------------------------------------------
 9099:   quit when done, or accumulate char in token and proceed to next char
 9100:   ------------------------------------------------------------------------ */
 9101:   /* --- quit when done --- */
 9102:   if ( iseox ) break;			/* null terminator signalled done */
 9103:   /* --- accumulate chars in token --- */
 9104:   if ( !iseoc )				/* don't accumulate delimiters */
 9105:     { *tokptr++ = *exprptr;		/* accumulate non-delim char */
 9106:       if ( !isthischar(*exprptr,WHITESPACE) ) /* this token isn't empty */
 9107: 	istokwhite = 0; }		/* so reset flag to rasterize it */
 9108:   /* --- ready for next char --- */
 9109:   exprptr++;				/* bump ptr */
 9110:   } /* --- end-of-while(*exprptr!='\000') --- */
 9111: /* --- make sure we got something to do --- */
 9112: if ( nnonwhite < 1 )			/* completely empty array */
 9113:   goto end_of_job;			/* NULL back to caller */
 9114: /* -------------------------------------------------------------------------
 9115: determine dimensions of array raster and allocate it
 9116: -------------------------------------------------------------------------- */
 9117: /* --- adjust colspace --- */
 9118: colspace = 2 + 2*size;			/* temp kludge */
 9119: /* --- reset propagated sizes at boundaries of array --- */
 9120: colwidth[maxcols] = rowheight[nrows] = 0; /* reset explicit 0's at edges */
 9121: /* --- determine width of array raster --- */
 9122: width = colspace*(maxcols-1);		/* empty space between cols */
 9123: if ( msglevel>=29 && msgfp!=NULL )	/* debugging */
 9124:   fprintf(msgfp,"rastarray> %d cols,  widths: ",maxcols);
 9125: for ( icol=0; icol<=maxcols; icol++ )	/* and for each col */
 9126:   { width += colwidth[icol];		/*width of this col (0 for maxcols)*/
 9127:     width += vlinespace(icol);		/*plus space for vline, if present*/
 9128:     if ( msglevel>=29 && msgfp!=NULL )	/* debugging */
 9129:      fprintf(msgfp," %d=%2d+%d",icol+1,colwidth[icol],(vlinespace(icol))); }
 9130: /* --- determine height of array raster --- */
 9131: height = rowspace*(nrows-1);		/* empty space between rows */
 9132: if ( msglevel>=29 && msgfp!=NULL )	/* debugging */
 9133:   fprintf(msgfp,"\nrastarray> %d rows, heights: ",nrows);
 9134: for ( irow=0; irow<=nrows; irow++ )	/* and for each row */
 9135:   { height += rowheight[irow];		/*height of this row (0 for nrows)*/
 9136:     height += hlinespace(irow);		/*plus space for hline, if present*/
 9137:     if ( msglevel>=29 && msgfp!=NULL )	/* debugging */
 9138:      fprintf(msgfp," %d=%2d+%d",irow+1,rowheight[irow],(hlinespace(irow))); }
 9139: /* --- allocate subraster and raster for array --- */
 9140: if ( msglevel>=29 && msgfp!=NULL )	/* debugging */
 9141:   fprintf(msgfp,"\nrastarray> tot width=%d(colspc=%d) height=%d(rowspc=%d)\n",
 9142:   width,colspace, height,rowspace);
 9143: if ( (arraysp=new_subraster(width,height,pixsz)) /* allocate new subraster */
 9144: ==   NULL )  goto end_of_job;		/* quit if failed */
 9145: /* --- initialize subraster parameters --- */
 9146: arraysp->type = IMAGERASTER;		/* image */
 9147: arraysp->symdef = NULL;			/* not applicable for image */
 9148: arraysp->baseline=min2(height/2+5,height-1); /*is a little above center good?*/
 9149: arraysp->size = size;			/* size (probably unneeded) */
 9150: arrayrp = arraysp->image;		/* raster embedded in subraster */
 9151: /* -------------------------------------------------------------------------
 9152: embed tokens/cells in array
 9153: -------------------------------------------------------------------------- */
 9154: itoken = 0;				/* start with first token */
 9155: toprow = 0;				/* start at top row of array */
 9156: for ( irow=0; irow<=nrows; irow++ )	/*tokens were accumulated row-wise*/
 9157:   {
 9158:   /* --- initialization for row --- */
 9159:   int	baseline = rowbaseln[irow];	/* baseline for this row */
 9160:   if ( hline[irow] != 0 )		/* need hline above this row */
 9161:     { int hrow = (irow<1? 0 : toprow - rowspace/2); /* row for hline */
 9162:       if ( irow >= nrows ) hrow = height-1; /* row for bottom hline */
 9163:       rule_raster(arrayrp,hrow,0,width,1,(hline[irow]<0?1:0)); } /* hline */
 9164:   if ( irow >= nrows ) break;		/*just needed \hline for irow=nrows*/
 9165:   toprow += hlinespace(irow);		/* space for hline above irow */
 9166:   leftcol = 0;				/* start at leftmost column */
 9167:   for ( icol=0; icol<ncols[irow]; icol++ ) /* go through cells in this row */
 9168:     {
 9169:     subraster *tsp = toksp[itoken];	/* token that belongs in this cell */
 9170:     /* --- first adjust leftcol for vline to left of icol, if present ---- */
 9171:     leftcol += vlinespace(icol);	/* space for vline to left of col */
 9172:     /* --- now rasterize cell ---- */
 9173:     if ( tsp != NULL )			/* have a rasterized cell token */
 9174:       {
 9175:       /* --- local parameters --- */
 9176:       int cwidth = colwidth[icol],	/* total column width */
 9177: 	  twidth = (tsp->image)->width,	/* token width */
 9178: 	  theight= (tsp->image)->height, /* token height */
 9179: 	  tokencol = 0,			/*H offset (init for left justify)*/
 9180: 	  tokenrow = baseline - tsp->baseline;/*V offset (init for baseline)*/
 9181:       /* --- adjust leftcol for vline to left of icol, if present ---- */
 9182:       /*leftcol += vlinespace(icol);*/	/* space for vline to left of col */
 9183:       /* --- reset justification (if not left-justified) --- */
 9184:       if ( justify[icol] == 0 )		/* but user wants it centered */
 9185: 	  tokencol = (cwidth-twidth+1)/2; /* so split margin left/right */
 9186:       else if ( justify[icol] == 1 )	/* or user wants right-justify */
 9187: 	  tokencol = cwidth-twidth;	/* so put entire margin at left */
 9188:       /* --- reset vertical centering (if not baseline-aligned) --- */
 9189:       if ( rowcenter[irow] )		/* center cells in row vertically */
 9190: 	  tokenrow = (rowheight[irow]-theight)/2; /* center row */
 9191:       /* --- embed token raster at appropriate place in array raster --- */
 9192:       rastput(arrayrp,tsp->image,	/* overlay cell token in array */
 9193: 	  toprow+ tokenrow,		/*with aligned baseline or centered*/
 9194: 	  leftcol+tokencol, 1);		/* and justified as requested */
 9195:       } /* --- end-of-if(tsp!=NULL) --- */
 9196:     itoken++;				/* bump index for next cell */
 9197:     leftcol += colwidth[icol] + colspace /*move leftcol right for next col*/
 9198:       /* + vlinespace(icol) */ ; /*don't add space for vline to left of col*/
 9199:     } /* --- end-of-for(icol) --- */
 9200:   toprow += rowheight[irow] + rowspace;	/* move toprow down for next row */
 9201:   } /* --- end-of-for(irow) --- */
 9202: /* -------------------------------------------------------------------------
 9203: draw vlines as necessary
 9204: -------------------------------------------------------------------------- */
 9205: leftcol = 0;				/* start at leftmost column */
 9206: for ( icol=0; icol<=maxcols; icol++ )	/* check each col for a vline */
 9207:   {
 9208:   if ( vline[icol] != 0 )		/* need vline to left of this col */
 9209:     { int vcol = (icol<1? 0 : leftcol - colspace/2); /* column for vline */
 9210:       if ( icol >= maxcols ) vcol = width-1; /*column for right edge vline*/
 9211:       rule_raster(arrayrp,0,vcol,1,height,(vline[icol]<0?2:0)); } /* vline */
 9212:   leftcol += vlinespace(icol);		/* space for vline to left of col */
 9213:   if ( icol < maxcols )			/* don't address past end of array */
 9214:     leftcol += colwidth[icol] + colspace; /*move leftcol right for next col*/
 9215:   } /* --- end-of-for(icol) --- */
 9216: /* -------------------------------------------------------------------------
 9217: free workspace and return final result to caller
 9218: -------------------------------------------------------------------------- */
 9219: end_of_job:
 9220:   /* --- free workspace --- */
 9221:   if ( ntokens > 0 )			/* if we have workspace to free */
 9222:     while ( --ntokens >= 0 )		/* free each token subraster */
 9223:       if ( toksp[ntokens] != NULL )	/* if we rasterized this cell */
 9224: 	delete_subraster(toksp[ntokens]); /* then free it */
 9225:   /* --- return final result to caller --- */
 9226:   return ( arraysp );
 9227: } /* --- end-of-function rastarray() --- */
 9228: 
 9229: 
 9230: /* ==========================================================================
 9231:  * Function:	rastpicture ( expression, size, basesp, arg1, arg2, arg3 )
 9232:  * Purpose:	\picture handler, returns subraster corresponding to picture
 9233:  *		expression (immediately following \picture) at font size
 9234:  * --------------------------------------------------------------------------
 9235:  * Arguments:	expression (I/O) char **  to first char of null-terminated
 9236:  *				string immediately following \picture to be
 9237:  *				rasterized, and returning ptr immediately
 9238:  *				following last character processed.
 9239:  *		size (I)	int containing 0-4 default font size
 9240:  *		basesp (I)	subraster *  to character (or subexpression)
 9241:  *				immediately preceding \picture
 9242:  *				(unused, but passed for consistency)
 9243:  *		arg1 (I)	int unused
 9244:  *		arg2 (I)	int unused
 9245:  *		arg3 (I)	int unused
 9246:  * --------------------------------------------------------------------------
 9247:  * Returns:	( subraster * )	ptr to subraster corresponding to picture
 9248:  *				expression, or NULL for any parsing error
 9249:  * --------------------------------------------------------------------------
 9250:  * Notes:     o	Summary of syntax...
 9251:  *		  \picture(width,height){(x,y){pic_elem}~(x,y){pic_elem}~etc}
 9252:  *	      o	
 9253:  * ======================================================================= */
 9254: /* --- entry point --- */
 9255: subraster *rastpicture ( char **expression, int size, subraster *basesp,
 9256: 			int arg1, int arg2, int arg3 )
 9257: {
 9258: /* -------------------------------------------------------------------------
 9259: Allocations and Declarations
 9260: -------------------------------------------------------------------------- */
 9261: char	*texsubexpr(), picexpr[2049], *picptr=picexpr, /* picture {expre} */
 9262: 	putexpr[256], *putptr,*multptr,	/*[multi]put (x,y[;xinc,yinc;num])*/
 9263: 	pream[64], *preptr,		/* optional put preamble */
 9264: 	picelem[1025];			/* picture element following put */
 9265: subraster   *rasterize(), *picelemsp=NULL, /* rasterize picture elements */
 9266: 	*new_subraster(), *picturesp=NULL, /* subraster for entire picture */
 9267: 	*oldworkingbox = workingbox;	/* save working box on entry */
 9268: raster	*picturerp=NULL;		/* raster for entire picture */
 9269: int	delete_subraster();		/* free picelemsp[] workspace */
 9270: int	pixsz = 1;			/* pixels are one bit each */
 9271: double	strtod(),			/* convert ascii params to doubles */
 9272: 	x=0.0,y=0.0,			/* x,y-coords for put,multiput*/
 9273: 	xinc=0.0,yinc=0.0;		/* x,y-incrementss for multiput*/
 9274: int	width=0,  height=0,		/* #pixels width,height of picture */
 9275: 	ewidth=0, eheight=0,		/* pic element width,height */
 9276: 	ix=0,xpos=0, iy=0,ypos=0,	/* mimeTeX x,y pixel coords */
 9277: 	num=1, inum;			/* number reps, index of element */
 9278: int	iscenter=0;			/* center or lowerleft put position*/
 9279: int	*oldworkingparam = workingparam, /* save working param on entry */
 9280: 	origin = 0;			/* x,yinc ++=00 +-=01 -+=10 --=11 */
 9281: int	rastput();			/* embed elements in picture */
 9282: int	type_raster();			/* display debugging output */
 9283: /* -------------------------------------------------------------------------
 9284: First obtain (width,height) arguments immediately following \picture command
 9285: -------------------------------------------------------------------------- */
 9286: /* --- parse for (width,height) arguments, and bump expression past it --- */
 9287: *expression = texsubexpr(*expression,putexpr,254,"(",")",0,0);
 9288: if ( *putexpr == '\000' ) goto end_of_job; /* couldn't get (width,height) */
 9289: /* --- now interpret width,height returned in putexpr --- */
 9290: if ( (putptr=strchr(putexpr,',')) != NULL ) /* look for ',' in width,height*/
 9291:   *putptr = '\000';			/* found it, so replace ',' by '\0'*/
 9292: width=height = iround(unitlength*strtod(putexpr,NULL)); /*width pixels*/
 9293: if ( putptr != NULL )			/* 2nd arg, if present, is height */
 9294:   height = iround(unitlength*strtod(putptr+1,NULL)); /*in pixels*/
 9295: /* -------------------------------------------------------------------------
 9296: Then obtain entire picture {...} subexpression following (width,height)
 9297: -------------------------------------------------------------------------- */
 9298: /* --- parse for picture subexpression, and bump expression past it --- */
 9299: *expression = texsubexpr(*expression,picexpr,2047,"{","}",0,0);
 9300: if ( *picexpr == '\000' ) goto end_of_job; /* couldn't get {pic_elements} */
 9301: /* -------------------------------------------------------------------------
 9302: allocate subraster and raster for complete picture
 9303: -------------------------------------------------------------------------- */
 9304: /* --- sanity check on width,height args --- */
 9305: if ( width < 2 ||  width > 600
 9306: ||  height < 2 || height > 600 ) goto end_of_job;
 9307: /* --- allocate and initialize subraster for constructed picture --- */
 9308: if ( (picturesp=new_subraster(width,height,pixsz)) /*allocate new subraster*/
 9309: ==   NULL )  goto end_of_job;		/* quit if failed */
 9310: workingbox = picturesp;			/* set workingbox to our picture */
 9311: /* --- initialize picture subraster parameters --- */
 9312: picturesp->type = IMAGERASTER;		/* image */
 9313: picturesp->symdef = NULL;		/* not applicable for image */
 9314: picturesp->baseline = height/2 + 2;	/* is a little above center good? */
 9315: picturesp->size = size;			/* size (probably unneeded) */
 9316: picturerp = picturesp->image;		/* raster embedded in subraster */
 9317: if ( msgfp!=NULL && msglevel>=29 )	/* debugging */
 9318:   fprintf(msgfp,"picture> width,height=%d,%d\n",width,height);
 9319: /* -------------------------------------------------------------------------
 9320: parse out each picture element, rasterize it, and place it in picture
 9321: -------------------------------------------------------------------------- */
 9322: while ( *picptr != '\000' )		/* until we run out of pic_elems */
 9323:   {
 9324:   /* -----------------------------------------------------------------------
 9325:   first obtain leading \[multi]put(x,y[;xinc,yinc;num]) args for pic_elem
 9326:   ------------------------------------------------------------------------ */
 9327:   /* --- init default values in case not explicitly supplied in args --- */
 9328:   x=y=0.0;  xinc=yinc=0.0;  num=1;	/* init default values */
 9329:   iscenter = origin = 0;		/* center, origin */
 9330:   /* --- get (pream$x,y;xinc,yinc;num ) args and bump picptr past it --- */
 9331:   while ( *picptr != '\000' )		/* skip invalid chars preceding ( */
 9332:     if ( *picptr == '(' ) break;	/* found opening ( */
 9333:     else picptr++;			/* else skip invalid char */
 9334:   picptr = texsubexpr(picptr,putexpr,254,"(",")",0,0);
 9335:   if ( *putexpr == '\000' ) goto end_of_job; /* couldn't get (x,y) */
 9336:   /* --- first look for $-terminated or for any non-digit preamble --- */
 9337:   *pream = '\000';			/* init preamble as empty string */
 9338:   if ( (putptr=strchr(putexpr,'$')) != NULL ) /*check for $ pream terminator*/
 9339:     { *putptr++ = '\000';		/* replace $ by '\0', bump past $ */
 9340:       strcpy(pream,putexpr); }		/* copy leading preamble from put */
 9341:   else					/* look for any non-digit preamble */
 9342:     { for ( preptr=pream,putptr=putexpr; ; putptr++ )
 9343: 	if ( *putptr == '\000'		/* end-of-putdata signalled */
 9344: 	||   !isalpha((int)(*putptr)) ) break; /* or found non-alpha char */
 9345: 	else *preptr++ = *putptr;	/* copy alpha char to preamble */
 9346:       *preptr = '\000'; }		/* null-terminate preamble */
 9347:   /* --- interpret preamble --- */
 9348:   for ( preptr=pream; ; preptr++ )	/* examine each preamble char */
 9349:     if ( *preptr == '\000' ) break;	/* end-of-preamble signalled */
 9350:     else switch ( tolower(*preptr) )	/* check lowercase preamble char */
 9351:       {
 9352:       default: break;			/* unrecognized flag */
 9353:       case 'c': iscenter=1; break;	/* center pic_elem at x,y coords */
 9354:       } /* --- end-of-switch --- */
 9355:   /* --- interpret x,y;xinc,yinc;num following preamble --- */      
 9356:   if ( *putptr != '\000' )		/*check for put data after preamble*/
 9357:    {
 9358:    /* --- first squeeze preamble out of put expression --- */
 9359:    if ( *pream != '\000' ) strcpy(putexpr,putptr); /* squeeze out preamble */
 9360:    /* --- interpret x,y --- */
 9361:    if ( (multptr=strchr(putexpr,';')) != NULL ) /*semicolon signals multiput*/
 9362:      *multptr = '\000';			/* replace semicolon by '\0' */
 9363:    if ( (putptr=strchr(putexpr,',')) != NULL ) /* comma separates x,y */
 9364:      *putptr = '\000';			/* replace comma by '\0'  */
 9365:    if ( *putexpr != '\000' )		/* leading , may be placeholder */
 9366:      x = unitlength*strtod(putexpr,NULL); /* x coord in pixels*/
 9367:    if ( putptr != NULL )		/* 2nd arg, if present, is y coord */
 9368:      y = unitlength*strtod(putptr+1,NULL); /* in pixels */
 9369:    /* --- interpret xinc,yinc,num if we have a multiput --- */
 9370:    if ( multptr != NULL )		/* found ';' signalling multiput */
 9371:      {
 9372:      if ( (preptr=strchr(multptr+1,';')) != NULL ) /* ';' preceding num arg*/
 9373:        *preptr = '\000';		/* replace ';' by '\0' */
 9374:      if ( (putptr=strchr(multptr+1,',')) != NULL ) /* ',' between xinc,yinc*/
 9375:        *putptr = '\000';		/* replace ',' by '\0' */
 9376:      if ( *(multptr+1) != '\000' )	/* leading , may be placeholder */
 9377:        xinc = unitlength*strtod(multptr+1,NULL); /* xinc in pixels */
 9378:      if ( putptr != NULL )		/* 2nd arg, if present, is yinc */
 9379:        yinc = unitlength*strtod(putptr+1,NULL); /* in user pixels */
 9380:      num = (preptr==NULL? 999 : atoi(preptr+1)); /*explicit num val or 999*/
 9381:      } /* --- end-of-if(multptr!=NULL) --- */
 9382:    } /* --- end-of-if(*preptr!='\000') --- */
 9383:   if ( msgfp!=NULL && msglevel>=29 )	/* debugging */
 9384:     fprintf(msgfp,
 9385:     "picture> pream;x,y;xinc,yinc;num=\"%s\";%.2f,%.2f;%.2f,%.2f;%d\n",
 9386:     pream,x,y,xinc,yinc,num);
 9387:   /* -----------------------------------------------------------------------
 9388:   now obtain {...} picture element following [multi]put, and rasterize it
 9389:   ------------------------------------------------------------------------ */
 9390:   /* --- parse for {...} picture element and bump picptr past it --- */
 9391:   picptr = texsubexpr(picptr,picelem,1023,"{","}",0,0);
 9392:   if ( *picelem == '\000' ) goto end_of_job; /* couldn't get {pic_elem} */
 9393:   if ( msgfp!=NULL && msglevel>=29 )	/* debugging */
 9394:     fprintf(msgfp, "picture> picelem=\"%.50s\"\n",picelem);
 9395:   /* --- rasterize picture element --- */
 9396:   origin = 0;				/* init origin as working param */
 9397:   workingparam = &origin;		/* and point working param to it */
 9398:   picelemsp = rasterize(picelem,size);	/* rasterize picture element */
 9399:   if ( picelemsp == NULL ) continue;	/* failed to rasterize, skip elem */
 9400:   ewidth  = (picelemsp->image)->width;	/* width of element, in pixels */
 9401:   eheight = (picelemsp->image)->height;	/* height of element, in pixels */
 9402:   if ( origin == 55 ) iscenter = 1;	/* origin set to (.5,.5) for center*/
 9403:   if ( msgfp!=NULL && msglevel>=29 )	/* debugging */
 9404:     { fprintf(msgfp, "picture> ewidth,eheight,origin,num=%d,%d,%d,%d\n",
 9405:       ewidth,eheight,origin,num);
 9406:       if ( msglevel >= 999 ) type_raster(picelemsp->image,msgfp); }
 9407:   /* -----------------------------------------------------------------------
 9408:   embed element in picture (once, or multiple times if requested)
 9409:   ------------------------------------------------------------------------ */
 9410:   for ( inum=0; inum<num; inum++ )	/* once, or for num repetitions */
 9411:     {
 9412:     /* --- set x,y-coords for this iteration --- */
 9413:     ix = iround(x);  iy = iround(y);	/* round x,y to nearest integer */
 9414:     if ( iscenter )			/* place center of element at x,y */
 9415:       {	xpos = ix - ewidth/2;		/* x picture coord to center elem */
 9416: 	ypos = height - iy - eheight/2; } /* y pixel coord to center elem */
 9417:     else				/* default places lower-left at x,y*/
 9418:       {	xpos = ix;			/* set x pixel coord for left */
 9419: 	if ( origin==10 || origin==11 )	/* x,yinc's are -+ or -- */
 9420: 	  xpos = ix - ewidth;		/* so set for right instead */
 9421: 	ypos = height - iy - eheight;	/* set y pixel coord for lower */
 9422: 	if ( origin==1 || origin==11 )	/* x,yinc's are +- or -- */
 9423: 	  ypos = height - iy; }		/* so set for upper instead */
 9424:     if ( msgfp!=NULL && msglevel>=29 )	/* debugging */
 9425:       fprintf(msgfp,
 9426:       "picture> inum,x,y,ix,iy,xpos,ypos=%d,%.2f,%.2f,%d,%d,%d,%d\n",
 9427:       inum,x,y,ix,iy,xpos,ypos);
 9428:     /* --- embed token raster at xpos,ypos, and quit if out-of-bounds --- */
 9429:     if ( !rastput(picturerp,picelemsp->image,ypos,xpos,0) ) break;
 9430:     /* --- apply increment --- */
 9431:     if ( xinc==0. && yinc==0. ) break;	/* quit if both increments zero */
 9432:     x += xinc;  y += yinc;		/* increment coords for next iter */
 9433:     } /* --- end-of-for(inum) --- */
 9434:   /* --- free picture element subraster after embedding it in picture --- */
 9435:   delete_subraster(picelemsp);		/* done with subraster, so free it */
 9436:   } /* --- end-of-while(*picptr!=0) --- */
 9437: /* -------------------------------------------------------------------------
 9438: return picture constructed from pic_elements to caller
 9439: -------------------------------------------------------------------------- */
 9440: end_of_job:
 9441:   workingbox = oldworkingbox;		/* restore original working box */
 9442:   workingparam = oldworkingparam;	/* restore original working param */
 9443:   return ( picturesp );			/* return our picture to caller */
 9444: } /* --- end-of-function rastpicture() --- */
 9445: 
 9446: 
 9447: /* ==========================================================================
 9448:  * Function:	rastline ( expression, size, basesp, arg1, arg2, arg3 )
 9449:  * Purpose:	\line handler, returns subraster corresponding to line
 9450:  *		parameters (xinc,yinc){xlen}
 9451:  * --------------------------------------------------------------------------
 9452:  * Arguments:	expression (I/O) char **  to first char of null-terminated
 9453:  *				string immediately following \line to be
 9454:  *				rasterized, and returning ptr immediately
 9455:  *				following last character processed.
 9456:  *		size (I)	int containing 0-7 default font size
 9457:  *		basesp (I)	subraster *  to character (or subexpression)
 9458:  *				immediately preceding \line
 9459:  *				(unused, but passed for consistency)
 9460:  *		arg1 (I)	int unused
 9461:  *		arg2 (I)	int unused
 9462:  *		arg3 (I)	int unused
 9463:  * --------------------------------------------------------------------------
 9464:  * Returns:	( subraster * )	ptr to subraster corresponding to line
 9465:  *				requested, or NULL for any parsing error
 9466:  * --------------------------------------------------------------------------
 9467:  * Notes:     o	Summary of syntax...
 9468:  *		  \line(xinc,yinc){xlen}
 9469:  *	      o	if {xlen} not given, then it's assumed xlen = |xinc|
 9470:  * ======================================================================= */
 9471: /* --- entry point --- */
 9472: subraster *rastline ( char **expression, int size, subraster *basesp,
 9473: 			int arg1, int arg2, int arg3 )
 9474: {
 9475: /* -------------------------------------------------------------------------
 9476: Allocations and Declarations
 9477: -------------------------------------------------------------------------- */
 9478: char	*texsubexpr(),linexpr[257], *xptr=linexpr; /*line(xinc,yinc){xlen}*/
 9479: subraster *new_subraster(), *linesp=NULL; /* subraster for line */
 9480: /*char	*origexpression = *expression;*/ /*original expression after \line*/
 9481: int	pixsz = 1;			/* pixels are one bit each */
 9482: int	thickness = 1;			/* line thickness */
 9483: double	strtod(),			/* convert ascii params to doubles */
 9484: 	xinc=0.0, yinc=0.0,		/* x,y-increments for line, */
 9485: 	xlen=0.0, ylen=0.0;		/* x,y lengths for line */
 9486: int	width=0,  height=0,		/* #pixels width,height of line */
 9487: 	rwidth=0, rheight=0;		/*alloc width,height plus thickness*/
 9488: int	istop=0,  isright=0,		/* origin at bot-left if x,yinc>=0 */
 9489: 	origin = 0;			/* x,yinc: ++=00 +-=01 -+=10 --=11 */
 9490: int	line_raster();			/* draw line in linesp->image */
 9491: /* -------------------------------------------------------------------------
 9492: obtain (xinc,yinc) arguments immediately following \line command
 9493: -------------------------------------------------------------------------- */
 9494: /* --- parse for (xinc,yinc) arguments, and bump expression past it --- */
 9495: *expression = texsubexpr(*expression,linexpr,253,"(",")",0,0);
 9496: if ( *linexpr == '\000' ) goto end_of_job; /* couldn't get (xinc,yinc) */
 9497: /* --- now interpret xinc,yinc;thickness returned in linexpr --- */
 9498: if ( (xptr=strchr(linexpr,';')) != NULL ) /* look for ';' after xinc,yinc */
 9499:   { *xptr = '\000';			/* terminate linexpr at ; */
 9500:     thickness = (int)strtol(xptr+1,NULL,10); } /* get int thickness */
 9501: if ( (xptr=strchr(linexpr,',')) != NULL ) /* look for ',' in xinc,yinc */
 9502:   *xptr = '\000';			/* found it, so replace ',' by '\0'*/
 9503: if ( *linexpr != '\000' )		/* check against missing 1st arg */
 9504:   xinc = xlen = strtod(linexpr,NULL);	/* xinc in user units */
 9505: if ( xptr != NULL )			/* 2nd arg, if present, is yinc */
 9506:   yinc = ylen = strtod(xptr+1,NULL);	/* in user units */
 9507: /* -------------------------------------------------------------------------
 9508: obtain optional {xlen} following (xinc,yinc), and calculate ylen
 9509: -------------------------------------------------------------------------- */
 9510: /* --- check if {xlen} given --- */
 9511: if ( *(*expression) == '{' )		/*have {xlen} if leading char is { */
 9512:   {
 9513:   /* --- parse {xlen} and bump expression past it, interpret as double --- */
 9514:   *expression = texsubexpr(*expression,linexpr,253,"{","}",0,0);
 9515:   if ( *linexpr == '\000' ) goto end_of_job; /* couldn't get {xlen} */
 9516:   xlen = strtod(linexpr,NULL);		/* xlen in user units */
 9517:   /* --- set other values accordingly --- */
 9518:   if ( xlen  < 0.0 ) xinc = -xinc;	/* if xlen negative, flip xinc sign*/
 9519:   if ( xinc != 0.0 ) ylen = xlen*yinc/xinc; /* set ylen from xlen and slope*/
 9520:   else xlen  = 0.0;			/* can't have xlen if xinc=0 */
 9521:   } /* --- end-of-if(*(*expression)=='{') --- */
 9522: /* -------------------------------------------------------------------------
 9523: calculate width,height, etc, based on xlen,ylen, etc
 9524: -------------------------------------------------------------------------- */
 9525: /* --- force lengths positive --- */
 9526: xlen = absval(xlen);			/* force xlen positive */
 9527: ylen = absval(ylen);			/* force ylen positive */
 9528: /* --- calculate corresponding lengths in pixels --- */
 9529: width   = max2(1,iround(unitlength*xlen)); /*scale by unitlength and round,*/
 9530: height  = max2(1,iround(unitlength*ylen)); /* and must be at least 1 pixel */
 9531: rwidth  = width  + (ylen<0.001?0:max2(0,thickness-1));
 9532: rheight = height + (xlen<0.001?0:max2(0,thickness-1));
 9533: /* --- set origin corner, x,yinc's: ++=0=(0,0) +-=1=(0,1) -+=10=(1,0) --- */
 9534: if ( xinc < 0.0 ) isright = 1;		/*negative xinc, so corner is (1,?)*/
 9535: if ( yinc < 0.0 ) istop = 1;		/*negative yinc, so corner is (?,1)*/
 9536: origin = isright*10 + istop;		/* interpret 0=(0,0), 11=(1,1), etc*/
 9537: if ( msgfp!=NULL && msglevel>=29 )	/* debugging */
 9538:   fprintf(msgfp,"rastline> width,height,origin;x,yinc=%d,%d,%d;%g,%g\n",
 9539:   width,height,origin,xinc,yinc);
 9540: /* -------------------------------------------------------------------------
 9541: allocate subraster and raster for line
 9542: -------------------------------------------------------------------------- */
 9543: /* --- sanity check on width,height,thickness args --- */
 9544: if ( width < 1 ||  width > 600
 9545: ||  height < 1 || height > 600
 9546: ||  thickness<1||thickness>25 ) goto end_of_job;
 9547: /* --- allocate and initialize subraster for constructed line --- */
 9548: if ( (linesp=new_subraster(rwidth,rheight,pixsz)) /* alloc new subraster */
 9549: ==   NULL )  goto end_of_job;		/* quit if failed */
 9550: /* --- initialize line subraster parameters --- */
 9551: linesp->type = IMAGERASTER;		/* image */
 9552: linesp->symdef = NULL;			/* not applicable for image */
 9553: linesp->baseline = height/2 + 2		/* is a little above center good? */
 9554: 	+ (rheight-height)/2;		/* account for line thickness too */
 9555: linesp->size = size;			/* size (probably unneeded) */
 9556: /* -------------------------------------------------------------------------
 9557: draw the line
 9558: -------------------------------------------------------------------------- */
 9559: line_raster ( linesp->image,		/* embedded raster image */
 9560: 	(istop?   0 : height-1),	/* row0, from bottom or top */
 9561: 	(isright?  width-1 : 0),	/* col0, from left or right */
 9562: 	(istop?   height-1 : 0),	/* row1, to top or bottom */
 9563: 	(isright? 0 :  width-1),	/* col1, to right or left */
 9564: 	thickness );			/* line thickness (usually 1 pixel)*/
 9565: /* -------------------------------------------------------------------------
 9566: return constructed line to caller
 9567: -------------------------------------------------------------------------- */
 9568: end_of_job:
 9569:   if ( workingparam != NULL )		/* caller wants origin */
 9570:     *workingparam = origin;		/* return origin corner to caller */
 9571:   return ( linesp );			/* return line to caller */
 9572: } /* --- end-of-function rastline() --- */
 9573: 
 9574: 
 9575: /* ==========================================================================
 9576:  * Function:	rastrule ( expression, size, basesp, arg1, arg2, arg3 )
 9577:  * Purpose:	\rule handler, returns subraster corresponding to rule
 9578:  *		parameters [lift]{width}{height}
 9579:  * --------------------------------------------------------------------------
 9580:  * Arguments:	expression (I/O) char **  to first char of null-terminated
 9581:  *				string immediately following \rule to be
 9582:  *				rasterized, and returning ptr immediately
 9583:  *				following last character processed.
 9584:  *		size (I)	int containing 0-7 default font size
 9585:  *		basesp (I)	subraster *  to character (or subexpression)
 9586:  *				immediately preceding \rule
 9587:  *				(unused, but passed for consistency)
 9588:  *		arg1 (I)	int unused
 9589:  *		arg2 (I)	int unused
 9590:  *		arg3 (I)	int unused
 9591:  * --------------------------------------------------------------------------
 9592:  * Returns:	( subraster * )	ptr to subraster corresponding to rule
 9593:  *				requested, or NULL for any parsing error
 9594:  * --------------------------------------------------------------------------
 9595:  * Notes:     o	Summary of syntax...
 9596:  *		  \rule[lift]{width}{height}
 9597:  *	      o	if [lift] not given, then bottom of rule on baseline
 9598:  *	      o	if width=0 then you get an invisible strut 1 (one) pixel wide
 9599:  * ======================================================================= */
 9600: /* --- entry point --- */
 9601: subraster *rastrule ( char **expression, int size, subraster *basesp,
 9602: 			int arg1, int arg2, int arg3 )
 9603: {
 9604: /* -------------------------------------------------------------------------
 9605: Allocations and Declarations
 9606: -------------------------------------------------------------------------- */
 9607: char	*texsubexpr(), rulexpr[257];	/* rule[lift]{wdth}{hgt} */
 9608: subraster *new_subraster(), *rulesp=NULL; /* subraster for rule */
 9609: int	pixsz = 1;			/* pixels are one bit each */
 9610: int	lift=0, width=0, height=0;	/* default rule parameters */
 9611: double	strtod(), dval;			/* convert ascii params to doubles */
 9612: int	rwidth=0, rheight=0;		/* alloc width, height plus lift */
 9613: int	rule_raster();			/* draw rule in rulesp->image */
 9614: /* -------------------------------------------------------------------------
 9615: Obtain lift,width,height
 9616: -------------------------------------------------------------------------- */
 9617: /* --- check for optional lift arg  --- */
 9618: if ( *(*expression) == '[' )		/*check for []-enclosed optional arg*/
 9619:   { *expression = texsubexpr(*expression,rulexpr,255,"[","]",0,0);
 9620:     dval = (int)(strtod(rulexpr,NULL)+0.5); /* convert [lift] to int */
 9621:     if ( dval <= 99 && dval >= (-99) )	/* sanity check */
 9622:       lift = iround(unitlength*dval); }	/* scale by unitlength and round */
 9623: /* --- parse for width --- */
 9624: *expression = texsubexpr(*expression,rulexpr,255,"{","}",0,0);
 9625: if ( *rulexpr == '\000' ) goto end_of_job; /* quit if args missing */
 9626: dval = (int)(strtod(rulexpr,NULL)+0.5);	/* convert {width} to int */
 9627: if ( dval <= 500 && dval >= 0 )		/* sanity check */
 9628:   width = max2(0,iround(unitlength*dval)); /* scale by unitlength and round*/
 9629: /* --- parse for height --- */
 9630: *expression = texsubexpr(*expression,rulexpr,255,"{","}",0,0);
 9631: if ( *rulexpr == '\000' ) goto end_of_job; /* quit if args missing */
 9632: dval = (int)(strtod(rulexpr,NULL)+0.5);	/* convert {height} to int */
 9633: if ( dval <= 500 && dval > 0 )		/* sanity check */
 9634:   height= max2(1,iround(unitlength*dval)); /* scale by unitlength and round*/
 9635: /* --- raster width,height in pixels --- */
 9636: rwidth  = max2(1,width);		/* raster must be at least 1 pixel*/
 9637: rheight = height + (lift>=0?lift:	/* raster height plus lift */
 9638:   (-lift<height?0:-lift-height+1));	/* may need empty space above rule */
 9639: /* -------------------------------------------------------------------------
 9640: allocate subraster and raster for rule
 9641: -------------------------------------------------------------------------- */
 9642: /* --- sanity check on width,height,thickness args --- */
 9643: if ( rwidth < 1 ||  rwidth > 600
 9644: ||  rheight < 1 || rheight > 600 ) goto end_of_job;
 9645: /* --- allocate and initialize subraster for constructed rule --- */
 9646: if ( (rulesp=new_subraster(rwidth,rheight,pixsz)) /* alloc new subraster */
 9647: ==   NULL )  goto end_of_job;		/* quit if failed */
 9648: /* --- initialize line subraster parameters --- */
 9649: rulesp->type = IMAGERASTER;		/* image */
 9650: rulesp->symdef = NULL;			/* not applicable for image */
 9651: rulesp->baseline = rheight-1 + (lift>=0?0:lift); /*adjust baseline for lift*/
 9652: rulesp->size = size;			/* size (probably unneeded) */
 9653: /* -------------------------------------------------------------------------
 9654: draw the rule
 9655: -------------------------------------------------------------------------- */
 9656: rule_raster ( rulesp->image,		/* embedded raster image */
 9657: 	(-lift<height?0:rheight-height), /* topmost row for top-left corner*/
 9658: 	0,				/* leftmost col for top-left corner*/
 9659: 	width,				/* rule width */
 9660: 	height,				/* rule height */
 9661: 	( width>0? 0:4 ) );		/* rule type */
 9662: /* -------------------------------------------------------------------------
 9663: return constructed rule to caller
 9664: -------------------------------------------------------------------------- */
 9665: end_of_job:
 9666:   return ( rulesp );			/* return rule to caller */
 9667: } /* --- end-of-function rastrule() --- */
 9668: 
 9669: 
 9670: /* ==========================================================================
 9671:  * Function:	rastcircle ( expression, size, basesp, arg1, arg2, arg3 )
 9672:  * Purpose:	\circle handler, returns subraster corresponding to ellipse
 9673:  *		parameters (xdiam[,ydiam])
 9674:  * --------------------------------------------------------------------------
 9675:  * Arguments:	expression (I/O) char **  to first char of null-terminated
 9676:  *				string immediately following \circle to be
 9677:  *				rasterized, and returning ptr immediately
 9678:  *				following last character processed.
 9679:  *		size (I)	int containing 0-4 default font size
 9680:  *		basesp (I)	subraster *  to character (or subexpression)
 9681:  *				immediately preceding \circle
 9682:  *				(unused, but passed for consistency)
 9683:  *		arg1 (I)	int unused
 9684:  *		arg2 (I)	int unused
 9685:  *		arg3 (I)	int unused
 9686:  * --------------------------------------------------------------------------
 9687:  * Returns:	( subraster * )	ptr to subraster corresponding to ellipse
 9688:  *				requested, or NULL for any parsing error
 9689:  * --------------------------------------------------------------------------
 9690:  * Notes:     o	Summary of syntax...
 9691:  *		  \circle(xdiam[,ydiam])
 9692:  *	      o
 9693:  * ======================================================================= */
 9694: /* --- entry point --- */
 9695: subraster *rastcircle ( char **expression, int size, subraster *basesp,
 9696: 			int arg1, int arg2, int arg3 )
 9697: {
 9698: /* -------------------------------------------------------------------------
 9699: Allocations and Declarations
 9700: -------------------------------------------------------------------------- */
 9701: char	*texsubexpr(), circexpr[512],*xptr=circexpr; /*circle(xdiam[,ydiam])*/
 9702: char	*qptr=NULL, quads[256]="1234";	/* default to draw all quadrants */
 9703: double	theta0=0.0, theta1=0.0;		/* ;theta0,theta1 instead of ;quads*/
 9704: subraster *new_subraster(), *circsp=NULL; /* subraster for ellipse */
 9705: int	pixsz = 1;			/* pixels are one bit each */
 9706: double	strtod(),			/* convert ascii params to doubles */
 9707: 	xdiam=0.0, ydiam=0.0;		/* x,y major/minor axes/diameters */
 9708: int	width=0,  height=0;		/* #pixels width,height of ellipse */
 9709: int	thickness = 1;			/* drawn lines are one pixel thick */
 9710: int	origin = 55;			/* force origin centered */
 9711: int	circle_raster(),		/* draw ellipse in circsp->image */
 9712: 	circle_recurse();		/* for theta0,theta1 args */
 9713: /* -------------------------------------------------------------------------
 9714: obtain (xdiam[,ydiam]) arguments immediately following \circle command
 9715: -------------------------------------------------------------------------- */
 9716: /* --- parse for (xdiam[,ydiam]) args, and bump expression past it --- */
 9717: *expression = texsubexpr(*expression,circexpr,511,"(",")",0,0);
 9718: if ( *circexpr == '\000' ) goto end_of_job; /* couldn't get (xdiam[,ydiam])*/
 9719: /* --- now interpret xdiam[,ydiam] returned in circexpr --- */
 9720: if ( (qptr=strchr(circexpr,';')) != NULL ) /* semicolon signals quads data */
 9721:   { *qptr = '\000';			/* replace semicolon by '\0' */
 9722:     strcpy(quads,qptr+1);		/* save user-requested quads */
 9723:     if ( (qptr=strchr(quads,',')) != NULL ) /* have theta0,theta1 instead */
 9724:       {	*qptr = '\000';			/* replace , with null */
 9725: 	theta0 = strtod(quads,NULL);	/* theta0 precedes , */
 9726: 	theta1 = strtod(qptr+1,NULL);	/* theta1 follows , */
 9727: 	qptr = NULL; }			/* signal thetas instead of quads */
 9728:     else
 9729: 	qptr = quads; }			/* set qptr arg for circle_raster()*/
 9730: else					/* no ;quads at all */
 9731:   qptr = quads;				/* default to all 4 quadrants */
 9732: if ( (xptr=strchr(circexpr,',')) != NULL ) /* look for ',' in xdiam[,ydiam]*/
 9733:   *xptr = '\000';			/* found it, so replace ',' by '\0'*/
 9734: xdiam = ydiam = strtod(circexpr,NULL);	/* xdiam=ydiam in user units */
 9735: if ( xptr != NULL )			/* 2nd arg, if present, is ydiam */
 9736:   ydiam = strtod(xptr+1,NULL);		/* in user units */
 9737: /* -------------------------------------------------------------------------
 9738: calculate width,height, etc
 9739: -------------------------------------------------------------------------- */
 9740: /* --- calculate width,height in pixels --- */
 9741: width  = max2(1,iround(unitlength*xdiam)); /*scale by unitlength and round,*/
 9742: height = max2(1,iround(unitlength*ydiam)); /* and must be at least 1 pixel */
 9743: if ( msgfp!=NULL && msglevel>=29 )	/* debugging */
 9744:   fprintf(msgfp,"rastcircle> width,height;quads=%d,%d,%s\n",
 9745:   width,height,(qptr==NULL?"default":qptr));
 9746: /* -------------------------------------------------------------------------
 9747: allocate subraster and raster for complete picture
 9748: -------------------------------------------------------------------------- */
 9749: /* --- sanity check on width,height args --- */
 9750: if ( width < 1 ||  width > 600
 9751: ||  height < 1 || height > 600 ) goto end_of_job;
 9752: /* --- allocate and initialize subraster for constructed ellipse --- */
 9753: if ( (circsp=new_subraster(width,height,pixsz)) /* allocate new subraster */
 9754: ==   NULL )  goto end_of_job;		/* quit if failed */
 9755: /* --- initialize ellipse subraster parameters --- */
 9756: circsp->type = IMAGERASTER;		/* image */
 9757: circsp->symdef = NULL;			/* not applicable for image */
 9758: circsp->baseline = height/2 + 2;	/* is a little above center good? */
 9759: circsp->size = size;			/* size (probably unneeded) */
 9760: /* -------------------------------------------------------------------------
 9761: draw the ellipse
 9762: -------------------------------------------------------------------------- */
 9763: if ( qptr != NULL )			/* have quads */
 9764:   circle_raster ( circsp->image,	/* embedded raster image */
 9765: 	0, 0,				/* row0,col0 are upper-left corner */
 9766: 	height-1, width-1,		/* row1,col1 are lower-right */
 9767: 	thickness,			/* line thickness is 1 pixel */
 9768: 	qptr );				/* "1234" quadrants to be drawn */
 9769: else					/* have theta0,theta1 */
 9770:   circle_recurse ( circsp->image,	/* embedded raster image */
 9771: 	0, 0,				/* row0,col0 are upper-left corner */
 9772: 	height-1, width-1,		/* row1,col1 are lower-right */
 9773: 	thickness,			/* line thickness is 1 pixel */
 9774: 	theta0,theta1 );		/* theta0,theta1 arc to be drawn */
 9775: /* -------------------------------------------------------------------------
 9776: return constructed ellipse to caller
 9777: -------------------------------------------------------------------------- */
 9778: end_of_job:
 9779:   if ( workingparam != NULL )		/* caller wants origin */
 9780:     *workingparam = origin;		/* return center origin to caller */
 9781:   return ( circsp );			/* return ellipse to caller */
 9782: } /* --- end-of-function rastcircle() --- */
 9783: 
 9784: 
 9785: /* ==========================================================================
 9786:  * Function:	rastbezier ( expression, size, basesp, arg1, arg2, arg3 )
 9787:  * Purpose:	\bezier handler, returns subraster corresponding to bezier
 9788:  *		parameters (col0,row0)(col1,row1)(colt,rowt)
 9789:  * --------------------------------------------------------------------------
 9790:  * Arguments:	expression (I/O) char **  to first char of null-terminated
 9791:  *				string immediately following \bezier to be
 9792:  *				rasterized, and returning ptr immediately
 9793:  *				following last character processed.
 9794:  *		size (I)	int containing 0-5 default font size
 9795:  *		basesp (I)	subraster *  to character (or subexpression)
 9796:  *				immediately preceding \bezier
 9797:  *				(unused, but passed for consistency)
 9798:  *		arg1 (I)	int unused
 9799:  *		arg2 (I)	int unused
 9800:  *		arg3 (I)	int unused
 9801:  * --------------------------------------------------------------------------
 9802:  * Returns:	( subraster * )	ptr to subraster corresponding to bezier
 9803:  *				requested, or NULL for any parsing error
 9804:  * --------------------------------------------------------------------------
 9805:  * Notes:     o	Summary of syntax...
 9806:  *		  \bezier(col1,row1)(colt,rowt)
 9807:  *	      o	col0=0,row0=0 assumed, i.e., given by
 9808:  *		\picture(){~(col0,row0){\bezier(col1,row1)(colt,rowt)}~}
 9809:  * ======================================================================= */
 9810: /* --- entry point --- */
 9811: subraster *rastbezier ( char **expression, int size, subraster *basesp,
 9812: 			int arg1, int arg2, int arg3 )
 9813: {
 9814: /* -------------------------------------------------------------------------
 9815: Allocations and Declarations
 9816: -------------------------------------------------------------------------- */
 9817: subraster *new_subraster(), *bezsp=NULL; /* subraster for bezier */
 9818: char	*texsubexpr(), bezexpr[129],*xptr=bezexpr; /*\bezier(r,c)(r,c)(r,c)*/
 9819: double	strtod();			/* convert ascii params to doubles */
 9820: double	r0=0.0,c0=0.0, r1=0.0,c1=0.0, rt=0.0,ct=0.0, /* bezier points */
 9821: 	rmid=0.0, cmid=0.0,		/* coords at parameterized midpoint*/
 9822: 	rmin=0.0, cmin=0.0,		/* minimum r,c */
 9823: 	rmax=0.0, cmax=0.0,		/* maximum r,c */
 9824: 	rdelta=0.0, cdelta=0.0,		/* rmax-rmin, cmax-cmin */
 9825: 	r=0.0, c=0.0;			/* some point */
 9826: int	iarg=0;				/* 0=r0,c0 1=r1,c1 2=rt,ct */
 9827: int	width=0, height=0;		/* dimensions of bezier raster */
 9828: int	pixsz = 1;			/* pixels are one bit each */
 9829: /*int	thickness = 1;*/		/* drawn lines are one pixel thick */
 9830: int	origin = 0;			/*c's,r's reset to lower-left origin*/
 9831: int	bezier_raster();		/* draw bezier in bezsp->image */
 9832: /* -------------------------------------------------------------------------
 9833: obtain (c1,r1)(ct,rt) args immediately following \bezier command
 9834: -------------------------------------------------------------------------- */
 9835: for ( iarg=1; iarg<=2; iarg++ )		/* 0=c0,r0 1=c1,r1 2=ct,rt */
 9836:   {
 9837:   /* --- parse for (r,c) args, and bump expression past them all --- */
 9838:   *expression = texsubexpr(*expression,bezexpr,127,"(",")",0,0);
 9839:   if ( *bezexpr == '\000' ) goto end_of_job; /* couldn't get (r,c)*/
 9840:   /* --- now interpret (r,c) returned in bezexpr --- */
 9841:   c = r = 0.0;				/* init x-coord=col, y-coord=row */
 9842:   if ( (xptr=strchr(bezexpr,',')) != NULL ) /* comma separates row,col */
 9843:     { *xptr = '\000';			/* found it, so replace ',' by '\0'*/
 9844:       r = unitlength*strtod(xptr+1,NULL); } /* row=y-coord in pixels */
 9845:   c = unitlength*strtod(bezexpr,NULL);	/* col=x-coord in pixels */
 9846:   /* --- store r,c --- */
 9847:   switch ( iarg )
 9848:     { case 0: r0=r; c0=c; break;
 9849:       case 1: r1=r; c1=c; break;
 9850:       case 2: rt=r; ct=c; break; }
 9851:   } /* --- end-of-for(iarg) --- */
 9852: /* --- determine midpoint and maximum,minimum points --- */
 9853: rmid = 0.5*(rt + 0.5*(r0+r1));		/* y-coord at middle of bezier */
 9854: cmid = 0.5*(ct + 0.5*(c0+c1));		/* x-coord at middle of bezier */
 9855: rmin = min3(r0,r1,rmid);		/* lowest row */
 9856: cmin = min3(c0,c1,cmid);		/* leftmost col */
 9857: rmax = max3(r0,r1,rmid);		/* highest row */
 9858: cmax = max3(c0,c1,cmid);		/* rightmost col */
 9859: rdelta = rmax-rmin;			/* height */
 9860: cdelta = cmax-cmin;			/* width */
 9861: /* --- rescale coords so we start at 0,0 --- */
 9862: r0 -= rmin;  c0 -= cmin;		/* rescale r0,c0 */
 9863: r1 -= rmin;  c1 -= cmin;		/* rescale r1,c1 */
 9864: rt -= rmin;  ct -= cmin;		/* rescale rt,ct */
 9865: /* --- flip rows so 0,0 becomes lower-left corner instead of upper-left--- */
 9866: r0 = rdelta - r0 + 1;			/* map 0-->height-1, height-1-->0 */
 9867: r1 = rdelta - r1 + 1;
 9868: rt = rdelta - rt + 1;
 9869: /* --- determine width,height of raster needed for bezier --- */
 9870: width  = (int)(cdelta + 0.9999) + 1;	/* round width up */
 9871: height = (int)(rdelta + 0.9999) + 1;	/* round height up */
 9872: if ( msgfp!=NULL && msglevel>=29 )	/* debugging */
 9873:   fprintf(msgfp,"rastbezier> width,height,origin=%d,%d,%d; c0,r0=%g,%g; "
 9874:   "c1,r1=%g,%g\n rmin,mid,max=%g,%g,%g; cmin,mid,max=%g,%g,%g\n",
 9875:   width,height,origin, c0,r0, c1,r1, rmin,rmid,rmax, cmin,cmid,cmax);
 9876: /* -------------------------------------------------------------------------
 9877: allocate raster
 9878: -------------------------------------------------------------------------- */
 9879: /* --- sanity check on width,height args --- */
 9880: if ( width < 1 ||  width > 600
 9881: ||  height < 1 || height > 600 ) goto end_of_job;
 9882: /* --- allocate and initialize subraster for constructed bezier --- */
 9883: if ( (bezsp=new_subraster(width,height,pixsz)) /* allocate new subraster */
 9884: ==   NULL )  goto end_of_job;		/* quit if failed */
 9885: /* --- initialize bezier subraster parameters --- */
 9886: bezsp->type = IMAGERASTER;		/* image */
 9887: bezsp->symdef = NULL;			/* not applicable for image */
 9888: bezsp->baseline = height/2 + 2;		/* is a little above center good? */
 9889: bezsp->size = size;			/* size (probably unneeded) */
 9890: /* -------------------------------------------------------------------------
 9891: draw the bezier
 9892: -------------------------------------------------------------------------- */
 9893: bezier_raster ( bezsp->image,		/* embedded raster image */
 9894: 	r0, c0,				/* row0,col0 are lower-left corner */
 9895: 	r1, c1,				/* row1,col1 are upper-right */
 9896: 	rt, ct );			/* bezier tangent point */
 9897: /* -------------------------------------------------------------------------
 9898: return constructed bezier to caller
 9899: -------------------------------------------------------------------------- */
 9900: end_of_job:
 9901:   if ( workingparam != NULL )		/* caller wants origin */
 9902:     *workingparam = origin;		/* return center origin to caller */
 9903:   return ( bezsp );			/* return bezier to caller */
 9904: } /* --- end-of-function rastbezier() --- */
 9905: 
 9906: 
 9907: /* ==========================================================================
 9908:  * Function:	rastraise ( expression, size, basesp, arg1, arg2, arg3 )
 9909:  * Purpose:	\raisebox{lift}{subexpression} handler, returns subraster
 9910:  *		containing subexpression with its baseline "lifted" by lift
 9911:  *		pixels, scaled by \unitlength, or "lowered" if lift arg
 9912:  *		negative
 9913:  * --------------------------------------------------------------------------
 9914:  * Arguments:	expression (I/O) char **  to first char of null-terminated
 9915:  *				string immediately following \raisebox to be
 9916:  *				rasterized, and returning ptr immediately
 9917:  *				following last character processed.
 9918:  *		size (I)	int containing 0-7 default font size
 9919:  *		basesp (I)	subraster *  to character (or subexpression)
 9920:  *				immediately preceding \raisebox
 9921:  *				(unused, but passed for consistency)
 9922:  *		arg1 (I)	int unused
 9923:  *		arg2 (I)	int unused
 9924:  *		arg3 (I)	int unused
 9925:  * --------------------------------------------------------------------------
 9926:  * Returns:	( subraster * )	ptr to subraster corresponding to \raisebox
 9927:  *				requested, or NULL for any parsing error
 9928:  * --------------------------------------------------------------------------
 9929:  * Notes:     o	Summary of syntax...
 9930:  *		  \raisebox{lift}{subexpression}
 9931:  *	      o
 9932:  * ======================================================================= */
 9933: /* --- entry point --- */
 9934: subraster *rastraise ( char **expression, int size, subraster *basesp,
 9935: 			int arg1, int arg2, int arg3 )
 9936: {
 9937: /* -------------------------------------------------------------------------
 9938: Allocations and Declarations
 9939: -------------------------------------------------------------------------- */
 9940: char	*texsubexpr(), subexpr[MAXSUBXSZ+1], *liftexpr=subexpr; /* args */
 9941: subraster *rasterize(), *raisesp=NULL;	/* rasterize subexpr to be raised */
 9942: int	lift=0;				/* amount to raise/lower baseline */
 9943: /* -------------------------------------------------------------------------
 9944: obtain {lift} argument immediately following \raisebox command
 9945: -------------------------------------------------------------------------- */
 9946: /* --- parse for {lift} arg, and bump expression past it --- */
 9947: *expression = texsubexpr(*expression,liftexpr,0,"{","}",0,0);
 9948: if ( *liftexpr == '\000' ) goto end_of_job; /* couldn't get {lift} */
 9949: lift = (int)((unitlength*strtod(liftexpr,NULL))+0.0);	/*{lift} to integer*/
 9950: if ( abs(lift) > 200 ) lift=0;		/* sanity check */
 9951: /* -------------------------------------------------------------------------
 9952: obtain {subexpr} argument after {lift}, and rasterize it
 9953: -------------------------------------------------------------------------- */
 9954: /* --- parse for {subexpr} arg, and bump expression past it --- */
 9955: *expression = texsubexpr(*expression,subexpr,0,"{","}",0,0);
 9956: /* --- rasterize subexpression to be raised/lowered --- */
 9957: if ( (raisesp = rasterize(subexpr,size)) /* rasterize subexpression */
 9958: ==   NULL ) goto end_of_job;		/* and quit if failed */
 9959: /* -------------------------------------------------------------------------
 9960: raise/lower baseline and return it to caller
 9961: -------------------------------------------------------------------------- */
 9962: /* --- raise/lower baseline --- */
 9963: raisesp->baseline += lift;		/* new baseline (no height checks) */
 9964: /* --- return raised subexpr to caller --- */
 9965: end_of_job:
 9966:   return ( raisesp );			/* return raised subexpr to caller */
 9967: } /* --- end-of-function rastraise() --- */
 9968: 
 9969: 
 9970: /* ==========================================================================
 9971:  * Function:	rastrotate ( expression, size, basesp, arg1, arg2, arg3 )
 9972:  * Purpose:	\rotatebox{degrees}{subexpression} handler, returns subraster
 9973:  *		containing subexpression rotated by degrees (counterclockwise
 9974:  *		if degrees positive)
 9975:  * --------------------------------------------------------------------------
 9976:  * Arguments:	expression (I/O) char **  to first char of null-terminated
 9977:  *				string immediately following \rotatebox to be
 9978:  *				rasterized, and returning ptr immediately
 9979:  *				following last character processed.
 9980:  *		size (I)	int containing 0-7 default font size
 9981:  *		basesp (I)	subraster *  to character (or subexpression)
 9982:  *				immediately preceding \rotatebox
 9983:  *				(unused, but passed for consistency)
 9984:  *		arg1 (I)	int unused
 9985:  *		arg2 (I)	int unused
 9986:  *		arg3 (I)	int unused
 9987:  * --------------------------------------------------------------------------
 9988:  * Returns:	( subraster * )	ptr to subraster corresponding to \rotatebox
 9989:  *				requested, or NULL for any parsing error
 9990:  * --------------------------------------------------------------------------
 9991:  * Notes:     o	Summary of syntax...
 9992:  *		  \rotatebox{degrees}{subexpression}
 9993:  *	      o
 9994:  * ======================================================================= */
 9995: /* --- entry point --- */
 9996: subraster *rastrotate ( char **expression, int size, subraster *basesp,
 9997: 			int arg1, int arg2, int arg3 )
 9998: {
 9999: /* -------------------------------------------------------------------------
10000: Allocations and Declarations
10001: -------------------------------------------------------------------------- */
10002: char	*texsubexpr(), subexpr[MAXSUBXSZ+1], *degexpr=subexpr; /* args */
10003: subraster *rasterize(), *rotsp=NULL;	/* subraster for rotated subexpr */
10004: raster	*rastrot(), *rotrp=NULL;	/* rotate subraster->image 90 degs */
10005: int	delete_raster();		/* delete intermediate rasters */
10006: int	baseline=0;			/* baseline of rasterized image */
10007: double	strtod(),			/* convert ascii params to doubles */
10008: 	degrees=0.0, ipart,fpart;	/* degrees to be rotated */
10009: int	idegrees=0, isneg=0;		/* positive ipart, isneg=1 if neg */
10010: int	n90=0, isn90=1;			/* degrees is n90 multiples of 90 */
10011: /* -------------------------------------------------------------------------
10012: obtain {degrees} argument immediately following \rotatebox command
10013: -------------------------------------------------------------------------- */
10014: /* --- parse for {degrees} arg, and bump expression past it --- */
10015: *expression = texsubexpr(*expression,degexpr,0,"{","}",0,0);
10016: if ( *degexpr == '\000' ) goto end_of_job; /* couldn't get {degrees} */
10017: degrees = strtod(degexpr,NULL);		/* degrees to be rotated */
10018: if ( degrees < 0.0 )			/* clockwise rotation desired */
10019:   { degrees = -degrees;			/* flip sign so degrees positive */
10020:     isneg = 1; }			/* and set flag to indicate flip */
10021: fpart = modf(degrees,&ipart);		/* integer and fractional parts */
10022: ipart = (double)(((int)degrees)%360);	/* degrees mod 360 */
10023: degrees = ipart + fpart;		/* restore fractional part */
10024: if ( isneg )				/* if clockwise rotation requested */
10025:   degrees = 360.0 - degrees;		/* do equivalent counterclockwise */
10026: idegrees = (int)(degrees+0.5);		/* integer degrees */
10027: n90 = idegrees/90;			/* degrees is n90 multiples of 90 */
10028: isn90 = (90*n90==idegrees);		/*true if degrees is multiple of 90*/
10029: isn90 = 1;				/* forced true for time being */
10030: /* -------------------------------------------------------------------------
10031: obtain {subexpr} argument after {degrees}, and rasterize it
10032: -------------------------------------------------------------------------- */
10033: /* --- parse for {subexpr} arg, and bump expression past it --- */
10034: *expression = texsubexpr(*expression,subexpr,0,"{","}",0,0);
10035: /* --- rasterize subexpression to be rotated --- */
10036: if ( (rotsp = rasterize(subexpr,size))	/* rasterize subexpression */
10037: ==   NULL ) goto end_of_job;		/* and quit if failed */
10038: /* --- return unmodified image if no rotation requested --- */
10039: if ( abs(idegrees) < 2 ) goto end_of_job; /* don't bother rotating image */
10040: /* --- extract params for image to be rotated --- */
10041: rotrp = rotsp->image;			/* unrotated rasterized image */
10042: baseline = rotsp->baseline;		/* and baseline of that image */
10043: /* -------------------------------------------------------------------------
10044: rotate by multiples of 90 degrees
10045: -------------------------------------------------------------------------- */
10046: if ( isn90 )				/* rotation by multiples of 90 */
10047:  if ( n90 > 0 )				/* do nothing for 0 degrees */
10048:   {
10049:   n90 = 4-n90;				/* rasrot() rotates clockwise */
10050:   while ( n90 > 0 )			/* still have remaining rotations */
10051:     { raster *nextrp = rastrot(rotrp);	/* rotate raster image */
10052:       if ( nextrp == NULL ) break;	/* something's terribly wrong */
10053:       delete_raster(rotrp);		/* free previous raster image */
10054:       rotrp = nextrp;			/* and replace it with rotated one */
10055:       n90--; }				/* decrement remaining count */
10056:   } /* --- end-of-if(isn90) --- */
10057: /* -------------------------------------------------------------------------
10058: requested rotation not multiple of 90 degrees
10059: -------------------------------------------------------------------------- */
10060: if ( !isn90 )				/* explicitly construct rotation */
10061:   { ; }					/* not yet implemented */
10062: /* -------------------------------------------------------------------------
10063: re-populate subraster envelope with rotated image
10064: -------------------------------------------------------------------------- */
10065: /* --- re-init various subraster parameters, embedding raster in it --- */
10066: if ( rotrp != NULL )			/* rotated raster constructed okay */
10067:  { rotsp->type = IMAGERASTER;		/* signal constructed image */
10068:    rotsp->image = rotrp;		/* raster we just constructed */
10069:    /* --- now try to guess pleasing baseline --- */
10070:    if ( idegrees > 2 ) {		/* leave unchanged if unrotated */
10071:     if ( strlen(subexpr) < 3		/* we rotated a short expression */
10072:     ||   abs(idegrees-180) < 3 )	/* or just turned it upside-down */
10073:       baseline = rotrp->height - 1;	/* so set with nothing descending */
10074:     else				/* rotated a long expression */
10075:       baseline = (65*(rotrp->height-1))/100; } /* roughly center long expr */
10076:    rotsp->baseline = baseline; }	/* set baseline as calculated above*/
10077: /* --- return rotated subexpr to caller --- */
10078: end_of_job:
10079:   return ( rotsp );			/*return rotated subexpr to caller*/
10080: } /* --- end-of-function rastrotate() --- */
10081: 
10082: 
10083: /* ==========================================================================
10084:  * Function:	rastreflect ( expression, size, basesp, arg1, arg2, arg3 )
10085:  * Purpose:	\reflectbox[axis]{subexpression} handler, returns subraster
10086:  *		containing subexpression reflected horizontally (i.e., around
10087:  *		vertical axis, |_ becomes _|) if [axis] not given or axis=1,
10088:  *		or reflected vertically if axis=2 given.
10089:  * --------------------------------------------------------------------------
10090:  * Arguments:	expression (I/O) char **  to first char of null-terminated
10091:  *				string immediately following \reflectbox to
10092:  *				be rasterized, and returning ptr immediately
10093:  *				following last character processed.
10094:  *		size (I)	int containing 0-7 default font size
10095:  *		basesp (I)	subraster *  to character (or subexpression)
10096:  *				immediately preceding \reflectbox
10097:  *				(unused, but passed for consistency)
10098:  *		arg1 (I)	int unused
10099:  *		arg2 (I)	int unused
10100:  *		arg3 (I)	int unused
10101:  * --------------------------------------------------------------------------
10102:  * Returns:	( subraster * )	ptr to subraster corresponding to \reflectbox
10103:  *				requested, or NULL for any parsing error
10104:  * --------------------------------------------------------------------------
10105:  * Notes:     o	Summary of syntax...
10106:  *		  \reflectbox[axis]{subexpression}
10107:  *	      o
10108:  * ======================================================================= */
10109: /* --- entry point --- */
10110: subraster *rastreflect ( char **expression, int size, subraster *basesp,
10111: 			int arg1, int arg2, int arg3 )
10112: {
10113: /* -------------------------------------------------------------------------
10114: Allocations and Declarations
10115: -------------------------------------------------------------------------- */
10116: char	*texsubexpr(), subexpr[MAXSUBXSZ+1], *axisexpr=subexpr; /* args */
10117: subraster *rasterize(), *refsp=NULL;	/* subraster for reflected subexpr */
10118: raster	*rastref(), *refrp=NULL;	/* reflect subraster->image */
10119: int	axis = 1;			/* default horizontal reflection */
10120: int	delete_raster();		/* delete intermediate raster */
10121: int	baseline=0;			/* baseline of rasterized image */
10122: /* -------------------------------------------------------------------------
10123: obtain [axis] argument immediately following \reflectbox command, if given
10124: -------------------------------------------------------------------------- */
10125: /* --- check for optional [axis] arg  --- */
10126: if ( *(*expression) == '[' )		/*check for []-enclosed optional arg*/
10127:   { *expression = texsubexpr(*expression,axisexpr,255,"[","]",0,0);
10128:     axis = atoi(axisexpr);		/* convert [axis] to int */
10129:     if ( axis<1 || axis>2 )		/* check axis input */
10130:       axis = 1; }			/* back to default if illegal */
10131: /* -------------------------------------------------------------------------
10132: obtain {subexpr} argument after optional [axis], and rasterize it
10133: -------------------------------------------------------------------------- */
10134: /* --- parse for {subexpr} arg, and bump expression past it --- */
10135: *expression = texsubexpr(*expression,subexpr,0,"{","}",0,0);
10136: /* --- rasterize subexpression to be reflected --- */
10137: if ( (refsp = rasterize(subexpr,size))	/* rasterize subexpression */
10138: ==   NULL ) goto end_of_job;		/* and quit if failed */
10139: /* --- return unmodified image if no reflection requested --- */
10140: if ( axis<1 || axis>2 ) goto end_of_job; /* don't bother reflecting image */
10141: /* --- extract params for image to be reflected --- */
10142: refrp = refsp->image;			/* unreflected rasterized image */
10143: baseline = refsp->baseline;		/* and baseline of that image */
10144: /* -------------------------------------------------------------------------
10145: reflect image and adjust its parameters
10146: -------------------------------------------------------------------------- */
10147: /* --- reflect image --- */
10148: refrp = rastref(refsp->image,axis);	/* reflect raster image */
10149: if ( refrp == NULL ) goto end_of_job;	/* failed to reflect image */
10150: delete_raster(refsp->image);		/* free original raster image */
10151: refsp->image = refrp;			/*and replace it with reflected one*/
10152: /* --- adjust parameters --- */
10153: if ( axis == 2 )			/* for vertical reflection */
10154:   baseline = refrp->height - 1;		/* set with nothing descending */
10155: refsp->baseline = baseline;		/* reset baseline of reflected image*/
10156: /* --- return reflected subexpr to caller --- */
10157: end_of_job:
10158:   return ( refsp );			/*back to caller with reflected expr*/
10159: } /* --- end-of-function rastreflect() --- */
10160: 
10161: 
10162: /* ==========================================================================
10163:  * Function:	rastfbox ( expression, size, basesp, arg1, arg2, arg3 )
10164:  * Purpose:	\fbox{subexpression} handler, returns subraster
10165:  *		containing subexpression with frame box drawn around it
10166:  * --------------------------------------------------------------------------
10167:  * Arguments:	expression (I/O) char **  to first char of null-terminated
10168:  *				string immediately following \fbox to be
10169:  *				rasterized, and returning ptr immediately
10170:  *				following last character processed.
10171:  *		size (I)	int containing 0-5 default font size
10172:  *		basesp (I)	subraster *  to character (or subexpression)
10173:  *				immediately preceding \fbox
10174:  *				(unused, but passed for consistency)
10175:  *		arg1 (I)	int unused
10176:  *		arg2 (I)	int unused
10177:  *		arg3 (I)	int unused
10178:  * --------------------------------------------------------------------------
10179:  * Returns:	( subraster * )	ptr to subraster corresponding to \fbox
10180:  *				requested, or NULL for any parsing error
10181:  * --------------------------------------------------------------------------
10182:  * Notes:     o	Summary of syntax...
10183:  *		  \fbox[width][height]{subexpression}
10184:  *	      o
10185:  * ======================================================================= */
10186: /* --- entry point --- */
10187: subraster *rastfbox ( char **expression, int size, subraster *basesp,
10188: 			int arg1, int arg2, int arg3 )
10189: {
10190: /* -------------------------------------------------------------------------
10191: Allocations and Declarations
10192: -------------------------------------------------------------------------- */
10193: char	*texsubexpr(), subexpr[MAXSUBXSZ+1], widtharg[512]; /* args */
10194: subraster *rasterize(), *framesp=NULL;	/* rasterize subexpr to be framed */
10195: raster	*border_raster(), *bp=NULL;	/* framed image raster */
10196: double	strtod();			/* interpret [width][height] */
10197: int	fwidth=6, fthick=1;		/*extra frame width, line thickness*/
10198: int	width=(-1), height=(-1),	/* optional [width][height] args */
10199: 	iscompose = 0;			/* set true if optional args given */
10200: /* -------------------------------------------------------------------------
10201: obtain optional [width][height] arguments immediately following \fbox
10202: -------------------------------------------------------------------------- */
10203: /* --- first check for optional \fbox[width] --- */
10204: if ( *(*expression) == '[' )		/* check for []-enclosed width arg */
10205:   { *expression = texsubexpr(*expression,widtharg,511,"[","]",0,0);
10206:     if ( *widtharg != '\000' )		/* got widtharg */
10207:      { width = max2(1,iround(unitlength*strtod(widtharg,NULL)));
10208:        height = 1;  fwidth = 2; iscompose = 1; }
10209:   } /* --- end-of-if(**expression=='[') --- */
10210: if ( width > 0 )			/* found leading [width], so... */
10211:  if ( *(*expression) == '[' )		/* check for []-enclosed height arg */
10212:   { *expression = texsubexpr(*expression,widtharg,511,"[","]",0,0);
10213:     if ( *widtharg != '\000' )		/* got widtharg */
10214:      { height = max2(1,iround(unitlength*strtod(widtharg,NULL)));
10215:        fwidth = 0; }			/* no extra border */
10216:   } /* --- end-of-if(**expression=='[') --- */
10217: /* -------------------------------------------------------------------------
10218: obtain {subexpr} argument
10219: -------------------------------------------------------------------------- */
10220: /* --- parse for {subexpr} arg, and bump expression past it --- */
10221: *expression = texsubexpr(*expression,subexpr,0,"{","}",0,0);
10222: /* --- rasterize subexpression to be framed --- */
10223: if ( width<0 || height<0 )		/* no explicit dimensions given */
10224:   { if ( (framesp = rasterize(subexpr,size)) /* rasterize subexpression */
10225:     ==   NULL ) goto end_of_job; }	/* and quit if failed */
10226: else
10227:   { char composexpr[8192];		/* compose subexpr with empty box */
10228:     sprintf(composexpr,"\\compose{\\hspace{%d}\\vspace{%d}}{%s}",
10229:     width,height,subexpr);
10230:     if ( (framesp = rasterize(composexpr,size)) /* rasterize subexpression */
10231:     ==   NULL ) goto end_of_job; }	/* and quit if failed */
10232: /* -------------------------------------------------------------------------
10233: draw frame, reset params, and return it to caller
10234: -------------------------------------------------------------------------- */
10235: /* --- draw border --- */
10236: if ( (bp = border_raster(framesp->image,-fwidth,-fwidth,fthick,1))
10237: ==   NULL ) goto end_of_job;		/* draw border and quit if failed */
10238: /* --- replace original image and raise baseline to accommodate frame --- */
10239: framesp->image = bp;			/* replace image with framed one */
10240: if ( !iscompose )			/* simple border around subexpr */
10241:   framesp->baseline += fwidth;		/* so just raise baseline */
10242: else
10243:   framesp->baseline = (framesp->image)->height - 1; /* set at bottom */
10244: /* --- return framed subexpr to caller --- */
10245: end_of_job:
10246:   return ( framesp );			/* return framed subexpr to caller */
10247: } /* --- end-of-function rastfbox() --- */
10248: 
10249: 
10250: /* ==========================================================================
10251:  * Function:	rastinput ( expression, size, basesp, arg1, arg2, arg3 )
10252:  * Purpose:	\input{filename} handler, reads filename and returns
10253:  *		subraster containing image of expression read from filename
10254:  * --------------------------------------------------------------------------
10255:  * Arguments:	expression (I/O) char **  to first char of null-terminated
10256:  *				string immediately following \input to be
10257:  *				rasterized, and returning ptr immediately
10258:  *				following last character processed.
10259:  *		size (I)	int containing 0-5 default font size
10260:  *		basesp (I)	subraster *  to character (or subexpression)
10261:  *				immediately preceding \input
10262:  *				(unused, but passed for consistency)
10263:  *		arg1 (I)	int unused
10264:  *		arg2 (I)	int unused
10265:  *		arg3 (I)	int unused
10266:  * --------------------------------------------------------------------------
10267:  * Returns:	( subraster * )	ptr to subraster corresponding to expression
10268:  *				in filename, or NULL for any parsing error
10269:  * --------------------------------------------------------------------------
10270:  * Notes:     o	Summary of syntax...
10271:  *		  \input{filename}
10272:  *	      o
10273:  * ======================================================================= */
10274: /* --- entry point --- */
10275: subraster *rastinput ( char **expression, int size, subraster *basesp,
10276: 			int arg1, int arg2, int arg3 )
10277: {
10278: /* -------------------------------------------------------------------------
10279: Allocations and Declarations
10280: -------------------------------------------------------------------------- */
10281: char	*texsubexpr(), tag[1024]="\000", filename[1024]="\000"; /* args */
10282: subraster *rasterize(), *inputsp=NULL; /* rasterized input image */
10283: int	status, rastreadfile();	/* read input file */
10284: int	format=0, npts=0;	/* don't reformat (numerical) input */
10285: char	subexpr[MAXFILESZ+1] = "\000", /*concatanated lines from input file*/
10286: 	*mimeprep(),		/* preprocess inputted data */
10287: 	*dbltoa(), *reformat=NULL; /* reformat numerical input */
10288: /* -------------------------------------------------------------------------
10289: obtain [tag]{filename} argument
10290: -------------------------------------------------------------------------- */
10291: /* --- parse for optional [tag] or [fmt] arg, bump expression past it --- */
10292: if ( *(*expression) == '[' )		/* check for []-enclosed value */
10293:   { char argfld[MAXTOKNSZ+1];		/* optional argument field */
10294:     *expression = texsubexpr(*expression,argfld,MAXTOKNSZ,"[","]",0,0);
10295:     if ( (reformat=strstr(argfld,"dtoa")) != NULL ) /*dtoa/dbltoa requested*/
10296:       {	format = 1;			/* signal dtoa()/dbltoa() format */
10297: 	if ( (reformat=strchr(reformat,'=')) != NULL ) /* have dtoa= */
10298: 	  npts = (int)strtol(reformat+1,NULL,0); } /* so set npts */
10299:     if ( format == 0 )			/* reformat not requested */
10300:       strcpy(tag,argfld); }		/* so interpret arg as tag */
10301: /* --- parse for {filename} arg, and bump expression past it --- */
10302: *expression = texsubexpr(*expression,filename,1023,"{","}",0,0);
10303: /* --- check for alternate filename:tag --- */
10304: if ( *filename != '\000'		/* got filename */
10305: /*&& *tag == '\000'*/ )			/* but no [tag] */
10306:  { char	*delim = strchr(filename,':');	/* look for : in filename:tag */
10307:    if ( delim != (char *)NULL )		/* found it */
10308:     { *delim = '\000';			/* null-terminate filename at : */
10309:       strcpy(tag,delim+1); } }		/* and stuff after : is tag */
10310: /* --------------------------------------------------------------------------
10311: Read file and rasterize constructed subexpression
10312: -------------------------------------------------------------------------- */
10313: status = rastreadfile(filename,0,tag,subexpr); /* read file */
10314: if ( *subexpr == '\000' ) goto end_of_job;   /* quit if problem */
10315: /* --- rasterize input subexpression  --- */
10316: mimeprep(subexpr);			/* preprocess subexpression */
10317: if ( format == 1 )			/* dtoa()/dbltoa() */
10318:  { double d = strtod(subexpr,NULL);	/* interpret subexpr as double */
10319:    if ( d != 0.0 )			/* conversion to double successful */
10320:     if ( (reformat=dbltoa(d,npts)) != NULL ) /* reformat successful */
10321:      strcpy(subexpr,reformat); }	/*replace subexpr with reformatted*/
10322: inputsp = rasterize(subexpr,size);	/* rasterize subexpression */
10323: /* --- return input image to caller --- */
10324: end_of_job:
10325:   return ( inputsp );			/* return input image to caller */
10326: } /* --- end-of-function rastinput() --- */
10327: 
10328: 
10329: /* ==========================================================================
10330:  * Function:	rastcounter ( expression, size, basesp, arg1, arg2, arg3 )
10331:  * Purpose:	\counter[value]{filename} handler, returns subraster
10332:  *		containing image of counter value read from filename
10333:  *		(or optional [value]), and increments counter
10334:  * --------------------------------------------------------------------------
10335:  * Arguments:	expression (I/O) char **  to first char of null-terminated
10336:  *				string immediately following \counter to be
10337:  *				rasterized, and returning ptr immediately
10338:  *				following last character processed.
10339:  *		size (I)	int containing 0-5 default font size
10340:  *		basesp (I)	subraster *  to character (or subexpression)
10341:  *				immediately preceding \counter
10342:  *				(unused, but passed for consistency)
10343:  *		arg1 (I)	int unused
10344:  *		arg2 (I)	int unused
10345:  *		arg3 (I)	int unused
10346:  * --------------------------------------------------------------------------
10347:  * Returns:	( subraster * )	ptr to subraster corresponding to \counter
10348:  *				requested, or NULL for any parsing error
10349:  * --------------------------------------------------------------------------
10350:  * Notes:     o	Summary of syntax...
10351:  *		  \counter[value][logfile]{filename:tag}
10352:  *	      o	:tag is optional
10353:  * ======================================================================= */
10354: /* --- entry point --- */
10355: subraster *rastcounter ( char **expression, int size, subraster *basesp,
10356: 			int arg1, int arg2, int arg3 )
10357: {
10358: /* -------------------------------------------------------------------------
10359: Allocations and Declarations
10360: -------------------------------------------------------------------------- */
10361: char	*texsubexpr(), filename[1024]="\000", /* counter file */
10362: 	logfile[1024]="\000", tag[1024]="\000"; /*optional log file and tag*/
10363: subraster *rasterize(), *countersp=NULL; /* rasterized counter image */
10364: FILE	/* *fp=NULL,*/ *logfp=NULL; /* counter and log file pointers */
10365: int	status=0,rastreadfile(),rastwritefile(), /*read,write counter file*/
10366: 	isstrict = 1;		/* true to only write to existing files */
10367: char	text[MAXFILESZ] = "1_",	/* only line in counter file without tags */
10368: 	*delim = NULL,		/* delimiter in text */
10369: 	utext[128] = "1_",	/* default delimiter */
10370: 	*udelim = utext+1;	/* underscore delimiter */
10371: char	*rasteditfilename(),	/* edit log file name */
10372: 	*timestamp(),		/* timestamp for logging */
10373: 	*dbltoa();		/* double to comma-separated ascii */
10374: int	counter = 1,		/* atoi(text) (after _ removed, if present) */
10375: 	value = 1,		/* optional [value] argument */
10376: 	gotvalue = 0,		/* set true if [value] supplied */
10377: 	isdelta = 0,		/* set true if [+value] or [-value] is delta*/
10378: 	ordindex = (-1);	/* ordinal[] index to append ordinal suffix */
10379: /*--- ordinal suffixes based on units digit of counter ---*/
10380: static	char *ordinal[]={"th","st","nd","rd","th","th","th","th","th","th"};
10381: static	char *logvars[]={"REMOTE_ADDR","HTTP_REFERER",NULL}; /* log vars*/
10382: static	int  commentvar = 1;	/* logvars[commentvar] replaced by comment */
10383: /* -------------------------------------------------------------------------
10384: first obtain optional [value][logfile] args immediately following \counter
10385: -------------------------------------------------------------------------- */
10386: /* --- first check for optional \counter[value] --- */
10387: if ( *(*expression) == '[' )		/* check for []-enclosed value */
10388:   { *expression = texsubexpr(*expression,text,1023,"[","]",0,0);
10389:     if ( *text != '\000' )		/* got counter value (or logfile) */
10390:      if ( strlen(text) >= 1 ) {		/* and it's not an empty string */
10391:       if ( isthischar(*text,"+-0123456789") ) /* check for leading +-digit */
10392: 	gotvalue = 1;			/* signal we got optional value */
10393:       else				/* not +-digit, so must be logfile */
10394: 	strcpy(logfile,text); }		/* so just copy it */
10395:   } /* --- end-of-if(**expression=='[') --- */
10396: /* --- next check for optional \counter[][logfile] --- */
10397: if ( *(*expression) == '[' )		/* check for []-enclosed logfile */
10398:   { *expression = texsubexpr(*expression,filename,1023,"[","]",0,0);
10399:     if ( *filename != '\000' )		/* got logfile (or counter value) */
10400:      if ( strlen(filename) >= 1 ) {	/* and it's not an empty string */
10401:       if ( !(isthischar(*text,"+-0123456789")) /* not a leading +-digit */
10402:       ||   gotvalue )			/* or we already got counter value */
10403: 	strcpy(logfile,filename);	/* so just copy it */
10404:       else				/* leading +-digit must be value */
10405: 	{ strcpy(text,filename);	/* copy value to text line */
10406: 	  gotvalue = 1; } }		/* and signal we got optional value*/
10407:   } /* --- end-of-if(**expression=='[') --- */
10408: /* --- evaluate [value] if present --- */
10409: if ( gotvalue ) {			/*leading +-digit should be in text*/
10410:  if ( *text == '+' ) isdelta = (+1);	/* signal adding */
10411:  if ( *text == '-' ) isdelta = (-1);	/* signal subtracting */
10412:  value = (int)(strtod((isdelta==0?text:text+1),&udelim)+0.1); /*abs(value)*/
10413:  if ( isdelta == (-1) ) value = (-value); /* set negative value if needed */
10414:  counter = value;			/* re-init counter */
10415:  } /* --- end-of-if(gotvalue) --- */
10416: /* -------------------------------------------------------------------------
10417: obtain counter {filename} argument
10418: -------------------------------------------------------------------------- */
10419: /* --- parse for {filename} arg, and bump expression past it --- */
10420: *expression = texsubexpr(*expression,filename,1023,"{","}",0,0);
10421: /* --- check for counter filename:tag --- */
10422: if ( *filename != '\000' )		/* got filename */
10423:  if ( (delim=strchr(filename,':'))	/* look for : in filename:tag */
10424:  !=   (char *)NULL )			/* found it */
10425:   { *delim = '\000';			/* null-terminate filename at : */
10426:     strcpy(tag,delim+1); }		/* and stuff after : is tag */
10427: /* --------------------------------------------------------------------------
10428: Read and parse file, increment and rewrite counter (with optional underscore)
10429: -------------------------------------------------------------------------- */
10430: if ( strlen(filename) > 1 )		/* make sure we got {filename} arg */
10431:   {
10432:   /* --- read and interpret first (and only) line from counter file --- */
10433:   if ( !gotvalue || (isdelta!=0) )	/*if no [count] arg or if delta arg*/
10434:    if ( (status=rastreadfile(filename,1,tag,text)) > 0 ) /*try reading file*/
10435:     { char *vdelim = NULL;		/* underscore delim from file */
10436:       double fileval  = strtod(text,&vdelim); /* value and delim from file */
10437:       counter = (int)(fileval<0.0?fileval-0.1:fileval+0.1); /* integerized */
10438:       counter += value;			/* bump count by 1 or add/sub delta*/
10439:       if ( !gotvalue ) udelim=vdelim; }	/* default to file's current delim */
10440:   /* --- check for ordinal suffix --- */
10441:   if ( udelim != (char *)NULL )		/* have some delim after value */
10442:    if ( *udelim == '_' )		/* underscore signals ordinal */
10443:     { int abscount = (counter>=0?counter:(-counter)); /* abs(counter) */
10444:       ordindex = abscount%10;		/* least significant digit */
10445:       if ( abscount >= 10 )		/* counter is 10 or greater */
10446:        if ( (abscount/10)%10 == 1 )	/* and the last two are 10-19 */
10447: 	ordindex = 0; }		/* use th for 11,12,13 rather than st,nd,rd */
10448:   /* --- rewrite counter file --- */
10449:   if ( status >= 0 )			/* file was read okay */
10450:    { sprintf(text,"%d",counter);	/*build image of incremented counter*/
10451:      if ( ordindex >= 0 ) strcat(text,"_"); /* tack on _ */
10452:      if ( *tag == '\000' ) strcat(text,"\n"); /* and newline */
10453:      status = rastwritefile(filename,tag,text,isstrict); } /*rewrite counter*/
10454:   } /* --- end-of-if(strlen(filename)>1) --- */
10455: /* --------------------------------------------------------------------------
10456: log counter request
10457: -------------------------------------------------------------------------- */
10458: if ( strlen(logfile) > 1 )		/* optional [logfile] given */
10459:  {
10460:  char	comment[1024] = "\000",		/* embedded comment, logfile:comment*/
10461: 	*commptr = strchr(logfile,':');	/* check for : signalling comment */
10462:  int	islogokay = 1;			/* logfile must exist if isstrict */
10463:  if ( commptr != NULL )			/* have embedded comment */
10464:   { strcpy(comment,commptr+1);		/* comment follows : */
10465:     *commptr = '\000'; }		/* null-terminate actual logfile */
10466:  strcpy(logfile,rasteditfilename(logfile)); /* edit log file name */
10467:  if ( *logfile == '\000' ) islogokay = 0; /* given an invalid file name */
10468:  else if ( isstrict ) {			/*okay, but only write if it exists*/
10469:   if ( (logfp=fopen(logfile,"r")) == (FILE *)NULL ) /*doesn't already exist*/
10470:     islogokay = 0;			/* so don't write log file */
10471:   else fclose(logfp); }			/* close file opened for test read */
10472:  if ( islogokay )			/* okay to write logfile */
10473:   if ( (logfp = fopen(logfile,"a"))	/* open logfile */
10474:   != (FILE *)NULL ) {			/* opened successfully for append */
10475:    int	ilog=0;				/* logvars[] index */
10476:    fprintf(logfp,"%s  ",timestamp(TZDELTA,0)); /* first emit timestamp */
10477:    if (*tag=='\000') fprintf(logfp,"%s",filename); /* emit counter filename */
10478:    else fprintf(logfp,"<%s>",tag);	/* or tag if we have one */
10479:    fprintf(logfp,"=%d",counter);	/* emit counter value */
10480:    if ( status < 1 )			/* read or re-write failed */
10481:     fprintf(logfp,"(%s %d)","error status",status); /* emit error */
10482:    for ( ilog=0; logvars[ilog] != NULL; ilog++ ) /* log till end-of-table */
10483:     if ( ilog == commentvar		/* replace with comment... */
10484:     &&   commptr != NULL )		/* ...if available */  
10485:      fprintf(logfp,"  %.256s",comment); /* log embedded comment */
10486:     else
10487:      { char *logval = getenv(logvars[ilog]); /*getenv(variable) to be logged*/
10488:        fprintf(logfp,"  %.64s",		/* log variable */
10489: 	(logval!=NULL?logval:"<unknown>")); } /* emit value or <unknown> */
10490:    fprintf(logfp,"\n");			/* terminating newline */
10491:    fclose(logfp);			/* close logfile */
10492:    } /* --- end-of-if(islogokay&&logfp!=NULL) --- */
10493:  } /* --- end-of-if(strlen(logfile)>1) --- */
10494: /* --------------------------------------------------------------------------
10495: construct counter expression and rasterize it
10496: -------------------------------------------------------------------------- */
10497: /* --- construct expression --- */
10498: /*sprintf(text,"%d",counter);*/		/* start with counter */
10499: strcpy(text,dbltoa(((double)counter),0)); /* comma-separated counter value */
10500: if ( ordindex >= 0 )			/* need to tack on ordinal suffix */
10501:   { strcat(text,"^{\\underline{\\rm~");	/* start with ^ and {\underline{\rm */
10502:     strcat(text,ordinal[ordindex]);	/* then st,nd,rd, or th */
10503:     strcat(text,"}}"); }		/* finish with }} */
10504: /* --- rasterize it --- */
10505: countersp = rasterize(text,size);	/* rasterize counter subexpression */
10506: /* --- return counter image to caller --- */
10507: /*end_of_job:*/
10508:   return ( countersp );			/* return counter image to caller */
10509: } /* --- end-of-function rastcounter() --- */
10510: 
10511: 
10512: /* ==========================================================================
10513:  * Function:	rasttoday ( expression, size, basesp, arg1, arg2, arg3 )
10514:  * Purpose:	handle \today
10515:  * --------------------------------------------------------------------------
10516:  * Arguments:	expression (I/O) char **  to first char of null-terminated
10517:  *				string immediately following \today,
10518:  *				and returning ptr immediately
10519:  *				following last character processed.
10520:  *		size (I)	int containing 0-5 default font size
10521:  *		basesp (I)	subraster *  to character (or subexpression)
10522:  *				immediately preceding \today
10523:  *				(unused, but passed for consistency)
10524:  *		arg1 (I)	int unused
10525:  *		arg2 (I)	int unused
10526:  *		arg3 (I)	int unused
10527:  * --------------------------------------------------------------------------
10528:  * Returns:	( subraster * )	subraster ptr to date stamp
10529:  * --------------------------------------------------------------------------
10530:  * Notes:     o
10531:  * ======================================================================= */
10532: /* --- entry point --- */
10533: subraster *rasttoday ( char **expression, int size, subraster *basesp,
10534: 			int arg1, int arg2, int arg3 )
10535: {
10536: /* -------------------------------------------------------------------------
10537: Allocations and Declarations
10538: -------------------------------------------------------------------------- */
10539: char	*texsubexpr(), optarg[2050];	/* optional [+/-tzdelta,ifmt] args */
10540: char	*timestamp(), *today=optarg;	/* timestamp to be rasterized */
10541: subraster *rasterize(), *todaysp=NULL;	/* rasterize timestamp */
10542: int	ifmt=1, tzdelta=0;		/* default timestamp() args */
10543: /* -------------------------------------------------------------------------
10544: Get optional args \today[+/-tzdelta,ifmt]
10545: -------------------------------------------------------------------------- */
10546: /* --- check for optional \today[+/-tzdelta,ifmt] --- */
10547: if ( *(*expression) == '[' )		/* check for []-enclosed value */
10548:   { *expression = texsubexpr(*expression,optarg,2047,"[","]",0,0);
10549:     if ( *optarg != '\000' )		/* got optional arg */
10550:      { char *comma = strchr(optarg,','); /* comma between +/-tzdelta,ifmt */
10551:        int iarg, nargs=(comma==NULL?1:2); /* #optional args between []'s */
10552:        if ( comma != NULL ) *comma = '\000'; /* null-terminate first arg */
10553:        for ( iarg=1; iarg<=nargs; iarg++ ) /* process one or both args */
10554: 	{ char *arg = (iarg==1?optarg:comma+1); /* choose 1st or 2nd arg */
10555: 	  if ( isthischar(*arg,"+-") )	/* leading +/- signals tzdelta */
10556: 	    tzdelta = atoi(arg);	/* so interpret arg as tzdelta */
10557: 	  else ifmt = atoi(arg); }	/* else interpret args as ifmt */
10558:      } /* --- end-of-if(*optarg!='\0') --- */
10559:   } /* --- end-of-if(**expression=='[') --- */
10560: /* -------------------------------------------------------------------------
10561: Get timestamp and rasterize it
10562: -------------------------------------------------------------------------- */
10563: strcpy(today,"\\text{");		/* rasterize timestamp as text */
10564: strcat(today,timestamp(tzdelta,ifmt));	/* get timestamp */
10565: strcat(today,"}");			/* terminate \text{} braces */
10566: todaysp = rasterize(today,size);	/* rasterize timestamp */
10567: /* --- return timestamp raster to caller --- */
10568: /*end_of_job:*/
10569:   return ( todaysp );			/* return timestamp to caller */
10570: } /* --- end-of-function rasttoday() --- */
10571: 
10572: 
10573: /* ==========================================================================
10574:  * Function:	rastcalendar ( expression, size, basesp, arg1, arg2, arg3 )
10575:  * Purpose:	handle \calendar
10576:  * --------------------------------------------------------------------------
10577:  * Arguments:	expression (I/O) char **  to first char of null-terminated
10578:  *				string immediately following \calendar
10579:  *				and returning ptr immediately
10580:  *				following last character processed.
10581:  *		size (I)	int containing 0-5 default font size
10582:  *		basesp (I)	subraster *  to character (or subexpression)
10583:  *				immediately preceding \calendar
10584:  *				(unused, but passed for consistency)
10585:  *		arg1 (I)	int unused
10586:  *		arg2 (I)	int unused
10587:  *		arg3 (I)	int unused
10588:  * --------------------------------------------------------------------------
10589:  * Returns:	( subraster * )	subraster ptr to rendered one-month calendar
10590:  * --------------------------------------------------------------------------
10591:  * Notes:     o
10592:  * ======================================================================= */
10593: /* --- entry point --- */
10594: subraster *rastcalendar ( char **expression, int size, subraster *basesp,
10595: 			int arg1, int arg2, int arg3 )
10596: {
10597: /* -------------------------------------------------------------------------
10598: Allocations and Declarations
10599: -------------------------------------------------------------------------- */
10600: char	*texsubexpr(), optarg[2050];	/* optional [year,month] args */
10601: char	*calendar(), *calstr=NULL;	/* calendar to be rasterized */
10602: subraster *rasterize(), *calendarsp=NULL; /* rasterize calendar string */
10603: int	year=0,month=0,day=0, argval=0;	/* default calendar() args */
10604: /* -------------------------------------------------------------------------
10605: Get optional args \today[+/-tzdelta,ifmt]
10606: -------------------------------------------------------------------------- */
10607: /* --- check for optional \calendar[year,month] --- */
10608: if ( *(*expression) == '[' )		/* check for []-enclosed value */
10609:   { *expression = texsubexpr(*expression,optarg,2047,"[","]",0,0);
10610:     if ( *optarg != '\000' )		/* got optional arg */
10611:      { char *comma = strchr(optarg,','), /* comma between year,month */
10612:        *comma2 = NULL;			/* second comma before day */
10613:        int iarg, nargs=(comma==NULL?1:2); /* #optional args between []'s */
10614:        if ( comma != NULL ) { *comma = '\000'; /*null-terminate first arg*/
10615: 	if ( (comma2=strchr(comma+1,',')) != NULL ) /* have third arg */
10616: 	 { *comma2 = '\000'; nargs++; } } /* null-term 2nd arg, bump count */
10617:        for ( iarg=1; iarg<=nargs; iarg++ ) /* process one or both args */
10618: 	{ char *arg= (iarg==1?optarg:(iarg==2?comma+1:comma2+1)); /*get arg*/
10619: 	  argval = atoi(arg);		/* interpret arg as integer */
10620: 	  if ( iarg < 3 )		/* first two args are month,year */
10621: 	   {if ( argval>1972 && argval<2100 ) year = argval; /* year value */
10622: 	    else if ( argval>=1 && argval<=12 ) month = argval;} /*or month*/
10623: 	  else				/* only 3rd arg can be day */
10624: 	   if ( argval>=1 && argval<=31 ) day = argval; } /* day value */
10625:      } /* --- end-of-if(*optarg!='\0') --- */
10626:   } /* --- end-of-if(**expression=='[') --- */
10627: /* -------------------------------------------------------------------------
10628: Get calendar string and rasterize it
10629: -------------------------------------------------------------------------- */
10630: if ( msgfp!= NULL && msglevel>=9 )
10631:   fprintf(msgfp,"rastcalendar> year=%d, month=%d, day=%d\n",
10632:   year,month,day);
10633: calstr = calendar(year,month,day);		/* get calendar string */
10634: calendarsp = rasterize(calstr,size);	/* rasterize calendar string */
10635: /* --- return calendar raster to caller --- */
10636: /*end_of_job:*/
10637:   return ( calendarsp );		/* return calendar to caller */
10638: } /* --- end-of-function rastcalendar() --- */
10639: 
10640: 
10641: /* ==========================================================================
10642:  * Function:	rastnoop ( expression, size, basesp, nargs, arg2, arg3 )
10643:  * Purpose:	no op -- flush \escape without error
10644:  * --------------------------------------------------------------------------
10645:  * Arguments:	expression (I/O) char **  to first char of null-terminated
10646:  *				string immediately following \escape to be
10647:  *				flushed, and returning ptr immediately
10648:  *				following last character processed.
10649:  *		size (I)	int containing 0-5 default font size
10650:  *		basesp (I)	subraster *  to character (or subexpression)
10651:  *				immediately preceding \escape
10652:  *				(unused, but passed for consistency)
10653:  *		nargs (I)	int containing number of {}-args after
10654:  *				\escape to be flushed along with it
10655:  *		arg2 (I)	int unused
10656:  *		arg3 (I)	int unused
10657:  * --------------------------------------------------------------------------
10658:  * Returns:	( subraster * )	NULL subraster ptr
10659:  * --------------------------------------------------------------------------
10660:  * Notes:     o
10661:  * ======================================================================= */
10662: /* --- entry point --- */
10663: subraster *rastnoop ( char **expression, int size, subraster *basesp,
10664: 			int nargs, int arg2, int arg3 )
10665: {
10666: /* -------------------------------------------------------------------------
10667: Allocations and Declarations
10668: -------------------------------------------------------------------------- */
10669: char	*texsubexpr(), subexpr[MAXSUBXSZ+1]; /*dummy args eaten by \escape*/
10670: subraster *rasterize(), *noopsp=NULL;	/* rasterize subexpr */
10671: /* --- flush accompanying args if necessary --- */
10672: if ( nargs != NOVALUE			/* not unspecified */
10673: &&   nargs > 0 )			/* and args to be flushed */
10674:   while ( --nargs >= 0 )		/* count down */
10675:     *expression = texsubexpr(*expression,subexpr,0,"{","}",0,0); /*flush arg*/
10676: /* --- return null ptr to caller --- */
10677: /*end_of_job:*/
10678:   return ( noopsp );			/* return NULL ptr to caller */
10679: } /* --- end-of-function rastnoop() --- */
10680: 
10681: 
10682: /* ==========================================================================
10683:  * Function:	rastopenfile ( filename, mode )
10684:  * Purpose:	Opens filename[.tex] in mode, returning FILE *
10685:  * --------------------------------------------------------------------------
10686:  * Arguments:	filename (I/O)	char * to null-terminated string containing
10687:  *				name of file to open (preceded by path
10688:  *				relative to mimetex executable)
10689:  *				If fopen() fails, .tex appeneded,
10690:  *				and returned if that fopen() succeeds
10691:  *		mode (I)	char * to null-terminated string containing
10692:  *				fopen() mode
10693:  * --------------------------------------------------------------------------
10694:  * Returns:	( FILE * )	pointer to opened file, or NULL if error
10695:  * --------------------------------------------------------------------------
10696:  * Notes:     o
10697:  * ======================================================================= */
10698: /* --- entry point --- */
10699: FILE	*rastopenfile ( char *filename, char *mode )
10700: {
10701: /* -------------------------------------------------------------------------
10702: Allocations and Declarations
10703: -------------------------------------------------------------------------- */
10704: FILE	*fp = (FILE *)NULL /*,*fopen()*/; /*file pointer to opened filename*/
10705: char	texfile[2050] = "\000",		/* local, edited copy of filename */
10706: 	*rasteditfilename(),		/* prepend pathprefix if necessary */
10707: 	amode[512] = "r";		/* test open mode if arg mode=NULL */
10708: int	ismode = 0;			/* true of mode!=NULL */
10709: /* --------------------------------------------------------------------------
10710: Check mode and open file
10711: -------------------------------------------------------------------------- */
10712: /* --- edit filename --- */
10713: strncpy(texfile,rasteditfilename(filename),2047); /*edited copy of filename*/
10714: texfile[2047] = '\000';			/* make sure it's null terminated */
10715: /* --- check mode --- */
10716: if ( mode != (char *)NULL )		/* caller passed mode arg */
10717:  if ( *mode != '\000' )			/* and it's not an empty string */
10718:   { ismode = 1;				/* so flip mode flag true */
10719:     strncpy(amode,mode,254);		/* and replace "r" with caller's */
10720:     amode[254] = '\000';		/* make sure it's null terminated */
10721:     compress(amode,' '); }		/* remove embedded blanks */
10722: /* --- open filename or filename.tex --- */
10723: if ( strlen(texfile) > 1 )		/* make sure we got actual filename*/
10724:   if ( (fp = fopen(texfile,amode))	/* try opening given filename */
10725:   ==   NULL )				/* failed to open given filename */
10726:   { strcpy(filename,texfile);		/* signal possible filename error */
10727:     strcat(texfile,".tex");		/* but first try adding .tex */
10728:     if ( (fp = fopen(texfile,amode))	/* now try opening filename.tex */
10729:     !=   NULL )				/* filename.tex succeeded */
10730:       strcpy(filename,texfile); }	/* replace caller's filename */
10731: /* --- close file if only opened to check name --- */
10732: if ( !ismode && fp!=NULL )		/* no mode, so just checking */
10733:   fclose(fp);				/* close file, fp signals success */
10734: /* --- return fp or NULL to caller --- */
10735: /*end_of_job:*/
10736:   if ( msglevel>=9 && msgfp!=NULL )	/* debuging */
10737:     { fprintf(msgfp,"rastopenfile> returning fopen(%s,%s) = %s\n",
10738:       filename,amode,(fp==NULL?"NULL":"Okay")); fflush(msgfp); }
10739:   return ( fp );			/* return fp or NULL to caller */
10740: } /* --- end-of-function rastopenfile() --- */
10741: 
10742: 
10743: /* ==========================================================================
10744:  * Function:	rasteditfilename ( filename )
10745:  * Purpose:	edits filename to remove security problems,
10746:  *		e.g., removes all ../'s and ..\'s.
10747:  * --------------------------------------------------------------------------
10748:  * Arguments:	filename (I)	char * to null-terminated string containing
10749:  *				name of file to be edited
10750:  * --------------------------------------------------------------------------
10751:  * Returns:	( char * )	pointer to edited filename,
10752:  *				or empty string "\000" if any problem
10753:  * --------------------------------------------------------------------------
10754:  * Notes:     o
10755:  * ======================================================================= */
10756: /* --- entry point --- */
10757: char	*rasteditfilename ( char *filename )
10758: {
10759: /* -------------------------------------------------------------------------
10760: Allocations and Declarations
10761: -------------------------------------------------------------------------- */
10762: static	char editname[2050];		/*edited filename returned to caller*/
10763: char	*strchange();			/* prepend pathprefix if necessary */
10764: int	strreplace(),			/* remove ../'s and ..\'s */
10765: 	isprefix = (*pathprefix=='\000'?0:1); /* true if paths have prefix */
10766: /* --------------------------------------------------------------------------
10767: edit filename
10768: -------------------------------------------------------------------------- */
10769: /* --- first check filename arg --- */
10770: *editname = '\000';			/* init edited name as empty string*/
10771: if ( filename == (char *)NULL ) goto end_of_job; /* no filename arg */
10772: if ( *filename == '\000' ) goto end_of_job; /* filename is an empty string */
10773: /* --- init edited filename --- */
10774: strcpy(editname,filename);		/* init edited name as input name */
10775: compress(editname,' ');			/* remove embedded blanks */
10776: /* --- remove leading or embedded ....'s --- */
10777: while ( strreplace(editname,"....",NULL,0) > 0 ) ;  /* squeeze out ....'s */
10778: /* --- remove leading / and \ and dots (and blanks) --- */
10779: if ( *editname != '\000' )		/* still have chars in filename */
10780:  while ( isthischar(*editname," ./\\") ) /* absolute paths invalid */
10781:    strcpy(editname,editname+1);		/* so flush leading / or \ (or ' ')*/
10782: if ( *editname == '\000' ) goto end_of_job; /* no chars left in filename */
10783: /* --- remove leading or embedded ../'s and ..\'s --- */
10784: while ( strreplace(editname,"../",NULL,0) > 0 ) ;  /* squeeze out ../'s */
10785: while ( strreplace(editname,"..\\",NULL,0) > 0 ) ; /* and ..\'s */
10786: while ( strreplace(editname,"../",NULL,0) > 0 ) ;  /* and ../'s again */
10787: /* --- prepend path prefix (if compiled with -DPATHPREFIX) --- */
10788: if ( isprefix && *editname!='\000' )	/* filename is preceded by prefix */
10789:   strchange(0,editname,pathprefix);	/* so prepend prefix */
10790: end_of_job:
10791:   return ( editname );			/* back with edited filename */
10792: } /* --- end-of-function rasteditfilename() --- */
10793: 
10794: 
10795: /* ==========================================================================
10796:  * Function:	rastreadfile ( filename, islock, tag, value )
10797:  * Purpose:	Read filename, returning value as string
10798:  *		between <tag>...</tag> or entire file if tag=NULL passed.
10799:  * --------------------------------------------------------------------------
10800:  * Arguments:	filename (I)	char * to null-terminated string containing
10801:  *				name of file to read (preceded by path
10802:  *				relative to mimetex executable)
10803:  *		islock (I)	int containing 1 to lock file while reading
10804:  *				(hopefully done by opening in "r+" mode)
10805:  *		tag (I)		char * to null-terminated string containing
10806:  *				html-like tagname.  File contents between
10807:  *				<tag> and </tag> will be returned, or
10808:  *				entire file if tag=NULL passed.
10809:  *		value (O)	char * returning value between <tag>...</tag>
10810:  *				or entire file if tag=NULL.
10811:  * --------------------------------------------------------------------------
10812:  * Returns:	( int )		1=okay, 0=some error
10813:  * --------------------------------------------------------------------------
10814:  * Notes:     o
10815:  * ======================================================================= */
10816: /* --- entry point --- */
10817: int	rastreadfile ( char *filename, int islock, char *tag, char *value )
10818: {
10819: /* -------------------------------------------------------------------------
10820: Allocations and Declarations
10821: -------------------------------------------------------------------------- */
10822: FILE	*fp = (FILE *)NULL, *rastopenfile(); /* pointer to opened filename */
10823: char	texfile[1024] = "\000",		/* local copy of input filename */
10824: 	text[MAXLINESZ+1];		/* line from input file */
10825: char	*tagp, tag1[1024], tag2[1024];	/* left <tag> and right <tag/> */
10826: int	vallen=0, maxvallen=MAXFILESZ;	/* #chars in value, max allowed */
10827: int	status = (-1);			/* status returned, 1=okay */
10828: int	tagnum = 0;			/* tag we're looking for */
10829: /*int	islock = 1;*/			/* true to lock file */
10830: /* --------------------------------------------------------------------------
10831: Open file
10832: -------------------------------------------------------------------------- */
10833: /* --- first check output arg --- */
10834: if ( value == (char *)NULL ) goto end_of_job; /* no output buffer supplied */
10835: *value = '\000';			/* init buffer with empty string */
10836: /* --- open filename or filename.tex --- */
10837: if ( filename != (char *)NULL )		/* make sure we got filename arg */
10838:   { strncpy(texfile,filename,1023);	/* local copy of filename */
10839:     texfile[1023] = '\000';		/* make sure it's null terminated */
10840:     fp = rastopenfile(texfile,(islock?"r+":"r")); } /* try opening it */
10841: /* --- check that file opened --- */
10842: if ( fp == (FILE *)NULL )		/* failed to open file */
10843:   { sprintf(value,"{\\normalsize\\rm[file %s?]}",texfile);
10844:     goto end_of_job; }			/* return error message to caller */
10845: status = 0;				/* file opened successfully */
10846: if ( islock ) rewind(fp);		/* start at beginning of file */
10847: /* --------------------------------------------------------------------------
10848: construct <tag>'s
10849: -------------------------------------------------------------------------- */
10850: if ( tag != (char *)NULL )		/* caller passed tag arg */
10851:  if ( *tag != '\000' )			/* and it's not an empty string */
10852:   { strcpy(tag1,"<"); strcpy(tag2,"</"); /* begin with < and </ */
10853:     strcat(tag1,tag); strcat(tag2,tag);	/* followed by caller's tag */
10854:     strcat(tag1,">"); strcat(tag2,">");	/* ending both tags with > */
10855:     compress(tag1,' '); compress(tag2,' '); /* remove embedded blanks */
10856:     tagnum = 1; }			/* signal that we have tag */
10857: /* --------------------------------------------------------------------------
10858: Read file, concatnate lines
10859: -------------------------------------------------------------------------- */
10860: while ( fgets(text,MAXLINESZ-1,fp) != (char *)NULL ) { /*read input till eof*/
10861:   switch ( tagnum ) {			/* look for left- or right-tag */
10862:     case 0: status = 1; break;		/* no tag to look for */
10863:     case 1:				/* looking for opening left <tag> */
10864:       if ( (tagp=strstr(text,tag1)) == NULL ) break; /*haven't found it yet*/
10865:       strcpy(text,tagp+strlen(tag1));	/* shift out preceding text */
10866:       tagnum = 2;			/*now looking for closing right tag*/
10867:     case 2:				/* looking for closing right </tag> */
10868:       if ( (tagp=strstr(text,tag2)) == NULL ) break; /*haven't found it yet*/
10869:       *tagp = '\000';			/* terminate line at tag */
10870:       tagnum = 3;			/* done after this line */
10871:       status = 1;			/* successfully read tag */
10872:       break;
10873:     } /* ---end-of-switch(tagnum) --- */
10874:   if ( tagnum != 1 ) {			/* no tag or left tag already found*/
10875:     int	textlen = strlen(text);		/* #chars in current line */
10876:     if ( vallen+textlen > maxvallen ) break; /* quit before overflow */
10877:     strcat(value,text);			/* concat line to end of value */
10878:     vallen += textlen;			/* bump length */
10879:     if ( tagnum > 2 ) break; }		/* found right tag, so we're done */
10880:   } /* --- end-of-while(fgets()!=NULL) --- */
10881: if ( tagnum<1 || tagnum>2 ) status=1;	/* okay if no tag or we found tag */
10882: fclose ( fp );				/* close input file after reading */
10883: /* --- return value and status to caller --- */
10884: end_of_job:
10885:   return ( status );			/* return status to caller */
10886: } /* --- end-of-function rastreadfile() --- */
10887: 
10888: 
10889: /* ==========================================================================
10890:  * Function:	rastwritefile ( filename, tag, value, isstrict )
10891:  * Purpose:	Re/writes filename, replacing string between <tag>...</tag>
10892:  *		with value, or writing entire file as value if tag=NULL.
10893:  * --------------------------------------------------------------------------
10894:  * Arguments:	filename (I)	char * to null-terminated string containing
10895:  *				name of file to write (preceded by path
10896:  *				relative to mimetex executable)
10897:  *		tag (I)		char * to null-terminated string containing
10898:  *				html-like tagname.  File contents between
10899:  *				<tag> and </tag> will be replaced, or
10900:  *				entire file written if tag=NULL passed.
10901:  *		value (I)	char * containing string replacing value
10902:  *				between <tag>...</tag> or replacing entire
10903:  *				file if tag=NULL.
10904:  *		isstrict (I)	int containing 1 to only rewrite existing
10905:  *				files, or 0 to create new file if necessary.
10906:  * --------------------------------------------------------------------------
10907:  * Returns:	( int )		1=okay, 0=some error
10908:  * --------------------------------------------------------------------------
10909:  * Notes:     o
10910:  * ======================================================================= */
10911: /* --- entry point --- */
10912: int	rastwritefile( char *filename, char *tag, char *value, int isstrict )
10913: {
10914: /* -------------------------------------------------------------------------
10915: Allocations and Declarations
10916: -------------------------------------------------------------------------- */
10917: FILE	*fp = (FILE *)NULL, *rastopenfile(); /* pointer to opened filename */
10918: char	texfile[1024] = "\000",		/* local copy of input filename */
10919: 	filebuff[MAXFILESZ+1] = "\000",	/* entire contents of file */
10920: 	tag1[1024], tag2[1024],		/* left <tag> and right <tag/> */
10921: 	*strchange(),			/* put value between <tag>...</tag>*/
10922: 	*timestamp();			/* log modification time */
10923: int	istag=0, rastreadfile(),	/* read file if tag!=NULL */
10924: 	/*isstrict = (seclevel>5? 1:0),*/ /*true only writes existing files*/
10925: 	isnewfile = 0,			/* true if writing new file */
10926: 	status = 0;			/* status returned, 1=okay */
10927: int	istimestamp = 0;		/* true to update <timestamp> tag */
10928: /* --------------------------------------------------------------------------
10929: check args
10930: -------------------------------------------------------------------------- */
10931: /* --- check filename and value --- */
10932: if ( filename == (char *)NULL		/* quit if no filename arg supplied*/
10933: ||   value == (char *)NULL ) goto end_of_job; /* or no value arg supplied */
10934: if ( strlen(filename) < 2		/* quit if unreasonable filename */
10935: ||   *value == '\000' ) goto end_of_job; /* or empty value string supplied */
10936: /* --- establish filename[.tex] --- */
10937: strncpy(texfile,filename,1023);		/* local copy of input filename */
10938: texfile[1023] = '\000';			/* make sure it's null terminated */
10939: if ( rastopenfile(texfile,NULL)		/* unchanged or .tex appended */
10940: ==   (FILE *)NULL )			/* can't open, so write new file */
10941:   { if ( isstrict ) goto end_of_job;	/* fail if new files not permitted */
10942:     isnewfile = 1; }			/* signal we're writing new file */
10943: /* --- check whether tag supplied by caller --- */
10944: if ( tag != (char *)NULL )		/* caller passed tag argument */
10945:  if ( *tag != '\000' )			/* and it's not an empty string */
10946:   { istag = 1;				/* so flip tag flag true */
10947:     strcpy(tag1,"<"); strcpy(tag2,"</");  /* begin tags with < and </ */
10948:     strcat(tag1,tag); strcat(tag2,tag);   /* followed by caller's tag */
10949:     strcat(tag1,">"); strcat(tag2,">");	/* ending both tags with > */
10950:     compress(tag1,' '); compress(tag2,' '); } /* remove embedded blanks */
10951: /* --------------------------------------------------------------------------
10952: read existing file if just rewriting a single tag
10953: -------------------------------------------------------------------------- */
10954: /* --- read original file if only replacing a tag within it --- */
10955: *filebuff = '\000';			/* init as empty file */
10956: if ( !isnewfile )			/* if file already exists */
10957:  if ( istag )				/* and just rewriting one tag */
10958:   if ( rastreadfile(texfile,1,NULL,filebuff) /* read entire existing file */
10959:   <=   0 ) goto end_of_job;		/* signal error if failed to read */
10960: /* --------------------------------------------------------------------------
10961: construct new file data if needed (entire file replaced by value if no tag)
10962: -------------------------------------------------------------------------- */
10963: if ( istag )				/* only replacing tag in file */
10964:  {
10965:  /* --- find <tag> and </tag> in file --- */
10966:  int	tlen1=strlen(tag1),  tlen2=strlen(tag2), flen;  /*tag,buff lengths*/
10967:  char	*tagp1 = (isnewfile? NULL:strstr(filebuff,tag1)), /* <tag> in file*/
10968: 	*tagp2 = (isnewfile? NULL:strstr(filebuff,tag2)); /*</tag> in file*/
10969:  /* --- if adding new <tag> just concatanate at end of file --- */
10970:  if ( tagp1 == (char *)NULL )		/* add new tag to file */
10971:   {
10972:   /* --- preprocess filebuff --- */
10973:   if ( tagp2 != (char *)NULL )		/* apparently have ...</tag> */
10974:     strcpy(filebuff,tagp2+tlen2);	/* so get rid of leading ...</tag> */
10975:   if ( (flen = strlen(filebuff))	/* #chars currently in buffer */
10976:   > 0 )					/* we have non-empty buffer */
10977:    if (!isthischar(*(filebuff+flen-1),"\n\r")) /*no newline at end of file*/
10978:      if(0)strcat(filebuff,"\n");	/* so add one before new tag */
10979:   /* --- add new tag --- */
10980:   strcat(filebuff,tag1);		/* add opening <tag> */
10981:   strcat(filebuff,value);		/* then value */
10982:   strcat(filebuff,tag2);		/* finally closing </tag> */
10983:   strcat(filebuff,"\n");		/* newline at end of file */
10984:   } /* --- end-of-if(tagp1==NULL) --- */
10985:  else					/* found existing opening <tag> */
10986:   {
10987:   if ( tagp2 == NULL )			/* apparently have <tag>... */
10988:     { *(tagp1+tlen1) = '\000';		/* so get rid of trailing ... */
10989:       strcat(filebuff,value);		/* then concatanate value */
10990:       strcat(filebuff,tag2); }		/* and finally closing </tag> */
10991:   else					/* else have <tag>...<tag/> */
10992:    if ( (flen=((int)(tagp2-tagp1))-tlen1) /* len of .'s in <tag>...</tag> */
10993:    >=   0 )				/* usually <tag> precedes </tag> */
10994:     strchange(flen,tagp1+tlen1,value);	/* change ...'s to value */
10995:    else					/* weirdly, </tag> precedes <tag> */
10996:     { char fbuff[4096];			/* field buff for <tag>value</tag> */
10997:       if ( (flen = ((int)(tagp1-tagp2))+tlen1) /* strlen(</tag>...<tag>) */
10998:       <=   0 ) goto end_of_job;		/* must be internal error */
10999:       strcpy(fbuff,tag1);		/* set opening <tag> */
11000:       strcat(fbuff,value);		/* then value */
11001:       strcat(fbuff,tag2);		/* finally closing </tag> */
11002:       strchange(flen,tagp2,fbuff); }	/* replace original </tag>...<tag> */
11003:   } /* --- end-of-if/else(tagp1==NULL) --- */
11004:  } /* --- end-of-if(istag) --- */
11005: /* --------------------------------------------------------------------------
11006: rewrite file and return to caller
11007: -------------------------------------------------------------------------- */
11008: /* --- first open file for write --- */
11009: if ( (fp=rastopenfile(texfile,"w"))	/* open for write */
11010: ==   (FILE *)NULL ) goto end_of_job;	/* signal error if can't open */
11011: /* --- rewrite and close file --- */
11012: if ( fputs((istag?filebuff:value),fp)	/* write filebuff or value */
11013: !=  EOF ) status = 1;			/* signal success if succeeded */
11014: fclose ( fp );				/* close output file after writing */
11015: /* --- modify timestamp --- */
11016: if ( status > 0 )			/*forget timestamp if write failed*/
11017:  if ( istimestamp )			/* if we're updating timestamp */
11018:   if ( istag )				/* only log time in tagged file */
11019:    if ( strstr(tag,"timestamp") == (char *)NULL ) /* but avoid recursion */
11020:     { char fbuff[2048];			/* field buff <timestamp> value */
11021:       strcpy(fbuff,tag);		/* tag modified */
11022:       strcat(fbuff," modified at ");	/* spacer */
11023:       strcat(fbuff,timestamp(TZDELTA,0)); /* start with timestamp */
11024:       status = rastwritefile(filename,"timestamp",fbuff,1); }
11025: /* --- return status to caller --- */
11026: end_of_job:
11027:   return ( status );			/* return status to caller */
11028: } /* --- end-of-function rastwritefile() --- */
11029: 
11030: 
11031: /* ==========================================================================
11032:  * Function:	calendar ( year, month, day )
11033:  * Purpose:	returns null-terminated character string containing
11034:  *		\begin{array}...\end{array} for the one-month calendar
11035:  *		specified by year=1973...2099 and month=1...12.
11036:  *		If either arg out-of-range, today's value is used.
11037:  * --------------------------------------------------------------------------
11038:  * Arguments:	year (I)	int containing 1973...2099 or 0 for current
11039:  *				year
11040:  *		month (I)	int containing 1...12 or 0 for current month
11041:  *		day (I)		int containing day to emphasize or 0
11042:  * --------------------------------------------------------------------------
11043:  * Returns:	( char * )	char ptr to null-terminated buffer
11044:  *				containing \begin{array}...\end{array}
11045:  *				string that will render calendar for
11046:  *				requested month, or NULL for any error.
11047:  * --------------------------------------------------------------------------
11048:  * Notes:     o
11049:  * ======================================================================= */
11050: /* --- entry point --- */
11051: char	*calendar( int year, int month, int day )
11052: {
11053: /* -------------------------------------------------------------------------
11054: Allocations and Declarations
11055: -------------------------------------------------------------------------- */
11056: static char calbuff[4096];		/* calendar returned to caller */
11057: time_t	time_val = (time_t)(0);		/* binary value returned by time() */
11058: struct tm *tmstruct=(struct tm *)NULL, *localtime(); /* interpret time_val */
11059: int	yy=0, mm=0, dd=0;		/* today (emphasize today's dd) */
11060: int	idd=1, iday=0, daynumber();	/* day-of-week for idd=1...31 */
11061: char	aval[64];			/* ascii day or 4-digit year */
11062: /* --- calendar data --- */
11063: static	char *monthnames[] = { "?", "January", "February", "March", "April",
11064: 	 "May", "June", "July", "August", "September", "October",
11065: 	"November", "December", "?" } ;
11066: static	int modays[] =
11067: 	{ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0 };
11068: /* -------------------------------------------------------------------------
11069: initialization
11070: -------------------------------------------------------------------------- */
11071: /* --- get current date/time --- */
11072: time((time_t *)(&time_val));		/* get date and time */
11073: tmstruct = localtime((time_t *)(&time_val)); /* interpret time_val */
11074: yy  =  1900 + (int)(tmstruct->tm_year);	/* current four-digit year */
11075: mm  =  1 + (int)(tmstruct->tm_mon);	/* current month, 1-12 */
11076: dd  =  (int)(tmstruct->tm_mday);	/* current day, 1-31 */
11077: /* --- check args --- */
11078: if ( year<1973 || year>2099 ) year  = yy; /* current year if out-of-bounds */
11079: if ( month<1 || month>12 ) month = mm;	/* current month if out-of-bounds */
11080: if ( month==mm && year==yy && day==0 )	/* current month and default day */
11081:   day = dd;				/* emphasize current day */
11082: modays[2] = (year%4==0?29:28);		/* Feb has 29 days in leap years */
11083: /* --- initialize calendar string --- */
11084: strcpy(calbuff,"{\\begin{gather}");	/* center `month year` above cal */
11085: strcat(calbuff,"\\small\\text{");	/* month set in roman */
11086: strcat(calbuff,monthnames[month]);	/* insert month name */
11087: strcat(calbuff," }");			/* add a space */
11088: sprintf(aval,"%d",year);		/* convert year to ascii */
11089: strcat(calbuff,aval);			/* add year */
11090: strcat(calbuff,"\\\\");			/* end top row */
11091: strcat(calbuff,				/* now begin calendar arrayr */
11092: 	"\\begin{array}{|c|c|c|c|c|c|c|CCCCCC} \\hline"
11093: 	"\\tiny\\text{Sun} & \\tiny\\text{Mon} & \\tiny\\text{Tue} &"
11094: 	"\\tiny\\text{Wed} & \\tiny\\text{Thu} & \\tiny\\text{Fri} &"
11095: 	"\\tiny\\text{Sat} \\\\ \\hline " );
11096: /* -------------------------------------------------------------------------
11097: generate calendar
11098: -------------------------------------------------------------------------- */
11099: for ( idd=1; idd<=modays[month]; idd++ ) /* run through days of month */
11100:   {
11101:   /* --- get day-of-week for this day --- */
11102:   iday = 1 + (daynumber(year,month,idd)%7); /* 1=Monday...7=Sunday */
11103:   if ( iday == 7 ) iday = 0;		/* now 0=Sunday...6=Saturday */
11104:   /* --- may need empty cells at beginning of month --- */
11105:   if ( idd == 1 )			/* first day of month */
11106:    if ( iday > 0 )			/* need to skip cells */
11107:     { strcpy(aval,"\\ &\\ &\\ &\\ &\\ &\\ &\\ &\\ &\\ &\\"); /*cells to skip*/
11108:       aval[3*iday] = '\000';		/*skip cells preceding 1st of month*/
11109:       strcat(calbuff,aval); }		/* add skip string to buffer */
11110:   /* --- add idd to current cell --- */
11111:   sprintf(aval,"%d",idd);		/* convert idd to ascii */
11112:   if ( idd == day			/* emphasize today's date */
11113:   /*&&   month==mm && year==yy*/ )	/* only if this month's calendar */
11114:    { strcat(calbuff,"{\\fs{-1}\\left\\langle "); /*emphasize, 1 size smaller*/
11115:      strcat(calbuff,aval);		/* put in idd */
11116:      strcat(calbuff,"\\right\\rangle}"); } /* finish emphasis */
11117:   else					/* not today's date */
11118:     strcat(calbuff,aval);		/* so just put in idd */
11119:   /* --- terminate cell --- */
11120:   if ( idd < modays[month] ) {		/* not yet end-of-month */
11121:    if ( iday < 6 )			/* still have days left in week */
11122:     strcat(calbuff,"&");		/* new cell in same week */
11123:    else					/* reached end-of-week */
11124:     strcat(calbuff,"\\\\ \\hline"); }	/* so start new week */
11125:   } /* --- end-of-for(idd) --- */
11126: strcat(calbuff,"\\\\ \\hline");		/* final underline at end-of-month */
11127: /* --- return calendar to caller --- */
11128: strcat(calbuff,"\\end{array}\\end{gather}}"); /* terminate array */
11129: return ( calbuff );			/* back to caller with calendar */
11130: } /* --- end-of-function calendar() --- */
11131: 
11132: 
11133: /* ==========================================================================
11134:  * Function:	timestamp ( tzdelta, ifmt )
11135:  * Purpose:	returns null-terminated character string containing
11136:  *		current date:time stamp as ccyy-mm-dd:hh:mm:ss{am,pm}
11137:  * --------------------------------------------------------------------------
11138:  * Arguments:	tzdelta (I)	integer, positive or negative, containing
11139:  *				containing number of hours to be added or
11140:  *				subtracted from system time (to accommodate
11141:  *				your desired time zone).
11142:  *		ifmt (I)	integer containing 0 for default format
11143:  * --------------------------------------------------------------------------
11144:  * Returns:	( char * )	ptr to null-terminated buffer
11145:  *				containing current date:time stamp
11146:  * --------------------------------------------------------------------------
11147:  * Notes:     o
11148:  * ======================================================================= */
11149: /* --- entry point --- */
11150: char	*timestamp( int tzdelta, int ifmt )
11151: {
11152: /* -------------------------------------------------------------------------
11153: Allocations and Declarations
11154: -------------------------------------------------------------------------- */
11155: static	char timebuff[256];		/* date:time buffer back to caller */
11156: /*long	time_val = 0L;*/		/* binary value returned by time() */
11157: time_t	time_val = (time_t)(0);		/* binary value returned by time() */
11158: struct tm *tmstruct=(struct tm *)NULL, *localtime(); /* interpret time_val */
11159: int	year=0, hour=0,ispm=1,		/* adjust year, and set am/pm hour */
11160: 	month=0, day=0;			/* adjust day and month for delta  */
11161: int	tzadjust();			/* time zone adjustment function */
11162: int	daynumber();			/* #days since Jan 1, 1973 */
11163: static	char *daynames[] = { "Monday", "Tuesday", "Wednesday",
11164: 	 "Thursday", "Friday", "Saturday", "Sunday" } ;
11165: static	char *monthnames[] = { "?", "January", "February", "March", "April",
11166: 	 "May", "June", "July", "August", "September", "October",
11167: 	"November", "December", "?" } ;
11168: /* -------------------------------------------------------------------------
11169: get current date:time, adjust values, and and format stamp
11170: -------------------------------------------------------------------------- */
11171: /* --- first init returned timebuff in case of any error --- */
11172: *timebuff = '\000';
11173: /* --- get current date:time --- */
11174: time((time_t *)(&time_val));		/* get date and time */
11175: tmstruct = localtime((time_t *)(&time_val)); /* interpret time_val */
11176: /* --- extract fields --- */
11177: year  = (int)(tmstruct->tm_year);	/* local copy of year,  0=1900 */
11178: month = (int)(tmstruct->tm_mon) + 1;	/* local copy of month, 1-12 */
11179: day   = (int)(tmstruct->tm_mday);	/* local copy of day,   1-31 */
11180: hour  = (int)(tmstruct->tm_hour);	/* local copy of hour,  0-23 */
11181: /* --- adjust year --- */
11182: year += 1900;				/* set century in year */
11183: /* --- adjust for timezone --- */
11184: tzadjust(tzdelta,&year,&month,&day,&hour);
11185: /* --- check params --- */
11186: if ( hour<0  || hour>23
11187: ||   day<1   || day>31
11188: ||   month<1 || month>12
11189: ||   year<1973 ) goto end_of_job;
11190: /* --- adjust hour for am/pm --- */
11191: switch ( ifmt )
11192:   {
11193:   default:
11194:   case 0:
11195:     if ( hour < 12 )			/* am check */
11196:      { ispm=0;				/* reset pm flag */
11197:        if ( hour == 0 ) hour = 12; }	/* set 00hrs = 12am */
11198:     if ( hour > 12 ) hour -= 12;	/* pm check sets 13hrs to 1pm, etc */
11199:     break;
11200:   } /* --- end-of-switch(ifmt) --- */
11201: /* --- format date:time stamp --- */
11202: switch ( ifmt )
11203:   {
11204:   default:
11205:   case 0:  /* --- 2005-03-05:11:49:59am --- */
11206:     sprintf(timebuff,"%04d-%02d-%02d:%02d:%02d:%02d%s", year,month,day,
11207:     hour,(int)(tmstruct->tm_min),(int)(tmstruct->tm_sec),((ispm)?"pm":"am"));
11208:     break;
11209:   case 1:  /* --- Saturday, March 5, 2005 --- */
11210:     sprintf(timebuff,"%s, %s %d, %d",
11211:     daynames[daynumber(year,month,day)%7],monthnames[month],day,year);
11212:     break;
11213:   case 2: /* --- Saturday, March 5, 2005, 11:49:59am --- */
11214:     sprintf(timebuff,"%s, %s %d, %d, %d:%02d:%02d%s",
11215:     daynames[daynumber(year,month,day)%7],monthnames[month],day,year,
11216:     hour,(int)(tmstruct->tm_min),(int)(tmstruct->tm_sec),((ispm)?"pm":"am"));
11217:     break;
11218:   case 3: /* --- 11:49:59am --- */
11219:     sprintf(timebuff,"%d:%02d:%02d%s",
11220:     hour,(int)(tmstruct->tm_min),(int)(tmstruct->tm_sec),((ispm)?"pm":"am"));
11221:     break;
11222:   } /* --- end-of-switch(ifmt) --- */
11223: end_of_job:
11224:   return ( timebuff );			/* return stamp to caller */
11225: } /* --- end-of-function timestamp() --- */
11226: 
11227: 
11228: /* ==========================================================================
11229:  * Function:	tzadjust ( tzdelta, year, month, day, hour )
11230:  * Purpose:	Adjusts hour, and day,month,year if necessary,
11231:  *		by delta increment to accommodate your time zone.
11232:  * --------------------------------------------------------------------------
11233:  * Arguments:	tzdelta (I)	integer, positive or negative, containing
11234:  *				containing number of hours to be added or
11235:  *				subtracted from given time (to accommodate
11236:  *				your desired time zone).
11237:  *		year (I)	addr of int containing        4-digit year
11238:  *		month (I)	addr of int containing month  1=Jan - 12=Dec.
11239:  *		day (I)		addr of int containing day    1-31 for Jan.
11240:  *		hour (I)	addr of int containing hour   0-23
11241:  * Returns:	( int )		1 for success, or 0 for error
11242:  * --------------------------------------------------------------------------
11243:  * Notes:     o
11244:  * ======================================================================= */
11245: /* --- entry point --- */
11246: int	tzadjust ( int tzdelta, int *year, int *month, int *day, int *hour )
11247: {
11248: /* --------------------------------------------------------------------------
11249: Allocations and Declarations
11250: -------------------------------------------------------------------------- */
11251: int	yy = *year, mm = *month, dd = *day, hh = *hour; /*dereference args*/
11252: /* --- calendar data --- */
11253: static	int modays[] =
11254: 	{ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0 };
11255: /* --------------------------------------------------------------------------
11256: check args
11257: -------------------------------------------------------------------------- */
11258: if ( mm<1 || mm>12 ) return(-1);	/* bad month */
11259: if ( dd<1 || dd>modays[mm] ) return(-1); /* bad day */
11260: if ( hh<0 || hh>23 ) return(-1);	/* bad hour */
11261: if ( tzdelta>23 || tzdelta<(-23) ) return(-1); /* bad tzdelta */
11262: /* --------------------------------------------------------------------------
11263: make adjustments
11264: -------------------------------------------------------------------------- */
11265: /* --- adjust hour --- */
11266: hh += tzdelta;				/* apply caller's delta */
11267: /* --- adjust for feb 29 --- */
11268: modays[2] = (yy%4==0?29:28);		/* Feb has 29 days in leap years */
11269: /* --- adjust day --- */
11270: if ( hh < 0 )				/* went to preceding day */
11271:   { dd--;  hh += 24; }
11272: if ( hh > 23 )				/* went to next day */
11273:   { dd++;  hh -= 24; }
11274: /* --- adjust month --- */
11275: if ( dd < 1 )				/* went to preceding month */
11276:   { mm--;  dd = modays[mm]; }
11277: if ( dd > modays[mm] )			/* went to next month */
11278:   { mm++;  dd = 1; }
11279: /* --- adjust year --- */
11280: if ( mm < 1 )				/* went to preceding year */
11281:   { yy--;  mm = 12;  dd = modays[mm]; }
11282: if ( mm > 12 )				/* went to next year */
11283:   { yy++;  mm = 1;   dd = 1; }
11284: /* --- back to caller --- */
11285: *year=yy; *month=mm; *day=dd; *hour=hh;	/* reset adjusted args */
11286: return ( 1 );
11287: } /* --- end-of-function tzadjust() --- */
11288: 
11289: 
11290: /* ==========================================================================
11291:  * Function:	daynumber ( year, month, day )
11292:  * Purpose:	Returns number of actual calendar days from Jan 1, 1973
11293:  *		to the given date (e.g., bvdaynumber(1974,1,1)=365).
11294:  * --------------------------------------------------------------------------
11295:  * Arguments:	year (I)	int containing year -- may be either 1995 or
11296:  *				95, or may be either 2010 or 110 for those
11297:  *				years.
11298:  *		month (I)	int containing month, 1=Jan thru 12=Dec.
11299:  *		day (I)		int containing day of month, 1-31 for Jan, etc.
11300:  * Returns:	( int )		Number of days from Jan 1, 1973 to given date,
11301:  *				or -1 for error (e.g., year<1973).
11302:  * --------------------------------------------------------------------------
11303:  * Notes:     o
11304:  * ======================================================================= */
11305: /* --- entry point --- */
11306: int	daynumber ( int year, int month, int day )
11307: {
11308: /* --------------------------------------------------------------------------
11309: Allocations and Declarations
11310: -------------------------------------------------------------------------- */
11311: /* --- returned value (note: returned as a default "int") --- */
11312: int	ndays;				/* #days since jan 1, year0 */
11313: /* --- initial conditions --- */
11314: static	int year0 = 73, 		/* jan 1 was a monday, 72 was a leap */
11315: 	days4yrs = 1461,		/* #days in 4 yrs = 365*4 + 1 */
11316: 	days1yr  = 365;
11317: /* --- table of accumulated days per month (last index not used) --- */
11318: static	int modays[] =
11319: 	{ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
11320: /* --- variables for #days since day0 --- */
11321: int	nyears, nfouryrs;		/*#years, #4-yr periods since year0*/
11322: /* --------------------------------------------------------------------------
11323: Check input
11324: -------------------------------------------------------------------------- */
11325: if ( month < 1 || month > 12 )		/*month used as index, so must be ok*/
11326: 	return ( -1 );			/* otherwise, forget it */
11327: if ( year >= 1900 ) year -= 1900;	/*use two-digit years (3 after 2000)*/
11328: /* --------------------------------------------------------------------------
11329: Find #days since jan 1, 1973
11330: -------------------------------------------------------------------------- */
11331: /* --- figure #complete 4-year periods and #remaining yrs till current --- */
11332: nyears = year - year0;			/* #years since year0 */
11333: if ( nyears < 0 ) return ( -1 );	/* we're not working backwards */
11334: nfouryrs = nyears/4;			/* #complete four-year periods */
11335: nyears -= (4*nfouryrs); 		/* remainder excluding current year*/
11336: /* --- #days from jan 1, year0 till jan 1, this year --- */
11337: ndays = (days4yrs*nfouryrs)		/* #days in 4-yr periods */
11338:       +  (days1yr*nyears);		/* +remaining days */
11339: /*if ( year > 100 ) ndays--;*/		/* subtract leap year for 2000AD */
11340: /* --- add #days within current year --- */
11341: ndays += (modays[month-1] + (day-1));
11342: /* --- may need an extra day if current year is a leap year --- */
11343: if ( nyears == 3 )			/*three preceding yrs so this is 4th*/
11344:     { if ( month > 2 )			/* past feb so need an extra day */
11345: 	/*if ( year != 100 )*/		/* unless it's 2000AD */
11346: 	  ndays++; }			/* so add it in */
11347: return ( (int)(ndays) );		/* #days back to caller */
11348: } /* --- end-of-function daynumber() --- */
11349: 
11350: 
11351: /* ==========================================================================
11352:  * Function:	dbltoa ( dblval, npts )
11353:  * Purpose:	Converts double to ascii, in financial format
11354:  *		(e.g., comma-separated and negatives enclosed in ()'s).
11355:  * -------------------------------------------------------------------------
11356:  * Arguments:	dblval (I)	double containing value to be converted.
11357:  *		npts (I)	int containing #places after decimal point
11358:  *				to be displayed in returned string.
11359:  * Returns:	( char * )	null-terminated string containing
11360:  *				double converted to financial format.
11361:  * -------------------------------------------------------------------------
11362:  * Notes:     o
11363:  * ======================================================================= */
11364: /* --- entry point --- */
11365: char	*dbltoa ( double dblval, int npts )
11366: /* double dblval;
11367:    int	npts; */
11368: {
11369: /* -------------------------------------------------------------------------
11370: Allocations and Declarations
11371: ------------------------------------------------------------------------- */
11372: static	char finval[256];		/* buffer returned to caller */
11373: static	char digittbl[32]="0123456789*"; /* table of ascii decimal digits */
11374: char	*finptr = finval;		/* ptr to next char being converted*/
11375: double	floor();			/* integer which is glb(double) */
11376: double	dbldigit;			/* to shift out digits from dblval */
11377: int	digit;				/* one digit from dblval */
11378: int	isneg = 0;			/* reset true if dblval negative */
11379: int	ifrac = 0;			/* npts fractional digits of dblval*/
11380: char	digits[64]; int ndigits=0;	/* all the digits [0]=least signif */
11381: /* -------------------------------------------------------------------------
11382: Check sign
11383: ------------------------------------------------------------------------- */
11384: if ( dblval < 0.0 )			/* got a negative value to convert */
11385:     { isneg=1; dblval=(-dblval); }	/* set flag and make it positive */
11386: /* -------------------------------------------------------------------------
11387: Get fractional part of dblval if required
11388: ------------------------------------------------------------------------- */
11389: if ( npts > 0 )
11390:     { int ipts = npts;			/* loop index */
11391:       dbldigit = dblval-floor(dblval);	/* fractional part as double */
11392:       digit = 1;			/* check if rounded frac > 1 */
11393:       while ( --ipts >= 0 )		/* count down */
11394: 	{ dbldigit *= 10.0;		/* shift left one digit at a time */
11395: 	  digit *= 10; }		/* and keep max up-to-date */
11396:       ifrac = (int)(dbldigit + 0.5);	/* store fractional part as integer*/
11397:       if ( ifrac >= digit )		/* round to next whole number */
11398: 	{ dblval++; ifrac=0; }		/* bump val, reset frac to zero */
11399:     } /* --- end-of-if(npts>0) --- */
11400: else dblval += 0.5;			/* no frac, round to nearest whole */
11401: /* -------------------------------------------------------------------------
11402: Get whole digits
11403: ------------------------------------------------------------------------- */
11404: dblval = floor(dblval);			/* get rid of fractional part */
11405: while ( dblval > 0.0 )			/* still have data digits remaining*/
11406:     { dbldigit = floor(dblval/10.0);	/* shift out next digit */
11407:       digit = (int)(dblval - 10.0*dbldigit + 0.01); /* least signif digit */
11408:       if ( digit<0 || digit>9 ) digit=10; /* index check */
11409:       digits[ndigits++] = digittbl[digit]; /* store ascii digit */
11410:       dblval = dbldigit; }		/* ready for next digit */
11411: if ( ndigits < 1 ) digits[ndigits++] = '0'; /* store a single '0' for 0.0 */
11412: /* -------------------------------------------------------------------------
11413: Format whole part from digits[] array
11414: ------------------------------------------------------------------------- */
11415: if ( isneg ) *finptr++ = '(';		/* leading paren for negative value*/
11416: for ( digit=ndigits-1; digit>=0; digit-- ) /* start with most significant */
11417:     { *finptr++ = digits[digit];	/* store digit */
11418:       if ( digit>0 && digit%3==0 )	/* need a comma */
11419: 	*finptr++ = ','; }		/* put in separating comma */
11420: /* -------------------------------------------------------------------------
11421: Format fractional part using ifrac
11422: ------------------------------------------------------------------------- */
11423: if ( npts > 0 )
11424:     { *finptr++ = '.';			/* start with decimal point */
11425:       sprintf(finptr,"%0*d",npts,ifrac); /* convert to string */
11426:       finptr += npts; }			/* bump ptr past fractional digits */
11427: /* -------------------------------------------------------------------------
11428: End-of-Job
11429: ------------------------------------------------------------------------- */
11430: if ( isneg ) *finptr++ = ')';		/*trailing paren for negative value*/
11431: *finptr = '\000';			/* null-terminate converted double */
11432: return ( finval );			/* converted double back to caller */
11433: } /* --- end-of-function dbltoa() --- */
11434: 
11435: 
11436: /* ==========================================================================
11437:  * Function:	aalowpass ( rp, bytemap, grayscale )
11438:  * Purpose:	calculates a lowpass anti-aliased bytemap
11439:  *		for rp->bitmap, with each byte 0...grayscale-1
11440:  * --------------------------------------------------------------------------
11441:  * Arguments:	rp (I)		raster *  to raster whose bitmap
11442:  *				is to be anti-aliased
11443:  *		bytemap (O)	intbyte * to bytemap, calculated
11444:  *				by applying lowpass filter to rp->bitmap,
11445:  *				and returned (as you'd expect) in 1-to-1
11446:  *				addressing correspondence with rp->bitmap
11447:  *		grayscale (I)	int containing number of grayscales
11448:  *				to be calculated, 0...grayscale-1
11449:  *				(should typically be given as 256)
11450:  * --------------------------------------------------------------------------
11451:  * Returns:	( int )		1=success, 0=any error
11452:  * --------------------------------------------------------------------------
11453:  * Notes:     o	If the center point of the box being averaged is black,
11454:  *		then the entire "average" is forced black (grayscale-1)
11455:  *		regardless of the surrounding points.  This is my attempt
11456:  *		to avoid a "washed-out" appearance of thin (one-pixel-wide)
11457:  *		lines, which would otherwise turn from black to a gray shade.
11458:  *	     o	Also, while the weights for neighbor points are fixed,
11459:  *		you may adjust the center point weight on the compile line.
11460:  *		A higher weight sharpens the resulting anti-aliased image;
11461:  *		lower weights blur it out more (but keep the "center" black
11462:  *		as per the preceding note).
11463:  * ======================================================================= */
11464: /* --- entry point --- */
11465: int	aalowpass (raster *rp, intbyte *bytemap, int grayscale)
11466: {
11467: /* -------------------------------------------------------------------------
11468: Allocations and Declarations
11469: -------------------------------------------------------------------------- */
11470: int	status = 1;			/* 1=success, 0=failure to caller */
11471: pixbyte	*bitmap= (rp==NULL?NULL:rp->pixmap); /*local rp->pixmap ptr*/
11472: int	irow=0, icol=0;			/* rp->height, rp->width indexes */
11473: int	weights[9] = { 1,3,1, 3,0,3, 1,3,1 }; /* matrix of weights */
11474: int	adjindex[9]= { 0,1,2, 7,-1,3, 6,5,4 }; /*clockwise from upper-left*/
11475: int	totwts = 0;			/* sum of all weights in matrix */
11476: int	isforceavg = 1,			/*force avg black if center black?*/
11477: 	isminmaxwts = 1,		/*use wts or #pts for min/max test */
11478: 	blackscale = 0; /*(grayscale+1)/4;*/ /*force black if wgted avg>bs */
11479: /* -------------------------------------------------------------------------
11480: Initialization
11481: -------------------------------------------------------------------------- */
11482: /* --- calculate total weights --- */
11483: weights[4]= centerwt;			/* weight for center point */
11484: weights[1]= weights[3]= weights[5]= weights[7]= adjacentwt; /*adjacent pts*/
11485: totwts = centerwt + 4*(1+adjacentwt);	/* tot is center plus neighbors */
11486: /* -------------------------------------------------------------------------
11487: Calculate bytemap as 9-point weighted average over bitmap
11488: -------------------------------------------------------------------------- */
11489: for ( irow=0; irow<rp->height; irow++ )
11490:  for ( icol=0; icol<rp->width; icol++ )
11491:   {
11492:   int	ipixel = icol + irow*(rp->width); /* center pixel index */
11493:   int	jrow=0, jcol=0,			/* box around ipixel */
11494: 	bitval = 0,			/* value of bit/pixel at jrow,jcol */
11495: 	iscenter = 0,			/* set true if center pixel black */
11496: 	nadjacent=0, wadjacent=0,	/* #adjacent black pixels, their wts*/
11497: 	ngaps = 0,			/* #gaps in 8 pixels around center */
11498: 	iwt=(-1), sumwts=0;		/* weights index, sum in-bound wts */
11499:   char	adjmatrix[8];			/* adjacency "matrix" */
11500:   memset(adjmatrix,0,8);		/* zero out adjacency matrix */
11501:   bytemap[ipixel] = 0;			/* init pixel white */
11502:   /*--- for ipixel at irow,icol, get weighted average of adjacent pixels ---*/
11503:   for ( jrow=irow-1; jrow<=irow+1; jrow++ )  /* jrow = irow-1...irow+1 */
11504:    for ( jcol=icol-1; jcol<=icol+1; jcol++ ) /* jcol = icol-1...icol+1 */
11505:     {
11506:     int	jpixel = jcol + jrow*(rp->width); /* averaging index */
11507:     iwt++;				/*always bump weight index*/
11508:     if ( jrow<0 || jrow>=rp->height	/* if row out pf bounds */
11509:     ||   jcol<0 || jcol>=rp->width )	/* or col out of bounds */
11510: 	continue;			/* ignore this point */
11511:     bitval = (int)getlongbit(bitmap,jpixel); /* value of bit at jrow,jcol */
11512:     if ( bitval )			/* this is a black pixel */
11513:       {	if ( jrow==irow && jcol==icol )	/* and this is center point */
11514: 	  iscenter = 1;			/* set flag for center point black */
11515: 	else				/* adjacent point black */
11516: 	  { nadjacent++;		/* bump adjacent black count */
11517: 	    adjmatrix[adjindex[iwt]] = 1; } /*set "bit" in adjacency matrix*/
11518: 	wadjacent += weights[iwt]; }	/* sum weights for black pixels */
11519:     sumwts += weights[iwt];		/* and sum weights for all pixels */
11520:     } /* --- end-of-for(jrow,jcol) --- */
11521:   /* --- count gaps --- */
11522:   ngaps = (adjmatrix[7]!=adjmatrix[0]?1:0); /* init count */
11523:   for ( iwt=0; iwt<7; iwt++ )		/* clockwise around adjacency */
11524:     if ( adjmatrix[iwt] != adjmatrix[iwt+1] ) ngaps++; /* black/white flip */
11525:   ngaps /= 2;				/*each gap has 2 black/white flips*/
11526:   /* --- anti-alias pixel, but leave it black if it was already black --- */
11527:   if ( isforceavg && iscenter )		/* force avg if center point black */
11528:       bytemap[ipixel] = grayscale-1;	/* so force grayscale-1=black */
11529:   else					/* center point not black */
11530:    if ( ngaps <= 2 )			/*don't darken checkerboarded pixel*/
11531:     { bytemap[ipixel] =			/* 0=white ... grayscale-1=black */
11532: 	((totwts/2 - 1) + (grayscale-1)*wadjacent)/totwts; /* not /sumwts; */
11533:       if ( blackscale > 0		/* blackscale kludge turned on */
11534:       &&   bytemap[ipixel] > blackscale ) /* weighted avg > blackscale */
11535: 	bytemap[ipixel] = grayscale-1; } /* so force it entirely black */
11536:   /*--- only anti-alias pixels whose adjacent pixels fall within bounds ---*/
11537:   if ( !iscenter ) {			/* apply min/maxadjacent test */
11538:    if ( isminmaxwts )			/* min/max refer to adjacent weights*/
11539:     { if ( wadjacent < minadjacent	/* wts of adjacent points too low */
11540:       ||   wadjacent > maxadjacent )	/* or too high */
11541: 	bytemap[ipixel] = 0; }		/* so leave point white */
11542:    else					/* min/max refer to #adjacent points*/
11543:     { if ( nadjacent < minadjacent	/* too few adjacent points black */
11544:       ||   nadjacent > maxadjacent )	/* or too many */
11545: 	bytemap[ipixel] = 0; } }	/* so leave point white */
11546:   } /* --- end-of-for(irow,icol) --- */
11547: /* -------------------------------------------------------------------------
11548: Back to caller with gray-scale anti-aliased bytemap
11549: -------------------------------------------------------------------------- */
11550: /*end_of_job:*/
11551:   return ( status );
11552: } /* --- end-of-function aalowpass() --- */
11553: 
11554: 
11555: /* ==========================================================================
11556:  * Function:	aapnm ( rp, bytemap, grayscale )
11557:  * Purpose:	calculates a lowpass anti-aliased bytemap
11558:  *		for rp->bitmap, with each byte 0...grayscale-1,
11559:  *		based on the pnmalias.c algorithm
11560:  * --------------------------------------------------------------------------
11561:  * Arguments:	rp (I)		raster *  to raster whose bitmap
11562:  *				is to be anti-aliased
11563:  *		bytemap (O)	intbyte * to bytemap, calculated
11564:  *				by applying pnm-based filter to rp->bitmap,
11565:  *				and returned (as you'd expect) in 1-to-1
11566:  *				addressing correspondence with rp->bitmap
11567:  *		grayscale (I)	int containing number of grayscales
11568:  *				to be calculated, 0...grayscale-1
11569:  *				(should typically be given as 256)
11570:  * --------------------------------------------------------------------------
11571:  * Returns:	( int )		1=success, 0=any error
11572:  * --------------------------------------------------------------------------
11573:  * Notes:    o	Based on the pnmalias.c algorithm in the netpbm package
11574:  *		on sourceforge.
11575:  * ======================================================================= */
11576: /* --- entry point --- */
11577: int	aapnm (raster *rp, intbyte *bytemap, int grayscale)
11578: {
11579: /* -------------------------------------------------------------------------
11580: Allocations and Declarations
11581: -------------------------------------------------------------------------- */
11582: pixbyte	*bitmap = rp->pixmap;		/* local rp->pixmap ptr */
11583: int	width=rp->width, height=rp->height, /* width, height of raster */
11584: 	icol = 0,        irow = 0,	/* width, height indexes */
11585: 	imap = (-1);			/* pixel index = icol + irow*width */
11586: int	bgbitval=0, fgbitval=1;		/* background, foreground bitval */
11587: int	isfirstaa = 1;			/*debugging switch signals 1st pixel*/
11588: #if 0
11589: int	totwts=12, wts[9]={1,1,1, 1,4,1, 1,1,1}; /* pnmalias default wts */
11590: int	totwts=16, wts[9]={1,2,1, 2,4,2, 1,2,1}; /* weights */
11591: #endif
11592: int	totwts=18, wts[9]={1,2,1, 2,6,2, 1,2,1}; /* pnmalias default wts */
11593: int	isresetparams = 1,		/* true to set antialiasing params */
11594: 	isfgalias  = 1,			/* true to antialias fg bits */
11595: 	isfgonly   = 0,			/* true to only antialias fg bits */
11596: 	isbgalias  = 0,			/* true to antialias bg bits */
11597: 	isbgonly   = 0;			/* true to only antialias bg bits */
11598: /* -------------------------------------------------------------------------
11599: Initialization
11600: -------------------------------------------------------------------------- */
11601: /* --- check for bold light --- */
11602: if ( 0 )
11603:  { if ( weightnum > 2 ) { isbgalias=1; }	/* simulate bold */
11604:    if ( weightnum < 1 ) { isbgonly=1; isfgalias=0; } } /* simulate light */
11605: /* --- reset wts[], etc, and calculate total weights --- */
11606: if ( isresetparams )			/* wts[], etc taken from params */
11607:   { int	iwt=0;				/* wts[iwt] index */
11608:     wts[4]= centerwt;			/* weight for center point */
11609:     wts[1]=wts[3]=wts[5]=wts[7] = adjacentwt; /* and adjacent points */
11610:     wts[0]=wts[2]=wts[6]=wts[8] = cornerwt;   /* and corner points */
11611:     for ( totwts=0,iwt=0; iwt<9; iwt++ ) totwts += wts[iwt]; /* sum wts */
11612:     isfgalias = fgalias;		/* set isfgalias */
11613:     isfgonly = fgonly;			/* set isfgonly */
11614:     isbgalias = bgalias;		/* set isbgalias */
11615:     isbgonly = bgonly; }		/* set isbgonly */
11616: /* -------------------------------------------------------------------------
11617: Calculate bytemap as 9-point weighted average over bitmap
11618: -------------------------------------------------------------------------- */
11619: for ( irow=0; irow<height; irow++ )
11620:  for ( icol=0; icol<width; icol++ )
11621:   {
11622:   /* --- local allocations and declarations --- */
11623:   int	bitval=0,			/* value of rp bit at irow,icol */
11624: 	nnbitval=0, nebitval=0, eebitval=0, sebitval=0,	/*adjacent vals*/
11625: 	ssbitval=0, swbitval=0, wwbitval=0, nwbitval=0;	/*compass pt names*/
11626:   int	isbgedge=0, isfgedge=0;		/*does pixel border a bg or fg edge*/
11627:   int	aabyteval=0;			/* antialiased (or unchanged) value*/
11628:   /* --- bump imap index and get center bit value --- */
11629:   imap++;				/* imap = icol + irow*width */
11630:   bitval = getlongbit(bitmap,imap);	/* value of rp input bit at imap */
11631:   aabyteval = (intbyte)(bitval==bgbitval?0:grayscale-1); /* default aa val */
11632:   bytemap[imap] = (intbyte)(aabyteval);	/* init antialiased pixel */
11633:   /* --- check if we're antialiasing this pixel --- */
11634:   if ( (isbgonly && bitval==fgbitval)	/* only antialias background bit */
11635:   ||   (isfgonly && bitval==bgbitval) )	/* only antialias foreground bit */
11636:     continue;				/* leave default and do next bit */
11637:   /* --- get surrounding bits --- */
11638:   if ( irow > 0 )			/* nn (north) bit available */
11639:      nnbitval = getlongbit(bitmap,imap-width); /* nn bit value */
11640:   if ( irow < height-1 )		/* ss (south) bit available */
11641:      ssbitval = getlongbit(bitmap,imap+width); /* ss bit value */
11642:   if ( icol > 0 )			/* ww (west) bit available */
11643:    { wwbitval = getlongbit(bitmap,imap-1); /* ww bit value */
11644:      if ( irow > 0 )			/* nw bit available */
11645:        nwbitval = getlongbit(bitmap,imap-width-1); /* nw bit value */
11646:      if ( irow < height-1 )		/* sw bit available */
11647:        swbitval = getlongbit(bitmap,imap+width-1); } /* sw bit value */
11648:   if ( icol < width-1 )			/* ee (east) bit available */
11649:    { eebitval = getlongbit(bitmap,imap+1); /* ee bit value */
11650:      if ( irow > 0 )			/* ne bit available */
11651:        nebitval = getlongbit(bitmap,imap-width+1); /* ne bit value */
11652:      if ( irow < height-1 )		/* se bit available */
11653:        sebitval = getlongbit(bitmap,imap+width+1); } /* se bit value */
11654:   /* --- check for edges --- */
11655:   isbgedge =				/* current pixel borders a bg edge */
11656: 	(nnbitval==bgbitval && eebitval==bgbitval) ||	/*upper-right edge*/
11657: 	(eebitval==bgbitval && ssbitval==bgbitval) ||	/*lower-right edge*/
11658: 	(ssbitval==bgbitval && wwbitval==bgbitval) ||	/*lower-left  edge*/
11659: 	(wwbitval==bgbitval && nnbitval==bgbitval) ;	/*upper-left  edge*/
11660:   isfgedge =				/* current pixel borders an fg edge*/
11661: 	(nnbitval==fgbitval && eebitval==fgbitval) ||	/*upper-right edge*/
11662: 	(eebitval==fgbitval && ssbitval==fgbitval) ||	/*lower-right edge*/
11663: 	(ssbitval==fgbitval && wwbitval==fgbitval) ||	/*lower-left  edge*/
11664: 	(wwbitval==fgbitval && nnbitval==fgbitval) ;	/*upper-left  edge*/
11665:   /* ---check top/bot left/right edges for corners (added by j.forkosh)--- */
11666:   if ( 1 ) {				/* true to perform test */
11667:     int	isbghorz=0, isfghorz=0, isbgvert=0, isfgvert=0; /* horz/vert edges */
11668:     isbghorz =				/* top or bottom edge is all bg */
11669: 	(nwbitval+nnbitval+nebitval == 3*bgbitval) ||	/* top edge bg */
11670: 	(swbitval+ssbitval+sebitval == 3*bgbitval) ;	/* bottom edge bg */
11671:     isfghorz =				/* top or bottom edge is all fg */
11672: 	(nwbitval+nnbitval+nebitval == 3*fgbitval) ||	/* top edge fg */
11673: 	(swbitval+ssbitval+sebitval == 3*fgbitval) ;	/* bottom edge fg */
11674:     isbgvert =				/* left or right edge is all bg */
11675: 	(nwbitval+wwbitval+swbitval == 3*bgbitval) ||	/* left edge bg */
11676: 	(nebitval+eebitval+sebitval == 3*bgbitval) ;	/* right edge bg */
11677:     isfgvert =				/* left or right edge is all bg */
11678: 	(nwbitval+wwbitval+swbitval == 3*fgbitval) ||	/* left edge fg */
11679: 	(nebitval+eebitval+sebitval == 3*fgbitval) ;	/* right edge fg */
11680:     if ( (isbghorz && isbgvert && (bitval==fgbitval))	/* we're at an...*/
11681:     ||   (isfghorz && isfgvert && (bitval==bgbitval)) )	/*...inside corner */
11682: 	continue;					/* don't antialias */
11683:     } /* --- end-of-if(1) --- */
11684:   /* --- check #gaps for checkerboard (added by j.forkosh) --- */
11685:   if ( 0 ) {				/* true to perform test */
11686:     int	ngaps=0, mingaps=1,maxgaps=2;	/* count #fg/bg flips (max=4 noop) */
11687:     if ( nwbitval!=nnbitval ) ngaps++;	/* upper-left =? upper */
11688:     if ( nnbitval!=nebitval ) ngaps++;	/* upper =? upper-right */
11689:     if ( nebitval!=eebitval ) ngaps++;	/* upper-right =? right */
11690:     if ( eebitval!=sebitval ) ngaps++;	/* right =? lower-right */
11691:     if ( sebitval!=ssbitval ) ngaps++;	/* lower-right =? lower */
11692:     if ( ssbitval!=swbitval ) ngaps++;	/* lower =? lower-left */
11693:     if ( swbitval!=wwbitval ) ngaps++;	/* lower-left =? left */
11694:     if ( wwbitval!=nwbitval ) ngaps++;	/* left =? upper-left */
11695:     if ( ngaps > 0 ) ngaps /= 2;	/* each gap has 2 bg/fg flips */
11696:     if ( ngaps<mingaps || ngaps>maxgaps ) continue;
11697:     } /* --- end-of-if(1) --- */
11698:   /* --- antialias if necessary --- */
11699:   if ( (isbgalias && isbgedge)		/* alias pixel surrounding bg */
11700:   ||   (isfgalias && isfgedge)		/* alias pixel surrounding fg */
11701:   ||   (isbgedge  && isfgedge) )	/* neighboring fg and bg pixel */
11702:     {
11703:     int	aasumval =			/* sum wts[]*bitmap[] */
11704: 	wts[0]*nwbitval + wts[1]*nnbitval + wts[2]*nebitval +
11705: 	wts[3]*wwbitval +  wts[4]*bitval  + wts[5]*eebitval +
11706: 	wts[6]*swbitval + wts[7]*ssbitval + wts[8]*sebitval ;
11707:     double aawtval = ((double)aasumval)/((double)totwts); /* weighted val */
11708:     aabyteval= (int)(((double)(grayscale-1))*aawtval+0.5); /*0...grayscale-1*/
11709:     bytemap[imap] = (intbyte)(aabyteval); /* set antialiased pixel */
11710:     if ( msglevel>=99 && msgfp!=NULL ) { fprintf(msgfp, /*diagnostic output*/
11711:       "%s> irow,icol,imap=%d,%d,%d aawtval=%.4f aabyteval=%d\n",
11712:       (isfirstaa?"aapnm algorithm":"aapnm"),
11713:       irow,icol,imap, aawtval,aabyteval);
11714:       isfirstaa = 0; }
11715:     } /* --- end-of-if(isedge) --- */
11716:   } /* --- end-of-for(irow,icol) --- */
11717: /* -------------------------------------------------------------------------
11718: Back to caller with gray-scale anti-aliased bytemap
11719: -------------------------------------------------------------------------- */
11720: /*end_of_job:*/
11721:   return ( 1 );
11722: } /* --- end-of-function aapnm() --- */
11723: 
11724: 
11725: /* ==========================================================================
11726:  * Function:	aapnmlookup ( rp, bytemap, grayscale )
11727:  * Purpose:	calculates a lowpass anti-aliased bytemap
11728:  *		for rp->bitmap, with each byte 0...grayscale-1,
11729:  *		based on the pnmalias.c algorithm.
11730:  *		This version uses aagridnum() and aapatternnum() lookups
11731:  *		to interpret 3x3 lowpass pixel grids.
11732:  * --------------------------------------------------------------------------
11733:  * Arguments:	rp (I)		raster *  to raster whose bitmap
11734:  *				is to be anti-aliased
11735:  *		bytemap (O)	intbyte * to bytemap, calculated
11736:  *				by applying pnm-based filter to rp->bitmap,
11737:  *				and returned (as you'd expect) in 1-to-1
11738:  *				addressing correspondence with rp->bitmap
11739:  *		grayscale (I)	int containing number of grayscales
11740:  *				to be calculated, 0...grayscale-1
11741:  *				(should typically be given as 256)
11742:  * --------------------------------------------------------------------------
11743:  * Returns:	( int )		1=success, 0=any error
11744:  * --------------------------------------------------------------------------
11745:  * Notes:    o	Based on the pnmalias.c algorithm in the netpbm package
11746:  *		on sourceforge.
11747:  *	     o	This version uses aagridnum() and aapatternnum() lookups
11748:  *		to interpret 3x3 lowpass pixel grids.
11749:  * ======================================================================= */
11750: /* --- entry point --- */
11751: int	aapnmlookup (raster *rp, intbyte *bytemap, int grayscale)
11752: {
11753: /* -------------------------------------------------------------------------
11754: Allocations and Declarations
11755: -------------------------------------------------------------------------- */
11756: int	width=rp->width, height=rp->height, /* width, height of raster */
11757: 	icol = 0,        irow = 0,	/* width, height indexes */
11758: 	imap = (-1);			/* pixel index = icol + irow*width */
11759: int	bgbitval=0, fgbitval=1;		/* background, foreground bitval */
11760: int	isfirstaa = 1;			/*debugging switch signals 1st pixel*/
11761: int	aacenterwt=centerwt, aaadjacentwt=adjacentwt, aacornerwt=cornerwt,
11762: 	totwts = centerwt + 4*(adjacentwt+cornerwt); /*pnmalias default wts*/
11763: int	isfgalias  = fgalias,		/*(1) true to antialias fg bits */
11764: 	isfgonly   = fgonly,		/*(0) true to only antialias fg bits*/
11765: 	isbgalias  = bgalias,		/*(0) true to antialias bg bits */
11766: 	isbgonly   = bgonly;		/*(0) true to only antialias bg bits*/
11767: int	gridnum=(-1), aagridnum(),	/* grid# for 3x3 grid at irow,icol */
11768: 	patternum=(-1), aapatternnum();	/*pattern#, 1-51, for input gridnum*/
11769: int	aapatterns();			/* to antialias special patterns */
11770: /* ---
11771:  * pattern number data
11772:  * ------------------- */
11773: /* --- number of adjacent fg pixels set in pattern --- */
11774: static	int nadjacents[] = { -1,	/* #adjacent fg pixels for pattern */
11775:    0,  4,  0,  1,  4,  3,  1,  0,  1,  0,	/*  1-10 */
11776:    2,  2,  3,  4,  3,  4,  2,  2,  1,  2,	/* 11-20 */
11777:    1,  2,  1,  2,  0,  1,  3,  2,  3,  2,	/* 21-30 */
11778:    3,  2,  3,  2,  4,  3,  1,  2,  2,  2,	/* 31-40 */
11779:    2,  1,  2,  2,  3,  0,  3,  2,  2,  1,  4,	/* 41-51 */
11780:    -1 } ; /* --- end-of-nadjacents[] --- */
11781: /* --- number of corner fg pixels set in pattern --- */
11782: static	int ncorners[] = { -1,		/* #corner fg pixels for pattern */
11783:    0,  4,  1,  0,  3,  4,  1,  2,  1,  2,	/*  1-10 */
11784:    0,  0,  3,  2,  3,  2,  4,  4,  2,  1,	/* 11-20 */
11785:    2,  1,  2,  1,  3,  2,  0,  1,  2,  3,	/* 21-30 */
11786:    2,  3,  2,  3,  1,  2,  4,  3,  2,  2,	/* 31-40 */
11787:    2,  3,  2,  2,  1,  4,  1,  2,  2,  3,  0,	/* 41-51 */
11788:    -1 } ; /* --- end-of-ncorners[] --- */
11789: /* --- 0,1,2=pattern contains horizontal bg,fg,both edge; -1=no edge --- */
11790: static	int horzedges[] = { -1,		/* 0,1,2 = horz bg,fg,both edge */
11791:    0,  1,  0,  0,  1,  1,  0,  0,  0, -1,	/*  1-10 */
11792:    0, -1,  1,  1,  1, -1,  1, -1,  2,  0,	/* 11-20 */
11793:   -1, -1, -1,  0, -1, -1, -1, -1,  2,  1,	/* 21-30 */
11794:   -1, -1, -1,  1, -1, -1, -1, -1,  2, -1,	/* 31-40 */
11795:   -1,  1,  1, -1, -1, -1,  0,  0, -1, -1, -1,	/* 41-51 */
11796:    -1 } ; /* --- end-of-horzedges[] --- */
11797: /* --- 0,1,2=pattern contains vertical bg,fg,both edge; -1=no edge --- */
11798: static	int vertedges[] = { -1,		/* 0,1,2 = vert bg,fg,both edge */
11799:    0,  1,  0,  0,  1,  1,  0, -1, -1, -1,	/*  1-10 */
11800:    0,  0,  1, -1, -1, -1,  1,  1, -1, -1,	/* 11-20 */
11801:   -1,  0,  0,  0, -1, -1,  0, -1, -1, -1,	/* 21-30 */
11802:   -1,  1,  1,  1, -1, -1,  1, -1, -1, -1,	/* 31-40 */
11803:   -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,	/* 41-51 */
11804:    -1 } ; /* --- end-of-vertedges[] --- */
11805: /* --- 0,1,2=pattern contains diagonal bg,fg,both edge; -1=no edge --- */
11806: static	int diagedges[] = { -1,		/* 0,1,2 = diag bg,fg,both edge */
11807:    0,  1,  0,  0,  1,  1,  0,  0,  0,  0,	/*  1-10 */
11808:    2, -1,  1,  1,  1,  1,  1, -1,  0,  2,	/* 11-20 */
11809:    0, -1,  0,  2,  0, -1,  1,  1,  1,  1,	/* 21-30 */
11810:    1, -1,  1,  2,  1,  1, -1,  1,  2, -1,	/* 31-40 */
11811:    1,  0, -1,  2,  1,  0,  1, -1,  1, -1,  1,	/* 41-51 */
11812:    -1 } ; /* --- end-of-diagedges[] --- */
11813: /* -------------------------------------------------------------------------
11814: Calculate bytemap as 9-point weighted average over bitmap
11815: -------------------------------------------------------------------------- */
11816: for ( irow=0; irow<height; irow++ )
11817:  for ( icol=0; icol<width; icol++ )
11818:   {
11819:   /* --- local allocations and declarations --- */
11820:   int	bitval=0,			/* value of rp bit at irow,icol */
11821: 	isbgdiag=0, isfgdiag=0,		/*does pixel border a bg or fg edge*/
11822: 	aabyteval=0;			/* antialiased (or unchanged) value*/
11823:   /* --- get gridnum and center bit value, init aabyteval --- */
11824:   imap++;				/* first set imap=icol + irow*width*/
11825:   gridnum = aagridnum(rp,irow,icol);	/*grid# coding 3x3 grid at irow,icol*/
11826:   bitval = (gridnum&1);			/* center bit set if gridnum odd */
11827:   aabyteval = (intbyte)(bitval==bgbitval?0:grayscale-1); /* default aa val */
11828:   bytemap[imap] = (intbyte)(aabyteval);	/* init antialiased pixel */
11829:   if ( gridnum<0 || gridnum>511 ) continue; /* gridnum out of bounds*/
11830:   /* --- check if we're antialiasing this pixel --- */
11831:   if ( (isbgonly && bitval==fgbitval)	/* only antialias background bit */
11832:   ||   (isfgonly && bitval==bgbitval) )	/* only antialias foreground bit */
11833:     continue;				/* leave default and do next bit */
11834:   /* --- look up pattern number, 1-51, corresponding to input gridnum --- */
11835:   patternum = aapatternnum(gridnum);	/* look up pattern number */
11836:   if ( patternum<1 || patternum>51 ) continue; /* some internal error */
11837:   /* --- special pattern number processing --- */
11838:   if ( (aabyteval = aapatterns(rp,irow,icol,gridnum,patternum,grayscale))
11839:   >=   0 ) {				/* special processing for pattern */
11840:     bytemap[imap] = (intbyte)(aabyteval); /* set antialiased pixel */
11841:     continue; }				/* and continue with next pixel */
11842:   /* --- check for diagonal edges --- */
11843:   isbgdiag = ( diagedges[patternum]==2 || /*current pixel borders a bg edge*/
11844:                diagedges[patternum]==0 );
11845:   isfgdiag = ( diagedges[patternum]==2 || /*current pixel borders a fg edge*/
11846:                diagedges[patternum]==1 );
11847:   /* ---check top/bot left/right edges for corners (added by j.forkosh)--- */
11848:   if ( 1 ) {				/* true to perform test */
11849:     int	isbghorz=0, isfghorz=0, isbgvert=0, isfgvert=0, /* horz/vert edges */
11850: 	horzedge=horzedges[patternum], vertedge=vertedges[patternum];
11851:     isbghorz = (horzedge==2||horzedge==0); /* top or bottom edge is all bg */
11852:     isfghorz = (horzedge==2||horzedge==1); /* top or bottom edge is all fg */
11853:     isbgvert = (vertedge==2||vertedge==0); /* left or right edge is all bg */
11854:     isfgvert = (vertedge==2||vertedge==1); /* left or right edge is all fg */
11855:     if ( (isbghorz && isbgvert && (bitval==fgbitval))	/* we're at an...*/
11856:     ||   (isfghorz && isfgvert && (bitval==bgbitval)) )	/*...inside corner */
11857: 	continue;					/* don't antialias */
11858:     } /* --- end-of-if(1) --- */
11859: #if 0
11860:   /* --- check #gaps for checkerboard (added by j.forkosh) --- */
11861:   if ( 0 ) {				/* true to perform test */
11862:     int	ngaps=0, mingaps=1,maxgaps=2;	/* count #fg/bg flips (max=4 noop) */
11863:     if ( nwbitval!=nnbitval ) ngaps++;	/* upper-left =? upper */
11864:     if ( nnbitval!=nebitval ) ngaps++;	/* upper =? upper-right */
11865:     if ( nebitval!=eebitval ) ngaps++;	/* upper-right =? right */
11866:     if ( eebitval!=sebitval ) ngaps++;	/* right =? lower-right */
11867:     if ( sebitval!=ssbitval ) ngaps++;	/* lower-right =? lower */
11868:     if ( ssbitval!=swbitval ) ngaps++;	/* lower =? lower-left */
11869:     if ( swbitval!=wwbitval ) ngaps++;	/* lower-left =? left */
11870:     if ( wwbitval!=nwbitval ) ngaps++;	/* left =? upper-left */
11871:     if ( ngaps > 0 ) ngaps /= 2;	/* each gap has 2 bg/fg flips */
11872:     if ( ngaps<mingaps || ngaps>maxgaps ) continue;
11873:     } /* --- end-of-if(1) --- */
11874: #endif
11875:   /* --- antialias if necessary --- */
11876:   if ( (isbgalias && isbgdiag)		/* alias pixel surrounding bg */
11877:   ||   (isfgalias && isfgdiag)		/* alias pixel surrounding fg */
11878:   ||   (isbgdiag  && isfgdiag) )	/* neighboring fg and bg pixel */
11879:     {
11880:     int	aasumval =			/* sum wts[]*bitmap[] */
11881: 	aacenterwt*bitval +		/* apply centerwt to center pixel */
11882: 	aaadjacentwt*nadjacents[patternum] + /* similarly for adjacents */
11883: 	aacornerwt*ncorners[patternum];	/* and corners */
11884:     double aawtval = ((double)aasumval)/((double)totwts); /* weighted val */
11885:     aabyteval= (int)(((double)(grayscale-1))*aawtval+0.5); /*0...grayscale-1*/
11886:     bytemap[imap] = (intbyte)(aabyteval); /* set antialiased pixel */
11887:     if ( msglevel>=99 && msgfp!=NULL ) { fprintf(msgfp, /*diagnostic output*/
11888:       "%s> irow,icol,imap=%d,%d,%d aawtval=%.4f aabyteval=%d",
11889:       (isfirstaa?"aapnmlookup algorithm":"aapnm"),
11890:       irow,icol,imap, aawtval,aabyteval);
11891:       if ( msglevel < 100 ) fprintf(msgfp,"\n"); /* no more output */
11892:       else fprintf(msgfp,", grid#,pattern#=%d,%d\n",gridnum,patternum);
11893:       isfirstaa = 0; }
11894:     } /* --- end-of-if(isedge) --- */
11895:   } /* --- end-of-for(irow,icol) --- */
11896: /* -------------------------------------------------------------------------
11897: Back to caller with gray-scale anti-aliased bytemap
11898: -------------------------------------------------------------------------- */
11899: /*end_of_job:*/
11900:   return ( 1 );
11901: } /* --- end-of-function aapnmlookup() --- */
11902: 
11903: 
11904: /* ==========================================================================
11905:  * Function:	aapatterns ( rp, irow, icol, gridnum, patternum, grayscale )
11906:  * Purpose:	For patterns requireing special processing,
11907:  *		calculates anti-aliased value for pixel at irow,icol,
11908:  *		whose surrounding 3x3 pixel grid is coded by gridnum
11909:  *		(which must correspond to a pattern requiring special
11910:  *		processing).
11911:  * --------------------------------------------------------------------------
11912:  * Arguments:	rp (I)		raster *  to raster whose bitmap
11913:  *				is to be anti-aliased
11914:  *		irow (I)	int containing row, 0...height-1,
11915:  *				of pixel to be antialiased
11916:  *		icol (I)	int containing col, 0...width-1,
11917:  *				of pixel to be antialiased
11918:  *		gridnum (I)	int containing 0...511 corresponding to
11919:  *				3x3 pixel grid surrounding irow,icol
11920:  *		patternum (I)	int containing 1...51 pattern# of
11921:  *				the 3x3 grid surrounding irow,icol
11922:  *		grayscale (I)	int containing number of grayscales
11923:  *				to be calculated, 0...grayscale-1
11924:  *				(should typically be given as 256)
11925:  * --------------------------------------------------------------------------
11926:  * Returns:	( int )		0...grayscale-1 for success,
11927:  *				-1 = error, or no special processing required
11928:  * --------------------------------------------------------------------------
11929:  * Notes:    o
11930:  * ======================================================================= */
11931: /* --- entry point --- */
11932: int	aapatterns (raster *rp, int irow, int icol,
11933: 	int gridnum, int patternum, int grayscale)
11934: {
11935: /* -------------------------------------------------------------------------
11936: Allocations and Declarations
11937: -------------------------------------------------------------------------- */
11938: int	aaval = (-1);			/* antialiased value returned */
11939: int	iscenter = (gridnum&1);		/* true if center pixel set/black */
11940: int	aapatternnum(),			/* if patternum not supplied */
11941: 	aapattern1124(),		/* routine for patterns #11,24 */
11942: 	aapattern19(),			/* special routine for pattern #19 */
11943: 	aapattern20(),			/* special routine for pattern #20 */
11944: 	aapattern39();			/* special routine for pattern #39 */
11945: /* -------------------------------------------------------------------------
11946: special pattern number processing
11947: -------------------------------------------------------------------------- */
11948: if ( 1 ) {
11949:   if ( patternum < 1 )			/* pattern# not supplied by caller */
11950:     patternum = aapatternnum(gridnum);	/* so look it up ourselves */
11951:   switch ( patternum ) {
11952:     default: break;			/* no special processing */
11953:     case 11:
11954:     case 24: aaval = aapattern1124(rp,irow,icol,gridnum,grayscale); break;
11955:     case 19: aaval = aapattern19(rp,irow,icol,gridnum,grayscale); break;
11956:     case 20: aaval = aapattern20(rp,irow,icol,gridnum,grayscale); break;
11957:     case 39: aaval = aapattern39(rp,irow,icol,gridnum,grayscale); break;
11958:     /* case 24: if ( (gridnum&1) == 0 ) aaval=0; break; */
11959:     case 29: aaval = (iscenter?grayscale-1:0); break; /* no antialiasing */
11960:     } /* --- end-of-switch(patternum) --- */
11961:   } /* --- end-of-if() --- */
11962: return ( aaval );			/* return antialiased val to caller*/
11963: } /* --- end-of-function aapatterns() --- */
11964: 
11965: 
11966: /* ==========================================================================
11967:  * Function:	aapattern1124 ( rp, irow, icol, gridnum, grayscale )
11968:  * Purpose:	calculates anti-aliased value for pixel at irow,icol,
11969:  *		whose surrounding 3x3 pixel grid is coded by gridnum
11970:  *		(which must correspond to pattern #11 or #24).
11971:  * --------------------------------------------------------------------------
11972:  * Arguments:	rp (I)		raster *  to raster whose bitmap
11973:  *				is to be anti-aliased
11974:  *		irow (I)	int containing row, 0...height-1,
11975:  *				of pixel to be antialiased
11976:  *		icol (I)	int containing col, 0...width-1,
11977:  *				of pixel to be antialiased
11978:  *		gridnum (I)	int containing 0...511 corresponding to
11979:  *				3x3 pixel grid surrounding irow,icol
11980:  *		grayscale (I)	int containing number of grayscales
11981:  *				to be calculated, 0...grayscale-1
11982:  *				(should typically be given as 256)
11983:  * --------------------------------------------------------------------------
11984:  * Returns:	( int )		0...grayscale-1 for success, -1=any error
11985:  * --------------------------------------------------------------------------
11986:  * Notes:    o	Handles the eight gridnum's
11987:  *		(gridnum/2 shown to eliminate irrelevant low-order bit)
11988:  *		  ---        ---         -*-          -*-
11989:  *		  --* = 10   *-- = 18    --* = 72     *-- = 80  (pattern$11)
11990:  *		  -*-        -*-         ---          ---
11991:  *
11992:  *		  ---        ---         -**          **-
11993:  *		  --* = 11   *-- = 22    --* = 104    *-- = 208 (pattern$24)
11994:  *		  -**        **-         ---          ---
11995:  *	     o	For black * center pixel, using grid#10 as an example,
11996:  *		pixel stays ---      antialiased  ---*
11997:  *		black if    -***     if part of	  -**
11998:  *		part of a   -*-      a diagonal	  -*- 
11999:  *		corner, eg,  *       line, eg,	  *
12000:  * ======================================================================= */
12001: /* --- entry point --- */
12002: int	aapattern1124 (raster *rp, int irow, int icol,
12003: 	int gridnum, int grayscale)
12004: {
12005: /* -------------------------------------------------------------------------
12006: Allocations and Declarations
12007: -------------------------------------------------------------------------- */
12008: int	aaval = (-1);			/* antialiased value returned */
12009: int	iscenter = gridnum&1;		/* true if pixel at irow,icol black*/
12010: int	patternum = 24;			/* init for pattern#24 default */
12011: pixbyte	*bitmap = rp->pixmap;		/* local rp->pixmap ptr */
12012: int	width=rp->width, height=rp->height; /* width, height of raster */
12013: int	jrow=irow, jcol=icol;		/* corner or diagonal row,col */
12014: int	vertcornval=0, horzcornval=0,	/* vertical, horizontal corner bits*/
12015: 	topdiagval=0,  botdiagval=0,	/* upper,lower diagonal pixel bits */
12016: 	cornval=0, diagval=0;		/* vert+horzcorn, top+botdiag */
12017: int	hdirection=99, vdirection=99,	/* horz,vert corner direction */
12018: 	hturn=99,vturn=99, aafollowline(); /* follow corner till turns */
12019: /* -------------------------------------------------------------------------
12020: Check corner and diagonal pixels
12021: -------------------------------------------------------------------------- */
12022: if ( 0 ) goto end_of_job;		/* true to turn off pattern1124 */
12023: switch ( gridnum/2 ) {			/* check pattern#11,24 corner, diag*/
12024:   default: goto end_of_job;		/* not a pattern#11,24 gridnum */
12025:   case 10: patternum=11; case 11:
12026:     hdirection = 2;  vdirection = -1;	/* directions to follow corner */
12027:     if ( (jrow=irow+2) < height ) {	/* vert corner below center pixel */
12028:       vertcornval = getlongbit(bitmap,(icol+jrow*width));
12029:       if ( (icol-1) >= 0 )		/* lower diag left of center */
12030:         botdiagval = getlongbit(bitmap,((icol-1)+jrow*width)); }
12031:     if ( (jcol=icol+2) < width ) {	/* horz corner right of center */
12032:       horzcornval = getlongbit(bitmap,(jcol+irow*width));
12033:       if ( (irow-1) >= 0 )		/* upper diag above center */
12034:         topdiagval = getlongbit(bitmap,(jcol+(irow-1)*width)); }
12035:     break;
12036:   case 18: patternum=11; case 22:
12037:     hdirection = -2;  vdirection = -1;	/* directions to follow corner */
12038:     if ( (jrow=irow+2) < height ) {	/* vert corner below center pixel */
12039:       vertcornval = getlongbit(bitmap,(icol+jrow*width));
12040:       if ( (icol+1) < width )		/* lower diag right of center */
12041:         botdiagval = getlongbit(bitmap,((icol+1)+jrow*width)); }
12042:     if ( (jcol=icol-2) >= 0 ) {		/* horz corner left of center */
12043:       horzcornval = getlongbit(bitmap,(jcol+irow*width));
12044:       if ( (irow-1) >= 0 )		/* upper diag above center */
12045:         topdiagval = getlongbit(bitmap,(jcol+(irow-1)*width)); }
12046:     break;
12047:   case 72: patternum=11; case 104:
12048:     hdirection = 2;  vdirection = 1;	/* directions to follow corner */
12049:     if ( (jrow=irow-2) >= 0 ) {		/* vert corner above center pixel */
12050:       vertcornval = getlongbit(bitmap,(icol+jrow*width));
12051:       if ( (icol-1) >= 0 )		/* upper diag left of center */
12052:         topdiagval = getlongbit(bitmap,((icol-1)+jrow*width)); }
12053:     if ( (jcol=icol+2) < width ) {	/* horz corner right of center */
12054:       horzcornval = getlongbit(bitmap,(jcol+irow*width));
12055:       if ( (irow+1) < height )		/* lower diag below center */
12056:         botdiagval = getlongbit(bitmap,(jcol+(irow+1)*width)); }
12057:     break;
12058:   case 80: patternum=11; case 208:
12059:     hdirection = -2;  vdirection = 1;	/* directions to follow corner */
12060:     if ( (jrow=irow-2) >= 0 ) {		/* vert corner above center pixel */
12061:       vertcornval = getlongbit(bitmap,(icol+jrow*width));
12062:       if ( (icol+1) < width )		/* upper diag right of center */
12063:         topdiagval = getlongbit(bitmap,((icol+1)+jrow*width)); }
12064:     if ( (jcol=icol-2) >= 0 ) {		/* horz corner left of center */
12065:       horzcornval = getlongbit(bitmap,(jcol+irow*width));
12066:       if ( (irow+1) < height )		/* lower diag below center */
12067:         botdiagval = getlongbit(bitmap,(jcol+(irow+1)*width)); }
12068:     break;
12069:   } /* --- end-of-switch(gridnum/2) --- */
12070: cornval = vertcornval+horzcornval;	/* 0=no corner bits, 1, 2=both */
12071: diagval = topdiagval+botdiagval;	/* 0=no diag bits, 1, 2=both */
12072: /* -------------------------------------------------------------------------
12073: Handle white center
12074: -------------------------------------------------------------------------- */
12075: if ( 1 && !iscenter ) { aaval = (patternum==11?51:64);  goto end_of_job; }
12076: /* -------------------------------------------------------------------------
12077: Handle black center
12078: -------------------------------------------------------------------------- */
12079: if ( diagval > 1 ) aaval = ( patternum==24? 255:191 );
12080: else {
12081:   hturn = aafollowline(rp,irow,icol,hdirection);
12082:   vturn = aafollowline(rp,irow,icol,vdirection);
12083:   if ( vturn*hdirection < 0  && hturn*vdirection < 0 )
12084:        aaval = ( patternum==24? 255:191 );
12085:   else aaval = grayscale-1; }		/* actual corner */
12086: /* -------------------------------------------------------------------------
12087: Back to caller with grayscale antialiased value for pixel at irow,icol
12088: -------------------------------------------------------------------------- */
12089: end_of_job:
12090:   if ( aaval >= 0 )			/* have antialiasing result */
12091:    if ( msglevel>=99 && msgfp!=NULL ) fprintf(msgfp, /* diagnostic output */
12092:     "aapattern1124> irow,icol,grid#/2=%d,%d,%d, top,botdiag=%d,%d, "
12093:     "vert,horzcorn=%d,%d, v,hdir=%d,%d, v,hturn=%d,%d, aaval=%d\n",
12094:     irow,icol,gridnum/2, topdiagval,botdiagval, vertcornval,horzcornval,
12095:     vdirection,hdirection, vturn,hturn, aaval);
12096:   return ( aaval );			/* back with antialiased value */
12097: } /* --- end-of-function aapattern1124() --- */
12098: 
12099: 
12100: /* ==========================================================================
12101:  * Function:	aapattern19 ( rp, irow, icol, gridnum, grayscale )
12102:  * Purpose:	calculates anti-aliased value for pixel at irow,icol,
12103:  *		whose surrounding 3x3 pixel grid is coded by gridnum
12104:  *		(which must correspond to pattern #19).
12105:  * --------------------------------------------------------------------------
12106:  * Arguments:	rp (I)		raster *  to raster whose bitmap
12107:  *				is to be anti-aliased
12108:  *		irow (I)	int containing row, 0...height-1,
12109:  *				of pixel to be antialiased
12110:  *		icol (I)	int containing col, 0...width-1,
12111:  *				of pixel to be antialiased
12112:  *		gridnum (I)	int containing 0...511 corresponding to
12113:  *				3x3 pixel grid surrounding irow,icol
12114:  *		grayscale (I)	int containing number of grayscales
12115:  *				to be calculated, 0...grayscale-1
12116:  *				(should typically be given as 256)
12117:  * --------------------------------------------------------------------------
12118:  * Returns:	( int )		0...grayscale-1 for success, -1=any error
12119:  * --------------------------------------------------------------------------
12120:  * Notes:    o	Handles the four gridnum's
12121:  *		(gridnum/2 shown to eliminate irrelevant low-order bit)
12122:  *		  ---        --*         *--          ***
12123:  *		  --- = 7    --* = 41    *-- = 148    --- = 224
12124:  *		  ***        --*         *--          ---
12125:  * ======================================================================= */
12126: /* --- entry point --- */
12127: int	aapattern19 (raster *rp, int irow, int icol,
12128: 	int gridnum, int grayscale)
12129: {
12130: /* -------------------------------------------------------------------------
12131: Allocations and Declarations
12132: -------------------------------------------------------------------------- */
12133: int	aaval = (-1);			/* antialiased value returned */
12134: int	iscenter = gridnum&1;		/* true if pixel at irow,icol black*/
12135: int	orientation = 1,		/* 1=vertical, 2=horizontal */
12136: 	jrow=irow, jcol=icol;		/* middle pixel of *** line */
12137: int	turn1=0,turn2=0, aafollowline(); /* follow *** line till it turns */
12138: /* -------------------------------------------------------------------------
12139: Initialization and calculation of antialiased value
12140: -------------------------------------------------------------------------- */
12141: /* --- check input -- */
12142: if ( iscenter ) goto end_of_job;	/* we only antialias white pixels */
12143: /* --- set params --- */
12144: switch ( gridnum/2 ) {			/* check pattern#19 orientation */
12145:   default: goto end_of_job;		/* not a pattern#19 gridnum */
12146:   case 7:   orientation=2; jrow++; break;
12147:   case 41:  orientation=1; jcol++; break;
12148:   case 148: orientation=1; jcol--; break;
12149:   case 224: orientation=2; jrow--; break;
12150:   } /* --- end-of-switch(gridnum/2) --- */
12151: /* --- get turns in both directions --- */
12152: if ( (turn1 = aafollowline(rp,jrow,jcol,orientation)) == 0 ) goto end_of_job;
12153: if ( (turn2 = aafollowline(rp,jrow,jcol,-orientation)) == 0) goto end_of_job;
12154: if ( turn1*turn2 >= 0 ) goto end_of_job; /* both turns in same direction */
12155: /* --- weight pixel --- */
12156: aaval = grayscale / ( 3 + min2(abs(turn1),abs(turn2)) );
12157: /* -------------------------------------------------------------------------
12158: Back to caller with grayscale antialiased value for pixel at irow,icol
12159: -------------------------------------------------------------------------- */
12160: end_of_job:
12161:   if ( aaval >= 0 )			/* have antialiasing result */
12162:    if ( msglevel>=99 && msgfp!=NULL ) fprintf(msgfp, /* diagnostic output */
12163:     "aapattern19> irow,icol,grid#/2=%d,%d,%d, turn+%d,%d=%d,%d, aaval=%d\n",
12164:     irow,icol,gridnum/2, orientation,-orientation,turn1,turn2, aaval);
12165:   return ( aaval );			/* back with antialiased value */
12166: } /* --- end-of-function aapattern19() --- */
12167: 
12168: 
12169: /* ==========================================================================
12170:  * Function:	aapattern20 ( rp, irow, icol, gridnum, grayscale )
12171:  * Purpose:	calculates anti-aliased value for pixel at irow,icol,
12172:  *		whose surrounding 3x3 pixel grid is coded by gridnum
12173:  *		(which must correspond to pattern #20).
12174:  * --------------------------------------------------------------------------
12175:  * Arguments:	rp (I)		raster *  to raster whose bitmap
12176:  *				is to be anti-aliased
12177:  *		irow (I)	int containing row, 0...height-1,
12178:  *				of pixel to be antialiased
12179:  *		icol (I)	int containing col, 0...width-1,
12180:  *				of pixel to be antialiased
12181:  *		gridnum (I)	int containing 0...511 corresponding to
12182:  *				3x3 pixel grid surrounding irow,icol
12183:  *		grayscale (I)	int containing number of grayscales
12184:  *				to be calculated, 0...grayscale-1
12185:  *				(should typically be given as 256)
12186:  * --------------------------------------------------------------------------
12187:  * Returns:	( int )		0...grayscale-1 for success, -1=any error
12188:  * --------------------------------------------------------------------------
12189:  * Notes:    o	Handles the eight gridnum's
12190:  *		(gridnum/2 shown to eliminate irrelevant low-order bit)
12191:  *		  ---        ---         --*          -*-      
12192:  *		  --* = 14   *-- = 19    --* = 42     --* = 73
12193:  *		  **-        -**         -*-          --*     
12194:  *
12195:  *		  -*-        -**         *--          **-      
12196:  *		  *-- = 84   *-- = 112   *-- = 146    --* = 200
12197:  *		  *--        ---         -*-          ---     
12198:  * ======================================================================= */
12199: /* --- entry point --- */
12200: int	aapattern20 (raster *rp, int irow, int icol,
12201: 	int gridnum, int grayscale)
12202: {
12203: /* -------------------------------------------------------------------------
12204: Allocations and Declarations
12205: -------------------------------------------------------------------------- */
12206: int	aaval = (-1);			/* antialiased value returned */
12207: int	iscenter = gridnum&1;		/* true if pixel at irow,icol black*/
12208: int	direction = 1,			/* direction to follow ** line */
12209: 	jrow1=irow, jcol1=icol,		/* coords of * */
12210: 	jrow2=irow, jcol2=icol;		/* coords of adjacent ** pixel */
12211: int	turn1=0,turn2=0, aafollowline(); /* follow *,** lines till turns */
12212: /* -------------------------------------------------------------------------
12213: Initialization and calculation of antialiased value
12214: -------------------------------------------------------------------------- */
12215: /* --- check input -- */
12216: if ( 1 ) goto end_of_job;		/* don't want this one */
12217: if ( iscenter ) goto end_of_job;	/* we only antialias white pixels */
12218: /* --- set params --- */
12219: switch ( gridnum/2 ) {			/* check pattern#20 orientation */
12220:   default: goto end_of_job;		/* not a pattern#20 gridnum */
12221:   case 14:  direction=-2; jcol1++; jrow2++; break;
12222:   case 19:  direction=2;  jcol1--; jrow2++; break;
12223:   case 42:  direction=1;  jrow1++; jcol2++; break;
12224:   case 73:  direction=-1; jrow1--; jcol2++; break;
12225:   case 84:  direction=-1; jrow1--; jcol2--; break;
12226:   case 112: direction=2;  jcol1--; jrow2--; break;
12227:   case 146: direction=1;  jrow1++; jcol2--; break;
12228:   case 200: direction=-2; jcol1++; jrow2--; break;
12229:   } /* --- end-of-switch(gridnum/2) --- */
12230: /* --- get turns in both directions --- */
12231: if ( (turn1=aafollowline(rp,jrow1,jcol1,-direction)) == 0 ) goto end_of_job;
12232: if ( (turn2=aafollowline(rp,jrow2,jcol2,direction))  == 0 ) goto end_of_job;
12233: if ( turn1*turn2 >= 0 ) goto end_of_job; /* both turns in same direction */
12234: /* --- weight pixel --- */
12235: aaval = grayscale / ( 3 + min2(abs(turn1),abs(turn2)) );
12236: /* -------------------------------------------------------------------------
12237: Back to caller with grayscale antialiased value for pixel at irow,icol
12238: -------------------------------------------------------------------------- */
12239: end_of_job:
12240:   if ( aaval >= 0 )			/* have antialiasing result */
12241:    if ( msglevel>=99 && msgfp!=NULL ) fprintf(msgfp, /* diagnostic output */
12242:     "aapattern20> irow,icol,grid#/2=%d,%d,%d, turn%d,%d=%d,%d, aaval=%d\n",
12243:     irow,icol,gridnum/2, -direction,direction,turn1,turn2, aaval);
12244:   return ( aaval );			/* back with antialiased value */
12245: } /* --- end-of-function aapattern20() --- */
12246: 
12247: 
12248: /* ==========================================================================
12249:  * Function:	aapattern39 ( rp, irow, icol, gridnum, grayscale )
12250:  * Purpose:	calculates anti-aliased value for pixel at irow,icol,
12251:  *		whose surrounding 3x3 pixel grid is coded by gridnum
12252:  *		(which must correspond to pattern #39).
12253:  * --------------------------------------------------------------------------
12254:  * Arguments:	rp (I)		raster *  to raster whose bitmap
12255:  *				is to be anti-aliased
12256:  *		irow (I)	int containing row, 0...height-1,
12257:  *				of pixel to be antialiased
12258:  *		icol (I)	int containing col, 0...width-1,
12259:  *				of pixel to be antialiased
12260:  *		gridnum (I)	int containing 0...511 corresponding to
12261:  *				3x3 pixel grid surrounding irow,icol
12262:  *		grayscale (I)	int containing number of grayscales
12263:  *				to be calculated, 0...grayscale-1
12264:  *				(should typically be given as 256)
12265:  * --------------------------------------------------------------------------
12266:  * Returns:	( int )		0...grayscale-1 for success, -1=any error
12267:  * --------------------------------------------------------------------------
12268:  * Notes:    o	Handles the eight gridnum's
12269:  *		(gridnum/2 shown to eliminate irrelevant low-order bit)
12270:  *		  ---        ---         --*          -**      
12271:  *		  --* = 15   *-- = 23    --* = 43     --* = 105
12272:  *		  ***        ***         -**          --*     
12273:  *
12274:  *		  **-        ***         *--          ***      
12275:  *		  *-- = 212  *-- = 240   *-- = 150    --* = 232
12276:  *		  *--        ---         **-          ---     
12277:  * ======================================================================= */
12278: /* --- entry point --- */
12279: int	aapattern39 (raster *rp, int irow, int icol,
12280: 	int gridnum, int grayscale)
12281: {
12282: /* -------------------------------------------------------------------------
12283: Allocations and Declarations
12284: -------------------------------------------------------------------------- */
12285: int	aaval = (-1);			/* antialiased value returned */
12286: int	iscenter = gridnum&1;		/* true if pixel at irow,icol black*/
12287: int	direction = 1,			/* direction to follow ** line */
12288: 	jrow1=irow, jcol1=icol,		/* coords of * */
12289: 	jrow2=irow, jcol2=icol;		/* coords of adjacent ** pixel */
12290: int	turn1=0,turn2=0, aafollowline(); /* follow *,** lines till turns */
12291: /* -------------------------------------------------------------------------
12292: Initialization and calculation of antialiased value
12293: -------------------------------------------------------------------------- */
12294: /* --- check input -- */
12295: if ( iscenter ) goto end_of_job;	/* we only antialias white pixels */
12296: /* --- set params --- */
12297: switch ( gridnum/2 ) {			/* check pattern#39 orientation */
12298:   default: goto end_of_job;		/* not a pattern#39 gridnum */
12299:   case 15:  direction=-2; jcol1++; jrow2++; break;
12300:   case 23:  direction=2;  jcol1--; jrow2++; break;
12301:   case 43:  direction=1;  jrow1++; jcol2++; break;
12302:   case 105: direction=-1; jrow1--; jcol2++; break;
12303:   case 212: direction=-1; jrow1--; jcol2--; break;
12304:   case 240: direction=2;  jcol1--; jrow2--; break;
12305:   case 150: direction=1;  jrow1++; jcol2--; break;
12306:   case 232: direction=-2; jcol1++; jrow2--; break;
12307:   } /* --- end-of-switch(gridnum/2) --- */
12308: /* --- get turns directions (tunr1==1 signals inside corner) --- */
12309: if ( (turn1=aafollowline(rp,jrow1,jcol1,-direction)) == 1 )
12310:   { aaval=0; goto end_of_job; }
12311: if ( 1 ) goto end_of_job;  /* stop here for now */
12312: if ( (turn2=aafollowline(rp,jrow2,jcol2,direction))  == 0 ) goto end_of_job;
12313: if ( turn1*turn2 >= 0 ) goto end_of_job; /* both turns in same direction */
12314: /* --- weight pixel --- */
12315: aaval = grayscale / ( 3 + min2(abs(turn1),abs(turn2)) );
12316: /* -------------------------------------------------------------------------
12317: Back to caller with grayscale antialiased value for pixel at irow,icol
12318: -------------------------------------------------------------------------- */
12319: end_of_job:
12320:   if ( aaval >= 0 )			/* have antialiasing result */
12321:    if ( msglevel>=99 && msgfp!=NULL ) fprintf(msgfp, /* diagnostic output */
12322:     "aapattern39> irow,icol,grid#/2=%d,%d,%d, turn%d,%d=%d,%d, aaval=%d\n",
12323:     irow,icol,gridnum/2, -direction,direction,turn1,turn2, aaval);
12324:   return ( aaval );			/* back with antialiased value */
12325: } /* --- end-of-function aapattern39() --- */
12326: 
12327: 
12328: /* ==========================================================================
12329:  * Function:	aafollowline ( rp, irow, icol, direction )
12330:  * Purpose:	starting with pixel at irow,icol, moves in
12331:  *		specified direction looking for a "turn"
12332:  * --------------------------------------------------------------------------
12333:  * Arguments:	rp (I)		raster *  to raster containing pixel image
12334:  *		irow (I)	int containing row, 0...height-1,
12335:  *				of first pixel
12336:  *		icol (I)	int containing col, 0...width-1,
12337:  *				of first pixel
12338:  *		direction (I)	int containing +1 to follow line up/north
12339:  *				(decreasing irow), -1 to follow line
12340:  *				down/south (increasing irow), +2 to follow
12341:  *				line right/east (increasing icol),
12342:  *				-2 to follow line left/west (decreasing icol)
12343:  * --------------------------------------------------------------------------
12344:  * Returns:	( int )		#rows or #cols traversed prior to turn,
12345:  *				or 0 if no turn detected (or for any error).
12346:  *				Sign is + if turn direction is right/east or
12347:  *				up/north, or is - if left/west or down/south.
12348:  * --------------------------------------------------------------------------
12349:  * Notes:     o	Here are some examples illustrating turn detection in
12350:  *		+2 (right/east) direction.  Turns in other directions
12351:  *		are detected similarly/symmetrically.  * denotes black
12352:  *		bits (usually fg), - denotes white bits (usually bg),
12353:  *		and ? denotes "don't care" bit (won't affect outcome).
12354:  *		Arrow --> points to start pixel denoted by irow,icol.
12355:  *
12356:  *		   *???         -???	turn=0 (no turn) is returned
12357:  *		-->*???   or -->-???	because the start pixel isn't
12358:  *		   *???         -???	on an edge to begin with
12359:  *
12360:  *		   ----         **--	turn=0 returned because the
12361:  *		-->***-   or -->***-	line ends abruptly without
12362:  *		   ----	        ----	turning (even the second case)
12363:  *
12364:  *		   ---*         ---*	turn=0 returned because the
12365:  *		-->***-   or -->****	line forms a Y or T rather
12366:  *		   ---*	        ---*	than turning
12367:  *
12368:  *		   ***-	        ****	turn=+3 returned
12369:  *		-->***-   or -->***-	(outside corner)
12370:  *		   ----	        ----
12371:  *
12372:  *		   *****        ****-	turn=-4 returned
12373:  *		-->*****  or -->****-	(inside corner)
12374:  *		   ----*        ----*
12375:  *
12376:  *		   ----*        ----*	turn=+4 returned
12377:  *		-->****-  or -->*****	(outside or inside corner)
12378:  *		   -----        -----
12379:  * ======================================================================= */
12380: /* --- entry point --- */
12381: int	aafollowline (raster *rp, int irow, int icol, int direction)
12382: {
12383: /* -------------------------------------------------------------------------
12384: Allocations and Declarations
12385: -------------------------------------------------------------------------- */
12386: pixbyte	*bitmap = rp->pixmap;		/* local rp->pixmap ptr */
12387: int	width=rp->width, height=rp->height; /* width, height of raster */
12388: int	drow=0, dcol=0,			/* delta row,col to follow line */
12389: 	jrow=irow, jcol=icol;		/* current row,col following line */
12390: int	bitval=1,			/* value of rp bit at irow,icol */
12391: 	fgval=1, bgval=0,		/* "fg" is whatever bitval is */
12392: 	bitminus=0, bitplus=0;		/* value of left/down, right/up bit*/
12393: int	isline=1, isedge=0;		/*isline signals one-pixel wide line*/
12394: int	turn = 0,			/* detected turn back to caller */
12395: 	maxturn = maxfollow;		/* don't follow more than max pixels*/
12396: /* -------------------------------------------------------------------------
12397: Initialization
12398: -------------------------------------------------------------------------- */
12399: /* --- check input --- */
12400: if ( irow<0 || irow>=height		/* irow out-of-bounds */
12401: ||   icol<0 || icol>=width ) goto end_of_job; /* icol out-of-bounds */
12402: /* --- starting bit -- see if we're following a fg (usual), or bg line --- */
12403: bitval = getlongbit(bitmap,(icol+irow*width)); /* starting pixel (bg or fg)*/
12404: fgval = bitval;  bgval = (1-bitval);	/* define "fg" as whatever bitval is*/
12405: /* --- set drow,dcol corresponding to desired direction --- */
12406: switch ( direction ) {			/* determine drow,dcol for direction*/
12407:   default: goto end_of_job;		/* unrecognized direction arg */
12408:   case  1: drow = (-1); break;		/* follow line up/north */
12409:   case -1: drow =   1;  break;		/* down/south */
12410:   case  2: dcol =   1;  break;		/* right/east */
12411:   case -2: dcol = (-1); break; }	/* left/west */
12412: /* --- set bitminus and bitplus --- */
12413: if ( drow == 0 ) {			/* we're following line right/left */
12414:   if ( irow < height )			/* there's a pixel below current */
12415:     bitminus = getlongbit(bitmap,(icol+(irow+1)*width)); /* get it */
12416:   if ( irow > 0 )			/* there's a pixel above current */
12417:     bitplus = getlongbit(bitmap,(icol+(irow-1)*width)); } /* get it */
12418: if ( dcol == 0 ) {			/* we're following line up/down */
12419:   if ( icol < width )			/* there's a pixel to the right */
12420:     bitplus = getlongbit(bitmap,(icol+1+irow*width)); /* get it */
12421:   if ( icol > 0 )			/* there's a pixel to the left */
12422:     bitminus = getlongbit(bitmap,(icol-1+irow*width)); } /* get it */
12423: /* --- check for lack of line to follow --- */
12424: if ( bitval == bitplus			/* starting pixel same as above */
12425: &&   bitval == bitminus )		/* and below (or right and left) */
12426:   goto end_of_job;			/* so there's no line to follow */
12427: /* --- set isline and isedge (already initted for isline) --- */
12428: if ( bitval == bitplus )		/* starting pixel same as above */
12429:   { isedge = (-1);  isline = 0; }	/* so we're at an edge below */
12430: if (  bitval == bitminus )		/* starting pixel same as below */
12431:   { isedge = 1;  isline = 0; }		/* so we're at an edge above */
12432: /* -------------------------------------------------------------------------
12433: follow line
12434: -------------------------------------------------------------------------- */
12435: while ( 1 ) {				/* until turn found (or max) */
12436:   /* --- local allocations and declarations --- */
12437:   int	dbitval=0,			/* value of bit at jrow,jcol */
12438: 	dbitminus=0, dbitplus=0;	/* value of left/down, right/up bit*/
12439:   /* --- bump pixel count and indexes; check for max or end-of-raster --- */
12440:   turn++;				/* bump #pixels followed */
12441:   jrow += drow;  jcol += dcol;		/* indexes of next pixel to check */
12442:   if ( turn > maxturn			/* already followed max #pixels */
12443:   ||   jrow<0 || jrow>=height		/* or jrow past end-of-raster */
12444:   ||   jcol<0 || jcol>=width )		/* or jcol past end-of-raster */
12445:     { turn = 0;  goto end_of_job; }	/* so quit without finding a turn */
12446:   /* --- set current bit (dbitval) --- */
12447:   dbitval = getlongbit(bitmap,(jcol+jrow*width)); /*value of jrow,jcol bit*/
12448:   /* --- set dbitminus and dbitplus --- */
12449:   if ( drow == 0 ) {			/* we're following line right/left */
12450:     if ( irow < height )		/* there's a pixel below current */
12451:       dbitminus = getlongbit(bitmap,(jcol+(irow+1)*width)); /* get it */
12452:     if ( irow > 0 )			/* there's a pixel above current */
12453:       dbitplus = getlongbit(bitmap,(jcol+(irow-1)*width)); } /* get it */
12454:   if ( dcol == 0 ) {			/* we're following line up/down */
12455:     if ( icol < width )			/* there's a pixel to the right */
12456:       dbitplus = getlongbit(bitmap,(icol+1+jrow*width)); /* get it */
12457:     if ( icol > 0 )			/* there's a pixel to the left */
12458:       dbitminus = getlongbit(bitmap,(icol-1+jrow*width)); } /* get it */
12459:   /* --- first check for abrupt end-of-line, or for T or Y --- */
12460:   if ( isline != 0 )			/* abrupt end or T,Y must be a line*/
12461:     if ( ( bgval == dbitval		/* end-of-line if pixel flips to bg*/
12462:            && bgval == dbitplus		/* and bg same as above pixel */
12463:            && bgval == dbitminus )	/* and below (or right and left) */
12464:     ||   ( fgval == dbitplus		/* T or Y if fg same as above pixel*/
12465:            && fgval == dbitminus ) )	/* and below (or right and left) */
12466:       { turn = 0;  goto end_of_job; }	/* so we're at a T or Y */
12467:   /* --- check for turning line --- */
12468:   if ( isline != 0 ) {			/* turning line must be a line */
12469:     if ( fgval == dbitminus )		/* turning down */
12470:       { turn = -turn;  goto end_of_job; } /* so return negative turn */
12471:     else if ( fgval == dbitplus )	/* turning up */
12472:       goto end_of_job; }		/* so return positive turn */
12473:   /* --- check for inside corner at edge --- */
12474:   if ( isedge != 0 ) {			/* inside corner must be a edge */
12475:     if ( isedge < 0 && fgval == bitminus ) /* corner below */
12476:       { turn = -turn;  goto end_of_job; } /* so return negative turn */
12477:     if ( isedge > 0 && fgval == bitplus ) /* corner above */
12478:       goto end_of_job; }		/* so return positive turn */
12479:   /* --- check for abrupt end at edge --- */
12480:   if ( isedge != 0			/* abrupt edge end must be an edge */
12481:   &&   fgval == dbitval )		/* and line must not end */
12482:     if ( (isedge < 0 && bgval == bitplus) /* abrupt end above */
12483:     ||   (isedge > 0 && bgval == bitminus) ) /* or abrupt end below */
12484:       { turn = 0;  goto end_of_job; }	/* so edge ended abruptly */
12485:   /* --- check for outside corner at edge --- */
12486:   if ( isedge != 0			/* outside corner must be a edge */
12487:   &&   bgval == dbitval ) {		/* and line must end */
12488:     if ( isedge > 0 ) turn = -turn;	/* outside turn down from edge above*/
12489:     goto end_of_job; }
12490:   } /* --- end-of-while(1) --- */
12491: /* -------------------------------------------------------------------------
12492: Back to caller with #rows or #cols traversed, and direction of detected turn
12493: -------------------------------------------------------------------------- */
12494: end_of_job:
12495:   if ( msglevel>=99 && msgfp!=NULL )	/* debugging/diagnostic output */
12496:     fprintf(msgfp,"aafollowline> irow,icol,direction=%d,%d,%d, turn=%d\n",
12497:     irow,icol,direction,turn);
12498:   return ( turn );
12499: } /* --- end-of-function aafollowline() --- */
12500: 
12501: 
12502: /* ==========================================================================
12503:  * Function:	aagridnum ( rp, irow, icol )
12504:  * Purpose:	calculates gridnum, 0-511 (see Notes below),
12505:  *		for 3x3 grid centered at irow,icol
12506:  * --------------------------------------------------------------------------
12507:  * Arguments:	rp (I)		raster *  to raster containing
12508:  *				bitmap image (to be anti-aliased)
12509:  *		irow (I)	int containing row, 0...height-1,
12510:  *				at center of 3x3 grid
12511:  *		icol (I)	int containing col, 0...width-1,
12512:  *				at center of 3x3 grid
12513:  * --------------------------------------------------------------------------
12514:  * Returns:	( int )		0-511 grid number, or -1=any error
12515:  * --------------------------------------------------------------------------
12516:  * Notes:     o	Input gridnum is a 9-bit int, 0-511, coding a 3x3 pixel grid
12517:  *		whose bit positions (and corresponding values) in gridnum are
12518:  *		  876     256 128  64
12519:  *		  504  =   32   1  16
12520:  *		  321       8   4   2
12521:  *		Thus, for example (*=pixel set/black, -=pixel not set/white),
12522:  *		  *--         *--	  -**         (note that 209 is the
12523:  *		  -*- = 259   *-- = 302   -** = 209    inverse, set<-->unset,
12524:  *		  --*         ***         ---          of 302)
12525:  *	      o	A set pixel is considered black, an unset pixel considered
12526:  *		white.
12527:  * ======================================================================= */
12528: /* --- entry point --- */
12529: int	aagridnum (raster *rp, int irow, int icol)
12530: {
12531: /* -------------------------------------------------------------------------
12532: Allocations and Declarations
12533: -------------------------------------------------------------------------- */
12534: pixbyte	*bitmap = rp->pixmap;		/* local rp->pixmap ptr */
12535: int	width=rp->width, height=rp->height, /* width, height of raster */
12536: 	imap = icol + irow*width;	/* pixel index = icol + irow*width */
12537: int	bitval=0,			/* value of rp bit at irow,icol */
12538: 	nnbitval=0, nebitval=0, eebitval=0, sebitval=0,	/*adjacent vals*/
12539: 	ssbitval=0, swbitval=0, wwbitval=0, nwbitval=0,	/*compass pt names*/
12540: 	gridnum = (-1);			/* grid# 0-511 for above 9 bits */
12541: /* -------------------------------------------------------------------------
12542: check input
12543: -------------------------------------------------------------------------- */
12544: if ( irow<0 || irow>=height		/* irow out-of-bounds */
12545: ||   icol<0 || icol>=width ) goto end_of_job; /* icol out-of-bounds */
12546: /* -------------------------------------------------------------------------
12547: get the 9 bits comprising the 3x3 grid centered at irow,icol
12548: -------------------------------------------------------------------------- */
12549: /* --- get center bit --- */
12550: bitval = getlongbit(bitmap,imap);	/* value of rp input bit at imap */
12551: /* --- get 8 surrounding bits --- */
12552: if ( irow > 0 )				/* nn (north) bit available */
12553:    nnbitval = getlongbit(bitmap,imap-width); /* nn bit value */
12554: if ( irow < height-1 )			/* ss (south) bit available */
12555:    ssbitval = getlongbit(bitmap,imap+width); /* ss bit value */
12556: if ( icol > 0 )				/* ww (west) bit available */
12557:  { wwbitval = getlongbit(bitmap,imap-1); /* ww bit value */
12558:    if ( irow > 0 )			/* nw bit available */
12559:      nwbitval = getlongbit(bitmap,imap-width-1); /* nw bit value */
12560:    if ( irow < height-1 )		/* sw bit available */
12561:      swbitval = getlongbit(bitmap,imap+width-1); } /* sw bit value */
12562: if ( icol < width-1 )			/* ee (east) bit available */
12563:  { eebitval = getlongbit(bitmap,imap+1); /* ee bit value */
12564:    if ( irow > 0 )			/* ne bit available */
12565:      nebitval = getlongbit(bitmap,imap-width+1); /* ne bit value */
12566:    if ( irow < height-1 )		/* se bit available */
12567:      sebitval = getlongbit(bitmap,imap+width+1); } /* se bit value */
12568: /* --- set gridnum --- */
12569: gridnum = 0;				/* clear all bits */
12570: if (   bitval ) gridnum = 1;		/* set1bit(gridnum,0); */
12571: if ( nwbitval ) gridnum += 256;		/* set1bit(gridnum,8); */
12572: if ( nnbitval ) gridnum += 128;		/* set1bit(gridnum,7); */
12573: if ( nebitval ) gridnum += 64;		/* set1bit(gridnum,6); */
12574: if ( wwbitval ) gridnum += 32;		/* set1bit(gridnum,5); */
12575: if ( eebitval ) gridnum += 16;		/* set1bit(gridnum,4); */
12576: if ( swbitval ) gridnum += 8;		/* set1bit(gridnum,3); */
12577: if ( ssbitval ) gridnum += 4;		/* set1bit(gridnum,2); */
12578: if ( sebitval ) gridnum += 2;		/* set1bit(gridnum,1); */
12579: /* -------------------------------------------------------------------------
12580: Back to caller with gridnum coding 3x3 grid centered at irow,icol
12581: -------------------------------------------------------------------------- */
12582: end_of_job:
12583:   return ( gridnum );
12584: } /* --- end-of-function aagridnum() --- */
12585: 
12586: 
12587: /* ==========================================================================
12588:  * Function:	aapatternnum ( gridnum )
12589:  * Purpose:	Looks up the pattern number 1...51
12590:  *		corresponding to the 3x3 pixel grid coded by gridnum 0=no
12591:  *		pixels set (white) to 511=all pixels set (black).
12592:  * --------------------------------------------------------------------------
12593:  * Arguments:	gridnum (I)	int containing 0-511 coding a 3x3 pixel grid
12594:  *				(see Notes below)
12595:  * --------------------------------------------------------------------------
12596:  * Returns:	( int )		1 to 51, or -1=error
12597:  * --------------------------------------------------------------------------
12598:  * Notes:     o	Input gridnum is a 9-bit int, 0-511, coding a 3x3 pixel grid
12599:  *		whose bit positions (and corresponding values) in gridnum are
12600:  *		  876     256 128  64
12601:  *		  504  =   32   1  16
12602:  *		  321       8   4   2
12603:  *		Thus, for example (*=pixel set/black, -=pixel not set/white),
12604:  *		  *--         *--	  -**         (note that 209 is the
12605:  *		  -*- = 259   *-- = 302   -** = 209    inverse, set<-->unset,
12606:  *		  --*         ***         ---          of 302)
12607:  *	      o	A set pixel is considered black, an unset pixel considered
12608:  *		white.
12609:  *	      o	Ignoring whether the center pixel is set or unset, and
12610:  *		taking rotation, reflection and inversion (set<-->unset)
12611:  *		symmetries into account, there are 32 unique pixel patterns.
12612:  *		If inversions are listed separately, there are 51 patterns.
12613:  *	      o	Here are the 51 unique patterns, with ? always denoting the
12614:  *		undetermined center pixel.  At the upper-left corner of each
12615:  *		pattern is the "pattern index number" assigned to it in this
12616:  *		function. At the upper-right is the pattern's multiplicity,
12617:  *		i.e., the number of different patterns obtained by rotations
12618:  *		and reflection of the illustrated one.  Inverse patters are
12619:  *		illustrated immediately beneath the original (the first three
12620:  *		four-pixel patterns have identical inverses).
12621:  *		-------------------------------------------------------------
12622:  *		No pixels set:
12623:  *		 #1 1 (in this case, 1 signifies that rotation
12624:  *		  ---  and reflection give no different grids)
12625:  *		  -?-
12626:  *		  ---
12627:  *		Inverse, all eight pixels set
12628:  *		 #2 1 (the inverse multiplicity is always the same)
12629:  *		  ***
12630:  *		  *?*
12631:  *		  ***
12632:  *		-------------------------------------------------------------
12633:  *		One pixel set:
12634:  *		 #3 4  #4 4
12635:  *		  *--   -*-
12636:  *		  -?-   -?-
12637:  *		  ---   ---
12638:  *		Inverse, seven pixels set:
12639:  *		 #5 4  #6 4
12640:  *		  -**   *-*
12641:  *		  *?*   *?*
12642:  *		  ***   ***
12643:  *		-------------------------------------------------------------
12644:  *		Two pixels set:
12645:  *		 #7 8  #8 4  #9 8  10 2  11 4  12 2
12646:  *		  **-   *-*   *--   *--   -*-   -*-
12647:  *		  -?-   -?-   -?*   -?-   -?*   -?-
12648:  *		  ---   ---   ---   --*   ---   -*-
12649:  *		Inverse, six pixels set:
12650:  *		#13 8  14 4  15 8  16 2  17 4  18 2
12651:  *		  --*   -*-   -**   -**   *-*   *-*
12652:  *		  *?*   *?*   *?-   *?*   *?-   *?*
12653:  *		  ***   ***   ***   **-   ***   *-*
12654:  *		-------------------------------------------------------------
12655:  *		Three pixels set:
12656:  *		#19 4  20 8  21 8  22 8  23 8  24 4  25 4  26 4  27 4  28 4
12657:  *		  ***   **-   **-   **-   **-   **-   *-*   *-*   -*-   -*-
12658:  *		  -?-   -?*   -?-   -?-   -?-   *?-   -?-   -?-   -?*   -?*
12659:  *		  ---   ---   --*   -*-   *--   ---   --*   -*-   -*-   *--
12660:  *		Inverse, five pixels set:
12661:  *		#29 4  30 8  31 8  32 8  33 8  34 4  35 4  36 4  37 4  38 4
12662:  *		  ---   --*   --*   --*   --*   --*   -*-   -*-   *-*   *-*
12663:  *		  *?*   *?-   *?*   *?*   *?*   -?*   *?*   *?*   *?-   *?-
12664:  *		  ***   ***   **-   *-*   -**   ***   **-   *-*   *-*   -**
12665:  *		-------------------------------------------------------------
12666:  *		Four pixels set (including inverses):
12667:  *		#39 8  40 4  41 8  42 8  43 4  44 4  45 8  46 1
12668:  *		  ***   **-   **-   ***   ***   **-   **-   *-*
12669:  *		  -?*   -?-   -?*   -?-   -?-   -?*   -?*   -?-
12670:  *		  ---   -**   *--   --*   -*-   --*   -*-   *-*
12671:  *
12672:  *		                  #47 8  48 4  49 4  50 8  51 1
12673:  *		                    ---   ---   --*   --*   -*-
12674:  *		                    *?*   *?*   *?-   *?-   *?*
12675:  *		                    **-   *-*   **-   *-*   -*-
12676:  * ======================================================================= */
12677: /* --- entry point --- */
12678: int	aapatternnum ( int gridnum )
12679: {
12680: /* -------------------------------------------------------------------------
12681: Allocations and Declarations
12682: -------------------------------------------------------------------------- */
12683: int	pattern = (-1);			/*pattern#, 1-51, for input gridnum*/
12684: /* ---
12685:  * pattern number corresponding to input gridnum/2 code
12686:  * ( gridnum/2 strips off gridnum's low bit because it's
12687:  * the same pattern whether or not center pixel is set )
12688:  * --- */
12689: static int patternnum[] = {
12690:     1, 3, 4, 7, 3, 8, 7,19, 4, 7,11,24, 9,23,20,39,  /*   0- 15 */
12691:     4, 9,11,20, 7,23,24,39,12,22,27,47,22,48,47,29,  /*  16- 31 */
12692:     3, 8, 9,23,10,25,21,42, 7,19,20,39,21,42,44,34,  /*  32- 47 */
12693:     9,26,28,41,21,50,49,30,22,43,45,33,40,32,31,13,  /*  48- 63 */
12694:     4, 9,12,22, 9,26,22,43,11,20,27,47,28,41,45,33,  /*  64- 79 */
12695:    11,28,27,45,20,41,47,33,27,45,51,35,45,36,35,14,  /*  80- 95 */
12696:     7,23,22,48,21,50,40,32,24,39,47,29,49,30,31,13,  /*  96-111 */
12697:    20,41,45,36,44,38,31,15,47,33,35,14,31,15,16, 5,  /* 112-127 */
12698:     3,10, 9,21, 8,25,23,42, 9,21,28,49,26,50,41,30,  /* 128-143 */
12699:     7,21,20,44,19,42,39,34,22,40,45,31,43,32,33,13,  /* 144-159 */
12700:     8,25,26,50,25,46,50,37,23,42,41,30,50,37,38,17,  /* 160-175 */
12701:    23,50,41,38,42,37,30,17,48,32,36,15,32,18,15, 6,  /* 176-191 */
12702:     7,21,22,40,23,50,48,32,20,44,45,31,41,38,36,15,  /* 192-207 */
12703:    24,49,47,31,39,30,29,13,47,31,35,16,33,15,14, 5,  /* 208-223 */
12704:    19,42,43,32,42,37,32,18,39,34,33,13,30,17,15, 6,  /* 224-239 */
12705:    39,30,33,15,34,17,13, 6,29,13,14, 5,13, 6, 5, 2,  /* 240-255 */
12706:    -1 } ; /* --- end-of-patternnum[] --- */
12707: /* -------------------------------------------------------------------------
12708: look up pattern number for gridnum
12709: -------------------------------------------------------------------------- */
12710: /* --- first check input --- */
12711: if ( gridnum<0 || gridnum>511 ) goto end_of_job; /* gridnum out of bounds */
12712: /* --- look up pattern number, 1-51, corresponding to input gridnum --- */
12713: pattern = patternnum[gridnum/2];	/* /2 strips off gridnum's low bit */
12714: if ( pattern<1 || pattern>51 ) pattern = (-1); /* some internal error */
12715: end_of_job:
12716:   return ( pattern );			/* back to caller with pattern# */
12717: } /* --- end-of-function aapatternnum() --- */
12718: 
12719: 
12720: /* ==========================================================================
12721:  * Function:	aalookup ( gridnum )
12722:  * Purpose:	Looks up the grayscale value 0=white to 255=black
12723:  *		corresponding to the 3x3 pixel grid coded by gridnum 0=no
12724:  *		pixels set (white) to 511=all pixels set (black).
12725:  * --------------------------------------------------------------------------
12726:  * Arguments:	gridnum (I)	int containing 0-511 coding a 3x3 pixel grid
12727:  * --------------------------------------------------------------------------
12728:  * Returns:	( int )		0=white to 255=black, or -1=error
12729:  * --------------------------------------------------------------------------
12730:  * Notes:     o	Input gridnum is a 9-bit int, 0-511, coding a 3x3 pixel grid
12731:  *	      o	A set pixel is considered black, an unset pixel considered
12732:  *		white.  Likewise, the returned grayscale is 255 for black,
12733:  *		0 for white.  You'd more typically want to use 255-grayscale
12734:  *		so that 255 is white and 0 is black.
12735:  *	      o	The returned number is the (lowpass) antialiased grayscale
12736:  *		for the center pixel (gridnum bit 0) of the grid.
12737:  * ======================================================================= */
12738: /* --- entry point --- */
12739: int	aalookup ( int gridnum )
12740: {
12741: /* -------------------------------------------------------------------------
12742: Allocations and Declarations
12743: -------------------------------------------------------------------------- */
12744: int	grayscale = (-1);		/*returned grayscale, init for error*/
12745: int	pattern = (-1), aapatternnum();	/*pattern#, 1-51, for input gridnum*/
12746: int	iscenter = gridnum&1;		/*low-order bit set for center pixel*/
12747: /* --- gray scales --- */
12748: #define	WHT 0
12749: #define	LGT 64
12750: #define	GRY 128
12751: #define	DRK 192
12752: #define	BLK 255
12753: #if 1
12754: /* ---
12755:  * modified aapnm() grayscales (second try)
12756:  * --- */
12757: /* --- grayscale for each pattern when center pixel set/black --- */
12758: static int grayscale1[] = { -1,		/* [0] index not used */
12759:    BLK,BLK,BLK,BLK,242,230,BLK,BLK,BLK,160,	/*  1-10 */
12760: /* BLK,BLK,BLK,BLK,242,230,BLK,BLK,BLK,BLK, */	/*  1-10 */
12761:    BLK,BLK,217,230,217,230,204,BLK,BLK,166,	/* 11-20 */
12762:    BLK,BLK,BLK,BLK,BLK,BLK,178,166,204,191,	/* 21-30 */
12763:    204,BLK,204,191,217,204,BLK,191,178,BLK,	/* 31-40 */
12764:    178,BLK,BLK,178,191,BLK,191,BLK,178,BLK,204,	/* 41-51 */
12765:    -1 } ; /* --- end-of-grayscale1[] --- */
12766: /* --- grayscale for each pattern when center pixel not set/white --- */
12767: static int grayscale0[] = { -1,		/* [0] index not used */
12768:    WHT,WHT,WHT,WHT,WHT,WHT,WHT,WHT,WHT,WHT,	/*  1-10 */
12769:     64,WHT,WHT,128,115,128,WHT,WHT,WHT, 64,	/* 11-20 */
12770:  /* 51,WHT,WHT,128,115,128,WHT,WHT,WHT, 64, */	/* 11-20 */
12771:    WHT,WHT,WHT, 64,WHT,WHT, 76, 64,102, 89,	/* 21-30 */
12772:    102,WHT,102,WHT,115,102,WHT, 89, 76,WHT,	/* 31-40 */
12773:     76,WHT,WHT, 76, 89,WHT, 89,WHT, 76,WHT,102,	/* 41-51 */
12774:    -1 } ; /* --- end-of-grayscale0[] --- */
12775: #endif
12776: #if 0
12777: /* ---
12778:  * modified aapnm() grayscales (first try)
12779:  * --- */
12780: /* --- grayscale for each pattern when center pixel set/black --- */
12781: static int grayscale1[] = { -1,		/* [0] index not used */
12782:    BLK,BLK,BLK,BLK,242,230,GRY,BLK,BLK,BLK,	/*  1-10 */
12783: /* BLK,BLK,BLK,BLK,242,230,BLK,BLK,BLK,BLK, */	/*  1-10 */
12784:    BLK,BLK,217,230,217,230,204,BLK,BLK,166,	/* 11-20 */
12785:    BLK,BLK,BLK,BLK,BLK,BLK,BLK,166,204,191,	/* 21-30 */
12786: /* BLK,BLK,BLK,BLK,BLK,BLK,178,166,204,191, */	/* 21-30 */
12787:    204,BLK,204,BLK,217,204,BLK,191,GRY,BLK,	/* 31-40 */
12788: /* 204,BLK,204,191,217,204,BLK,191,178,BLK, */	/* 31-40 */
12789:    178,BLK,BLK,178,191,BLK,BLK,BLK,178,BLK,204,	/* 41-51 */
12790: /* 178,BLK,BLK,178,191,BLK,191,BLK,178,BLK,204, */ /* 41-51 */
12791:    -1 } ; /* --- end-of-grayscale1[] --- */
12792: /* --- grayscale for each pattern when center pixel not set/white --- */
12793: static int grayscale0[] = { -1,		/* [0] index not used */
12794:    WHT,WHT,WHT,WHT,WHT,WHT,WHT,WHT,WHT,WHT,	/*  1-10 */
12795:    GRY,WHT,WHT,128,115,128,WHT,WHT,WHT,GRY,	/* 11-20 */
12796: /*  51,WHT,WHT,128,115,128,WHT,WHT,WHT, 64, */	/* 11-20 */
12797:    WHT,WHT,WHT,GRY,WHT,WHT, 76, 64,102, 89,	/* 21-30 */
12798: /* WHT,WHT,WHT, 64,WHT,WHT, 76, 64,102, 89, */	/* 21-30 */
12799:    102,WHT,102,WHT,115,102,WHT, 89,GRY,WHT,	/* 31-40 */
12800: /* 102,WHT,102,WHT,115,102,WHT, 89, 76,WHT, */	/* 31-40 */
12801:     76,WHT,WHT,GRY, 89,WHT, 89,WHT, 76,WHT,102,	/* 41-51 */
12802: /*  76,WHT,WHT, 76, 89,WHT, 89,WHT, 76,WHT,102, */ /* 41-51 */
12803:    -1 } ; /* --- end-of-grayscale0[] --- */
12804: #endif
12805: #if 0
12806: /* ---
12807:  * these grayscales _exactly_ correspond to the aapnm() algorithm
12808:  * --- */
12809: /* --- grayscale for each pattern when center pixel set/black --- */
12810: static int grayscale1[] = { -1,		/* [0] index not used */
12811:    BLK,BLK,BLK,BLK,242,230,BLK,BLK,BLK,BLK,	/*  1-10 */
12812:    BLK,BLK,217,230,217,230,204,BLK,BLK,166,	/* 11-20 */
12813:    BLK,BLK,BLK,BLK,BLK,BLK,178,166,204,191,	/* 21-30 */
12814:    204,BLK,204,191,217,204,BLK,191,178,BLK,	/* 31-40 */
12815:    178,BLK,BLK,178,191,BLK,191,BLK,178,BLK,204,	/* 41-51 */
12816:    -1 } ; /* --- end-of-grayscale1[] --- */
12817: /* --- grayscale for each pattern when center pixel not set/white --- */
12818: static int grayscale0[] = { -1,		/* [0] index not used */
12819:    WHT,WHT,WHT,WHT,WHT,WHT,WHT,WHT,WHT,WHT,	/*  1-10 */
12820:     51,WHT,WHT,128,115,128,WHT,WHT,WHT, 64,	/* 11-20 */
12821:    WHT,WHT,WHT, 64,WHT,WHT, 76, 64,102, 89,	/* 21-30 */
12822:    102,WHT,102,WHT,115,102,WHT, 89, 76,WHT,	/* 31-40 */
12823:     76,WHT,WHT, 76, 89,WHT, 89,WHT, 76,WHT,102,	/* 41-51 */
12824:    -1 } ; /* --- end-of-grayscale0[] --- */
12825: #endif
12826: /* -------------------------------------------------------------------------
12827: look up grayscale for gridnum
12828: -------------------------------------------------------------------------- */
12829: /* --- first check input --- */
12830: if ( gridnum<0 || gridnum>511 ) goto end_of_job; /* gridnum out of bounds */
12831: /* --- look up pattern number, 1-51, corresponding to input gridnum --- */
12832: pattern = aapatternnum(gridnum);	/* look up pattern number */
12833: if ( pattern<1 || pattern>51 ) goto end_of_job; /* some internal error */
12834: if ( ispatternnumcount ) {		/* counts being accumulated */
12835:   if (iscenter)	patternnumcount1[pattern] += 1;	/* bump diagnostic count */
12836:   else		patternnumcount0[pattern] += 1; }
12837: /* --- look up grayscale for this pattern --- */
12838: grayscale = ( iscenter? grayscale1[pattern] : grayscale0[pattern] );
12839: end_of_job:
12840:   return ( grayscale );			/* back to caller with grayscale */
12841: } /* --- end-of-function aalookup() --- */
12842: 
12843: 
12844: /* ==========================================================================
12845:  * Function:	aalowpasslookup ( rp, bytemap, grayscale )
12846:  * Purpose:	calls aalookup() for each pixel in rp->bitmap
12847:  *		to create anti-aliased bytemap
12848:  * --------------------------------------------------------------------------
12849:  * Arguments:	rp (I)		raster *  to raster whose bitmap
12850:  *				is to be anti-aliased
12851:  *		bytemap (O)	intbyte * to bytemap, calculated
12852:  *				by calling aalookup() for each pixel
12853:  *				in rp->bitmap
12854:  *		grayscale (I)	int containing number of grayscales
12855:  *				to be calculated, 0...grayscale-1
12856:  *				(should typically be given as 256)
12857:  * --------------------------------------------------------------------------
12858:  * Returns:	( int )		1=success, 0=any error
12859:  * --------------------------------------------------------------------------
12860:  * Notes:    o
12861:  * ======================================================================= */
12862: /* --- entry point --- */
12863: int	aalowpasslookup (raster *rp, intbyte *bytemap, int grayscale)
12864: {
12865: /* -------------------------------------------------------------------------
12866: Allocations and Declarations
12867: -------------------------------------------------------------------------- */
12868: int	width=rp->width, height=rp->height, /* width, height of raster */
12869: 	icol = 0, irow = 0, imap = (-1); /* width, height, bitmap indexes */
12870: int	bgbitval=0 /*, fgbitval=1*/;	/* background, foreground bitval */
12871: int	bitval=0,			/* value of rp bit at irow,icol */
12872: 	aabyteval=0;			/* antialiased (or unchanged) value*/
12873: int	gridnum=0, aagridnum(),		/* grid# for 3x3 grid at irow,icol */
12874: 	aalookup();			/* table look up  antialiased value*/
12875: /* -------------------------------------------------------------------------
12876: generate bytemap by table lookup for each pixel of bitmap
12877: -------------------------------------------------------------------------- */
12878: for ( irow=0; irow<height; irow++ )
12879:  for ( icol=0; icol<width; icol++ )
12880:   {
12881:   /* --- get gridnum and center bit value, init aabyteval --- */
12882:   gridnum = aagridnum(rp,irow,icol);	/*grid# coding 3x3 grid at irow,icol*/
12883:   bitval = (gridnum&1);			/* center bit set if gridnum odd */
12884:   aabyteval = (intbyte)(bitval==bgbitval?0:grayscale-1); /* default aa val */
12885:   imap++;				/* first bump bitmap[] index */  
12886:   bytemap[imap] = (intbyte)(aabyteval);	/* init antialiased pixel */
12887:   /* --- look up antialiased value for this grid --- */
12888:   aabyteval = aalookup(gridnum);	/* look up on grid# */
12889:   if ( aabyteval>=0 && aabyteval<=255 )	/* check for success */
12890:     bytemap[imap] = (intbyte)(aabyteval); /* init antialiased pixel */
12891:   } /* --- end-of-for(irow,icol) --- */
12892: ispatternnumcount = 0;			/* accumulate counts only once */
12893: /* -------------------------------------------------------------------------
12894: Back to caller with gray-scale anti-aliased bytemap
12895: -------------------------------------------------------------------------- */
12896: /*end_of_job:*/
12897:   return ( 1 );
12898: } /* --- end-of-function aalowpasslookup() --- */
12899: 
12900: 
12901: /* ==========================================================================
12902:  * Function:	aasupsamp ( rp, aa, sf, grayscale )
12903:  * Purpose:	calculates a supersampled anti-aliased bytemap
12904:  *		for rp->bitmap, with each byte 0...grayscale-1
12905:  * --------------------------------------------------------------------------
12906:  * Arguments:	rp (I)		raster *  to raster whose bitmap
12907:  *				is to be anti-aliased
12908:  *		aa (O)		address of raster * to supersampled bytemap,
12909:  *				calculated by supersampling rp->bitmap
12910:  *		sf (I)		int containing supersampling shrinkfactor
12911:  *		grayscale (I)	int containing number of grayscales
12912:  *				to be calculated, 0...grayscale-1
12913:  *				(should typically be given as 256)
12914:  * --------------------------------------------------------------------------
12915:  * Returns:	( int )		1=success, 0=any error
12916:  * --------------------------------------------------------------------------
12917:  * Notes:     o	If the center point of the box being averaged is black,
12918:  *		then the entire "average" is forced black (grayscale-1)
12919:  *		regardless of the surrounding points.  This is my attempt
12920:  *		to avoid a "washed-out" appearance of thin (one-pixel-wide)
12921:  *		lines, which would otherwise turn from black to a gray shade.
12922:  * ======================================================================= */
12923: /* --- entry point --- */
12924: int	aasupsamp (raster *rp, raster **aa, int sf, int grayscale)
12925: {
12926: /* -------------------------------------------------------------------------
12927: Allocations and Declarations
12928: -------------------------------------------------------------------------- */
12929: int	status = 0;			/* 1=success, 0=failure to caller */
12930: int	rpheight=rp->height, rpwidth=rp->width, /*bitmap raster dimensions*/
12931: 	heightrem=0, widthrem=0,	/* rp+rem is a multiple of shrinkf */
12932: 	aaheight=0,  aawidth=0,		/* supersampled dimensions */
12933: 	aapixsz=8;			/* output pixels are 8-bit bytes */
12934: int	maxaaval=(-9999),		/* max grayscale val set in matrix */
12935: 	isrescalemax=1;			/* 1=rescale maxaaval to grayscale */
12936: int	irp=0,jrp=0, iaa=0,jaa=0, iwt=0,jwt=0; /*indexes, i=width j=height*/
12937: raster	*aap=NULL, *new_raster();	/* raster for supersampled image */
12938: raster	*aaweights();			/* get weight matrix applied to rp */
12939: static	raster *aawts = NULL;		/* aaweights() resultant matrix */
12940: static	int prevshrink = NOVALUE,	/* shrinkfactor from previous call */
12941: 	sumwts = 0;			/* sum of weights */
12942: static	int blackfrac = 40,		/* force black if this many pts are */
12943: 	/*grayfrac = 20,*/
12944: 	maxwt = 10,			/* max weight in weight matrix */
12945: 	minwtfrac=10, maxwtfrac=70;	/* force light pts white, dark black*/
12946: int	type_raster(), type_bytemap();	/* debugging display routines */
12947: int	delete_raster();		/* delete old rasters */
12948: /* -------------------------------------------------------------------------
12949: Initialization
12950: -------------------------------------------------------------------------- */
12951: /* --- check args --- */
12952: if ( aa == NULL ) goto end_of_job;	/* no ptr for return output arg */
12953: *aa = NULL;				/* init null ptr for error return */
12954: if ( rp == NULL				/* no ptr to input arg */
12955: ||   sf < 1				/* invalid shrink factor */
12956: ||   grayscale < 2 ) goto end_of_job;	/* invalid grayscale */
12957: /* --- get weight matrix (or use current one) --- */
12958: if ( sf != prevshrink )			/* have new shrink factor */
12959:   { if ( aawts != NULL )		/* have unneeded weight matrix */
12960:       delete_raster(aawts);		/* so free it */
12961:     sumwts = 0;				/* reinitialize sum of weights */
12962:     aawts = aaweights(sf,sf);		/* get new weight matrix */
12963:     if ( aawts != NULL )		/* got weight matrix okay*/
12964:       for ( jwt=0; jwt<sf; jwt++ )	/* for each row */
12965:        for ( iwt=0; iwt<sf; iwt++ )	/* and each column */
12966: 	{ int wt = (int)(getpixel(aawts,jwt,iwt)); /* weight */
12967: 	  if ( wt > maxwt )		/* don't overweight center pts */
12968: 	    { wt = maxwt;		/* scale it back */
12969: 	      setpixel(aawts,jwt,iwt,wt); } /* and replace it in matrix */
12970: 	  sumwts += wt; }		/* add weight to sum */
12971:     prevshrink = sf; }			/* save new shrink factor */
12972: if ( msgfp!=NULL && msglevel>=999 )
12973:   { fprintf(msgfp,"aasupsamp> sf=%d, sumwts=%d weights=...\n", sf,sumwts);
12974:     type_bytemap((intbyte *)aawts->pixmap,grayscale,
12975:     aawts->width,aawts->height,msgfp); }
12976: /* --- calculate supersampled height,width and allocate output raster */
12977: heightrem = rpheight%sf;		/* remainder after division... */
12978: widthrem  = rpwidth%sf;			/* ...by shrinkfactor */
12979: aaheight  = 1+(rpheight+sf-(heightrem+1))/sf; /* ss height */
12980: aawidth   = 1+(rpwidth+sf-(widthrem+1))/sf; /* ss width */
12981: if ( msgfp!=NULL && msglevel>=999 )
12982:  { fprintf(msgfp,"aasupsamp> rpwid,ht=%d,%d wd,htrem=%d,%d aawid,ht=%d,%d\n",
12983:    rpwidth,rpheight, widthrem,heightrem, aawidth,aaheight);
12984:    fprintf(msgfp,"aasupsamp> dump of original bitmap image...\n");
12985:    type_raster(rp,msgfp); }		/* ascii image of rp raster */
12986: if ( (aap = new_raster(aawidth,aaheight,aapixsz)) /* alloc output raster*/
12987: ==   NULL ) goto end_of_job;		/* quit if alloc fails */
12988: /* -------------------------------------------------------------------------
12989: Step through rp->bitmap, applying aawts to each "submatrix" of bitmap
12990: -------------------------------------------------------------------------- */
12991: for ( jaa=0,jrp=(-(heightrem+1)/2); jrp<rpheight; jrp+=sf ) /* height */
12992:  {
12993:  for ( iaa=0,irp=(-(widthrem+1)/2); irp<rpwidth; irp+=sf ) /* width */
12994:   {
12995:   int aaval=0;				/* weighted rpvals */
12996:   int nrp=0, mrp=0;			/* #rp bits set, #within matrix */
12997:   for ( jwt=0; jwt<sf; jwt++ )
12998:    for ( iwt=0; iwt<sf; iwt++ )
12999:     {
13000:     int i=irp+iwt, j=jrp+jwt;		/* rp->pixmap point */
13001:     int rpval = 0;			/* rp->pixmap value at i,j */
13002:     if ( i>=0 && i<rpwidth		/* i within actual pixmap */
13003:     &&   j>=0 && j<rpheight )		/* ditto j */
13004:       {	mrp++;				/* count another bit within matrix */
13005: 	rpval = (int)(getpixel(rp,j,i)); } /* get actual pixel value */
13006:     if ( rpval != 0 )
13007:       {	nrp++;				/* count another bit set */
13008: 	aaval += (int)(getpixel(aawts,jwt,iwt)); } /* sum weighted vals */
13009:     } /* --- end-of-for(iwt,jwt) --- */
13010:   if ( aaval > 0 )			/*normalize and rescale non-zero val*/
13011:     { int aafrac = (100*aaval)/sumwts;	/* weighted percent of black points */
13012:       /*if((100*nrp)/mrp >=blackfrac)*/	/* many black interior pts */
13013:       if( aafrac >= maxwtfrac )		/* high weight of sampledblack pts */
13014: 	aaval = grayscale-1;		/* so set supersampled pt black */
13015:       else if( aafrac <= minwtfrac )	/* low weight of sampledblack pts */
13016: 	aaval = 0;			/* so set supersampled pt white */
13017:       else				/* rescale calculated weight */
13018: 	aaval = ((sumwts/2 - 1) + (grayscale-1)*aaval)/sumwts; }
13019:   maxaaval = max2(maxaaval,aaval);	/* largest aaval so far */
13020:   if ( msgfp!=NULL && msglevel>=999 )
13021:     fprintf(msgfp,"aasupsamp> jrp,irp=%d,%d jaa,iaa=%d,%d"
13022:     " mrp,nrp=%d,%d aaval=%d\n",
13023:     jrp,irp, jaa,iaa, mrp,nrp, aaval);
13024:   if ( jaa<aaheight && iaa<aawidth )	/* bounds check */
13025:     setpixel(aap,jaa,iaa,aaval);	/*weighted val in supersamp raster*/
13026:   else if( msgfp!=NULL && msglevel>=9 )	/* emit error if out-of-bounds */
13027:     fprintf(msgfp,"aasupsamp> Error: aaheight,aawidth=%d,%d jaa,iaa=%d,%d\n",
13028:     aaheight,aawidth, jaa,iaa);
13029:   iaa++;				/* bump aa col index */
13030:   } /* --- end-of-for(irp) --- */
13031:  jaa++;					/* bump aa row index */
13032:  } /* --- end-of-for(jrp) --- */
13033: /* --- rescale supersampled image so darkest points become black --- */
13034: if ( isrescalemax )			/* flag set to rescale maxaaval */
13035:   {
13036:   double scalef = ((double)(grayscale-1))/((double)maxaaval);
13037:   for ( jaa=0; jaa<aaheight; jaa++ )	/* height */
13038:    for ( iaa=0; iaa<aawidth; iaa++ )	/* width */
13039:     { int aafrac, aaval = getpixel(aap,jaa,iaa); /* un-rescaled value */
13040:       aaval = (int)(0.5+((double)aaval)*scalef); /*multiply by scale factor*/
13041:       aafrac = (100*aaval)/(grayscale-1); /* fraction of blackness */
13042:       if( aafrac >= blackfrac )		/* high weight of sampledblack pts */
13043: 	aaval = grayscale-1;		/* so set supersampled pt black */
13044:       else if( 0&&aafrac <= minwtfrac )	/* low weight of sampledblack pts */
13045: 	aaval = 0;			/* so set supersampled pt white */
13046:       setpixel(aap,jaa,iaa,aaval); }	/* replace rescaled val in raster */
13047:   } /* --- end-of-if(isrescalemax) --- */
13048: *aa = aap;				/* return supersampled image*/
13049: status = 1;				/* set successful status */
13050: if ( msgfp!=NULL && msglevel>=999 )
13051:   { fprintf(msgfp,"aasupsamp> anti-aliased image...\n");
13052:     type_bytemap((intbyte *)aap->pixmap,grayscale,
13053:     aap->width,aap->height,msgfp);  fflush(msgfp); }
13054: /* -------------------------------------------------------------------------
13055: Back to caller with gray-scale anti-aliased bytemap
13056: -------------------------------------------------------------------------- */
13057: end_of_job:
13058:   return ( status );
13059: } /* --- end-of-function aasupsamp() --- */
13060: 
13061: 
13062: /* ==========================================================================
13063:  * Function:	aacolormap ( bytemap, nbytes, colors, colormap )
13064:  * Purpose:	searches bytemap, returning a list of its discrete values
13065:  *		in ascending order in colors[], and returning an "image"
13066:  *		of bytemap (where vales are replaced by colors[]
13067:  *		indexes) in colormap[].
13068:  * --------------------------------------------------------------------------
13069:  * Arguments:	bytemap (I)	intbyte *  to bytemap containing
13070:  *				grayscale values (usually 0=white
13071:  *				through 255=black) for which colors[]
13072:  *				and colormap[] will be constructed.
13073:  *		nbytes (I)	int containing #bytes in bytemap
13074:  *				(usually just #rows * #cols)
13075:  *		colors (O)	intbyte *  (to be interpreted as ints)
13076:  *				returning a list of the discrete/different
13077:  *				values in bytemap, in ascending value order,
13078:  *				and with gamma correction applied
13079:  *		colormap (O)	intbyte *  returning a bytemap "image",
13080:  *				i.e., in one-to-one pixel correspondence
13081:  *				with bytemap, but where the values have been
13082:  *				replaced with corresponding colors[] indexes.
13083:  * --------------------------------------------------------------------------
13084:  * Returns:	( int )		#colors in colors[], or 0 for any error
13085:  * --------------------------------------------------------------------------
13086:  * Notes:     o
13087:  * ======================================================================= */
13088: /* --- entry point --- */
13089: int	aacolormap ( intbyte *bytemap, int nbytes,
13090: 			intbyte *colors, intbyte *colormap )
13091: {
13092: /* -------------------------------------------------------------------------
13093: Allocations and Declarations
13094: -------------------------------------------------------------------------- */
13095: int	ncolors = 0,			/* #different values in bytemap */
13096: 	igray, grayscale = 256;		/* bytemap contains intbyte's */
13097: intbyte	*bytevalues = NULL;		/* 1's where bytemap contains value*/
13098: int	ibyte;				/* bytemap/colormap index */
13099: int	isscale = 0,			/* true to scale largest val to 255*/
13100: 	isgamma = 1;			/* true to apply gamma correction */
13101: int	maxcolors = 0;			/* maximum ncolors */
13102: /* -------------------------------------------------------------------------
13103: Accumulate colors[] from values occurring in bytemap
13104: -------------------------------------------------------------------------- */
13105: /* --- initialization --- */
13106: if ( (bytevalues = (intbyte *)malloc(grayscale)) /*alloc bytevalues*/
13107: ==   NULL ) goto end_of_job;		/* signal error if malloc() failed */
13108: memset(bytevalues,0,grayscale);		/* zero out bytevalues */
13109: /* --- now set 1's at offsets corresponding to values found in bytemap --- */
13110: for ( ibyte=0; ibyte<nbytes; ibyte++ )	/* for each byte in bytemap */
13111:   bytevalues[(int)bytemap[ibyte]] = 1;	/*use its value to index bytevalues*/
13112: /* --- collect the 1's indexes in colors[] --- */
13113: for ( igray=0; igray<grayscale; igray++ ) /* check all possible values */
13114:   if ( (int)bytevalues[igray] )		/*bytemap contains igray somewheres*/
13115:     { colors[ncolors] = (intbyte)igray;	/* so store igray in colors */
13116:       bytevalues[igray] = (intbyte)ncolors; /* save colors[] index */
13117:       if ( maxcolors>0 && ncolors>=maxcolors ) /* too many color indexes */
13118:         bytevalues[igray] = (intbyte)(maxcolors-1); /*so scale back to max*/
13119:       ncolors++; }			/* and bump #colors */
13120: /* --- rescale colors so largest, colors[ncolors-1], is black --- */
13121: if ( isscale )				/* only rescale if requested */
13122:  if ( ncolors > 1 )			/* and if not a "blank" raster */
13123:   if ( colors[ncolors-1] > 0 )		/*and at least one pixel non-white*/
13124:    {
13125:    /* --- multiply each colors[] by factor that scales largest to 255 --- */
13126:    double scalefactor = ((double)(grayscale-1))/((double)colors[ncolors-1]);
13127:    for ( igray=1; igray<ncolors; igray++ ) /* re-scale each colors[] */
13128:     { colors[igray] = min2(grayscale-1,(int)(scalefactor*colors[igray]+0.5));
13129:       if (igray>5) colors[igray] = min2(grayscale-1,colors[igray]+2*igray); }
13130:    } /* --- end-of-if(isscale) --- */
13131: /* --- apply gamma correction --- */
13132: if ( isgamma				/* only gamma correct if requested */
13133: &&   gammacorrection > 0.0001 )		/* and if we have gamma correction */
13134:  if ( ncolors > 1 )			/* and if not a "blank" raster */
13135:   if ( colors[ncolors-1] > 0 )		/*and at least one pixel non-white*/
13136:    {
13137:    for ( igray=1; igray<ncolors; igray++ ) { /*gamma correct each colors[]*/
13138:     int	grayval = colors[igray],	/* original 0=white to 255=black */
13139: 	gmax = grayscale-1;		/* should be 255 */
13140:     double dgray=((double)(gmax-grayval))/((double)gmax); /*0=black 1=white*/
13141:     dgray = pow(dgray,(1.0/gammacorrection)); /* apply gamma correction */
13142:     grayval = (int)( gmax*(1.0-dgray) + 0.5 ); /* convert back to grayval */
13143:     colors[igray] = grayval; }		/* store back in colors[] */
13144:    } /* --- end-of-if(isgamma) --- */
13145: /* -------------------------------------------------------------------------
13146: Construct colormap
13147: -------------------------------------------------------------------------- */
13148: for ( ibyte=0; ibyte<nbytes; ibyte++ )	/* for each byte in bytemap */
13149:   colormap[ibyte] = bytevalues[(int)bytemap[ibyte]]; /*index for this value*/
13150: /* -------------------------------------------------------------------------
13151: back to caller with #colors, or 0 for any error
13152: -------------------------------------------------------------------------- */
13153: end_of_job:
13154:   if ( bytevalues != NULL ) free(bytevalues); /* free working memory */
13155:   if ( maxcolors>0 && ncolors>maxcolors ) /* too many color indexes */
13156:     ncolors = maxcolors;		/* return maximum to caller */
13157:   return ( ncolors );			/* back with #colors, or 0=error */
13158: } /* --- end-of-function aacolormap() --- */
13159: 
13160: 
13161: /* ==========================================================================
13162:  * Function:	aaweights ( width, height )
13163:  *		Builds "canonical" weight matrix, width x height, in a raster
13164:  *		(see Notes below for discussion).
13165:  * --------------------------------------------------------------------------
13166:  * Arguments:	width (I)	int containing width (#cols) of returned
13167:  *				raster/matrix of weights
13168:  *		height (I)	int containing height (#rows) of returned
13169:  *				raster/matrix of weights
13170:  * --------------------------------------------------------------------------
13171:  * Returns:	( raster * )	ptr to raster containing width x height
13172:  *				weight matrix, or NULL for any error
13173:  * --------------------------------------------------------------------------
13174:  * Notes:     o For example, given width=7, height=5, builds the matrix
13175:  *			1 2 3  4 3 2 1
13176:  *			2 4 6  8 6 4 2
13177:  *			3 6 9 12 9 6 3
13178:  *			2 4 6  8 6 4 2
13179:  *			1 2 3  4 3 2 1
13180:  *		If an even dimension given, the two center numbers stay
13181:  *		the same, e.g., 123321 for the top row if width=6.
13182:  *	      o	For an odd square n x n matrix, the sum of all n^2
13183:  *		weights will be ((n+1)/2)^4.
13184:  *	      o	The largest weight (in the allocated pixsz=8 raster) is 255,
13185:  *		so the largest square matrix is 31 x 31.  Any weight that
13186:  *		tries to grow beyond 255 is held constant at 255.
13187:  *	      o	A new_raster(), pixsz=8, is allocated for the caller.
13188:  *		To avoid memory leaks, be sure to delete_raster() when done.
13189:  * ======================================================================= */
13190: /* --- entry point --- */
13191: raster	*aaweights ( int width, int height )
13192: {
13193: /* -------------------------------------------------------------------------
13194: Allocations and Declarations
13195: -------------------------------------------------------------------------- */
13196: raster	*new_raster(), *weights=NULL;	/* raster of weights returned */
13197: int	irow=0, icol=0,			/* height, width indexes */
13198: 	weight = 0;			/*running weight, as per Notes above*/
13199: /* -------------------------------------------------------------------------
13200: Initialization
13201: -------------------------------------------------------------------------- */
13202: /* --- allocate raster for weights --- */
13203: if ( (weights = new_raster(width,height,8)) /* allocate 8-bit byte raster */
13204: ==  NULL ) goto end_of_job;		/* return NULL error if failed */
13205: /* -------------------------------------------------------------------------
13206: Fill weight matrix, as per Notes above
13207: -------------------------------------------------------------------------- */
13208: for ( irow=0; irow<height; irow++ )	/* outer loop over rows */
13209:   for ( icol=0; icol<width; icol++ )	/* inner loop over cols */
13210:     {
13211:     int	jrow = height-irow-1,		/* backwards irow, height-1,...,0 */
13212: 	jcol =  width-icol-1;		/* backwards icol,  width-1,...,0 */
13213:     weight = min2(irow+1,jrow+1) * min2(icol+1,jcol+1); /* weight */
13214:     if ( aaalgorithm == 1 ) weight=1;	/* force equal weights */
13215:     setpixel(weights,irow,icol,min2(255,weight)); /*store weight in matrix*/
13216:     } /* --- end-of-for(irow,icol) --- */
13217: end_of_job:
13218:   return ( weights );			/* back with weights or NULL=error */
13219: } /* --- end-of-function aaweights() --- */
13220: 
13221: 
13222: /* ==========================================================================
13223:  * Function:	aawtpixel ( image, ipixel, weights, rotate )
13224:  * Purpose:	Applies matrix of weights to the pixels
13225:  *		surrounding ipixel in image, rotated clockwise
13226:  *		by rotate degrees (typically 0 or 30).
13227:  * --------------------------------------------------------------------------
13228:  * Arguments:	image (I)	raster * to bitmap (though it can be bytemap)
13229:  *				containing image with pixels to be averaged.
13230:  *		ipixel (I)	int containing index (irow*width+icol) of
13231:  *				center pixel of image for weighted average.
13232:  *		weights (I)	raster * to bytemap of relative weights
13233:  *				(0-255), whose dimensions (usually odd width
13234:  *				and odd height) determine the "subgrid" of
13235:  *				image surrounding ipixel to be averaged.
13236:  *		rotate (I)	int containing degrees clockwise rotation
13237:  *				(typically 0 or 30), i.e., imagine weights
13238:  *				rotated clockwise and then averaging the
13239:  *				image pixels "underneath" it now.
13240:  * --------------------------------------------------------------------------
13241:  * Returns:	( int )		0-255 weighted average, or -1 for any error
13242:  * --------------------------------------------------------------------------
13243:  * Notes:     o	The rotation matrix used (when requested) is
13244:  *		    / x' \     / cos(theta)  sin(theta)/a \  / x \
13245:  *		    |    |  =  |                          |  |   |
13246:  *                  \ y' /     \ -a*sin(theta) cos(theta) /  \ y /
13247:  *		where a=1 (current default) is the pixel (not screen)
13248:  *		aspect ratio width:height, and theta is rotate (converted
13249:  *		from degrees to radians).  Then x=col,y=row are the integer
13250:  *		pixel coords relative to the input center ipixel, and
13251:  *		x',y' are rotated coords which aren't necessarily integer.
13252:  *		The actual pixel used is the one nearest x',y'.
13253:  * ======================================================================= */
13254: /* --- entry point --- */
13255: int	aawtpixel ( raster *image, int ipixel, raster *weights, int rotate )
13256: {
13257: /* -------------------------------------------------------------------------
13258: Allocations and Declarations
13259: -------------------------------------------------------------------------- */
13260: int	aaimgval = 0,			/* weighted avg returned to caller */
13261: 	totwts=0, sumwts=0;		/* total of all wts, sum wts used */
13262: int	pixsz = image->pixsz,		/* #bits per image pixel */
13263: 	black1=1, black8=255,		/* black for 1-bit, 8-bit pixels */
13264: 	black = (pixsz==1? black1:black8), /* black value for our image */
13265: 	scalefactor = (black1+black8-black), /* only scale 1-bit images */
13266: 	iscenter = 0;			/* set true if center pixel black */
13267: /* --- grid dimensions and indexes --- */
13268: int	wtheight  = weights->height,	/* #rows in weight matrix */
13269: 	wtwidth   = weights->width,	/* #cols in weight matrix */
13270: 	imgheight =   image->height,	/* #rows in image */
13271: 	imgwidth  =   image->width;	/* #cols in image */
13272: int	wtrow,  wtrow0 = wtheight/2,	/* center row index for weights */
13273: 	wtcol,  wtcol0 = wtwidth/2,	/* center col index for weights */
13274: 	imgrow, imgrow0= ipixel/imgwidth, /* center row index for ipixel */
13275: 	imgcol, imgcol0= ipixel-(imgrow0*imgwidth); /*center col for ipixel*/
13276: /* --- rotated grid variables --- */
13277: static	int prevrotate = 0;		/* rotate from previous call */
13278: static	double costheta = 1.0,		/* cosine for previous rotate */
13279: 	sintheta = 0.0;			/* and sine for previous rotate */
13280: double	a = 1.0;			/* default aspect ratio */
13281: /* -------------------------------------------------------------------------
13282: Initialization
13283: -------------------------------------------------------------------------- */
13284: /* --- refresh trig functions for rotate when it changes --- */
13285: if ( rotate != prevrotate )		/* need new sine/cosine */
13286:   { costheta = cos(((double)rotate)/57.29578);	/*cos of rotate in radians*/
13287:     sintheta = sin(((double)rotate)/57.29578);	/*sin of rotate in radians*/
13288:     prevrotate = rotate; }		/* save current rotate as prev */
13289: /* -------------------------------------------------------------------------
13290: Calculate aapixel as weighted average over image points around ipixel
13291: -------------------------------------------------------------------------- */
13292: for ( wtrow=0; wtrow<wtheight; wtrow++ )
13293:  for ( wtcol=0; wtcol<wtwidth; wtcol++ )
13294:   {
13295:   /* --- allocations and declarations --- */
13296:   int	wt = (int)getpixel(weights,wtrow,wtcol); /* weight for irow,icol */
13297:   int	drow = wtrow - wtrow0,		/* delta row offset from center */
13298: 	dcol = wtcol - wtcol0;		/* delta col offset from center */
13299:   int	iscenter = 0;			/* set true if center point black */
13300:   /* --- initialization --- */
13301:   totwts += wt;				/* sum all weights */
13302:   /* --- rotate (if requested) --- */
13303:   if ( rotate != 0 )			/* non-zero rotation */
13304:     {
13305:     /* --- apply rotation matrix to (x=dcol,y=drow) --- */
13306:     double dx=(double)dcol, dy=(double)drow, dtemp; /* need floats */
13307:     dtemp = dx*costheta + dy*sintheta/a; /* save new dx' */
13308:     dy = -a*dx*sintheta + dy*costheta;	/* dy becomes new dy' */
13309:     dx = dtemp;				/* just for notational convenience */
13310:     /* --- replace original (drow,dcol) with nearest rotated point --- */
13311:     drow = (int)(dy+0.5);		/* round dy for nearest row */
13312:     dcol = (int)(dx+0.5);		/* round dx for nearest col */
13313:     } /* --- end-of-if(rotate!=0) --- */
13314:   /* --- select image pixel to be weighted --- */
13315:   imgrow = imgrow0 + drow;		/*apply displacement to center row*/
13316:   imgcol = imgcol0 + dcol;		/*apply displacement to center col*/
13317:   /* --- if pixel in bounds, accumulate weighted average --- */
13318:   if ( imgrow>=0 && imgrow<imgheight )	/* row is in bounds */
13319:    if ( imgcol>=0 && imgcol<imgwidth )	/* and col is in bounds */
13320:     {
13321:     /* --- accumulate weighted average --- */
13322:     int imgval = (int)getpixel(image,imgrow,imgcol); /* image value */
13323:     aaimgval += wt*imgval;		/* weighted sum of image values */
13324:     sumwts += wt;			/* and also sum weights used */
13325:     /* --- check if center image pixel black --- */
13326:     if ( drow==0 && dcol==0 )		/* this is center ipixel */
13327:       if ( imgval==black )		/* and it's black */
13328: 	iscenter = 1;			/* so set black center flag true */
13329:     } /* --- end-of-if(bounds checks ok) --- */
13330:   } /* --- end-of-for(irow,icol) --- */
13331: if ( 0 && iscenter )			/* center point is black */
13332:   aaimgval = black8;			/* so force average black */
13333: else					/* center point not black */
13334:   aaimgval =				/* 0=white ... black */
13335:       ((totwts/2 - 1) + scalefactor*aaimgval)/totwts; /* not /sumwts; */
13336: /*end_of_job:*/
13337:   return ( aaimgval );
13338: } /* --- end-of-function aawtpixel() --- */
13339: 
13340: 
13341: /* ==========================================================================
13342:  * Function:	mimetexsetmsg ( newmsglevel, newmsgfp )
13343:  * Purpose:	Sets msglevel and msgfp, usually called from
13344:  *		an external driver (i.e., DRIVER not defined
13345:  *		in this module).
13346:  * --------------------------------------------------------------------------
13347:  * Arguments:	newmsglevel (I)	int containing new msglevel
13348:  *				(unchanged if newmsglevel<0)
13349:  *		newmsgfp (I)	FILE * containing new msgfp
13350:  *				(unchanged if newmsgfp=NULL)
13351:  * --------------------------------------------------------------------------
13352:  * Returns:	( int )		always 1
13353:  * --------------------------------------------------------------------------
13354:  * Notes:     o
13355:  * ======================================================================= */
13356: /* --- entry point --- */
13357: int	mimetexsetmsg ( int newmsglevel, FILE *newmsgfp )
13358: {
13359: /* -------------------------------------------------------------------------
13360: set msglevel and msgfp
13361: -------------------------------------------------------------------------- */
13362: if ( newmsglevel >= 0 ) msglevel = newmsglevel;
13363: if ( newmsgfp != NULL ) msgfp = newmsgfp;
13364: return ( 1 );
13365: } /* --- end-of-function mimetexsetmsg() --- */
13366: #endif /* PART3 */
13367: 
13368: /* ---
13369:  * PART1
13370:  * ------ */
13371: #if !defined(PARTS) || defined(PART1)
13372: #ifdef DRIVER
13373: /* ==========================================================================
13374:  * Function:	main() driver for mimetex.c
13375:  * Purpose:	emits a mime xbitmap or gif image of a LaTeX math expression
13376:  *		entered either as
13377:  *		    (1)	html query string from a browser (most typical), or
13378:  *		    (2)	a query string from an html <form method="get">
13379:  *			whose <input name="formdata"> (mostly for demo), or
13380:  *		    (3)	command-line arguments (mostly to test).
13381:  *		If no input supplied, expression defaults to "f(x)=x^2",
13382:  *		treated as test (input method 3).
13383:  *		   If args entered on command-line (or if no input supplied),
13384:  *		output is (usually) human-viewable ascii raster images on
13385:  *		stdout rather than the usual mime xbitmaps or gif images.
13386:  * --------------------------------------------------------------------------
13387:  * Command-Line Arguments:
13388:  *		When running mimeTeX from the command-line, rather than
13389:  *		from a browser, syntax is
13390:  *		     ./mimetex	[-d ]		dump gif to stdout
13391:  *				[expression	expression, e.g., x^2+y^2,
13392:  *				|-f input_file]	or read expression from file
13393:  *				[-m msglevel]	verbosity of debugging output
13394:  *				[-s fontsize]	default fontsize, 0-5
13395:  *		-d   Rather than ascii debugging output, mimeTeX dumps the
13396:  *		     actual gif (or xbitmap) to stdout, e.g.,
13397:  *			./mimetex  -d  x^2+y^2  > expression.gif
13398:  *		     creates a gif file containing an image of x^2+y^2
13399:  *		-f   Reads expression from input_file, and automatically
13400:  *		     assumes -d switch.  The input_file may contain the
13401:  *		     expression on one line or spread out over many lines.
13402:  *		     MimeTeX will concatanate all lines from input_file
13403:  *		     to construct one long expression.  Blanks, tabs, and
13404:  *		     newlines will just be ignored.
13405:  *		-m   0-99, controls verbosity level for debugging output
13406:  *		     (usually used only while testing code).
13407:  *		-s   Font size, 0-5.  As usual, the font size can
13408:  *		     also be specified in the expression by a leading
13409:  *		     preamble terminated by $, e.g., 3$f(x)=x^2 displays
13410:  *		     f(x)=x^2 at font size 3.  Default font size is 2.
13411:  * --------------------------------------------------------------------------
13412:  * Exits:	0=success, 1=some error
13413:  * --------------------------------------------------------------------------
13414:  * Notes:     o For an executable that emits mime xbitmaps, compile as
13415:  *		     cc -DXBITMAP mimetex.c -lm -o mimetex.cgi
13416:  *		or, alternatively, for an executable that emits gif images
13417:  *		     cc -DGIF mimetex.c gifsave.c -lm -o mimetex.cgi
13418:  *		or for gif images with anti-aliasing
13419:  *		     cc -DGIF -DAA mimetex.c gifsave.c -lm -o mimetex.cgi
13420:  *		See Notes at top of file for other compile-line -D options.
13421:  *	      o	Move executable to your cgi-bin directory and either
13422:  *		point your browser to it directly in the form
13423:  *		     http://www.yourdomain.com/cgi-bin/mimetex.cgi?3$f(x)=x^2
13424:  *		or put a tag in your html document of the form
13425:  *		     <img src="../cgi-bin/mimetex.cgi?3$f(x)=x^2"
13426:  *		       border=0 align=absmiddle>
13427:  *		where f(x)=x^2 (or any other expression) will be displayed
13428:  *		either as a mime xbitmap or gif image (as per -D flag).
13429:  * ======================================================================= */
13430: 
13431: /* -------------------------------------------------------------------------
13432: header files and other data
13433: -------------------------------------------------------------------------- */
13434: /* --- (additional) standard headers --- */
13435: /* --- other data --- */
13436: #ifdef DUMPENVIRON
13437:  extern	char **environ;			/* environment information */
13438: #endif
13439: 
13440: /* -------------------------------------------------------------------------
13441: globals for gif and png callback functions
13442: -------------------------------------------------------------------------- */
13443: GLOBAL(raster,*bitmap_raster,NULL);	/* use 0/1 bitmap image or */
13444: GLOBAL(intbyte,*colormap_raster,NULL);	/* anti-aliased color indexes */
13445: /* --- anti-aliasing flags (needed by GetPixel() as well as main()) --- */
13446: #ifdef AA				/* if anti-aliasing requested */
13447:   #define ISAAVALUE 1			/* turn flag on */
13448: #else
13449:   #define ISAAVALUE 0			/* else turn flag off */
13450: #endif
13451: GLOBAL(int,isaa,ISAAVALUE);		/* set anti-aliasing flag */
13452: 
13453: /* -------------------------------------------------------------------------
13454: logging data structure, and default data to be logged
13455: -------------------------------------------------------------------------- */
13456: /* --- logging data structure --- */
13457: #define	logdata	struct logdata_struct	/* "typedef" for logdata_struct*/
13458: logdata
13459:   {
13460:   /* -----------------------------------------------------------------------
13461:   environment variable name, max #chars to display, min msglevel to display
13462:   ------------------------------------------------------------------------ */
13463:   char	*name;				/* environment variable name */
13464:   int	maxlen;				/* max #chars to display */
13465:   int	msglevel;			/* min msglevel to display data */
13466:   } ; /* --- end-of-logdata_struct --- */
13467: /* --- data logged by mimeTeX --- */
13468: STATIC logdata mimelog[]
13469: #ifdef INITVALS
13470:   =
13471:   {
13472:   /* ------ variable ------ maxlen msglevel ----- */
13473:     { "QUERY_STRING",         999,    4 },
13474:     { "REMOTE_ADDR",          999,    3 },
13475:     { "HTTP_REFERER",         999,    3 },
13476:     { "REQUEST_URI",          999,    5 },
13477:     { "HTTP_USER_AGENT",      999,    3 },
13478:     { "HTTP_X_FORWARDED_FOR", 999,    3 },
13479:     { NULL, -1, -1 }			/* trailer record */
13480:   } /* --- end-of-mimelog[] --- */
13481: #endif
13482:   ;
13483: 
13484: /* -------------------------------------------------------------------------
13485: messages
13486: -------------------------------------------------------------------------- */
13487: static	char *copyright =		/* copyright, gnu/gpl notice */
13488:  "+-----------------------------------------------------------------------+\n"
13489:  "|mimeTeX vers 1.70, Copyright(c) 2002-2008, John Forkosh Associates, Inc|\n"
13490:  "+-----------------------------------------------------------------------+\n"
13491:  "| mimeTeX is free software, licensed to you under terms of the GNU/GPL, |\n"
13492:  "|           and comes with absolutely no warranty whatsoever.           |\n"
13493:  "+-----------------------------------------------------------------------+";
13494: static	int maxmsgnum = 2;		/* maximum msgtable[] index */
13495: static	char *msgtable[] = {		/* messages referenced by [index] */
13496:  "\\red\\small\\rm\\fbox{\\array{"	/* [0] is invalid_referer_msg */
13497:    "Please~read~www.forkosh.com/mimetex.html\\\\and~install~mimetex.cgi~"
13498:    "on~your~own~server.\\\\Thank~you,~John~Forkosh}}",
13499:  "\\red\\small\\rm\\fbox{\\array{"	/* [1] */
13500:    "Please~provide~your~{\\tiny~HTTP-REFERER}~to~access~the~public\\\\"
13501:    "mimetex~server.~~Or~please~read~~www.forkosh.com/mimetex.html\\\\"
13502:    "and~install~mimetex.cgi~on~your~own~server.~~Thank~you,~John~Forkosh}}",
13503:  "\\red\\small\\rm\\fbox{\\array{"	/* [2] */
13504:    "The~public~mimetex~server~is~for~testing.~~For~production,\\\\"
13505:    "please~read~~www.forkosh.com/mimetex.html~~and~install\\\\"
13506:    "mimetex.cgi~on~your~own~server.~~Thank~you,~John~Forkosh}}",
13507:  NULL } ;				/* trailer */
13508: 
13509: 
13510: /* --- entry point --- */
13511: int	main ( int argc, char *argv[]
13512: 	  #ifdef DUMPENVP
13513: 	    , char *envp[]
13514: 	  #endif
13515: 	)
13516: {
13517: /* -------------------------------------------------------------------------
13518: Allocations and Declarations
13519: -------------------------------------------------------------------------- */
13520: /* --- expression to be emitted --- */
13521: static	char exprbuffer[MAXEXPRSZ+1] = "f(x)=x^2"; /* input TeX expression */
13522: char	*expression = exprbuffer;	/* ptr to expression */
13523: int	size = NORMALSIZE;		/* default font size */
13524: char	*query = getenv("QUERY_STRING"); /* getenv("QUERY_STRING") result */
13525: char	*mimeprep();			/* preprocess expression */
13526: int	unescape_url();			/* convert %xx's to ascii chars */
13527: int	emitcache();			/* emit cached image if it exists */
13528: int	isquery = 0,			/* true if input from QUERY_STRING */
13529: 	isqempty = 0,			/* true if query string empty */
13530: 	isqforce = 0,			/* true to force query emulation */
13531: 	isqlogging = 0,			/* true if logging in query mode */
13532: 	isformdata = 0,			/* true if input from html form */
13533: 	isinmemory = 1,			/* true to generate image in memory*/
13534: 	isdumpimage = 0,		/* true to dump image on stdout */
13535: 	isdumpbuffer = 0;		/* true to dump to memory buffer */
13536: /* --- rasterization --- */
13537: subraster *rasterize(), *sp=NULL;	/* rasterize expression */
13538: raster	*border_raster(), *bp=NULL;	/* put a border around raster */
13539: int	delete_subraster();		/* for clean-up at end-of-job */
13540: int	type_raster(), type_bytemap(),	/* screen dump function prototypes */
13541: 	xbitmap_raster();		/* mime xbitmap output function */
13542: /* --- http_referer --- */
13543: char	*referer = REFERER;		/* http_referer must contain this */
13544: struct	{ char *referer; int msgnum; }	/* http_referer can't contain this */
13545: 	denyreferer[] = {		/* referer table to deny access to */
13546: 	#ifdef DENYREFERER
13547: 	  #include DENYREFERER		/* e.g.,  {"",1},  for no referer */
13548: 	#endif
13549: 	{ NULL, -999 } };		/* trailer */
13550: char	*http_referer = getenv("HTTP_REFERER"); /* referer using mimeTeX */
13551: int	ishttpreferer = (http_referer==NULL?0:(*http_referer=='\000'?0:1));
13552: int	isstrstr();			/* search http_referer for referer */
13553: int	isinvalidreferer = 0;		/* true for inavlid referer */
13554: int	norefmaxlen = NOREFMAXLEN;	/*max query_string len if no referer*/
13555: /* --- gif --- */
13556: #if defined(GIF)
13557:   int	GetPixel();			/* feed pixels to gifsave library */
13558:   int	GIF_Create(),GIF_CompressImage(),GIF_Close(); /* prototypes for... */
13559:   void	GIF_SetColor(),GIF_SetTransparent(); /* ...gifsave enntry points */
13560: #endif
13561: char	*gif_outfile = (char *)NULL,	/* gif output defaults to stdout */
13562: 	gif_buffer[MAXGIFSZ] = "\000",	/* or gif written in memory buffer */
13563: 	cachefile[256] = "\000",	/* full path and name to cache file*/
13564: 	*md5str();			/* md5 has of expression */
13565: int	maxage = 7200;			/* max-age is two hours */
13566: int	valign = (-9999);		/*Vertical-Align:baseline-(height-1)*/
13567: /* --- pbm/pgm (-g switch) --- */
13568: int	ispbmpgm = 0;			/* true to write pbm/pgm file */
13569: int	type_pbmpgm(), ptype=0;		/* entry point, graphic format */
13570: char	*pbm_outfile = (char *)NULL;	/* output file defaults to stdout */
13571: /* --- anti-aliasing --- */
13572: intbyte	*bytemap_raster = NULL,		/* anti-aliased bitmap */
13573: 	colors[256];			/* grayscale vals in bytemap */
13574: int	aalowpass(), aapnm(),		/*lowpass filters for anti-aliasing*/
13575: 	grayscale = 256;		/* 0-255 grayscales in 8-bit bytes */
13576: int	ncolors=2,			/* #colors (2=b&w) */
13577: 	aacolormap();			/* build colormap from bytemap */
13578: int	ipattern;			/*patternnumcount[] index diagnostic*/
13579: /* --- messages --- */
13580: char	logfile[256] = LOGFILE,		/*log queries if msglevel>=LOGLEVEL*/
13581: 	cachelog[256] = CACHELOG;	/* cached image log in cachepath/ */
13582: char	*timestamp();			/* time stamp for logged messages */
13583: int	logger();			/* logs environ variables */
13584: int	ismonth();			/* check argv[0] for current month */
13585: char	*progname = (argc>0?argv[0]:"noname"); /* name program executed as */
13586: char	*dashes =			/* separates logfile entries */
13587:  "--------------------------------------------------------------------------";
13588: char	*invalid_referer_msg = msgtable[0]; /* msg to invalid http_referer */
13589: /* -------------------------------------------------------------------------
13590: initialization
13591: -------------------------------------------------------------------------- */
13592: /* --- run optional system command string --- */
13593: #ifdef SYSTEM
13594:   system(SYSTEM);
13595: #endif
13596: /* --- set global variables --- */
13597: msgfp = stdout;				/* for comamnd-line mode output */
13598: isss = issupersampling;			/* set supersampling flag */
13599: isemitcontenttype = 1;			/* true to emit mime content-type */
13600: iscachecontenttype = 0;			/* true to cache mime content-type */
13601: *contenttype = '\000';			/* reset content-type:, etc. cache */
13602: iscaching = ISCACHING;			/* true if caching images */
13603: if ( iscaching ) {			/* images are being cached */
13604:   strcpy(cachepath,CACHEPATH);		/* relative path to cached files */
13605:   if ( *cachepath == '%' ) {		/* leading % signals cache headers */
13606:     iscachecontenttype = 1;		/* signal caching mime content-type*/
13607:     strcpy(cachepath,cachepath+1); } }	/* and squeeze out leading % char */
13608: gifSize = 0;				/* signal that image not in memory */
13609: fgred=FGRED; fggreen=FGGREEN; fgblue=FGBLUE; /* default foreground colors */
13610: bgred=BGRED; bggreen=BGGREEN; bgblue=BGBLUE; /* default background colors */
13611: shrinkfactor = shrinkfactors[NORMALSIZE]; /* set shrinkfactor */
13612: for ( ipattern=1; ipattern<=51; ipattern++ )
13613:  patternnumcount0[ipattern] = patternnumcount1[ipattern] = 0;
13614: /* ---
13615:  * check QUERY_STRING query for expression overriding command-line arg
13616:  * ------------------------------------------------------------------- */
13617: if ( query != NULL )			/* check query string from environ */
13618:   if ( strlen(query) >= 1 )		/* caller gave us a query string */
13619:     { strncpy(expression,query,MAXEXPRSZ); /* so use it as expression */
13620:       expression[MAXEXPRSZ] = '\000';	/* make sure it's null terminated */
13621:       if ( 0 )				/*true to remove leading whitespace*/
13622:         while ( isspace(*expression) && *expression!='\000' )
13623:           strcpy(expression,expression+1); /* squeeze out white space */
13624:       isquery = 1; }			/* and set isquery flag */
13625: if ( !isquery )				/* empty query string */
13626:   { char *host = getenv("HTTP_HOST"),	/* additional getenv("") results */
13627:     *name = getenv("SERVER_NAME"), *addr = getenv("SERVER_ADDR");
13628:     if ( host!=NULL || name!=NULL || addr!=NULL ) /* assume http query */
13629:       {	isquery = 1;			/* set flag to signal query */
13630: 	strcpy(expression,"\\red\\small\\fbox{\\rm~no~query~string}"); }
13631:     isqempty = 1;			/* signal empty query string */
13632:   } /* --- end-of-if(!isquery) --- */
13633: /* ---
13634:  * process command-line input args (if not a query)
13635:  * ------------------------------------------------ */
13636: if ( !isquery				/* don't have an html query string */
13637: ||   ( /*isqempty &&*/ argc>1) )	/* or have command-line args */
13638:  {
13639:  char	*argsignal = ARGSIGNAL,		/* signals start of mimeTeX args */
13640: 	stopsignal[32] = "--";		/* default Unix end-of-args signal */
13641:  int	iarg=0, argnum=0,		/*argv[] index for command-line args*/
13642: 	exprarg = 0,			/* argv[] index for expression */
13643: 	infilearg = 0,			/* argv[] index for infile */
13644: 	nswitches = 0,			/* number of -switches */
13645: 	isstopsignal = 0,		/* true after stopsignal found */
13646: 	isstrict = 1/*iswindows*/,	/* true for strict arg checking */
13647: 					/*nb, windows has apache "x -3" bug*/
13648: 	nargs=0, nbadargs=0,		/* number of arguments, bad ones */
13649: 	maxbadargs = (isstrict?0:1),	/*assume query if too many bad args*/
13650: 	isgoodargs = 0;			/* true to accept command-line args*/
13651:  if ( argsignal != NULL )		/* if compiled with -DARGSIGNAL */
13652:   while ( argc > ++iarg )		/* check each argv[] for argsignal */
13653:     if ( !strcmp(argv[iarg],argsignal) ) /* check for exact match */
13654:      { argnum = iarg;			/* got it, start parsing next arg */
13655:        break; }				/* stop looking for argsignal */
13656:  while ( argc > ++argnum )		/* check for switches and values, */
13657:     {
13658:     nargs++;				/* count another command-line arg */
13659:     if ( strcmp(argv[argnum],stopsignal) == 0 ) /* found stopsignal */
13660:       {	isstopsignal = 1;		/* so set stopsignal flag */
13661: 	continue; }			/* and get expression after it */
13662:     if ( !isstopsignal			/* haven't seen stopsignal switch */
13663:     &&   *argv[argnum] == '-' )		/* and have some '-' switch */
13664:       {
13665:       char *field = argv[argnum] + 1;	/* ptr to char(s) following - */
13666:       char flag = tolower(*field);	/* single char following '-' */
13667:       int  arglen = strlen(field);	/* #chars following - */
13668:       argnum++;		/* arg following flag/switch is usually its value */
13669:       nswitches++;			/* another switch on command line */
13670:       if ( isstrict &&			/* if strict checking then... */
13671:       !isthischar(flag,"g") && arglen!=1 ) /*must be single-char switch*/
13672: 	{ nbadargs++; argnum--; }	/* so ignore longer -xxx switch */
13673:       else				/* process single-char -x switch */
13674:        switch ( flag ) {		/* see what user wants to tell us */
13675: 	/* --- ignore uninterpreted flag --- */
13676: 	default:  nbadargs++;                              argnum--;  break;
13677: 	/* --- adjustable program parameters (not checking input) --- */
13678: 	case 'b': isdumpimage++; isdumpbuffer++;           argnum--;  break;
13679: 	case 'd': isdumpimage++;                           argnum--;  break;
13680: 	case 'e': isdumpimage++;           gif_outfile=argv[argnum];  break;
13681: 	case 'f': isdumpimage++;                   infilearg=argnum;  break;
13682: 	case 'g': ispbmpgm++;
13683: 	     if ( arglen > 1 ) ptype = atoi(field+1);	/* -g2 ==> ptype=2 */
13684: 	     if ( 1 || *argv[argnum]=='-' ) argnum--; /*next arg is -switch*/
13685: 	     else pbm_outfile = argv[argnum]; break; /*next arg is filename*/
13686: 	case 'm': msglevel = atoi(argv[argnum]);                      break;
13687: 	case 'o': istransparent = (istransparent?0:1);     argnum--;  break;
13688: 	case 'q': isqforce = 1;                            argnum--;  break;
13689: 	case 's': size = atoi(argv[argnum]);                          break;
13690: 	} /* --- end-of-switch(flag) --- */
13691:       } /* --- end-of-if(*argv[argnum]=='-') --- */
13692:     else				/* expression if arg not a -flag */
13693:       if ( infilearg == 0 )		/* no infile arg yet */
13694: 	{ if ( exprarg != 0 ) nbadargs++; /* 2nd expression invalid */
13695: 	  exprarg = argnum;		/* but take last expression */
13696: 	  /*infilearg = (-1);*/ }	/* and set infilearg */
13697:       else nbadargs++;			/* infile and expression invalid */
13698:     } /* --- end-of-while(argc>++argnum) --- */
13699:  if ( msglevel>=999 && msgfp!=NULL )	/* display command-line info */
13700:   { fprintf(msgfp,"argc=%d, progname=%s, #args=%d, #badargs=%d\n",
13701:     argc,progname,nargs,nbadargs);
13702:     fprintf(msgfp,"cachepath=\"%.50s\" pathprefix=\"%.50s\"\n",
13703:     cachepath,pathprefix); }
13704:  /* ---
13705:   * decide whether command-line input overrides query_string
13706:   * -------------------------------------------------------- */
13707:  if ( isdumpimage > 2 ) nbadargs++;	/* duplicate/conflicting -switch */
13708:  isgoodargs =  ( !isstrict		/*good if not doing strict checking*/
13709:   || !isquery				/* or if no query, must use args */
13710:   || (nbadargs<nargs && nbadargs<=maxbadargs) ); /* bad args imply query */
13711:  /* ---
13712:   * take expression from command-line args
13713:   * -------------------------------------- */
13714:  if ( isgoodargs && exprarg > 0		/* good expression on command line */
13715:  &&   infilearg <= 0 )			/* and not given in input file */
13716:   if ( !isquery				/* no conflict if no query_string */
13717:   ||   nswitches > 0 )			/* explicit -switch(es) also given */
13718:    { strncpy(expression,argv[exprarg],MAXEXPRSZ); /*expr from command-line*/
13719:      expression[MAXEXPRSZ] = '\000';	/* make sure it's null terminated */
13720:      isquery = 0; }			/* and not from a query_string */
13721:  /* ---
13722:   * or read expression from input file
13723:   * ---------------------------------- */
13724:  if ( isgoodargs && infilearg > 0 )	/* have a good -f arg */
13725:   {
13726:   FILE *infile = fopen(argv[infilearg],"r"); /* open input file for read */
13727:   if ( infile != (FILE *)NULL )		/* opened input file successfully */
13728:    { char instring[MAXLINESZ+1];	/* line from file */
13729:      int  exprsz = 0;			/* total #bytes read from file */
13730:      isquery = 0;			/* file input, not a query_string */
13731:      *expression = '\000';		/* start expresion as empty string */
13732:      while ( fgets(instring,MAXLINESZ,infile) != (char *)NULL ) /*till eof*/
13733:       if ( exprsz + strlen(instring) < MAXEXPRSZ ) { /* have room for line */
13734: 	strcat(expression,instring);	/* concat line to end of expression*/
13735: 	exprsz += strlen(instring); }	/* update expression buffer length */
13736:      fclose ( infile ); }	/*close input file after reading expression*/
13737:   } /* --- end-of-if(infilearg>0) --- */
13738:  /* ---
13739:   * xlate +++'s to blanks only if query
13740:   * ----------------------------------- */
13741:  if ( !isquery ) isplusblank = 0;	/* don't xlate +++'s to blanks */
13742:  /* ---
13743:   * check if emulating query (for testing)
13744:   * -------------------------------------- */
13745:  if ( isqforce ) isquery = 1;		/* emulate query string processing */
13746:  /* ---
13747:   * check if emitting pbm/pgm graphic
13748:   * --------------------------------- */
13749:  if ( isgoodargs && ispbmpgm > 0 )	/* have a good -g arg */
13750:   if ( 1 && gif_outfile != NULL )	/* had an -e switch with file */
13751:    if ( *gif_outfile != '\000' )	/* make sure string isn't empty */
13752:      { pbm_outfile = gif_outfile;	/* use -e switch file for pbm/pgm */
13753:        gif_outfile = (char *)NULL;	/* reset gif output file */
13754:        /*isdumpimage--;*/ }		/* and decrement -e count */
13755:  } /* --- end-of-if(!isquery) --- */
13756: /* ---
13757:  * check for <form> input
13758:  * ---------------------- */
13759: if ( isquery ) {				/* must be <form method="get"> */
13760:  if ( !memcmp(expression,"formdata",8) ) /*must be <input name="formdata"> */
13761:   { char *delim=strchr(expression,'=');	/* find equal following formdata */
13762:     if ( delim != (char *)NULL )	/* found unescaped equal sign */
13763:       strcpy(expression,delim+1);	/* so shift name= out of expression*/
13764:     while ( (delim=strchr(expression,'+')) != NULL ) /*unescaped plus sign*/
13765:       *delim = ' ';			/* is "shorthand" for blank space */
13766:     /*unescape_url(expression,1);*/	/* convert unescaped %xx's to chars */
13767:     unescape_url(expression,0);		/* convert all %xx's to chars */
13768:     unescape_url(expression,0);		/* repeat */
13769:     if(0) msglevel = FORMLEVEL;		/* msglevel for forms */
13770:     isformdata = 1; }			/* set flag to signal form data */
13771:  else /* --- query, but not <form> input --- */
13772:     unescape_url(expression,0); }	/* convert _all_ %xx's to chars */
13773: /* ---
13774:  * check queries for embedded prefixes signalling special processing
13775:  * ----------------------------------------------------------------- */
13776: if ( isquery )				/* only check queries */
13777:  {
13778:  /* --- check for msglevel=###$ prefix --- */
13779:  if ( !memcmp(expression,"msglevel=",9) ) /* query has msglevel prefix */
13780:    { char *delim=strchr(expression,'$'); /* find $ delim following msglevel*/
13781:      if ( delim != (char *)NULL )	/* check that we found delim */
13782:       {	*delim = '\000';		/* replace delim with null */
13783: 	if ( seclevel <= 9 )		/* permit msglevel specification */
13784: 	  msglevel = atoi(expression+9); /* interpret ### in msglevel###$ */
13785: 	strcpy(expression,delim+1); } }	/* shift out prefix and delim */
13786:  /* --- next check for logfile=xxx$ prefix (must follow msglevel) --- */
13787:  if ( !memcmp(expression,"logfile=",8) ) /* query has logfile= prefix */
13788:    { char *delim=strchr(expression,'$'); /* find $ delim following logfile=*/
13789:      if ( delim != (char *)NULL )	/* check that we found delim */
13790:       {	*delim = '\000';		/* replace delim with null */
13791: 	if ( seclevel <= 3 )		/* permit logfile specification */
13792: 	  strcpy(logfile,expression+8);	/* interpret xxx in logfile=xxx$ */
13793: 	strcpy(expression,delim+1); } }	/* shift out prefix and delim */
13794:  } /* --- end-of-if(isquery) --- */
13795: /* ---
13796:  * log query (e.g., for debugging)
13797:  * ------------------------------- */
13798: if ( isquery )				/* only log query_string's */
13799:  if ( msglevel >= LOGLEVEL		/* check if logging */
13800:  &&   seclevel <= 5 )			/* and if logging permitted */
13801:   if ( logfile != NULL )		/* if a logfile is given */
13802:    if ( *logfile != '\000' ) {		/*and if it's not an empty string*/
13803:     if ( (msgfp=fopen(logfile,"a"))	/* open logfile for append */
13804:     !=   NULL )				/* ignore logging if can't open */
13805:      {
13806:      /* --- default logging --- */
13807:      logger(msgfp,msglevel,expression,mimelog); /* log query */
13808:      /* --- additional debug logging (argv and environment) --- */
13809:      if ( msglevel >= 9 )		/* log environment */
13810:       { int i;  /*char name[999],*value;*/
13811: 	fprintf(msgfp,"Command-line arguments...\n");
13812: 	if ( argc < 1 )			/* no command-line args */
13813: 	 fprintf(msgfp,"  ...argc=%d, no argv[] variables\n",argc);
13814: 	else
13815: 	 for ( i=0; i<argc; i++ )	/* display all argv[]'s */
13816: 	  fprintf(msgfp,"  argv[%d] = \"%s\"\n",i,argv[i]);
13817: 	#ifdef DUMPENVP			/* char *envp[] available for dump */
13818: 	fprintf(msgfp,"Environment variables (using envp[])...\n");
13819: 	if ( envp == (char **)NULL )	/* envp not provided */
13820: 	 fprintf(msgfp,"  ...envp[] environment variables not available\n");
13821: 	else
13822: 	 for ( i=0; ; i++ )		/* display all envp[]'s */
13823: 	  if ( envp[i] == (char *)NULL ) break;
13824: 	  else fprintf(msgfp,"  envp[%d] = \"%s\"\n",i,envp[i]);
13825: 	#endif /* --- DUMPENVP ---*/
13826: 	#ifdef DUMPENVIRON	/* skip what should be redundant output */
13827: 	fprintf(msgfp,"Environment variables (using environ)...\n");
13828: 	if ( environ == (char **)NULL )	/* environ not provided */
13829: 	 fprintf(msgfp,"  ...extern environ variables not available\n");
13830: 	else
13831: 	 for ( i=0; ; i++ )		/*display environ[] and getenv()'s*/
13832: 	  if ( environ[i] == (char *)NULL ) break;
13833: 	  else {
13834: 	    strcpy(name,environ[i]);	/* set up name for getenv() arg */
13835: 	    if ( (value=strchr(name,'=')) != NULL ) /* = delimits name */
13836: 	      {	*value = '\000';	/* got it, so null-terminate name */
13837: 		value = getenv(name); }	/* and look up name using getenv() */
13838: 	    else strcpy(name,"NULL");	/* missing = delim in environ[i] */
13839: 	    fprintf(msgfp,"environ[%d]: \"%s\"\n\tgetenv(%s) = \"%s\"\n",
13840: 	    i,environ[i],name,(value==NULL?"NULL":value));
13841: 	    } /* --- end-of-if/else --- */
13842: 	#endif /* --- DUMPENVIRON ---*/
13843:       } /* --- end-of-if(msglevel>=9) --- */
13844:      /* --- close log file if no longer needed --- */
13845:      if ( msglevel < DBGLEVEL )		/* logging, but not debugging */
13846:       {	fprintf(msgfp,"%s\n",dashes);	/* so log separator line, */
13847: 	fclose(msgfp);			/* close logfile immediately, */
13848: 	msgfp = NULL; }			/* and reset msgfp pointer */
13849:      else
13850: 	isqlogging = 1;			/* set query logging flag */
13851:      } /* --- end-of-if(msglevel>=LOGLEVEL) --- */
13852:     else				/* couldn't open logfile */
13853:      msglevel = 0; }			/* can't emit messages */
13854: /* ---
13855:  * prepend prefix to submitted expression
13856:  * -------------------------------------- */
13857: if ( 1 || isquery )			/* queries or command-line */
13858:  if ( *exprprefix != '\000' )		/* we have a prefix string */
13859:   { int npref = strlen(exprprefix);	/* #chars in prefix */
13860:     memmove(expression+npref+1,expression,strlen(expression)+1); /*make room*/
13861:     memcpy(expression,exprprefix,npref); /* copy prefix into expression */
13862:     expression[npref] = '{';		/* followed by { */
13863:     strcat(expression,"}"); }		/* and terminating } to balance { */
13864: /* ---
13865:  * check if http_referer is allowed to use this image
13866:  * -------------------------------------------------- */
13867: if ( isquery )				/* not relevant if "interactive" */
13868:  if ( referer != NULL )			/* nor if compiled w/o -DREFERER= */
13869:   if ( strcmp(referer,"month") != 0 )	/* nor if it's *only* "month" */
13870:    if ( http_referer != NULL )		/* nor if called "standalone" */
13871:     if ( !isstrstr(http_referer,referer,0) ) /* invalid http_referer */
13872:      { expression = invalid_referer_msg; /* so give user error message */
13873:        isinvalidreferer = 1; }		/* and signal invalid referer */
13874: /* ---
13875:  * check if referer contains "month" signal
13876:  * ---------------------------------------- */
13877: if ( isquery )				/* not relevant if "interactive" */
13878:  if ( referer != NULL )			/* nor if compiled w/o -DREFERER= */
13879:   if ( !isinvalidreferer )		/* nor if already invalid referer */
13880:    if ( strstr(referer,"month") != NULL ) /* month check requested */
13881:     if ( !ismonth(progname) )		/* not executed as mimetexJan-Dec */
13882:      { expression = invalid_referer_msg; /* so give user error message */
13883:        isinvalidreferer = 1; }		/* and signal invalid referer */
13884: /* ---
13885:  * check if http_referer is to be denied access
13886:  * -------------------------------------------- */
13887: if ( isquery )				/* not relevant if "interactive" */
13888:  if ( !isinvalidreferer )		/* nor if already invalid referer */
13889:   { int	iref=0, msgnum=(-999);		/* denyreferer index, message# */
13890:     for ( iref=0; msgnum<0; iref++ ) {	/* run through denyreferer[] table */
13891:       char *deny = denyreferer[iref].referer; /* referer to be denied */
13892:       if ( deny == NULL ) break;	/* null signals end-of-table */
13893:       if ( msglevel>=999 && msgfp!=NULL ) /* debugging */
13894: 	{fprintf(msgfp,"main> invalid iref=%d: deny=%s http_referer=%s\n",
13895: 	 iref,deny,(http_referer==NULL?"null":http_referer)); fflush(msgfp);}
13896:       if ( *deny == '\000' )		/* signal to check for no referer */
13897: 	{ if ( http_referer == NULL )	/* http_referer not supplied */
13898: 	   msgnum = denyreferer[iref].msgnum; } /* so set message# */
13899:       else				/* have referer to check for */
13900:        if ( http_referer != NULL )	/* and have referer to be checked */
13901: 	if ( isstrstr(http_referer,deny,0) ) /* invalid http_referer */
13902: 	 msgnum = denyreferer[iref].msgnum; /* so set message# */
13903:       } /* --- end-of-for(iref) --- */
13904:     if ( msgnum >= 0 )			/* deny access to this referer */
13905:      { if ( msgnum > maxmsgnum ) msgnum = 0; /* keep index within bounds */
13906:        expression = msgtable[msgnum];	/* set user error message */
13907:        isinvalidreferer = 1; }		/* and signal invalid referer */
13908:   } /* --- end-of-if(!isinvalidreferer) --- */
13909: /* --- also check maximum query_string length if no http_referer given --- */
13910: if ( isquery )				/* not relevant if "interactive" */
13911:  if ( !isinvalidreferer )		/* nor if already invalid referer */
13912:   if ( !ishttpreferer )			/* no http_referer supplied */
13913:    if ( strlen(expression) > norefmaxlen ) /* query_string too long */
13914:     { expression = invalid_referer_msg;	/* set invalid http_referer message*/
13915:       isinvalidreferer = 1; }		/* and signal invalid referer */
13916: /* ---
13917:  * check for image caching
13918:  * ----------------------- */
13919: if ( strstr(expression,"\\counter")  != NULL /* can't cache \counter{} */
13920: ||   strstr(expression,"\\input")    != NULL /* can't cache \input{} */
13921: ||   strstr(expression,"\\today")    != NULL /* can't cache \today */
13922: ||   strstr(expression,"\\calendar") != NULL /* can't cache \calendar */
13923: ||   strstr(expression,"\\nocach")   != NULL /* no caching requested */
13924: ||   isformdata				/* don't cache user form input */
13925:  ) { iscaching = 0;			/* so turn caching off */
13926:      maxage = 5; }			/* and set max-age to 5 seconds */
13927: if ( isquery )				/* don't cache command-line images */
13928:  if ( iscaching )			/* image caching enabled */
13929:   {
13930:   /* --- set up path to cached image file --- */
13931:   char *md5hash = md5str(expression);	/* md5 hash of expression */
13932:   if ( md5hash == NULL )		/* failed for some reason */
13933:     iscaching = 0;			/* so turn off caching */
13934:   else
13935:    {
13936:    strcpy(cachefile,cachepath);		/* start with (relative) path */
13937:    strcat(cachefile,md5hash);		/* add md5 hash of expression */
13938:    strcat(cachefile,".gif");		/* finish with .gif extension */
13939:    gif_outfile = cachefile;		/* signal GIF_Create() to cache */
13940:    /* --- emit mime content-type line --- */
13941:    if ( 0 && isemitcontenttype )	/* now done in emitcache() */
13942:     { fprintf( stdout, "Cache-Control: max-age=%d\n",maxage );
13943:       if ( abs(valign) < 999 )		/* have vertical align */
13944:         fprintf( stdout, "Vertical-Align: %d\n",valign );
13945:       fprintf( stdout, "Content-type: image/gif\n\n" ); }
13946:    /* --- emit cached image if it already exists --- */
13947:    if ( emitcache(cachefile,maxage,valign,0) > 0 ) /* cached image emitted */
13948:     goto end_of_job;			/* so nothing else to do */
13949:    /* --- log caching request --- */
13950:    if ( msglevel >= 1			/* check if logging */
13951:    /*&&   seclevel <= 5*/ )		/* and if logging permitted */
13952:     if ( cachelog != NULL )		/* if a logfile is given */
13953:      if ( *cachelog != '\000' )		/*and if it's not an empty string*/
13954:       { char filename[256];		/* construct cachepath/cachelog */
13955:         FILE *filefp=NULL;		/* fopen(filename) */
13956:         strcpy(filename,cachepath);	/* start with (relative) path */
13957:         strcat(filename,cachelog);	/* add cache log filename */
13958:         if ( (filefp=fopen(filename,"a")) /* open cache logfile for append */
13959:         !=   NULL )			/* ignore logging if can't open */
13960: 	 { int isreflogged = 0;		/* set true if http_referer logged */
13961: 	   fprintf(filefp,"%s                 %s\n", /* timestamp, md5 file */
13962: 	    timestamp(TZDELTA,0),cachefile+strlen(cachepath)); /*skip path*/
13963: 	   fprintf(filefp,"%s\n",expression); /* expression in filename */
13964: 	   if ( http_referer != NULL )	/* show referer if we have one */
13965: 	    if ( *http_referer != '\000' )    /* and if not an empty string*/
13966: 	      {	int loglen = strlen(dashes);  /* #chars on line in log file*/
13967: 		char *refp = http_referer;    /* line to be printed */
13968: 		isreflogged = 1;	      /* signal http_referer logged*/
13969: 		while ( 1 ) {		      /* printed in parts if needed*/
13970: 		  fprintf(filefp,"%.*s\n",loglen,refp); /* print a part */
13971: 		  if ( strlen(refp) <= loglen ) break;  /* no more parts */
13972: 		  refp += loglen; } }	      /* bump ptr to next part */
13973: 	   if ( !isreflogged )		      /* http_referer not logged */
13974: 	     fprintf(filefp,"http://none\n"); /* so log dummy referer line */
13975: 	   fprintf(filefp,"%s\n",dashes);     /* separator line */
13976: 	   fclose(filefp); }		     /* close logfile immediately */
13977:       } /* --- end-of-if(cachelog!=NULL) --- */
13978:    } /* --- end-of-if/else(md5hash==NULL) --- */
13979:   } /* --- end-of-if(iscaching) --- */
13980: /* ---
13981:  * emit copyright, gnu/gpl notice (if "interactive")
13982:  * ------------------------------------------------- */
13983: if ( !isdumpimage )			/* don't mix ascii with image dump */
13984:  if ( (!isquery||isqlogging) && msgfp!=NULL ) /* called from command line */
13985:    fprintf(msgfp,"%s\n",copyright);	/* display copyright, gnu/gpl info */
13986: /* -------------------------------------------------------------------------
13987: rasterize expression and put a border around it
13988: -------------------------------------------------------------------------- */
13989: /* --- preprocess expression, converting LaTeX constructs for mimeTeX  --- */
13990: if ( expression != NULL ) {		/* have expression to rasterize */
13991:   expression = mimeprep(expression); }	/* preprocess expression */
13992: /* --- double-check that we actually have an expression to rasterize --- */
13993: if ( expression == NULL )		/* nothing to rasterize */
13994:  { if ( (!isquery||isqlogging) && msgfp!=NULL ) /*emit error if not a query*/
13995:      fprintf(msgfp,"No expression to rasterize\n");
13996:    goto end_of_job; }			/* and then quit */
13997: /* --- rasterize expression --- */
13998: if ( (sp = rasterize(expression,size)) == NULL ) /* failed to rasterize */
13999:  { if ( (!isquery||isqlogging) && msgfp!=NULL ) /*emit error if not a query*/
14000:      fprintf(msgfp,"Failed to rasterize %s\n",expression);
14001:    if ( isquery ) sp = rasterize(	/* or emit error raster if query */
14002:      "\\red\\rm~\\fbox{mimeTeX~failed~to~render\\\\your~expression}",1);
14003:    if ( sp ==  NULL ) goto end_of_job; } /* re-check for failure */
14004: /* ---no border requested, but this adjusts width to multiple of 8 bits--- */
14005: if ( issupersampling )			/* no border needed for gifs */
14006:   bp = sp->image;			/* so just extract pixel map */
14007: else					/* for mime xbitmaps must have... */
14008:   bp = border_raster(sp->image,0,0,0,1); /* image width multiple of 8 bits */
14009: sp->image = bitmap_raster = bp;		/* global copy for gif,png output */
14010: if ( sp!=NULL && bp!=NULL ) {		/* have raster */
14011:   valign = sp->baseline - (bp->height - 1); /* #pixels for Vertical-Align: */
14012:   if ( abs(valign) > 255 ) valign = (-9999); } /* sanity check */
14013: if ( ispbmpgm && ptype<2 )		/* -g switch or -g1 switch */
14014:   type_pbmpgm(bp,ptype,pbm_outfile);	/* emit b/w pbm file */
14015: /* -------------------------------------------------------------------------
14016: generate anti-aliased bytemap from (bordered) bitmap
14017: -------------------------------------------------------------------------- */
14018: if ( isaa )				/* we want anti-aliased bitmap */
14019:   {
14020:   /* ---
14021:    * allocate bytemap and colormap as per width*height of bitmap
14022:    * ----------------------------------------------------------- */
14023:   int	nbytes = (bp->width)*(bp->height); /*#bytes needed in byte,colormap*/
14024:   if ( isss )				/* anti-aliasing by supersampling */
14025:     bytemap_raster = (intbyte *)(bitmap_raster->pixmap); /*bytemap in raster*/
14026:   else					/* need to allocate bytemap */
14027:     if ( aaalgorithm == 0 )		/* anti-aliasing not wanted */
14028:       isaa = 0;				/* so signal no anti-aliasing */
14029:     else				/* anti-aliasing wanted */
14030:       if ( (bytemap_raster = (intbyte *)malloc(nbytes)) /* malloc bytemap */
14031:       ==   NULL ) isaa = 0;		/* reset flag if malloc failed */
14032:   if ( isaa )				/* have bytemap, so... */
14033:     if ( (colormap_raster = (intbyte *)malloc(nbytes)) /* malloc colormap */
14034:     ==   NULL ) isaa = 0;		/* reset flag if malloc failed */
14035:   /* ---
14036:    * now generate anti-aliased bytemap and colormap from bitmap
14037:    * ---------------------------------------------------------- */
14038:   if ( isaa )				/*re-check that we're anti-aliasing*/
14039:     {
14040:     /* ---
14041:      * select anti-aliasing algorithm
14042:      * ------------------------------ */
14043:     if ( !isss )			/* generate bytemap for lowpass */
14044:      switch ( aaalgorithm ) {		/* choose antialiasing algorithm */
14045:        default: isaa = 0; break;	/* unrecognized algorithm */
14046:        case 1:				/* 1 for aalowpass() */
14047: 	if ( aalowpass(bp,bytemap_raster,grayscale) /*my own lowpass filter*/
14048: 	==   0 )  isaa = 0;		/*failed, so turn off anti-aliasing*/
14049: 	break;
14050:        case 2:				/*2 for netpbm pnmalias.c algorithm*/
14051: 	if ( aapnm(bp,bytemap_raster,grayscale) /* pnmalias.c filter */
14052: 	==   0 )  isaa = 0;		/*failed, so turn off anti-aliasing*/
14053: 	break;
14054:        case 3:				/*3 for aapnm() based on aagridnum()*/
14055: 	if ( aapnmlookup(bp,bytemap_raster,grayscale) /* pnmalias.c filter */
14056: 	==   0 )  isaa = 0;		/*failed, so turn off anti-aliasing*/
14057: 	break;
14058:        case 4:				/* 4 for aalookup() table lookup */
14059: 	if ( aalowpasslookup(bp,bytemap_raster,grayscale) /* aalookup() */
14060: 	==   0 )  isaa = 0;		/*failed, so turn off anti-aliasing*/
14061: 	break;
14062:        } /* --- end-of-switch(aaalgorithm) --- */
14063:     /* ---
14064:      * emit aalookup() pattern# counts/percents diagnostics
14065:      * ---------------------------------------------------- */
14066:     if ( !isquery && msgfp!=NULL && msglevel>=99 ) { /*emit patternnumcounts*/
14067:      int pcount0=0, pcount1=0;		/* init total w,b center counts */
14068:      for ( ipattern=1; ipattern<=51; ipattern++ ) { /*each possible pattern*/
14069:       if ( ipattern > 1 )		/* ignore all-white squares */
14070:        pcount0 += patternnumcount0[ipattern];  /* bump total white centers */
14071:       pcount1 += patternnumcount1[ipattern]; } /* bump total black centers */
14072:      if ( pcount0+pcount1 > 0 )		/* have pcounts (using aalookup) */
14073:       fprintf(msgfp, "  aalookup() patterns excluding#1 white"
14074:       " (%%'s are in tenths of a percent)...\n");
14075:      for ( ipattern=1; ipattern<=51; ipattern++ ) { /*each possible pattern*/
14076:       int tot = patternnumcount0[ipattern] + patternnumcount1[ipattern];
14077:       if ( tot > 0 )			/* this pattern occurs in image */
14078:        fprintf(msgfp,
14079:        "  pattern#%2d: %7d(%6.2f%%) +%7d(%6.2f%%) =%7d(%6.2f%%)\n",
14080:        ipattern, patternnumcount0[ipattern],  (ipattern<=1? 999.99:
14081:        1000.*((double)patternnumcount0[ipattern])/((double)pcount0)),
14082:        patternnumcount1[ipattern],
14083:        1000.*((double)patternnumcount1[ipattern])/((double)pcount1),
14084:        tot,  (ipattern<=1? 999.99:
14085:        1000.*((double)tot)/((double)(pcount0+pcount1))) ); }
14086:       if ( pcount0+pcount1 > 0 )	/* true when using aalookup() */
14087:        fprintf(msgfp,
14088:        "all patterns: %7d          +%7d          =%7d  total pixels\n",
14089:        pcount0,pcount1,pcount0+pcount1); }
14090:     /* ---
14091:      * finally, generate colors and colormap
14092:      * ------------------------------------- */
14093:     if ( isaa ) {			/* we have bytemap_raster */
14094:       ncolors = aacolormap(bytemap_raster,nbytes,colors,colormap_raster);
14095:       if ( ncolors < 2 )		/* failed */
14096: 	{ isaa = 0;			/* so turn off anti-aliasing */
14097: 	  ncolors = 2; }		/* and reset for black&white */
14098:       } /* --- end-of-if(isaa) --- */
14099:      if ( isaa && ispbmpgm && ptype>1 ) { /* -g2 switch  */
14100:       raster pbm_raster;		/*construct arg for write_pbmpgm()*/
14101:       pbm_raster.width  = bp->width;  pbm_raster.height = bp->height;
14102:       pbm_raster.pixsz  = 8;  pbm_raster.pixmap = (pixbyte *)bytemap_raster;
14103:       type_pbmpgm(&pbm_raster,ptype,pbm_outfile); } /*write grayscale file*/
14104:     } /* --- end-of-if(isaa) --- */
14105:   } /* --- end-of-if(isaa) --- */
14106: /* -------------------------------------------------------------------------
14107: display results on msgfp if called from command line (usually for testing)
14108: -------------------------------------------------------------------------- */
14109: if ( (!isquery||isqlogging) || msglevel >= 99 )	/*command line or debuging*/
14110:  if ( !isdumpimage )			/* don't mix ascii with image dump */
14111:   {
14112:   /* ---
14113:    * display ascii image of rasterize()'s rasterized bitmap
14114:    * ------------------------------------------------------ */
14115:   if ( !isss )				/* no bitmap for supersampling */
14116:     { fprintf(msgfp,"\nAscii dump of bitmap image...\n");
14117:       type_raster(bp,msgfp); }		/* emit ascii image of raster */
14118:   /* ---
14119:    * display anti-aliasing results applied to rasterized bitmap
14120:    * ---------------------------------------------------------- */
14121:   if ( isaa )				/* if anti-aliasing applied */
14122:     {
14123:     int	igray;				/* colors[] index */
14124:     /* --- anti-aliased bytemap image --- */
14125:     if ( msgfp!=NULL && msglevel>=9 )	/* don't usually emit raw bytemap */
14126:       {	fprintf(msgfp,"\nHex dump of anti-aliased bytemap, " /*emit bytemap*/
14127: 	"asterisks denote \"black\" bytes (value=%d)...\n",grayscale-1);
14128: 	type_bytemap(bytemap_raster,grayscale,bp->width,bp->height,msgfp); }
14129:     /* --- colormap image --- */
14130:     fprintf(msgfp,"\nHex dump of colormap indexes, "  /* emit colormap */
14131:       "asterisks denote \"black\" bytes (index=%d)...\n",ncolors-1);
14132:     type_bytemap(colormap_raster,ncolors,bp->width,bp->height,msgfp);
14133:     /* --- rgb values corresponding to colormap indexes */
14134:     fprintf(msgfp,"\nThe %d colormap indexes denote rgb values...",ncolors);
14135:     for ( igray=0; igray<ncolors; igray++ ) /* show colors[] values */
14136:       fprintf(msgfp,"%s%2x-->%3d", (igray%5?"   ":"\n"),
14137: 	igray,(int)(colors[ncolors-1]-colors[igray]));
14138:     fprintf(msgfp,"\n");		/* always needs a final newline */
14139:     } /* --- end-of-if(isaa) --- */
14140:   } /* --- end-of-if(!isquery||msglevel>=9) --- */
14141: /* -------------------------------------------------------------------------
14142: emit xbitmap or gif image, and exit
14143: -------------------------------------------------------------------------- */
14144: if (  isquery				/* called from browser (usual) */
14145: ||    (isdumpimage && !ispbmpgm)	/* or to emit gif dump of image */
14146: ||    msglevel >= 99 )			/* or for debugging */
14147:  {
14148:  int  igray = 0;			/* grayscale index */
14149:  #if defined(GIF)			/* compiled to emit gif */
14150:  /* ------------------------------------------------------------------------
14151:  emit GIF image
14152:  ------------------------------------------------------------------------- */
14153:   /* --- don't use memory buffer if outout file given --- */
14154:   if ( gif_outfile != NULL ) isinmemory = 0; /* reset memory buffer flag */
14155:   /* --- construct contenttype[] buffer containing mime headers --- */
14156:   if ( 1 ) {				/* always construct buffer */
14157:     sprintf( contenttype, "Cache-Control: max-age=%d\n", maxage );
14158:     /*sprintf(contenttype+strlen(contenttype),
14159:        "Expires: Fri, 31 Oct 2003 23:59:59 GMT\n" );*/
14160:     /*sprintf(contenttype+strlen(contenttype),
14161:        "Last-Modified: Wed, 15 Oct 2003 01:01:01 GMT\n");*/
14162:     if ( abs(valign) < 999 )		/* have Vertical-Align: header info*/
14163:       sprintf( contenttype+strlen(contenttype),
14164:        "Vertical-Align: %d\n", valign );
14165:     sprintf( contenttype+strlen(contenttype),
14166:       "Content-type: image/gif\n\n" ); }
14167:   /* --- emit mime content-type line --- */
14168:   if ( isemitcontenttype		/* content-type lines wanted */
14169:   &&   !isdumpimage			/* don't mix ascii with image dump */
14170:   &&   !isinmemory			/* done below if in memory */
14171:   &&   !iscaching )			/* done by emitcache() if caching */
14172:     { fputs(contenttype,stdout); }	/* emit content-type: header buffer*/
14173:   /* --- write output to memory buffer, possibly for testing --- */
14174:   if ( isinmemory			/* want gif written to memory */
14175:   ||   isdumpbuffer )			/*or dump memory buffer for testing*/
14176:    if ( gif_outfile == NULL )		/* and don't already have a file */
14177:     { *gif_buffer = '\000';		/* init buffer as empty string */
14178:       memset(gif_buffer,0,MAXGIFSZ);	/* zero out buffer */
14179:       gif_outfile = gif_buffer;		/* and point outfile to buffer */
14180:       if ( isdumpbuffer )		/* buffer dump test requested */
14181: 	isdumpbuffer = 999; }		/* so signal dumping to buffer */
14182:   /* --- initialize gifsave library and colors --- */
14183:   if ( msgfp!=NULL && msglevel>=999 )
14184:     { fprintf(msgfp,"main> calling GIF_Create(*,%d,%d,%d,8)\n",
14185:       bp->width,bp->height,ncolors); fflush(msgfp); }
14186:   while ( 1 )		/* init gifsave lib, and retry if caching fails */
14187:     { int status = GIF_Create(gif_outfile, bp->width,bp->height, ncolors, 8);
14188:       if ( status == 0 ) break;		/* continue if succeeded */
14189:       if ( iscaching == 0 ) goto end_of_job; /* quit if failed */
14190:       iscaching = 0;			/* retry without cache file */
14191:       isdumpbuffer = 0;			/* reset isdumpbuffer signal */
14192:       if ( isquery ) isinmemory = 1;	/* force in-memory image generation*/
14193:       if ( isinmemory ) {		/* using memory buffer */
14194: 	gif_outfile = gif_buffer;	/* emit images to memory buffer */
14195: 	*gif_outfile = '\000'; }	/* empty string signals buffer */
14196:       else {				/* or */
14197: 	gif_outfile = (char *)NULL;	/* emit images to stdout */
14198: 	if ( isemitcontenttype ) {	/* content-type lines wanted */
14199: 	  fprintf( stdout, "Cache-Control: max-age=%d\n",maxage );
14200: 	  fprintf( stdout, "Content-type: image/gif\n\n" ); } }
14201:     } /* --- end-of-while(1) --- */
14202:   GIF_SetColor(0,bgred,bggreen,bgblue);	/* background white if all 255 */
14203:   if ( !isaa )				/* just b&w if not anti-aliased */
14204:     { GIF_SetColor(1,fgred,fggreen,fgblue); /* foreground black if all 0 */
14205:       colors[0]='\000'; colors[1]='\001'; } /* and set 2 b&w color indexes */
14206:   else					/* set grayscales for anti-aliasing */
14207:     /* --- anti-aliased, so call GIF_SetColor() for each colors[] --- */
14208:     for ( igray=1; igray<ncolors; igray++ ) /* for colors[] values */
14209:       {
14210:       /*--- gfrac goes from 0 to 1.0, as igray goes from 0 to ncolors-1 ---*/
14211:       double gfrac = ((double)colors[igray])/((double)colors[ncolors-1]);
14212:       /* --- r,g,b components go from background to foreground color --- */
14213:       int red  = iround(((double)bgred)  +gfrac*((double)(fgred-bgred))),
14214: 	  green= iround(((double)bggreen)+gfrac*((double)(fggreen-bggreen))),
14215: 	  blue = iround(((double)bgblue) +gfrac*((double)(fgblue-bgblue)));
14216:       /* --- set color index number igray to rgb values gray,gray,gray --- */
14217:       GIF_SetColor(igray, red,green,blue); /*set gray,grayer,...,0=black*/
14218:       } /* --- end-of-for(igray) --- */
14219:   /* --- set gif color#0 (background) transparent --- */
14220:   if ( istransparent )			/* transparent background wanted */
14221:     GIF_SetTransparent(0);		/* set transparent background */
14222:   if (msgfp!=NULL && msglevel>=9) fflush(msgfp); /*flush debugging output*/
14223:   /* --- emit compressed gif image (to stdout or cache file) --- */
14224:   GIF_CompressImage(0, 0, -1, -1, GetPixel); /* emit gif */
14225:   GIF_Close();				/* close file */
14226:   if ( msgfp!=NULL && msglevel>=9 )
14227:     { fprintf(msgfp,"main> created gifSize=%d\n", gifSize);
14228:       fflush(msgfp); }
14229:   /* --- may need to emit image from cached file or from memory --- */
14230:   if ( isquery				/* have an actual query string */
14231:   ||   isdumpimage			/* or dumping image */
14232:   ||   msglevel >= 99 ) {		/* or debugging */
14233:   int maxage2 = (isdumpimage?(-1):maxage); /* no headers if dumping image */
14234:    if ( iscaching )			/* caching enabled */
14235:      emitcache(cachefile,maxage2,valign,0); /*emit cached image (hopefully)*/
14236:    else if ( isinmemory )		/* or emit image from memory buffer*/
14237:      emitcache(gif_buffer,maxage2,valign,1); } /*emitted from memory buffer*/
14238:   /* --- for testing, may need to write image buffer to file --- */
14239:   if ( isdumpbuffer > 99 )		/* gif image in memory buffer */
14240:    if ( gifSize > 0 )			/* and it's not an empty buffer */
14241:     { FILE *dumpfp = fopen("mimetex.gif","wb"); /* dump to mimetex.gif */
14242:       if ( dumpfp != NULL )		/* file opened successfully */
14243: 	{ fwrite(gif_buffer,sizeof(unsigned char),gifSize,dumpfp); /*write*/
14244: 	  fclose(dumpfp); }		/* and close file */
14245:     } /* --- end-of-if(isdumpbuffer>99) --- */
14246:  #else
14247:  /* ------------------------------------------------------------------------
14248:  emit mime XBITMAP image
14249:  ------------------------------------------------------------------------- */
14250:   xbitmap_raster(bp,stdout);		/* default emits mime xbitmap */
14251:  #endif
14252:  } /* --- end-of-if(isquery) --- */
14253: /* --- exit --- */
14254: end_of_job:
14255:   if ( !isss )				/*bytemap raster in sp for supersamp*/
14256:    if ( bytemap_raster != NULL ) free(bytemap_raster);/*free bytemap_raster*/
14257:   if (colormap_raster != NULL )free(colormap_raster); /*and colormap_raster*/
14258:   if ( 0 && gif_buffer != NULL ) free(gif_buffer); /* free malloced buffer */
14259:   if ( 1 && sp != NULL ) delete_subraster(sp);	/* and free expression */
14260:   if ( msgfp != NULL			/* have message/log file open */
14261:   &&   msgfp != stdout )		/* and it's not stdout */
14262:    { fprintf(msgfp,"mimeTeX> successful end-of-job at %s\n",
14263:        timestamp(TZDELTA,0));
14264:      fprintf(msgfp,"%s\n",dashes);	/* so log separator line */
14265:      fclose(msgfp); }			/* and close logfile */
14266:   /* --- dump memory leaks in debug window if in MS VC++ debug mode --- */
14267:   #if defined(_CRTDBG_MAP_ALLOC)
14268:     _CrtDumpMemoryLeaks();
14269:   #endif
14270:   /* --- exit() if not running as Windows DLL (see CreateGifFromEq()) --- */
14271:   #if !defined(_USRDLL)
14272:     exit ( 0 );
14273:   #endif
14274: } /* --- end-of-function main() --- */
14275: 
14276: /* ==========================================================================
14277:  * Function:	CreateGifFromEq ( expression, gifFileName )
14278:  * Purpose:	shortcut method to create GIF file for expression,
14279:  *		with antialising and all other capabilities
14280:  * --------------------------------------------------------------------------
14281:  * Arguments:	expression (I)	char *ptr to null-terminated string
14282:  *				containing LaTeX expression to be rendred
14283:  *		gifFileName (I)	char *ptr to null-terminated string
14284:  *				containing name of output gif file
14285:  * --------------------------------------------------------------------------
14286:  * Returns:	( int )		exit value from main (0 if successful)
14287:  * --------------------------------------------------------------------------
14288:  * Notes:     o	This function is the entry point when mimeTeX is built
14289:  *		as a Win32 DLL rather then a standalone app or CGI
14290:  *	      o	Contributed to mimeTeX by Shital Shah.  See his homepage
14291:  *		  http://www.shitalshah.com
14292:  *	      o	Shital discusses the mimeTeX Win32 DLL project at
14293:  *		  http://www.codeproject.com/dotnet/Eq2Img.asp
14294:  *		and you can download his latest code from
14295:  *		  http://www.shitalshah.com/dev/eq2img_all.zip
14296:  * ======================================================================= */
14297: /* --- include function to expose Win32 DLL to outside world --- */
14298: #if defined(_USRDLL)
14299:   extern _declspec(dllexport)int _cdecl
14300: 	CreateGifFromEq ( char *expression, char *gifFileName );
14301: #endif
14302: /* --- entry point --- */
14303: int	CreateGifFromEq ( char *expression, char *gifFileName )
14304: {
14305: /* -------------------------------------------------------------------------
14306: Allocations and Declarations
14307: -------------------------------------------------------------------------- */
14308: int	main();			/* main() akways returns an int */
14309: /* --- set constants --- */
14310: int	argc = 4;		/* count of args supplied to main() */
14311: char	*argv[5] =		/* command line args to run with -e option */
14312: 	  { "MimeTeXWin32DLL", "-e", /* constant args */
14313: 	    /*gifFileName, expression,*/ NULL, NULL, NULL };
14314: /* --- set argv[]'s not computable at load time --- */
14315: argv[2] = gifFileName;		/* args are -e gifFileName */
14316: argv[3] = expression;		/* and now  -e gifFileName expression */
14317: /* -------------------------------------------------------------------------
14318: Run mimeTeX in command-line mode with -e (export) option, and then return
14319: -------------------------------------------------------------------------- */
14320: return	main ( argc, argv
14321: 	  #ifdef DUMPENVP
14322: 	    , NULL
14323: 	  #endif
14324: 	) ;
14325: } /* --- end-of-function CreateGifFromEq() --- */
14326: 
14327: /* ==========================================================================
14328:  * Function:	isstrstr ( char *string, char *snippets, int iscase )
14329:  * Purpose:	determine whether any substring of 'string'
14330:  *		matches any of the comma-separated list of 'snippets',
14331:  *		ignoring case if iscase=0.
14332:  * --------------------------------------------------------------------------
14333:  * Arguments:	string (I)	char * containing null-terminated
14334:  *				string that will be searched for
14335:  *				any one of the specified snippets
14336:  *		snippets (I)	char * containing null-terminated,
14337:  *				comma-separated list of snippets
14338:  *				to be searched for in string
14339:  *		iscase (I)	int containing 0 for case-insensitive
14340:  *				comparisons, or 1 for case-sensitive
14341:  * --------------------------------------------------------------------------
14342:  * Returns:	( int )		1 if any snippet is a substring of
14343:  *				string, 0 if not
14344:  * --------------------------------------------------------------------------
14345:  * Notes:     o
14346:  * ======================================================================= */
14347: /* --- entry point --- */
14348: int	isstrstr ( char *string, char *snippets, int iscase )
14349: {
14350: /* -------------------------------------------------------------------------
14351: Allocations and Declarations
14352: -------------------------------------------------------------------------- */
14353: int	status = 0;			/*1 if any snippet found in string*/
14354: char	snip[99], *snipptr = snippets,	/* munge through each snippet */
14355: 	delim = ',', *delimptr = NULL;	/* separated by delim's */
14356: char	stringcp[999], *cp = stringcp;	/*maybe lowercased copy of string*/
14357: /* -------------------------------------------------------------------------
14358: initialization
14359: -------------------------------------------------------------------------- */
14360: /* --- arg check --- */
14361: if ( string==NULL || snippets==NULL ) goto end_of_job; /* missing arg */
14362: if ( *string=='\000' || *snippets=='\000' ) goto end_of_job; /* empty arg */
14363: /* --- copy string and lowercase it if case-insensitive --- */
14364: strcpy(stringcp,string);		/* local copy of string */
14365: if ( !iscase )				/* want case-insensitive compares */
14366:   for ( cp=stringcp; *cp != '\000'; cp++ ) /* so for each string char */
14367:     if ( isupper(*cp) ) *cp = tolower(*cp); /*lowercase any uppercase chars*/
14368: /* -------------------------------------------------------------------------
14369: extract each snippet and see if it's a substring of string
14370: -------------------------------------------------------------------------- */
14371: while ( snipptr != NULL )		/* while we still have snippets */
14372:   {
14373:   /* --- extract next snippet --- */
14374:   if ( (delimptr = strchr(snipptr,delim)) /* locate next comma delim */
14375:   ==   NULL )				/*not found following last snippet*/
14376:     { strcpy(snip,snipptr);		/* local copy of last snippet */
14377:       snipptr = NULL; }			/* signal end-of-string */
14378:   else					/* snippet ends just before delim */
14379:     { int sniplen = (int)(delimptr-snipptr) - 1;  /* #chars in snippet */
14380:       memcpy(snip,snipptr,sniplen);	/* local copy of snippet chars */
14381:       snip[sniplen] = '\000';		/* null-terminated snippet */
14382:       snipptr = delimptr + 1; }		/* next snippet starts after delim */
14383:   /* --- lowercase snippet if case-insensitive --- */
14384:   if ( !iscase )			/* want case-insensitive compares */
14385:     for ( cp=snip; *cp != '\000'; cp++ ) /* so for each snippet char */
14386:       if ( isupper(*cp) ) *cp=tolower(*cp); /*lowercase any uppercase chars*/
14387:   /* --- check if snippet in string --- */
14388:   if ( strstr(stringcp,snip) != NULL )	/* found snippet in string */
14389:     { status = 1;			/* so reset return status */
14390:       break; }				/* no need to check any further */
14391:   } /* --- end-of-while(*snipptr!=0) --- */
14392: end_of_job: return ( status );		/*1 if snippet found in list, else 0*/
14393: } /* --- end-of-function isstrstr() --- */
14394: 
14395: /* ==========================================================================
14396:  * Function:	ismonth ( char *month )
14397:  * Purpose:	returns 1 if month contains current month "jan"..."dec".
14398:  * --------------------------------------------------------------------------
14399:  * Arguments:	month (I)	char * containing null-terminated string
14400:  *				in which "jan"..."dec" is (putatively)
14401:  *				contained as a substring.
14402:  * --------------------------------------------------------------------------
14403:  * Returns:	( int )		1 if month contains current month,
14404:  *				0 otherwise
14405:  * --------------------------------------------------------------------------
14406:  * Notes:     o	There's a three day "grace period", e.g., Dec 3 mtaches Nov.
14407:  * ======================================================================= */
14408: /* --- entry point --- */
14409: int	ismonth ( char *month )
14410: {
14411: /* -------------------------------------------------------------------------
14412: Allocations and Declarations
14413: -------------------------------------------------------------------------- */
14414: int	isokay = 0;			/*1 if month contains current month*/
14415: /*long	time_val = 0L;*/		/* binary value returned by time() */
14416: time_t	time_val = (time_t)(0);		/* binary value returned by time() */
14417: struct tm *tmstruct=(struct tm *)NULL, *localtime(); /* interpret time_val */
14418: int	imonth, mday;			/* current month 1-12 and day 1-31 */
14419: int	ngrace = 3;			/* grace period */
14420: char	lcmonth[128]="\000"; int i=0;	/* lowercase month */
14421: static	char *months[] =		/* month must contain current one */
14422:    {"dec","jan","feb","mar","apr","may","jun",
14423:     "jul","aug","sep","oct","nov","dec","jan"};
14424: /* -------------------------------------------------------------------------
14425: get current date:time info, and check month
14426: -------------------------------------------------------------------------- */
14427: /* --- lowercase input month --- */
14428: if ( month != NULL )			/* check that we got input */
14429:   for ( i=0; i<120 && *month!='\000'; i++,month++ ) /* go thru month chars */
14430:     lcmonth[i] = tolower(*month);	/* lowerase each char in month */
14431: if ( i < 2 ) goto end_of_job;		/* must be invalid input */
14432: lcmonth[i] = '\000';			/* null-terminate lcmonth[] */
14433: /* --- get current date:time --- */
14434: time((time_t *)(&time_val));		/* get date and time */
14435: tmstruct = localtime((time_t *)(&time_val)); /* interpret time_val */
14436: /* --- month and day  --- */
14437: imonth = 1 + (int)(tmstruct->tm_mon);	/* 1=jan ... 12=dec */
14438: mday = (int)(tmstruct->tm_mday);	/* 1-31 */
14439: if ( imonth<1 || imonth>12		/* quit if month out-of-range */
14440: ||   mday<0 || mday>31 ) goto end_of_job; /* or date out of range */
14441: /* --- check input month against current date --- */
14442: if ( strstr(lcmonth,months[imonth]) != NULL ) isokay = 1; /* current month */
14443: if ( mday <= ngrace )			/* 1-3 within grace period */
14444:  if ( strstr(lcmonth,months[imonth-1]) != NULL ) isokay = 1; /* last month */
14445: if ( mday >= 31-ngrace )		/* 28-31 within grace period */
14446:  if ( strstr(lcmonth,months[imonth+1]) != NULL ) isokay = 1; /* next month */
14447: end_of_job:
14448:   return ( isokay );			/*1 if month contains current month*/
14449: } /* --- end-of-function ismonth() --- */
14450: 
14451: /* ==========================================================================
14452:  * Functions:	int  unescape_url ( char *url, int isescape )
14453:  *		char x2c ( char *what )
14454:  * Purpose:	unescape_url replaces 3-character sequences %xx in url
14455:  *		    with the single character represented by hex xx.
14456:  *		x2c returns the single character represented by hex xx
14457:  *		    passed as a 2-character sequence in what.
14458:  * --------------------------------------------------------------------------
14459:  * Arguments:	url (I)		char * containing null-terminated
14460:  *				string with embedded %xx sequences
14461:  *				to be converted.
14462:  *		isescape (I)	int containing 1 to _not_ unescape
14463:  *				\% sequences (0 would be NCSA default)
14464:  *		what (I)	char * whose first 2 characters are
14465:  *				interpreted as ascii representations
14466:  *				of hex digits.
14467:  * --------------------------------------------------------------------------
14468:  * Returns:	( int )		unescape_url always returns 0.
14469:  *		( char )	x2c returns the single char
14470:  *				corresponding to hex xx passed in what.
14471:  * --------------------------------------------------------------------------
14472:  * Notes:     o	These two functions were taken verbatim from util.c in
14473:  *   ftp://ftp.ncsa.uiuc.edu/Web/httpd/Unix/ncsa_httpd/cgi/ncsa-default.tar.Z
14474:  *	      o	Not quite "verbatim" -- I added the "isescape logic" 4-Dec-03
14475:  *		so unescape_url() can be safely applied to input which may or
14476:  *		may not have been url-encoded.  (Note: currently, all calls
14477:  *		to unescape_url() pass iescape=0, so it's not used.)
14478:  *	      o	Added +++'s to blank xlation on 24-Sep-06
14479:  *	      o	Added ^M,^F,etc to blank xlation 0n 01-Oct-06
14480:  * ======================================================================= */
14481: /* --- entry point --- */
14482: int unescape_url(char *url, int isescape) {
14483:     int x=0,y=0,prevescape=0,gotescape=0;
14484:     int xlateplus = (isplusblank==1?1:0); /* true to xlate plus to blank */
14485:     int strreplace();			/* replace + with blank, if needed */
14486:     char x2c();
14487:     static char *hex="0123456789ABCDEFabcdef";
14488:     /* ---
14489:      * xlate ctrl chars to blanks
14490:      * -------------------------- */
14491:     if ( 1 ) {				/* xlate ctrl chars to blanks */
14492:       char *ctrlchars = "\n\t\v\b\r\f\a\015";
14493:       int  seglen = strspn(url,ctrlchars); /*initial segment with ctrlchars*/
14494:       int  urllen = strlen(url);	/* total length of url string */
14495:       /* --- first, entirely remove ctrlchars from beginning and end --- */
14496:       if ( seglen > 0 ) {		/*have ctrlchars at start of string*/
14497: 	strcpy(url,url+seglen);		/* squeeze out initial ctrlchars */
14498: 	urllen -= seglen; }		/* string is now shorter */
14499:       while ( --urllen >= 0 )		/* now remove ctrlchars from end */
14500: 	if ( isthischar(url[urllen],ctrlchars) ) /* ctrlchar at end */
14501: 	  url[urllen] = '\000';		/* re-terminate string before it */
14502: 	else break;			/* or we're done */
14503:       urllen++;				/* length of url string */
14504:       /* --- now, replace interior ctrlchars with ~ blanks --- */
14505:       while ( (seglen=strcspn(url,ctrlchars)) < urllen ) /*found a ctrlchar*/
14506: 	url[seglen] = '~';		/* replace ctrlchar with ~ */
14507:       } /* --- end-of-if(1) --- */
14508:     /* ---
14509:      * xlate +'s to blanks if requested or if deemed necessary
14510:      * ------------------------------------------------------- */
14511:     if ( isplusblank == (-1) ) {	/*determine whether or not to xlate*/
14512:       char *searchfor[] = { " ","%20", "%2B","%2b", "+++","++",
14513: 	"+=+","+-+", NULL };
14514:       int  isearch = 0,			/* searchfor[] index */
14515: 	   nfound[11] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; /*#occurrences*/
14516:       /* --- locate occurrences of searchfor[] strings in url --- */
14517:       for ( isearch=0; searchfor[isearch] != NULL; isearch++ ) {
14518: 	char *psearch = url;		/* start search at beginning */
14519: 	nfound[isearch] = 0;		/* init #occurrences count */
14520: 	while ( (psearch=strstr(psearch,searchfor[isearch])) != NULL ) {
14521: 	  nfound[isearch] += 1;		/* count another occurrence */
14522: 	  psearch += strlen(searchfor[isearch]); } /*resume search after it*/
14523: 	} /* --- end-of-for(isearch) --- */
14524:       /* --- apply some common-sense logic --- */
14525:       if ( nfound[0] + nfound[1] > 0 )	/* we have actual " "s or "%20"s */
14526: 	isplusblank = xlateplus = 0;	/* so +++'s aren't blanks */
14527:       if ( nfound[2] + nfound[3] > 0 ) { /* we have "%2B" for +++'s */
14528:         if ( isplusblank != 0 )		/* and haven't disabled xlation */
14529: 	  isplusblank = xlateplus = 1;	/* so +++'s are blanks */
14530: 	else				/* we have _both_ "%20" and "%2b" */
14531: 	  xlateplus = 0; }		/* tough call */
14532:       if ( nfound[4] + nfound[5] > 0	/* we have multiple ++'s */
14533:       ||   nfound[6] + nfound[7] > 0 )	/* or we have a +=+ or +-+ */
14534: 	if ( isplusblank != 0 )		/* and haven't disabled xlation */
14535: 	  xlateplus = 1;		/* so xlate +++'s to blanks */
14536:       } /* --- end-of-if(isplusblank==-1) --- */
14537:     if ( xlateplus > 0 ) {		/* want +'s xlated to blanks */
14538:       char *xlateto[] = { ""," "," "," + "," "," "," "," "," " };
14539:       while ( xlateplus > 0 ) {		/* still have +++'s to xlate */
14540: 	char plusses[99] = "++++++++++++++++++++"; /* longest +++ string */
14541: 	plusses[xlateplus] = '\000';	/* null-terminate +++'s */
14542: 	strreplace(url,plusses,xlateto[xlateplus],0); /* xlate +++'s */
14543: 	xlateplus--;			/* next shorter +++ string */
14544: 	} /* --- end-of-while(xlateplus>0) --- */
14545:       } /* --- end-of-if(xlateplus) --- */
14546:     isplusblank = 0;			/* don't iterate this xlation */
14547:     /* ---
14548:      * xlate %nn to corresponding char
14549:      * ------------------------------- */
14550:     for(;url[y];++x,++y) {
14551: 	gotescape = prevescape;
14552: 	prevescape = (url[x]=='\\');
14553: 	if((url[x] = url[y]) == '%')
14554: 	 if(!isescape || !gotescape)
14555: 	  if(isthischar(url[y+1],hex)
14556: 	  && isthischar(url[y+2],hex))
14557: 	    { url[x] = x2c(&url[y+1]);
14558: 	      y+=2; }
14559:     }
14560:     url[x] = '\0';
14561:     return 0;
14562: } /* --- end-of-function unescape_url() --- */
14563: /* --- entry point --- */
14564: char x2c(char *what) {
14565:     char digit;
14566:     digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A')+10 : (what[0] - '0'));
14567:     digit *= 16;
14568:     digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A')+10 : (what[1] - '0'));
14569:     return(digit);
14570: } /* --- end-of-function x2c() --- */
14571: 
14572: /* ==========================================================================
14573:  * Function:	logger ( fp, msglevel, message, logvars )
14574:  * Purpose:	Logs the environment variables specified in logvars
14575:  *		to fp if their msglevel is >= the passed msglevel.
14576:  * --------------------------------------------------------------------------
14577:  * Arguments:	fp (I)		FILE * to file containing log
14578:  *		msglevel (I)	int containing logging message level
14579:  *		message (I)	char * to optional message, or NULL
14580:  *		logvars (I)	logdata * to array of environment variables
14581:  *				to be logged
14582:  * --------------------------------------------------------------------------
14583:  * Returns:	( int )		number of variables from logvars
14584:  *				that were actually logged
14585:  * --------------------------------------------------------------------------
14586:  * Notes:     o
14587:  * ======================================================================= */
14588: /* --- entry point --- */
14589: int	logger ( FILE *fp, int msglevel, char *message, logdata *logvars )
14590: {
14591: /* -------------------------------------------------------------------------
14592: Allocations and Declarations
14593: -------------------------------------------------------------------------- */
14594: int	ilog=0, nlogged=0;		/* logvars[] index, #vars logged */
14595: char	*timestamp();			/* timestamp logged */
14596: char	*value = NULL;			/* getenv(name) to be logged */
14597: /* -------------------------------------------------------------------------
14598: Log each variable
14599: -------------------------------------------------------------------------- */
14600: fprintf(fp,"%s\n",timestamp(TZDELTA,0)); /*emit timestamp before first var*/
14601: if ( message != NULL )			/* optional message supplied */
14602:  fprintf(fp,"  MESSAGE = %s\n",message); /* emit caller-supplied message */
14603: if ( logvars != (logdata *)NULL )	/* have logvars */
14604:  for ( ilog=0; logvars[ilog].name != NULL; ilog++ )  /* till end-of-table */
14605:   if ( msglevel >= logvars[ilog].msglevel ) /* check msglevel for this var */
14606:    if ( (value=getenv(logvars[ilog].name))  /* getenv(name) to be logged */
14607:    != NULL )				/* check that name exists */
14608:     {
14609:     fprintf(fp,"  %s = %.*s\n",		/* emit variable name = value */
14610:      logvars[ilog].name,logvars[ilog].maxlen,value);
14611:     nlogged++;				/* bump #vars logged */
14612:     } /* --- end-of-for(ilog) --- */
14613: return ( nlogged );			/* back to caller */
14614: } /* --- end-of-function logger() --- */
14615: 
14616: /* ==========================================================================
14617:  * Function:	emitcache ( cachefile, maxage, valign, isbuffer )
14618:  * Purpose:	dumps bytes from cachefile to stdout
14619:  * --------------------------------------------------------------------------
14620:  * Arguments:	cachefile (I)	pointer to null-terminated char string
14621:  *				containing full path to file to be dumped,
14622:  *				or contains buffer of bytes to be dumped
14623:  *		maxage (I)	int containing maxage, in seconds, for
14624:  *				http header, or -1 to not emit headers
14625:  *		valign (I)	int containing Vertical-Align:, in pixels,
14626:  *				for http header, or <= -999 to not emit
14627:  *		isbuffer (I)	1 if cachefile is buffer of bytes to be
14628:  *				dumped
14629:  * --------------------------------------------------------------------------
14630:  * Returns:	( int )		#bytes dumped (0 signals error)
14631:  * --------------------------------------------------------------------------
14632:  * Notes:     o
14633:  * ======================================================================= */
14634: /* --- entry point --- */
14635: int	emitcache ( char *cachefile, int maxage, int valign, int isbuffer )
14636: {
14637: /* -------------------------------------------------------------------------
14638: Allocations and Declarations
14639: -------------------------------------------------------------------------- */
14640: int	nbytes=gifSize, readcachefile(); /* read cache file */
14641: FILE	*emitptr = stdout;		/* emit cachefile to stdout */
14642: unsigned char buffer[MAXGIFSZ+1];	/* bytes from cachefile */
14643: unsigned char *buffptr = buffer;	/* ptr to buffer */
14644: int	isvalign = (abs(valign)<999?1:0); /* true to emit Vertical-Align: */
14645: int	iscontenttypecached = iscachecontenttype; /*true if headers cached*/
14646: /* -------------------------------------------------------------------------
14647: initialization
14648: -------------------------------------------------------------------------- */
14649: /* --- check that files opened okay --- */
14650: if ( emitptr == (FILE *)NULL )		/* failed to open emit file */
14651:   goto end_of_job;			/* so return 0 bytes to caller */
14652: /* --- read the file if necessary --- */
14653: if ( isbuffer ) {			/* cachefile is buffer */
14654:   buffptr = (unsigned char *)cachefile;	/* so reset buffer pointer */
14655:   iscontenttypecached = 0; }		/* and iscontenttypecached flag */
14656: else {					/* cachefile is file name */
14657:   if ( (nbytes = readcachefile(cachefile,buffer)) /* read the file */
14658:   < 1 ) goto end_of_job; }		/* quit if file not read */
14659: /* --- first emit http headers if requested --- */
14660: if ( isemitcontenttype			/* content-type lines enabled */
14661: &&   !iscontenttypecached		/* and not in cached image */
14662: &&   maxage >= 0 )			/* caller wants http headers */
14663:  { /* --- emit mime content-type line --- */
14664:    fprintf( emitptr, "Cache-Control: max-age=%d\n",maxage );
14665:    fprintf( emitptr, "Content-Length: %d\n",nbytes );
14666:    if ( isvalign )			/* Vertical-Align: header wanted */
14667:      fprintf( emitptr, "Vertical-Align: %d\n",valign );
14668:    fprintf( emitptr, "Content-type: image/gif\n\n" ); }
14669: /* -------------------------------------------------------------------------
14670: set stdout to binary mode (for Windows)
14671: -------------------------------------------------------------------------- */
14672: /* emitptr = fdopen(STDOUT_FILENO,"wb"); */  /* doesn't work portably, */
14673: #ifdef WINDOWS				/* so instead... */
14674:   #ifdef HAVE_SETMODE			/* prefer (non-portable) setmode() */
14675:     if ( setmode ( fileno (stdout), O_BINARY) /* windows specific call */
14676:     == -1 ) ; /* handle error */	/* sets stdout to binary mode */
14677:   #else					/* setmode() not available */
14678:     #if 1
14679:       freopen ("CON", "wb", stdout);	/* freopen() stdout binary */
14680:     #else
14681:       stdout = fdopen (STDOUT_FILENO, "wb"); /* fdopen() stdout binary */
14682:     #endif
14683:   #endif
14684: #endif
14685: /* -------------------------------------------------------------------------
14686: emit bytes from cachefile
14687: -------------------------------------------------------------------------- */
14688: /* --- write bytes to stdout --- */
14689: if ( fwrite(buffptr,sizeof(unsigned char),nbytes,emitptr) /* write buffer */
14690: <    nbytes )				/* failed to write all bytes */
14691:   nbytes = 0;				/* reset total count to 0 */
14692: end_of_job:
14693:   return ( nbytes );			/* back with #bytes emitted */
14694: } /* --- end-of-function emitcache() --- */
14695: 
14696: /* ==========================================================================
14697:  * Function:	readcachefile ( cachefile, buffer )
14698:  * Purpose:	read cachefile into buffer
14699:  * --------------------------------------------------------------------------
14700:  * Arguments:	cachefile (I)	pointer to null-terminated char string
14701:  *				containing full path to file to be read
14702:  *		buffer (O)	pointer to unsigned char string
14703:  *				returning contents of cachefile
14704:  *				(max 64000 bytes)
14705:  * --------------------------------------------------------------------------
14706:  * Returns:	( int )		#bytes read (0 signals error)
14707:  * --------------------------------------------------------------------------
14708:  * Notes:     o
14709:  * ======================================================================= */
14710: /* --- entry point --- */
14711: int	readcachefile ( char *cachefile, unsigned char *buffer )
14712: {
14713: /* -------------------------------------------------------------------------
14714: Allocations and Declarations
14715: -------------------------------------------------------------------------- */
14716: FILE	*cacheptr = fopen(cachefile,"rb"); /*open cachefile for binary read*/
14717: unsigned char cachebuff[64];		/* bytes from cachefile */
14718: int	buflen = 32,			/* #bytes we try to read from file */
14719: 	nread = 0,			/* #bytes actually read from file */
14720: 	maxbytes = MAXGIFSZ,		/* max #bytes returned in buffer */
14721: 	nbytes = 0;			/* total #bytes read */
14722: /* -------------------------------------------------------------------------
14723: initialization
14724: -------------------------------------------------------------------------- */
14725: /* --- check that files opened okay --- */
14726: if ( cacheptr == (FILE *)NULL ) goto end_of_job; /*failed to open cachefile*/
14727: /* --- check that output buffer provided --- */
14728: if ( buffer == (unsigned char *)NULL ) goto end_of_job; /* no buffer */
14729: /* -------------------------------------------------------------------------
14730: read bytes from cachefile
14731: -------------------------------------------------------------------------- */
14732: while ( 1 )
14733:   {
14734:   /* --- read bytes from cachefile --- */
14735:   nread = fread(cachebuff,sizeof(unsigned char),buflen,cacheptr); /* read */
14736:   if ( nbytes + nread > maxbytes )	/* block too big for buffer */
14737:     nread = maxbytes - nbytes;		/* so truncate it */
14738:   if ( nread < 1 ) break;		/* no bytes left in cachefile */
14739:   /* --- store bytes in buffer --- */
14740:   memcpy(buffer+nbytes,cachebuff,nread); /* copy current block to buffer */
14741:   /* --- ready to read next block --- */
14742:   nbytes += nread;			/* bump total #bytes emitted */
14743:   if ( nread < buflen ) break;		/* no bytes left in cachefile */
14744:   if ( nbytes >= maxbytes ) break;	/* avoid buffer overflow */
14745:   } /* --- end-of-while(1) --- */
14746: end_of_job:
14747:   if ( cacheptr != NULL ) fclose(cacheptr); /* close file if opened */
14748:   return ( nbytes );			/* back with #bytes emitted */
14749: } /* --- end-of-function readcachefile() --- */
14750: 
14751: /* ==========================================================================
14752:  * Function:	md5str ( instr )
14753:  * Purpose:	returns null-terminated character string containing
14754:  *		md5 hash of instr (input string)
14755:  * --------------------------------------------------------------------------
14756:  * Arguments:	instr (I)	pointer to null-terminated char string
14757:  *				containing input string whose md5 hash
14758:  *				is desired
14759:  * --------------------------------------------------------------------------
14760:  * Returns:	( char * )	ptr to null-terminated 32-character
14761:  *				md5 hash of instr
14762:  * --------------------------------------------------------------------------
14763:  * Notes:     o	Other md5 library functions are included below.
14764:  *		They're all taken from Christophe Devine's code,
14765:  *		which (as of 04-Aug-2004) is available from
14766:  *		     http://www.cr0.net:8040/code/crypto/md5/
14767:  *	      o	The P,F,S macros in the original code are replaced
14768:  *		by four functions P1()...P4() to accommodate a problem
14769:  *		with Compaq's vax/vms C compiler.
14770:  * ======================================================================= */
14771: /* --- #include "md5.h" --- */
14772: #ifndef uint8
14773:   #define uint8  unsigned char
14774: #endif
14775: #ifndef uint32
14776:   #define uint32 unsigned long int
14777: #endif
14778: typedef struct
14779:   { uint32 total[2];
14780:     uint32 state[4];
14781:     uint8 buffer[64];
14782:   } md5_context;
14783: void md5_starts( md5_context *ctx );
14784: void md5_update( md5_context *ctx, uint8 *input, uint32 length );
14785: void md5_finish( md5_context *ctx, uint8 digest[16] );
14786: /* --- md5.h --- */
14787: #define GET_UINT32(n,b,i)                       \
14788:   { (n) = ( (uint32) (b)[(i)    ]       )       \
14789:         | ( (uint32) (b)[(i) + 1] <<  8 )       \
14790:         | ( (uint32) (b)[(i) + 2] << 16 )       \
14791:         | ( (uint32) (b)[(i) + 3] << 24 ); }
14792: #define PUT_UINT32(n,b,i)                       \
14793:   { (b)[(i)    ] = (uint8) ( (n)       );       \
14794:     (b)[(i) + 1] = (uint8) ( (n) >>  8 );       \
14795:     (b)[(i) + 2] = (uint8) ( (n) >> 16 );       \
14796:     (b)[(i) + 3] = (uint8) ( (n) >> 24 ); }
14797: /* --- P,S,F macros defined as functions --- */
14798: void P1(uint32 *X,uint32 *a,uint32 b,uint32 c,uint32 d,int k,int s,uint32 t)
14799:   { *a += (uint32)(d ^ (b & (c ^ d))) + X[k] + t;
14800:     *a  = ((*a<<s) | ((*a & 0xFFFFFFFF) >> (32-s))) + b;
14801:     return; }
14802: void P2(uint32 *X,uint32 *a,uint32 b,uint32 c,uint32 d,int k,int s,uint32 t)
14803:   { *a += (uint32)(c ^ (d & (b ^ c))) + X[k] + t;
14804:     *a  = ((*a<<s) | ((*a & 0xFFFFFFFF) >> (32-s))) + b;
14805:     return; }
14806: void P3(uint32 *X,uint32 *a,uint32 b,uint32 c,uint32 d,int k,int s,uint32 t)
14807:   { *a += (uint32)(b ^ c ^ d) + X[k] + t;
14808:     *a  = ((*a<<s) | ((*a & 0xFFFFFFFF) >> (32-s))) + b;
14809:     return; }
14810: void P4(uint32 *X,uint32 *a,uint32 b,uint32 c,uint32 d,int k,int s,uint32 t)
14811:   { *a += (uint32)(c ^ (b | ~d)) + X[k] + t;
14812:     *a  = ((*a<<s) | ((*a & 0xFFFFFFFF) >> (32-s))) + b;
14813:     return; }
14814: 
14815: /* --- entry point (this one little stub written by me)--- */
14816: char *md5str( char *instr )
14817:   { static char outstr[64];
14818:     unsigned char md5sum[16];
14819:     md5_context ctx;
14820:     int j;
14821:     md5_starts( &ctx );
14822:     md5_update( &ctx, (uint8 *)instr, strlen(instr) );
14823:     md5_finish( &ctx, md5sum );
14824:     for( j=0; j<16; j++ )
14825:       sprintf( outstr + j*2, "%02x", md5sum[j] );
14826:     outstr[32] = '\000';
14827:     return ( outstr ); }
14828: 
14829: /* --- entry point (all md5 functions below by Christophe Devine) --- */
14830: void md5_starts( md5_context *ctx )
14831:   { ctx->total[0] = 0;
14832:     ctx->total[1] = 0;
14833:     ctx->state[0] = 0x67452301;
14834:     ctx->state[1] = 0xEFCDAB89;
14835:     ctx->state[2] = 0x98BADCFE;
14836:     ctx->state[3] = 0x10325476; }
14837: 
14838: void md5_process( md5_context *ctx, uint8 data[64] )
14839:   { uint32 X[16], A, B, C, D;
14840:     GET_UINT32( X[0],  data,  0 );
14841:     GET_UINT32( X[1],  data,  4 );
14842:     GET_UINT32( X[2],  data,  8 );
14843:     GET_UINT32( X[3],  data, 12 );
14844:     GET_UINT32( X[4],  data, 16 );
14845:     GET_UINT32( X[5],  data, 20 );
14846:     GET_UINT32( X[6],  data, 24 );
14847:     GET_UINT32( X[7],  data, 28 );
14848:     GET_UINT32( X[8],  data, 32 );
14849:     GET_UINT32( X[9],  data, 36 );
14850:     GET_UINT32( X[10], data, 40 );
14851:     GET_UINT32( X[11], data, 44 );
14852:     GET_UINT32( X[12], data, 48 );
14853:     GET_UINT32( X[13], data, 52 );
14854:     GET_UINT32( X[14], data, 56 );
14855:     GET_UINT32( X[15], data, 60 );
14856:     A = ctx->state[0];
14857:     B = ctx->state[1];
14858:     C = ctx->state[2];
14859:     D = ctx->state[3];
14860:     P1( X, &A, B, C, D,  0,  7, 0xD76AA478 );
14861:     P1( X, &D, A, B, C,  1, 12, 0xE8C7B756 );
14862:     P1( X, &C, D, A, B,  2, 17, 0x242070DB );
14863:     P1( X, &B, C, D, A,  3, 22, 0xC1BDCEEE );
14864:     P1( X, &A, B, C, D,  4,  7, 0xF57C0FAF );
14865:     P1( X, &D, A, B, C,  5, 12, 0x4787C62A );
14866:     P1( X, &C, D, A, B,  6, 17, 0xA8304613 );
14867:     P1( X, &B, C, D, A,  7, 22, 0xFD469501 );
14868:     P1( X, &A, B, C, D,  8,  7, 0x698098D8 );
14869:     P1( X, &D, A, B, C,  9, 12, 0x8B44F7AF );
14870:     P1( X, &C, D, A, B, 10, 17, 0xFFFF5BB1 );
14871:     P1( X, &B, C, D, A, 11, 22, 0x895CD7BE );
14872:     P1( X, &A, B, C, D, 12,  7, 0x6B901122 );
14873:     P1( X, &D, A, B, C, 13, 12, 0xFD987193 );
14874:     P1( X, &C, D, A, B, 14, 17, 0xA679438E );
14875:     P1( X, &B, C, D, A, 15, 22, 0x49B40821 );
14876:     P2( X, &A, B, C, D,  1,  5, 0xF61E2562 );
14877:     P2( X, &D, A, B, C,  6,  9, 0xC040B340 );
14878:     P2( X, &C, D, A, B, 11, 14, 0x265E5A51 );
14879:     P2( X, &B, C, D, A,  0, 20, 0xE9B6C7AA );
14880:     P2( X, &A, B, C, D,  5,  5, 0xD62F105D );
14881:     P2( X, &D, A, B, C, 10,  9, 0x02441453 );
14882:     P2( X, &C, D, A, B, 15, 14, 0xD8A1E681 );
14883:     P2( X, &B, C, D, A,  4, 20, 0xE7D3FBC8 );
14884:     P2( X, &A, B, C, D,  9,  5, 0x21E1CDE6 );
14885:     P2( X, &D, A, B, C, 14,  9, 0xC33707D6 );
14886:     P2( X, &C, D, A, B,  3, 14, 0xF4D50D87 );
14887:     P2( X, &B, C, D, A,  8, 20, 0x455A14ED );
14888:     P2( X, &A, B, C, D, 13,  5, 0xA9E3E905 );
14889:     P2( X, &D, A, B, C,  2,  9, 0xFCEFA3F8 );
14890:     P2( X, &C, D, A, B,  7, 14, 0x676F02D9 );
14891:     P2( X, &B, C, D, A, 12, 20, 0x8D2A4C8A );
14892:     P3( X, &A, B, C, D,  5,  4, 0xFFFA3942 );
14893:     P3( X, &D, A, B, C,  8, 11, 0x8771F681 );
14894:     P3( X, &C, D, A, B, 11, 16, 0x6D9D6122 );
14895:     P3( X, &B, C, D, A, 14, 23, 0xFDE5380C );
14896:     P3( X, &A, B, C, D,  1,  4, 0xA4BEEA44 );
14897:     P3( X, &D, A, B, C,  4, 11, 0x4BDECFA9 );
14898:     P3( X, &C, D, A, B,  7, 16, 0xF6BB4B60 );
14899:     P3( X, &B, C, D, A, 10, 23, 0xBEBFBC70 );
14900:     P3( X, &A, B, C, D, 13,  4, 0x289B7EC6 );
14901:     P3( X, &D, A, B, C,  0, 11, 0xEAA127FA );
14902:     P3( X, &C, D, A, B,  3, 16, 0xD4EF3085 );
14903:     P3( X, &B, C, D, A,  6, 23, 0x04881D05 );
14904:     P3( X, &A, B, C, D,  9,  4, 0xD9D4D039 );
14905:     P3( X, &D, A, B, C, 12, 11, 0xE6DB99E5 );
14906:     P3( X, &C, D, A, B, 15, 16, 0x1FA27CF8 );
14907:     P3( X, &B, C, D, A,  2, 23, 0xC4AC5665 );
14908:     P4( X, &A, B, C, D,  0,  6, 0xF4292244 );
14909:     P4( X, &D, A, B, C,  7, 10, 0x432AFF97 );
14910:     P4( X, &C, D, A, B, 14, 15, 0xAB9423A7 );
14911:     P4( X, &B, C, D, A,  5, 21, 0xFC93A039 );
14912:     P4( X, &A, B, C, D, 12,  6, 0x655B59C3 );
14913:     P4( X, &D, A, B, C,  3, 10, 0x8F0CCC92 );
14914:     P4( X, &C, D, A, B, 10, 15, 0xFFEFF47D );
14915:     P4( X, &B, C, D, A,  1, 21, 0x85845DD1 );
14916:     P4( X, &A, B, C, D,  8,  6, 0x6FA87E4F );
14917:     P4( X, &D, A, B, C, 15, 10, 0xFE2CE6E0 );
14918:     P4( X, &C, D, A, B,  6, 15, 0xA3014314 );
14919:     P4( X, &B, C, D, A, 13, 21, 0x4E0811A1 );
14920:     P4( X, &A, B, C, D,  4,  6, 0xF7537E82 );
14921:     P4( X, &D, A, B, C, 11, 10, 0xBD3AF235 );
14922:     P4( X, &C, D, A, B,  2, 15, 0x2AD7D2BB );
14923:     P4( X, &B, C, D, A,  9, 21, 0xEB86D391 );
14924:     ctx->state[0] += A;
14925:     ctx->state[1] += B;
14926:     ctx->state[2] += C;
14927:     ctx->state[3] += D; }
14928: 
14929: void md5_update( md5_context *ctx, uint8 *input, uint32 length )
14930:   { uint32 left, fill;
14931:     if( length < 1 ) return;
14932:     left = ctx->total[0] & 0x3F;
14933:     fill = 64 - left;
14934:     ctx->total[0] += length;
14935:     ctx->total[0] &= 0xFFFFFFFF;
14936:     if( ctx->total[0] < length )
14937:         ctx->total[1]++;
14938:     if( left && length >= fill )
14939:       { memcpy( (void *) (ctx->buffer + left),
14940:                 (void *) input, fill );
14941:         md5_process( ctx, ctx->buffer );
14942:         length -= fill;
14943:         input  += fill;
14944:         left = 0; }
14945:     while( length >= 64 )
14946:       { md5_process( ctx, input );
14947:         length -= 64;
14948:         input  += 64; }
14949:     if( length >= 1 )
14950:       memcpy( (void *) (ctx->buffer + left),
14951:               (void *) input, length ); }
14952: 
14953: void md5_finish( md5_context *ctx, uint8 digest[16] )
14954:   { static uint8 md5_padding[64] =
14955:      { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
14956:           0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
14957:           0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
14958:           0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
14959:     uint32 last, padn;
14960:     uint32 high, low;
14961:     uint8 msglen[8];
14962:     high = ( ctx->total[0] >> 29 )
14963:          | ( ctx->total[1] <<  3 );
14964:     low  = ( ctx->total[0] <<  3 );
14965:     PUT_UINT32( low,  msglen, 0 );
14966:     PUT_UINT32( high, msglen, 4 );
14967:     last = ctx->total[0] & 0x3F;
14968:     padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last );
14969:     md5_update( ctx, md5_padding, padn );
14970:     md5_update( ctx, msglen, 8 );
14971:     PUT_UINT32( ctx->state[0], digest,  0 );
14972:     PUT_UINT32( ctx->state[1], digest,  4 );
14973:     PUT_UINT32( ctx->state[2], digest,  8 );
14974:     PUT_UINT32( ctx->state[3], digest, 12 ); }
14975: /* --- end-of-function md5str() and "friends" --- */
14976: 
14977: #if defined(GIF)
14978: /* ==========================================================================
14979:  * Function:	GetPixel ( int x, int y )
14980:  * Purpose:	callback for GIF_CompressImage() returning the
14981:  *		pixel at column x, row y
14982:  * --------------------------------------------------------------------------
14983:  * Arguments:	x (I)		int containing column=0...width-1
14984:  *				of desired pixel
14985:  *		y (I)		int containing row=0...height-1
14986:  *				of desired pixel
14987:  * --------------------------------------------------------------------------
14988:  * Returns:	( int )		0 or 1, if pixel at x,y is off or on
14989:  * --------------------------------------------------------------------------
14990:  * Notes:     o
14991:  * ======================================================================= */
14992: /* --- entry point --- */
14993: int	GetPixel ( int x, int y )
14994: {
14995: int	ipixel = y*bitmap_raster->width + x; /* pixel index for x,y-coords*/
14996: int	pixval =0;			/* value of pixel */
14997: if ( !isaa )				/* use bitmap if not anti-aliased */
14998:   pixval = (int)getlongbit(bitmap_raster->pixmap,ipixel); /*pixel = 0 or 1*/
14999: else					/* else use anti-aliased grayscale*/
15000:   pixval = (int)(colormap_raster[ipixel]); /* colors[] index number */
15001: if ( msgfp!=NULL && msglevel>=9999 )	/* dump pixel */
15002:   { fprintf(msgfp,"GetPixel> x=%d, y=%d  pixel=%d\n",x,y,pixval);
15003:     fflush(msgfp); }
15004: return pixval;
15005: } /* --- end-of-function GetPixel() --- */
15006: #endif /* gif */
15007: #endif /* driver */
15008: #endif /* PART1 */
15009: /* ======================= END-OF-FILE MIMETEX.C ========================= */
15010: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>