ftp://ftp.metalab.unc.edu/pub/Linux/apps/serialcomm/fax/efax-0.9.tar.gz
[efax.git] / efaxlib.c
1 /* 
2               efaxlib.c - utility routines for efax
3                      Copyright 1995 Ed Casas
4 */
5
6 #include <ctype.h>
7 #include <stdio.h>
8 #include <string.h>
9
10 #include "efaxmsg.h"
11 #include "efaxlib.h"
12
13 #ifndef SEEK_SET
14 #define SEEK_SET 0
15 #endif
16
17 #define DEFXRES 204.145         /* fax x and y resolution in dpi */
18 #define DEFYRES 195.58
19
20 #define DEFWIDTH  1728          /* 215x297 mm image at fax resolution */
21 #define DEFHEIGHT 2287
22
23 extern t4tab wtab [ ( 64 + 27 + 13 ) + 1 ] ; /* T.4 coding tables */
24 extern t4tab btab [ ( 64 + 27 + 13 ) + 1 ] ;
25
26 short short256 = 256 ;          /* for endian-ness detection */
27
28 /* Make sure printf strings have only %d escapes and n or fewer
29    of them.  Returns 0 if OK, 1 on error. */
30
31 int ckfmt ( char *p, int n )
32 {
33   for ( ; *p ; p++ ) {
34     if ( p[0] == '%' ) {
35       if ( p[1] == 'd' ) n-- ;
36       else if ( p[1] == '%' ) p++ ;
37       else n=-1 ;
38     }
39   }
40   
41   return n < 0 ;
42 }
43
44
45 /* Initialize state of variable-length code word encoder. */
46
47 void newENCODER ( ENCODER *e )
48 {
49   e->x = 0 ;
50   e->shift = -8 ;
51 }
52
53
54 /* Store a code word `code' of length `bits' (<=24) in buffer pointed to by
55    `buf'.  Bits that don't fit in complete bytes are saved between calls.
56    To flush the remaining bits call the function with code=0 and bits=0.
57    Returns pointer to next free element in output buffer.  Calling function
58    must ensure at least bits/8 bytes are available in buffer.  */
59
60 uchar *putcode ( ENCODER *e, short code, short bits, uchar *buf )
61 {
62   e->x = ( e->x << bits ) | code ;
63   e->shift += bits ? bits : -e->shift ;
64
65   while ( e->shift >= 0 ) {
66     *buf++ = e->x >> e->shift ;
67     e->shift -= 8 ;
68   }
69
70   return buf ;
71 }
72
73
74 /* Convert run lengths to 1-D T.4-codes.  First run is white.  Silently
75    truncates run lengths that are too long. After using this function EOLs
76    may need to be added and/or the putcode() buffer flushed.  Returns
77    pointer to next free element in output buffer. */
78
79 uchar *runtocode ( ENCODER *e, short *runs, int nr, uchar *codes )
80 {
81   uchar col = 0, *maxcodes = codes + MAXCODES ;
82   t4tab *ctab = wtab, *p ;
83   short rlen ;
84   long x ;
85   short shift ;
86
87 #define PUTCODE(p) { x = ( x << p->bits ) | p->code ;  shift += p->bits ; \
88         while ( shift >= 0 ) { *codes++ = x >> shift ; shift -= 8 ; } }
89
90   x = e->x ; shift = e->shift ;
91
92   while ( nr-- > 0 ) {
93     rlen = *runs++ ;
94     if ( rlen > 63 ) {                          /* make-up code */
95       if ( rlen > MAXRUNLEN ) rlen = MAXRUNLEN ;
96       p = ctab + 63 + ( rlen >> 6 ) ;
97       if ( codes < maxcodes ) PUTCODE(p) ;
98     }
99     p = ctab + ( rlen & 0x3f ) ;                /* terminating code */
100     if ( codes < maxcodes ) PUTCODE(p) ;
101     ctab = ( col ^= 1 ) ? btab : wtab ;
102   }  
103   
104   e->x = x ; e->shift = shift ;
105
106   return codes ;
107 }
108
109
110 /* Pad/truncate run-length coded scan line 'runs' of 'nr' runs by 'pad'
111    pixels (truncate if negative).  Returns the new number of runs. */
112
113 int xpad ( short *runs, int nr, int pad )
114 {
115   if ( pad < 0 ) {                        /* truncate */
116     while ( pad < 0 ) pad += ( nr <= 0 ? -pad : runs [ --nr ] ) ;
117     runs [ nr++ ] = pad ;
118   } else {                                /* pad with white */
119     if ( nr & 1 ) runs [ nr - 1 ] += pad ;
120     else runs [ nr++ ] = pad ;
121   }
122   return nr ;
123 }
124
125
126 /* Shift a run-length coded scan line right by s pixels (left if negative).
127    If necessary, zero-length runs are created to avoid copying.  Returns
128    the pixel width change (+/-). */
129
130 int xshift ( short *runs, int nr, int s )
131 {
132   int i=0, n=0 ;
133   if ( s < 0 ) {
134     for ( i = 0 ; s < 0 && i < nr ; i++ ) { 
135       s += runs [ i ] ;
136       n -= runs [ i ] ;
137       runs [ i ] = 0 ; 
138     }
139     i-- ;
140   }
141   if ( i < nr ) {
142     runs [ i ] += s ;
143     n += s ;
144   }
145   return n ;
146 }
147
148
149 /* Scale nr run lengths in buffer pointed to by p to scale image
150    horizontally.  The scaling factor is xs/256. Returns new line width in
151    pixels. */
152
153 int xscale ( short *p, int nr, int xs )
154 {
155   int inlen=0, outlen=0 ;
156   for ( ; nr-- > 0 ; p++ ) {
157     inlen += *p ;
158     *p = ( ( inlen * xs + 128 ) >> 8 ) - outlen ;
159     outlen += *p ;
160   }
161   return outlen ;
162 }
163
164
165 /* Zero-terminated lists of run lengths for each byte. */
166
167 uchar byteruns [ 1408 + 1 ] = 
168    "8071061106205120511105210530413041210411110411204220421104310440"
169    "3140313103121103122031112031111103112103113032303221032111032120"
170    "3320331103410350215021410213110213202121202121110212210212302111"
171    "3021112102111111021111202112202112110211310211402240223102221102"
172    "2220221120221111022121022130233023210231110231202420241102510260"
173    "1160115101141101142011312011311101132101133011213011212101121111"
174    "0112112011222011221101123101124011114011113101111211011112201111"
175    "1120111111110111112101111130111230111221011121110111212011132011"
176    "1311011141011150125012410123110123201221201221110122210122301211"
177    "3012112101211111012111201212201212110121310121401340133101321101"
178    "3220131120131111013121013130143014210141110141201520151101610170"
179    "1701610151101520141201411101421014301313013121013111101311201322"
180    "0132110133101340121401213101212110121220121112012111110121121012"
181    "1130122301222101221110122120123201231101241012501115011141011131"
182    "1011132011121201112111011122101112301111130111112101111111101111"
183    "1120111122011112110111131011114011240112310112211011222011211201"
184    "1211110112121011213011330113210113111011312011420114110115101160"
185    "2602510241102420231202311102321023302213022121022111102211202222"
186    "0222110223102240211402113102112110211220211112021111110211121021"
187    "1130212302122102121110212120213202131102141021503503410331103320"
188    "3212032111032210323031130311210311111031112031220312110313103140"
189    "4404310421104220411204111104121041305305210511105120620611071080" ;
190
191 /* Convert byte-aligned bit-mapped n-byte scan line into array of run
192    lengths.  Run length array must have *more* than 8*n elements.  First
193    run is white.  Returns number of runs coded.  */
194
195 int bittorun ( uchar *bits, int n, short *runs )
196 {
197   static uchar init=0, *rltab [ 256 ] ;
198   register uchar *p, c, lastc = 0x00 ;
199   short *runs0 = runs ;
200
201   if ( ! init ) {               /* initialize pointer and run tables */
202     int i = 0 ;
203     for ( rltab[ 0 ] = p = byteruns ; *p ; p++ )
204       if ( ! ( *p -= '0' ) && i < 255 ) 
205         rltab [ ++i ] = p+1 ;
206     init = 1 ;
207   }
208
209   *runs = 0 ;
210   for ( ; n > 0 ; n-- ) {
211     p = rltab [ c = *bits++ ] ;
212     if ( ( lastc & 0x01 ) ? ! ( c & 0x80 ) : ( c & 0x80 ) )
213       *(++runs) = *p++ ;                  /* new run */
214     else                          
215       *runs += *p++ ;                     /* continue run */
216     while ( *p ) 
217       *(++runs) = *p++ ;
218     lastc = c ;
219   }
220
221   return runs - runs0 + 1  ;
222 }
223
224
225 /* Bitwise-OR two run-length coded scan lines.  The run length
226    vectors a and b are OR-ed into c.  If c is null, the result is
227    placed in a.  The new image width is stored in pels if it is
228    not null.  Returns the number of runs in the result.  */
229
230 int runor ( short *a, int na, short *b, int nb, short *c, int *pels )
231 {
232   register short la, lb ;
233   int ia, ib, ic, np=0 ;
234   short tmp [ MAXRUNS ] ;
235
236   if ( ! c ) c = tmp ;
237
238   la = a [ ia = 0 ] ;
239   lb = b [ ib = 0 ] ;
240   c [ ic = 0 ] = 0 ;
241
242   while ( 1 ) {
243     if ( la <= lb ) {                     /* select shorter sub-run */
244       if ( ( ( ia | ib ) ^ ic ) & 1 )     /* OR of subruns same colour as c? */
245         c [ ++ic ] = la ;                 /* no, new output run */
246       else 
247         c [ ic ] += la ;                  /* yes, add it */
248       lb -= la ;                          /* align subruns */
249       if ( ++ia >= na ) break ;           /* done */
250       la = a [ ia ] ;                     /* get new subrun */
251     } else {                              /* same for line b ... */
252       if ( ( ( ia | ib ) ^ ic ) & 1 ) 
253         c [ ++ic ] = lb ;
254       else 
255         c [ ic ] += lb ;
256       la -= lb ;
257       if ( ++ib >= nb ) break ;
258       lb = b [ ib ] ;
259     }
260   }
261
262   if ( ia < na )
263     while ( 1 ) {
264       if ( ( ia ^ ic ) & 1 )      
265         c [ ++ic ] = la ;                 
266       else 
267         c [ ic ] += la ;                  
268       if ( ++ia >= na ) break ;           
269       la = a [ ia ] ;                     
270     } 
271   else
272     while ( 1 ) {
273       if ( ( ib ^ ic ) & 1 ) 
274         c [ ++ic ] = lb ;
275       else 
276         c [ ic ] += lb ;
277       if ( ++ib >= nb ) break ;
278       lb = b [ ib ] ;
279     }
280
281   if ( c == tmp ) for ( ia=0 ; ia <= ic ; ia++ ) np += a[ia] = c[ia] ;
282
283   if ( pels ) *pels = np ;
284
285   return ic + 1 ;
286 }  
287
288
289 /* Get a number from a PBM file header while skipping whitespace
290    and comments. Returns the number or 0 on EOF. Reads one more
291    byte than used by the number. */
292
293 int pbmdim ( IFILE *f )
294 {
295   int c, n=0 ;
296   
297   /* scan for first digit and skip comments */
298   while ( ! isdigit ( c = fgetc ( f->f ) ) && c >= 0 ) 
299     if ( c == '#' )
300       while ( ( c = fgetc ( f->f ) ) != '\n' && c >= 0 ) ;
301
302   /* get the number */
303   if ( c >= 0 && isdigit( c ) ) {
304     n = c - '0' ;
305     while ( isdigit ( c = fgetc ( f->f ) ) && c >= 0 ) 
306       n = n * 10 + c - '0' ;
307   }
308
309   return n ;
310 }
311
312
313 /* Append nb bits from in[from] to bit-mapped scan line buffer
314    where `from' is a bit (not byte) index.  Bits in bytes are
315    ordered from MS to LS bit. Initialize before each scan line by
316    calling with nb=0 and in pointing to output buffer.  Flush
317    after each scan line by calling with nb=0 and in=NULL. */
318
319 #define putbits( c, b ) { x = ( x << (b) ) | (c) ; shift += (b) ; \
320           if ( shift >= 0 ) { *out++ = x >> shift ; shift -= 8 ; } }
321
322 void copybits ( uchar *in, int from, short nb )
323 {
324   uchar *f ;
325   short bits ;
326   static uchar *out ;
327   static short x, shift ;
328   static unsigned char right [ 9 ] = { 
329     0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff } ;
330   
331   if ( ! nb ) {                         /* reset for new scan line */
332     if ( in ) out = in ;                   
333     else putbits ( 0, -shift ) ;        /* or flush bit buffer */
334     x = 0 ;
335     shift = -8 ;
336   } else {
337     f = in + ( from >> 3 ) ;
338     bits = 8 - ( from & 7 ) ;
339
340     if ( nb >= bits ) {
341       putbits ( *f++ & right [ bits ], bits ) ;
342       nb -= bits ;
343     } else {
344       putbits ( ( *f >> ( bits - nb ) ) & right [ bits ], nb ) ;
345       nb = 0 ;
346     } 
347
348     while ( nb >= 8 ) { putbits ( *f++, 8 ) ; nb -= 8 ; }
349
350     if ( nb > 0 ) putbits ( *f >> ( 8 - nb ), nb );
351   }
352 }   
353
354
355 /* Generate scan line 'line' of string 'txt' using font `font'
356    and store the runs in 'runs'.  The font is scaled so it
357    appears to have cells of width w and height h.  lmargin pixels
358    of white space are added at the left margin. Sets 'pels' to
359    line width if not null.  Returns number of runs coded. */
360
361 int texttorun ( uchar *txt, faxfont *font, short line, 
362                int w, int h, int lmargin,
363                short *runs, int *ppels )
364 {
365   uchar *in, out [ MAXLINELEN * MAXFONTW / 8 + 1 ] ;
366   int i, nc = 0, cw, nr, pels ;
367
368   line = ( line * font->h + h/2 ) / h ;
369
370   cw = font->w ;
371   if ( line >= font->h ) line = font->h - 1 ;
372   in = font->buf + 256/8 * cw * line ;
373
374   copybits ( out, 0, 0 ) ;
375   for ( i=0 ; txt[i] && i < MAXLINELEN ; i++ ) {
376     copybits ( in, font->offset [ txt[i] ], cw ) ;
377     nc++ ;
378     while ( ( txt[i] == HT ) && ( nc & 7 ) ) { /* tab */
379       copybits ( in, font->offset [ ' ' ], cw ) ;
380       nc++ ;
381     }
382   }
383   copybits ( 0, 0, 0 ) ;
384
385   nr = bittorun ( out, ( nc*cw + 7 )/8, runs ) ;
386   
387   if ( font->w == w )
388     pels = nc*cw ;
389   else    
390     pels = xscale ( runs, nr, ( w * 256 ) / font->w ) ;
391   
392   pels += xshift ( runs, nr, lmargin ) ;
393   
394   if ( ppels ) *ppels = pels ;
395
396   return nr ;
397 }
398
399                 /* Image File Input Functions */
400
401
402 /* Names of file formats */
403
404 char *iformatname [ NIFORMATS ] = IFORMATS ;
405 char *oformatname [ NOFORMATS ] = OFORMATS ;
406 char *pformatname [ NPFORMATS ] = PFORMATS ;
407
408 /* Log the names of files still to be sent using the "msg()"
409    format string s. */
410
411 void logifnames ( IFILE *f, char *s )
412 {
413   PAGE *p ;
414   char *fn ;
415
416   if ( f && f->page )
417     for ( p = f->page ; p <= f->lastpage ; p++ ) {
418       fn = p->fname ;
419       if ( fn ) msg ( s, fn ) ;
420     }
421 }
422
423
424 /* Read run lengths for one scan line from T.4-coded IFILE f into buffer
425    runs.  If pointer pels is not null it is used to save pixel count.
426    Returns number of runs stored, EOF on RTC, or -2 on EOF or other
427    error. */
428
429 int readruns ( IFILE *f, short *runs, int *pels )
430 {
431   int err=0, c=EOF, n ;
432   register int x ;
433   dtab *tab, *t ;
434   short shift ;
435   short *p, *maxp, *q, len=0, npad=0 ;
436   DECODER *d ;
437   uchar reverse=f->page->revbits ;
438
439   maxp = ( p = runs ) + MAXRUNS ;
440   d = &f->d ;
441
442   x = d->x ; shift = d->shift ; tab = d->tab ; /* restore decoder state */
443
444   do {
445     do {
446       while ( shift < 0 ) { 
447         if ( ( c = fgetc ( f->f ) ) == EOF )  {
448           x = ( x << 15 ) | 1 ; shift += 15 ;  /* EOL pad at EOF */
449           npad++ ;
450         } else {
451           if ( reverse ) c = normalbits [ c & 0xff ] ;
452           x = ( x <<  8 ) | c ; shift +=  8 ; 
453         }
454       }
455       t = tab + ( ( x >> shift ) & 0x1ff ) ;
456       tab = t->next ;
457       shift -= t->bits ;
458     } while ( ! t->code ) ;
459     if ( p < maxp ) *p++ = t->code ;
460   } while ( t->code != -1 ) ;
461
462   d->x = x ; d->shift = shift ; d->tab = tab ; /* save state */
463
464   if ( npad > 1 ) msg ("W EOF before RTC" ) ;
465
466   if ( p >= maxp ) msg ( "W run length buffer overflow" ) ;
467
468   /* combine make-up and terminating codes and remove +1 offset
469      in run lengths */
470
471   n = p - runs - 1 ;
472   for ( p = q = runs ; n-- > 0 ; )
473     if ( *p > 64 && n-- > 0 ) {
474       len += *q++ = p[0] + p[1] - 2 ;
475       p+=2 ;
476     } else {
477       len += *q++ = *p++ - 1 ;
478     }
479   n = q - runs ;
480   
481   /* check for RTC and errors */
482
483   if ( len )
484     d->eolcnt = 0 ;
485   else
486     if ( ++(d->eolcnt) >= RTCEOL ) err = EOF ;
487
488   if ( c == EOF ) {
489     if ( ferror ( f->f ) ) {
490       err = -msg ("ES2error reading fax file:") ;
491     } else { 
492       err = -2 ;
493     }
494   }
495
496   if ( pels ) *pels = len ;
497   
498   return err ? err : n ;
499 }
500
501
502 /* Read a PCX compressed bit-map */
503
504 int readpcx ( char *p, int len, IFILE *f )
505 {
506   int err=0, n, c ;
507
508   while ( !err && len > 0 ) {
509     if ( ( c = fgetc ( f->f ) ) < 0 ) {
510       err = msg ( "ES2 PCX read failed" ) ;
511     } else {
512       if ( ( c & 0xc0 ) == 0xc0 ) {     /* a run count */
513         n = c & 0x3f ;
514         c = fgetc ( f->f ) ;
515         if ( ( c = fgetc ( f->f ) ) < 0 ) {
516           err = msg ( "ES2 PCX read failed" ) ;
517         } else {
518           memset ( p, c, n <= len ? n : len ) ;
519           p += n ;
520           len -= n ;
521         }
522       } else {                  /* bits 0 to 7 are image data */
523         *p++ = c ;
524         len-- ;
525       }
526     }
527   }
528
529   if ( len != 0 )
530     msg ( "W PCX run-length coding error" ) ;
531
532   return err ;
533 }
534
535 /* Read a scan line from the current page of IFILE f.  Stores
536    number of runs in runs and line width in pels if not null.
537    Pages ends at EOF. Text pages also end if a complete text line
538    would not fit or if the line contains a formfeed character.
539    PBM pages also end when all lines in the bitmap have been
540    read. Fax pages also end at RTC. Returns number of runs stored
541    or EOF at end of page. */
542
543 int readline ( IFILE *f, short *runs, int *pels )
544 {
545   int nr = 0, nb ;
546   uchar bits [ MAXBITS ] ;
547
548   if ( f->lines != 0 ) {        /* -1 allowed as well */
549     switch ( f->page->format ) {
550
551     case P_TEXT :
552       if ( f->txtlines <= 0 ) { /* need another text line */
553         if ( fgets ( f->text, MAXLINELEN, f->f ) ) {
554           f->txtlines = f->charh ;
555           if ( strchr ( f->text, FF ) ) {
556             f->lines = 0 ;      /* no more lines in this page */
557             nr = EOF ;          /* don't return any */
558           } 
559         } else {
560           nr = EOF ;
561         }
562       }
563       if ( nr != EOF ) {
564         nr = texttorun ( (uchar*) f->text, f->font, f->charh - f->txtlines, 
565                         f->charw, f->charh, f->lmargin,
566                         runs, pels ) ;
567         f->txtlines-- ;
568       } 
569       break ;
570
571     case P_RAW:
572     case P_PBM:
573       if ( fread ( bits, 1, f->page->w/8, f->f ) != f->page->w/8 ) {
574         nr = EOF ;
575       } else {
576         nr = bittorun ( bits, f->page->w/8, runs ) ;
577         if ( pels ) *pels = f->page->w ;
578       }
579       break ;
580
581     case P_FAX:
582       nr = readruns ( f, runs, pels ) ;
583       break ;
584
585     case P_PCX:
586       nb = ( ( f->page->w + 15 ) / 16 ) * 2 ;   /* round up */
587       if ( readpcx ( bits, nb, f ) != 0 ) {
588         nr = EOF ;
589       } else {
590         nr = bittorun ( bits, nb, runs ) ;
591         if ( pels ) *pels = f->page->w ;
592       }
593       break ;
594
595     }
596   } else {
597     nr = EOF ;
598   }
599   
600   if ( nr >= 0 && f->lines > 0 ) f->lines-- ;
601   
602   return nr ;
603 }
604
605
606 /* Deduce the file type by scanning buffer p of n bytes. */
607    
608 int getformat ( uchar *p, int n )
609 {
610   int format = 0 ;
611
612   /* figure out file type if not already set */
613
614   if ( ! format && n < 2 ) {
615     format = I_TEXT ;
616     msg ( "W only read %d byte(s) from input file, assuming text",  n ) ;
617   } 
618
619   if ( ! format && ! p[0] && ! ( p[1] & 0xe0 ) ) {
620     format = I_FAX ;
621   } 
622
623   if ( ! format && ! strncmp ( p, "P4", 2 ) ) {
624     format = I_PBM ;
625   }
626
627   if ( ! format && n >= 128 && p[0] == 0x0a && 
628        strchr ("\02\03\05", p[1] ) && p[2] <= 1 ) {
629     if ( p[65] != 1 ) {
630       msg ( "E can't read colour PCX" ) ;
631     } else {
632       format = p[2] ? I_PCX : I_PCX ;
633     }
634   }
635
636   if ( ! format && ! strncmp ( p, "%!", 2 ) ) {
637     msg ( "W Postscript input file will be treated as text" ) ;
638   }
639
640   if ( ! format && ( p[0] == 'M' || p[1] == 'I' ) && ( p[1] == p[0] ) ) {
641     format = I_TIFF ;
642   }
643   
644   if ( ! format &&
645        ( p[0] == 0x3a && p[1] == 0xde && 
646          p[2] == 0x68 && p[3] == 0xb1) ) {
647     format = I_DCX ;
648   }
649   
650   if ( ! format &&  n ) { /* "90% printable" heuristic */
651     int i, nprint = 0 ;
652     for ( i=0 ; i<n ; i++ ) {
653       if ( isspace ( p[i] ) || isprint ( p[i] ) ) {
654         nprint++ ;
655       }
656     }
657     if ( ( nprint / (float) n ) > 0.90 ) {
658       format = I_TEXT ;
659     }
660   }
661
662   return format ;
663 }
664
665
666 /* initialize page descriptor */
667
668 void page_init ( PAGE *p, char *fn )
669 {
670   p->fname = fn ;
671   p->offset = 0 ;
672   p->w = DEFWIDTH ;
673   p->h = DEFHEIGHT ;
674   p->xres = DEFXRES ;
675   p->yres = DEFYRES ;
676   p->format = P_FAX ;
677   p->revbits = 0 ;
678 }
679
680
681 void page_report ( PAGE *p, int fmt, int n )
682 {
683   msg ( "F page %d : %s + %ld : %dx%d @ %.fx%.f dpi %s/%s", 
684         n, 
685         p->fname, p->offset, p->w, p->h, 
686         p->xres, p->yres, 
687         iformatname [fmt], pformatname [p->format] ) ;
688 }
689         
690 /* File handling for undefined file types */
691
692 #define auto_first 0
693 #define auto_next 0
694
695 /* File handling for TIFF files */
696
697 #define tiff_reset 0 
698
699 /* Name of TIFF tag 'tag'. */
700
701 char *tagname ( int tag )
702 {
703   static struct tagnamestruct {  int code ;  char *name ; } 
704   tagnames [] = {
705   { 256, "width" },
706   { 257, "length" },
707   { 258, "bits/sample" },
708   { 259, "compresssion(g3=3)" },
709   { 262, "photometric(0-min=white)" },
710   { 266, "fill order(msb2lsb=1)" },
711   { 273, "strip offsets" },
712   { 274, "orientation(1=normal)" },
713   { 277, "samples/pixel" },
714   { 278, "rows/strip" },
715   { 279, "strip byte counts" },
716   { 282, "xresolution" },
717   { 283, "yresolution" },
718   { 284, "storage(1=single plane)" },
719   { 292, "g3options" },
720   { 296, "resolution units(2=in,3=cm)" },
721   { 297, "page number" },
722   { 327, "clean fax(0=clean/1=regen/2=errors)" },
723   {0,0} },
724   *p ;
725   
726   for ( p=tagnames ; p->code ; p++ )
727     if ( tag == p->code ) break ;
728   return p->code ? p->name :  "unknown tag" ;
729 }
730
731 /* Read 2- or 4-byte integers from a file and correct for file
732    endianness.  Returns 0 if OK, 1 on error. */
733
734 int fread2 ( unsigned short *p, IFILE *f )
735 {
736   int err=0 ;
737   uchar c[2] ;
738
739   err = fread ( c, 1, 2, f->f ) == 2 ? 0 : 1 ;
740   
741   *p = f->bigend ?
742     c[0] << 8 | c[1] << 0 :
743     c[1] << 8 | c[0] << 0 ;
744     
745   return err ;
746 }
747
748 int fread4 ( unsigned long *p, IFILE *f )
749 {
750   int err=0 ;
751   uchar c[4] ;
752
753   err = fread ( c, 1, 4, f->f ) == 4 ? 0 : 1 ;
754   
755   *p = f->bigend ?
756     c[0] << 24 | c[1] << 16 | c[2] << 8 | c[3] << 0 :
757     c[3] << 24 | c[2] << 16 | c[1] << 8 | c[0] << 0 ;
758     
759   return err ;
760 }
761
762
763 /* Read a TIFF directory at current file offset, save image
764    format information and seek to next directory if any.  Returns
765    0 if OK, 2 on errors. */
766
767 int tiff_next ( IFILE *f )
768 {
769   int err=0 ;
770   unsigned short ntag, tag, type ;
771   unsigned long count, tv ;
772   double ftv ;
773
774   msg ( "F+ TIFF directory at %ld", ftell ( f->f ) ) ;
775
776   if ( fread2 ( &ntag, f ) ) {
777     err = msg ( "E2can't read TIFF tag count" ) ;
778   } else {
779     msg ( "F+  with %d tags", (int) ntag ) ;
780   }
781
782   for ( ; ! err && ntag > 0 ; ntag-- ) {
783
784     err = err || fread2 ( &tag, f ) ;
785     err = err || fread2 ( &type, f ) ;
786     err = err || fread4 ( &count, f ) ;
787
788     if ( type == 3 ) {                /* left-aligned short */
789       unsigned short a, b ;
790       err = err || fread2 ( &a, f ) ;
791       err = err || fread2 ( &b, f ) ;
792       tv = a ;
793     } else {                          /* long or offset to data */
794       err = err || fread4 ( &tv, f ) ;
795     }
796
797     if ( type == 5 ) {                /* float as ratio in directory data */
798       long a, b, where=0 ;
799       err = err || ( ( where = ftell ( f->f ) ) < 0 ) ;
800       err = err || fseek ( f->f, tv, SEEK_SET ) ;
801       err = err || fread4 ( &a, f ) ;
802       err = err || fread4 ( &b, f ) ;
803       err = err || fseek ( f->f, where, SEEK_SET ) ;
804       ftv = (float) a / ( b ? b : 1 ) ;
805     } else { 
806       ftv = 0.0 ;
807     }
808
809     if ( err ) {
810       err = msg ( "ES2can't read TIFF tag" ) ;
811       continue ;
812     }
813     
814 #ifdef TIFF_DEBUG
815     {
816       char *tagtype[] = { "none", "byte", "ascii", "short", "long", "ratio" } ;
817       msg ( "F  %3d %-5s tag %s %5ld (%3d:%s)", 
818             count,
819             type <= 5 ? tagtype[type] : "other",
820             count > 1 ? "@" : "=",
821             type == 5 ? (long) ftv : tv, tag, tagname(tag) ) ; 
822     }
823 #endif
824
825     switch ( tag ) {
826     case 256 :                  /* width */
827       f->page->w = tv ;
828       break ;
829     case 257 :                  /* height */
830       f->page->h = tv ;
831       break ;
832     case 259 :                  /* compression: 1=none, 3=G3 */
833       if ( tv == 1 ) {
834         f->page->format = P_RAW ;
835       } else if ( tv == 3 ) {
836         f->page->format = P_FAX ;
837       } else {
838         err = msg ( "E2can only read TIFF/G3 or TIFF/uncompressed" ) ;
839       }
840       break ;
841     case 266 :                  /* fill order */
842       f->page->revbits = ( tv == 2 ? 1 : 0 ) ;
843       break ;
844     case 273 :                  /* data offset */
845       if ( count != 1 )
846         err = msg ( "E2can't read multi-strip TIFF files" ) ;
847       else
848         f->page->offset = tv ;
849       break ;
850     case 282 :                  /* x resolution */
851       f->page->xres = ftv ;
852       break ;
853     case 283 :                  /* y resolution */
854       f->page->yres = ftv ;
855       break ;
856     case 292 :                  /* T4 options: 1=2D, 2=uncompressed */
857       if ( tv & 0x1 )
858         err = msg ( "E2can't read 2D compressed TIFF-F file" ) ;
859       if ( tv & 0x2 )
860         err = msg ( "E2can't read uncompressed TIFF-F file" ) ;
861       break ;
862     case 296 :                  /* units: 2=in, 3=cm */
863       if ( tv == 3 ) {
864         f->page->xres *= 2.54 ;
865         f->page->yres *= 2.54 ;
866       }
867       break ;
868     }
869
870   } /* end of tag reading loop */
871
872
873   if ( f->page->format == I_AUTO ) {
874     msg ( "W missing TIFF compression format, set to raw" ) ;
875     f->page->format = P_RAW ;
876   }
877   
878   if ( ! err ) {
879
880     if ( fread4 ( &(f->next), f ) ) {
881       err = msg ( "E2can't read offset to next TIFF directory" ) ;
882     } else {
883       if ( f->next ) {
884         msg ( "F , next directory at %ld.", f->next ) ;
885         if ( fseek ( f->f, f->next, SEEK_SET ) )
886           err = msg ( "ES2 seek to next TIFF directory failed" ) ;
887       } else {
888         msg ( "F , last image." ) ;
889       }
890     }
891
892   }
893
894   if ( ! f->page->offset )
895     err = msg ( "E2 missing offset to TIFF data" ) ;
896
897   return err ;
898 }
899
900
901 int tiff_first ( IFILE *f )
902 {
903   short magic, version ;
904
905   fread ( (uchar*) &magic, 1, 2, f->f ) ;
906   f->bigend = ( *(uchar*) &magic == 'M' ) ? 1 : 0 ;
907   fread2 ( &version, f ) ;
908   fread4 ( &(f->next), f ) ;
909   
910   msg ( "F TIFF version %d.%d file (%s-endian)",
911        version/10, version%10, f->bigend ? "big" : "little" ) ;
912
913   fseek ( f->f, f->next, SEEK_SET ) ;
914
915   return tiff_next ( f ) ;
916 }
917
918
919 /* File handling for text files. */
920
921 int text_next ( IFILE *f )
922 {
923   int err = 0, i, nc ;
924   char buf [ MAXLINELEN ] ;
925
926   f->page->offset = ftell ( f->f ) ;
927   f->page->format = P_TEXT ;
928
929   nc = ( f->page->w - f->lmargin ) / f->charw ;
930
931   if ( nc > MAXLINELEN ) 
932     nc = MAXLINELEN ;
933
934   for ( i = 0 ; i < f->pglines && fgets ( buf, nc, f->f ) ; i++ ) ;
935
936   f->next = ! feof(f->f) ? ftell ( f->f ) : 0 ;
937
938   err = ferror(f->f) ? 2 : 0 ;
939
940   return err ;
941 }
942
943
944 int text_first ( IFILE *f )
945 {
946   static faxfont defaultfont ;
947
948   if ( ! f->font ) {
949     /* use default font scaled 2X, 1 inch margin, 66 lines/page */
950     f->font = &defaultfont ;
951     readfont ( 0, f->font ) ; 
952     if ( ! f->charw ) f->charw = 2 * f->font->w ;
953     if ( ! f->charh ) f->charh = 2 * f->font->h ;
954     if ( ! f->lmargin ) f->lmargin = 204 ;
955     if ( ! f->pglines ) f->pglines = DEFPGLINES ;
956   }
957   /* if not set, take default values from font  */
958   if ( ! f->charw ) f->charw = f->font->w ;
959   if ( ! f->charh ) f->charh = f->font->h ;
960   if ( ! f->lmargin ) f->lmargin = 0 ;
961   if ( ! f->pglines ) f->pglines = f->page->h / f->charh - 6 ;
962   
963   return text_next ( f ) ; 
964 }
965
966
967 /* File handling for PBM files */
968
969 int pbm_first ( IFILE *f )
970 {
971   int err=0 ;
972
973   fseek ( f->f, 2, SEEK_SET ) ;
974
975   if ( ! ( f->page->w = pbmdim ( f ) ) || ! ( f->page->h = pbmdim ( f ) ) ) {
976     err = msg ( "E2 EOF or 0 dimension in PBM header" ) ;
977   } else if ( f->page->w % 8 ) {
978     err = msg ( "E2 PBM width must be multiple of 8" ) ;
979   } else {
980     msg ( "F read %dx%d PBM header", f->page->w, f->page->h ) ;
981   }
982
983   f->page->offset = ftell ( f->f ) ;
984   f->page->format = P_PBM ;
985   f->next = 0 ;
986
987   return err ;
988 }
989
990 #define pbm_next 0
991
992
993 /* File handling for FAX files */
994
995 #define fax_first 0
996
997 #define fax_next 0
998
999 /* File handling for PCX files */
1000
1001 /* get a 16-bit word in Intel byte order. */
1002
1003 int fgeti ( IFILE *f )
1004 {
1005   return fgetc ( f->f ) + fgetc ( f->f ) * 256 ;
1006 }
1007
1008 int pcx_first ( IFILE *f )
1009 {
1010   int err=0, xmin, xmax, ymin, ymax, nc, nb ;
1011   long start ;
1012
1013   start = ftell ( f->f ) ;
1014
1015   fseek ( f->f, start+4, SEEK_SET ) ;
1016   xmin = fgeti ( f ) ;
1017   ymin = fgeti ( f ) ;
1018   xmax = fgeti ( f ) ;
1019   ymax = fgeti ( f ) ;
1020
1021   f->page->w = xmax - xmin + 1 ;
1022   f->page->h = ymax - ymin + 1 ;
1023
1024   f->page->xres = fgeti ( f ) ;
1025   f->page->yres = fgeti ( f ) ;
1026
1027   fseek ( f->f, start+0x41, SEEK_SET ) ;
1028   nc = fgetc ( f->f ) ;
1029   nb = fgeti ( f ) ;
1030
1031   if ( nc != 1 ) 
1032     msg ( "W mono PCX file has %d colour planes", nc ) ;
1033
1034   if ( nb != ( f->page->w + 15 ) / 16 * 2 )
1035     msg ( "W PCX file has %d bytes per scan line for %d pels",
1036           nb, f->page->w ) ;
1037
1038   f->page->offset = start + 128 ;
1039   f->page->format = P_PCX ;
1040
1041   return err ;
1042 }
1043
1044 #define pcx_next 0
1045
1046 /* File handling for DCX files */
1047
1048 int dcx_next ( IFILE *f )
1049 {
1050   int err=0 ;
1051   long thisp, nextp ;
1052
1053   /* get this and next pages' offsets */
1054
1055   fseek ( f->f, f->next, SEEK_SET ) ; 
1056   fread4 ( &thisp, f ) ;
1057   fread4 ( &nextp, f ) ;
1058
1059   /* save address of next directory entry, if any */
1060
1061   f->next = nextp ? f->next + 4 : 0 ;
1062
1063   if ( ! thisp )
1064     err = msg ( "E2 can't happen (dcx_next)" ) ;
1065   else
1066     fseek ( f->f, thisp, SEEK_SET ) ;
1067
1068   return err ? err : pcx_first ( f ) ;
1069 }
1070
1071 int dcx_first ( IFILE *f )
1072 {
1073   f->bigend = 0 ;
1074   f->next = 4 ;
1075   return dcx_next ( f ) ;
1076 }
1077
1078
1079 #define raw_reset 0
1080 #define raw_first 0
1081 #define raw_next 0
1082
1083
1084 /* input file state reset for different compression methods */
1085
1086 #define pcx_reset 0
1087 #define pbm_reset 0
1088
1089 int text_reset ( IFILE *f )
1090 {
1091   int err=0 ;
1092
1093   f->lines = ( ( f->pglines * f->charh ) / f->charh ) * f->charh ;
1094   f->txtlines = 0 ;
1095   f->page->yres = f->lines > 1078 ? 196 : 98 ; /* BOGUS */
1096
1097   return err ;
1098 }
1099
1100 int fax_reset ( IFILE *f )
1101 {
1102   int pels ;
1103   short runs [ MAXRUNS ] ;
1104   
1105   newDECODER ( &f->d ) ;
1106   if ( readruns ( f, runs, &pels ) < 0 || pels ) /* skip first EOL */
1107     msg ( "W first line has %d pixels: probably not fax data", pels ) ;
1108   f->lines = -1 ;
1109
1110   return 0 ;
1111 }
1112
1113
1114 /* Skip to start of same (dp=0) or next (dp=1) page image.
1115    Returns 0 if OK, 1 if no more pages, 2 on errors. */
1116
1117 int nextipage ( IFILE *f, int dp )
1118 {
1119   int err=0 ;
1120
1121   int ( *reset [NPFORMATS] ) ( IFILE * ) = {
1122     raw_reset, fax_reset, pbm_reset, text_reset, pcx_reset
1123   }, (*pf)(IFILE*) ;
1124
1125   /* close current file if any and set to NULL */
1126
1127   if ( f->f ) {
1128     fclose ( f->f ) ;
1129     f->f = 0 ;
1130   }
1131
1132   /*  if requested, point to next page and check if done */
1133
1134   if ( dp ) {
1135     f->page++ ;
1136   }
1137   
1138   if ( f->page > f->lastpage ) {
1139     err = 1 ;
1140   }
1141
1142   /* open the file and seek to start of image data */
1143
1144   if ( ! err ) {
1145     f->f = fopen ( f->page->fname, (f->page->format == P_TEXT) ? "r" : "rb" ) ;
1146     if ( ! f->f )
1147       err = msg ( "ES2can't open %s:", f->page->fname ) ;
1148   }
1149
1150   if ( ! err && fseek ( f->f, f->page->offset, SEEK_SET ) )
1151     err = msg ( "ES2 seek failed" ) ;
1152
1153   /* default initializations */
1154
1155   f->lines = f->page->h ;
1156
1157   /* coding-specific initializations for this page */
1158   
1159   if ( ! err ) {
1160     pf = reset[f->page->format] ;
1161     if ( pf )
1162       err = (*pf)(f) ;
1163   }
1164
1165   return err ;
1166 }
1167
1168
1169 /* Returns true if on last file. */
1170
1171 int lastpage ( IFILE *f )
1172 {
1173   return f->page >= f->lastpage ;
1174 }
1175
1176 #define dfax_first 0
1177 #define dfax_next 0
1178
1179 /* Initialize an input (IFILE) structure.  This structure
1180    collects the data about images to be processed to allow a
1181    simple interface for functions that need to read image files.
1182
1183    The IFILE is initialized by building an array of information
1184    for each page (image) in all of the files.  
1185
1186    The page pointer index is initialized so that the first call
1187    to nextipage with dp=1 actually opens the first file.
1188
1189 */
1190
1191
1192 int newIFILE ( IFILE *f, char **fnames )
1193 {
1194   int err=0, i, n, fformat=0 ;
1195   char **p ;
1196   uchar buf[128] ;
1197   int ( *fun ) ( IFILE * ) ;
1198   
1199   int ( *first [NIFORMATS] ) ( IFILE * ) = {
1200     auto_first, pbm_first, fax_first, text_first, tiff_first, 
1201     dfax_first, pcx_first, raw_first, dcx_first
1202   } ;
1203
1204   int ( *next [NIFORMATS] ) ( IFILE * ) = {
1205     auto_next, pbm_next, fax_next, text_next, tiff_next, 
1206     dfax_next, pcx_next, raw_next, dcx_next
1207   } ;
1208
1209   f->page = f->pages ;
1210
1211   /* get info for all pages in all files */
1212
1213   for ( p=fnames ; ! err && *p ; p++ ) {
1214
1215     if ( ! ( f->f = fopen ( *p, "rb" ) ) )
1216       err = msg ( "ES2 can't open %s:", *p ) ;
1217     
1218     if ( ! err ) {
1219       n = fread ( buf, 1, 128, f->f ) ;
1220       if ( ferror ( f->f ) )
1221         err = msg ( "ES2 can't open %s:", *p ) ;
1222     }
1223     
1224     if ( ! err ) {
1225       fformat = getformat ( buf, n ) ;
1226       if ( ! fformat )
1227         err = msg ( "E2 can't get format of %s", *p ) ;
1228     }
1229
1230     if ( ! err && fseek ( f->f, 0, SEEK_SET ) )
1231       err = msg ( "ES2 can't rewind %s:", *p ) ;
1232
1233     /* get format information for all pages in this file */
1234
1235     for ( i=0 ; ! err ; i++ ) {
1236
1237       page_init ( f->page, *p ) ;
1238
1239       if ( ( fun = i ? next[fformat] : first[fformat] ) )
1240         err = (*fun)(f) ;
1241
1242       if ( ! err ) {
1243
1244         page_report ( f->page, fformat, f->page - f->pages + 1 ) ;
1245
1246         f->page++ ;
1247         
1248         if ( f->page >= f->pages + MAXPAGE )
1249           err = msg ( "E2 too many pages (max is %d)", MAXPAGE ) ;
1250       }
1251
1252       if ( ! f->next ) break ;
1253     }
1254
1255     if ( f->f ) {
1256       fclose ( f->f ) ;
1257       f->f = 0 ;
1258     }
1259
1260   }
1261
1262   f->lastpage = f->page - 1 ;
1263
1264   f->page = f->pages ;
1265   
1266   if ( ! normalbits[1] ) initbittab() ; /* bit-reverse table initialization */
1267
1268   return err ;
1269 }
1270
1271                 /* Image File Output Functions */
1272
1273 /* Strings and function to write a bit map in HP-PCL format. The only
1274    compression is removal of trailing zeroes.  Margins and resolution are
1275    set before first write.  */
1276
1277 char *PCLBEGIN =
1278          "\033E"                /* Printer reset. */
1279          "\033&l0E"             /* top  margin = 0 */
1280          "\033&a0L"             /* left margin = 0 */
1281          "\033*t%dR"            /* Set raster graphics resolution */
1282          "\033*r1A" ;           /* Start raster graphics, rel. adressing */
1283
1284 char *PCLEND = 
1285          "\033*rB"              /* end raster graphics */
1286          "\014"                 /* form feed */
1287          "\033E" ;              /* Printer reset. */
1288
1289 void pclwrite ( OFILE *f, unsigned char *buf, int n )
1290 {
1291   while ( n > 0 && buf [ n-1 ] == 0 ) n-- ; 
1292   fprintf( f->f, "\033*b%dW", n ) ;
1293   fwrite ( buf, n, 1, f->f ) ;
1294 }
1295
1296
1297 /* Write a bit map as (raw) Portable Gray Map (PGM) format after
1298    decimating by a factor of 4.  Sums bits in each 4x4-pel square
1299    to compute sample value.  This function reduces each dimension
1300    of a bit map by 4 (it writes n*8/4 pixels per scan line and
1301    one scan line for every 4 in).  The 17 possible sample values
1302    are spread linearly over the range 0-255. */
1303
1304 void pgmwrite ( OFILE *f, uchar *buf, int n )
1305 {
1306   static uchar gval [ MAXBITS * 8 / 4 ] ;
1307   static int init=0, lines=0 ;
1308   static uchar hbits [ 256 ], lbits [ 256 ] ;
1309   static int nybblecnt [ 16 ] = { 0,1,1,2, 1,2,2,3, 1,2,2,3, 2,3,3,4 } ;
1310   static uchar corr [ 17 ] = { 255, 239, 223, 207, 191, 175, 159, 143, 127, 
1311                                 111,  95,  79,  63,  47,  31,  15,   0 } ;
1312   int m ;
1313   uchar *p, *q ; 
1314
1315   if ( ! init ) {           /*  build table of bit counts in each nybble */
1316     short i ;
1317     for ( i=0 ; i<256 ; i++ ) {
1318         hbits [ i ] = nybblecnt [ i >> 4 & 0x0f ] ;
1319         lbits [ i ] = nybblecnt [ i & 0x0f ] ;
1320       }
1321     init = 1 ;
1322   }
1323
1324   for ( m=n, p=gval, q=buf ; m-- > 0 ; q++ ) {
1325     *p++ += hbits [ *q ] ;
1326     *p++ += lbits [ *q ] ;
1327   }
1328   
1329   if ( ( lines++ & 0x03 ) == 0x03 ) {
1330     for ( p=gval, m=2*n ; m-- > 0 ; p++ ) *p = corr [ *p ] ;
1331     fwrite ( gval,  1, 2*n, f->f ) ;
1332     memset ( gval,  0, 2*n ) ;
1333   }
1334 }
1335
1336
1337 /* Postscript image data is differentially coded vertically and
1338    run-length coded horizontally.  A leading byte (n) defines the type
1339    of coding for subsequent data:
1340
1341    0        repeat previous line
1342    1-127    n data bytes follow
1343    128-254  copy n-127 bytes from previous line
1344    255 n    repeat the next character 'n' times 
1345
1346    The overhead for coding a copy is 2 bytes (copy count, data count),
1347    so copies > 2 bytes should be so coded.  The overhead for coding a
1348    run is 4 bytes (255, count, byte, data count), so runs > 4 bytes
1349    should be so coded.  Copies decode/execute faster and code more
1350    compactly so are preferred over runs.
1351
1352 */
1353
1354 const char PSBEGIN [] =         /* start of file */
1355   "%%!PS-Adobe-2.0 EPSF-2.0 \n"
1356   "%%%%Creator: efax (Copyright 1995 Ed Casas) \n"
1357   "%%%%Title: efix output\n"
1358   "%%%%Pages: (atend) \n"
1359   "%%%%BoundingBox: 0 0 %d %d \n"
1360   "%%%%BeginComments \n"
1361   "%%%%EndComments \n"
1362   "/val 1 string def \n"
1363   "/buf %d string def   \n"
1364   "/getval { \n"
1365   "  currentfile val readhexstring pop 0 get \n"
1366   "} bind def \n"
1367   "/readbuf { \n"
1368   "  0  %% => index \n"
1369   "  { \n"
1370   "    dup buf length ge { exit } if \n"
1371   "    getval   %% => index run_length \n"
1372   "    dup 127 le { \n"
1373   "      dup 0 eq { \n"
1374   "        pop buf length \n"
1375   "      } { \n"
1376   "        currentfile buf 3 index 3 index getinterval readhexstring pop pop\n"
1377   "      } ifelse \n"
1378   "    } { \n"
1379   "      dup 255 eq { \n"
1380   "        pop getval getval %% => index run_length value \n"
1381   "        2 index 1 3 index 2 index add 1 sub  %% => ... start 1 end \n"
1382   "          { buf exch 2 index put } for \n"
1383   "        pop \n"
1384   "      } { \n"
1385   "        127 sub \n"
1386   "      } ifelse \n"
1387   "    } ifelse \n"
1388   "    add %% => index \n"
1389   "  } loop \n"
1390   "  pop \n"
1391   "  buf \n"
1392   "} bind def \n"
1393   "%%%%EndProlog \n" ;
1394
1395 const char PSPAGE [] =          /* start of page */
1396   "%%%%Page: %d %d \n"
1397   "gsave \n"
1398   "%f %f translate \n"
1399   "%f %f scale \n"
1400   "%d %d %d [ %d %d %d %d %d %d ] { readbuf } image \n" ;
1401
1402 const char PSPAGEEND [] =       /* end of page */
1403   "\n"
1404   "grestore \n"
1405   "showpage \n" ;
1406
1407 const char PSEND [] =           /* end of file */
1408   "%%Trailer \n"
1409   "%%%%Pages: %d \n" ;
1410
1411
1412 void psinit ( OFILE *f, int newfile, int page, int w, int h, int n )
1413 {
1414   float ptw, pth ;
1415
1416   if ( ! f ) {
1417     msg ( "E2 can't happen (psinit)" ) ;
1418     return ;
1419   }
1420
1421   ptw = w/f->xres * 72.0 ;                 /* convert to points */
1422   pth = h/f->yres * 72.0 ;
1423
1424   if ( newfile )
1425     fprintf ( f->f, PSBEGIN, 
1426             (int) ptw, (int) pth,                /* Bounding Box */
1427             n ) ;                                /* buffer string length */
1428
1429   fprintf ( f->f, PSPAGE, 
1430           page, page,                            /* page number */
1431           0.0, 0.0,                              /* shift */
1432           ptw, pth,                              /* scaling */
1433           w, h, 1,                               /* image size */
1434           w, 0, 0, -h, 0, h ) ;                  /* CTM */
1435   f->pslines = 0 ;
1436   f->lastpageno = page ;
1437 }
1438
1439
1440 char nhexout = 0, hexchars [ 16 ] = "0123456789abcdef" ;
1441
1442 #define hexputc( f, c ) ( \
1443         putc ( hexchars [ (c) >>   4 ], f ), \
1444         putc ( hexchars [ (c) & 0x0f ], f ), \
1445         ( ( ( nhexout++ & 31 ) == 31 ) ? putc ( '\n', f ) : 0 ) )
1446
1447 void hexputs ( FILE *f, uchar *p, int n )
1448 {
1449   uchar c ;
1450   if ( n > 0 ) {
1451     hexputc ( f, n ) ;
1452     while ( n-- ) { c = *p++ ^ 0xff ; hexputc ( f, c ) ; }
1453   }
1454 }
1455
1456 /* Encode into postscript.  If not a repeated line, test (using
1457    index j) from current position (i) for possible encodings as:
1458    copy of > 2 bytes, runs of > 4 or data >=127.  Otherwise the
1459    byte is skipped. Uncoded bytes are output from the last
1460    uncoded byte (l) before output of runs/copies.  */
1461
1462 void pswrite ( OFILE *f, unsigned char *buf, int n )
1463 {
1464   int i, j, l ;
1465   static unsigned char last [ MAXBITS ] ;
1466   
1467   l=i=0 ;
1468
1469   if ( ! f || ! buf || n<0 ) {
1470     msg ( "E2 can't happen (pswrite)" ) ;
1471     return ;
1472   }
1473
1474   for ( j=0 ; j<n && buf[j]==last[j] && f->pslines ; j++ ) ;
1475   if ( j == n ) {               /* repeat line */
1476     hexputc ( f->f, 0 ) ;
1477     l=i=n ;
1478   }
1479
1480   while ( i<n ) {
1481
1482     for ( j=i ; j<n && buf[j]==last[j] && j-i<127 && f->pslines ; j++ ) ;
1483     if ( j-i > 2 ) {            /* skip */
1484       hexputs ( f->f, buf+l, i-l ) ;
1485       hexputc ( f->f, j-i + 127 ) ; 
1486       l=i=j ;
1487     } else {
1488       for ( j=i ; j<n && buf[j]==buf[i] && j-i<255 ; j++ ) ;
1489       if ( j-i > 4 ) {          /* run */
1490         hexputs ( f->f, buf+l, i-l ) ;
1491         hexputc ( f->f, 255 ) ; 
1492         hexputc ( f->f, j-i ) ; 
1493         hexputc ( f->f, buf[i] ^ 0xff ) ;
1494         l=i=j ;
1495       } else {
1496         if ( i-l >= 127 ) {     /* maximum data length */
1497           hexputs ( f->f, buf+l, i-l ) ;
1498           l=i ;
1499         } else {                /* data */
1500           i++ ;
1501         }
1502       }
1503     }
1504
1505   }
1506   hexputs ( f->f, buf+l, i-l ) ;
1507
1508   if ( n >= 0 ) 
1509     memcpy ( last, buf, n ) ;
1510
1511   f->pslines++ ;
1512 }
1513
1514
1515 /* Write 2- and 4-byte integers to an image output file.  Return
1516    as for fwrite. */
1517
1518 int fwrite2 ( short s, OFILE *f )
1519 {
1520   uchar *p = (void*) &s ;
1521   return fwrite ( bigendian ? p + sizeof(short) - 2 : p, 2, 1, f->f ) ;
1522 }
1523
1524 int fwrite4 ( long l, OFILE *f )
1525 {
1526   uchar *p = (void*) &l ;
1527   return fwrite ( bigendian ? p + sizeof(long ) - 4 : p, 4, 1, f->f ) ;
1528 }
1529
1530
1531 /* Write a TIFF directory tag.  Returns 0 if OK, 1 on errors. */
1532
1533 int wtag ( OFILE *f, int lng, short tag, short type, long count, long offset )
1534 {
1535   int err=0 ;
1536
1537   err = err || ! fwrite2 ( tag,   f ) ;
1538   err = err || ! fwrite2 ( type,  f ) ;
1539   err = err || ! fwrite4 ( count, f ) ;
1540   if ( lng ) {
1541     err = err || ! fwrite4 ( offset, f ) ;
1542   } else {
1543     err = err || ! fwrite2 ( offset, f ) ;
1544     err = err || ! fwrite2 (      0, f ) ;
1545   }
1546
1547   if ( err ) msg ( "ES2 can't write TIFF tag" ) ;
1548   return err ;
1549 }
1550
1551
1552 /* Write TIFF header and directory.  File format based on Sam
1553    Leffler's tiff.h.  Can only be used for single-image TIFFs
1554    because always seeks to start of file to re-write the
1555    header. */
1556
1557 #define NTAGS 17                      /* number of tags in directory */
1558 #define NRATIO 2                      /* number of floats (as ratios) */
1559
1560 int tiffinit ( OFILE *f )
1561 {
1562   int err=0, compr=1 ;
1563   long tdoff, doff ;
1564
1565   fseek ( f->f, 0, SEEK_SET ) ;
1566
1567   /* 0 ==> (start of TIFF file) */
1568
1569   /* write magic, TIFF version and offset to directory */
1570
1571   fwrite2 ( bigendian ? 0x4d4d : 0x4949, f ) ;
1572   fwrite2 ( 42, f ) ;
1573   fwrite4 ( 8, f ) ;
1574
1575   /* 8 ==> directory */
1576
1577   fwrite2 ( NTAGS, f ) ;
1578
1579   /* figure out offsets within file and compression code */
1580
1581   tdoff = 8 + 2 + NTAGS*12 + 4 ;     /* offset to directory data */
1582   doff = tdoff + NRATIO*8 ;          /* offset to image data */
1583
1584   switch ( f->format ) {
1585   case O_TIFF_RAW: compr = 1 ; break ;
1586   case O_TIFF_FAX: compr = 3 ; break ;
1587   default: err = msg ( "E2can't happen(tiffinit)" ) ; break ;
1588   }
1589
1590   /* write directory tags, 12 bytes each */
1591
1592   wtag( f, 1, 256, 4, 1, f->w ) ;     /* width long */
1593   wtag( f, 1, 257, 4, 1, f->h ) ;     /* length long */
1594   wtag( f, 0, 258, 3, 1, 1 ) ;        /* bits/sample short */
1595
1596   wtag( f, 0, 259, 3, 1, compr ) ;    /* compresssion(g3=3) short */
1597   wtag( f, 0, 262, 3, 1, 0 ) ;        /* photometric(0-min=white) short */
1598   wtag( f, 0, 266, 3, 1, 1 ) ;        /* fill order(msb2lsb=1) short */
1599   wtag( f, 1, 273, 4, 1, doff ) ;     /* strip offsets long */
1600
1601   wtag( f, 0, 274, 3, 1, 1 ) ;        /* orientation(1=normal) short */
1602   wtag( f, 0, 277, 3, 1, 1 ) ;        /* samples/pixel short */
1603   wtag( f, 1, 278, 4, 1, f->h ) ;     /* rows/strip long */
1604   wtag( f, 1, 279, 4, 1, f->bytes ) ; /* strip byte counts long */
1605
1606   wtag( f, 1, 282, 5, 1, tdoff+0 ) ;  /* xresolution ratio */
1607   wtag( f, 1, 283, 5, 1, tdoff+8 ) ;  /* yresolution ratio */
1608   wtag( f, 0, 284, 3, 1, 1 ) ;        /* storage(1=single plane) short */
1609   wtag( f, 1, 292, 4, 1, 0 ) ;        /* g3options long */
1610
1611   wtag( f, 0, 296, 3, 1, 2 ) ;        /* resolution units(2=in,3=cm) short */
1612   wtag( f, 0, 327, 3, 1, 0 ) ;        /* clean fax(0=clean) short */
1613   
1614   fwrite4 ( 0, f ) ;                  /* offset to next dir (no more) */
1615
1616   /* ==> tdoff (tag data offset), write ratios for floats here */
1617
1618   fwrite4 ( f->xres+0.5, f ) ;
1619   fwrite4 ( 1, f ) ;
1620   fwrite4 ( f->yres+0.5, f ) ;
1621   fwrite4 ( 1, f ) ;
1622
1623   /* ==> doff (strip data offset), image data goes here */
1624
1625   return err ;
1626 }
1627
1628
1629 /* Convert array 'runs' of 'nr' run lengths into a bit map 'buf'. Returns
1630    the number of bytes filled. */
1631
1632 int runtobit ( short *runs, int nr, uchar *buf )
1633 {
1634   static uchar zerofill [ 9 ] = { 
1635     0xff,  0xfe, 0xfc, 0xf8, 0xf0,  0xe0, 0xc0, 0x80, 0x00 } ;
1636   static uchar onefill [ 9 ] = { 
1637     0x00,  0x01, 0x03, 0x07, 0x0f,  0x1f, 0x3f, 0x7f, 0xff } ; 
1638
1639   uchar col=0, *buf0 = buf ;
1640   register short len, b=8, bytes ;
1641   
1642   while ( nr-- > 0 ) {
1643     len = *runs++ ;
1644     if ( col ) *buf |= onefill  [ b ] ;          /* right bits of cur. byte */
1645     else       *buf &= zerofill [ b ] ;
1646     if ( b > len ) {                             /* done fill */
1647       b -= len ;
1648     } else {                                     /* continue to next byte */
1649       len -= b ; 
1650       buf++ ; 
1651       b = 8 ;
1652       if ( ( bytes = len>>3 ) > 0 ) {            /* fill >1 byte */
1653         memset ( buf, col, bytes ) ;
1654         len -= bytes*8; 
1655         buf += bytes ;
1656       } 
1657       *buf = col ;                               /* flood the rest */
1658       b -= len ;
1659     }
1660     col ^= 0xff ;
1661   }
1662
1663   return buf - buf0 + ( b < 8 ) ;
1664 }
1665
1666
1667 /* Write a PCX file header. */
1668
1669 int fputi ( int i, OFILE *f )
1670 {
1671   putc ( i & 0xff, f->f ) ;
1672   putc ( ( i >> 8 ) & 0xff, f->f ) ;
1673   return 0 ;
1674 }
1675
1676 void pcxinit ( OFILE *f )
1677 {
1678   uchar buf [ 60 ] = { 0x0a, 3, 1, 1 } ; /* magic, version, compr, BPP */
1679   
1680   fwrite ( buf, 1, 4, f->f ) ;  /* 4 */
1681   fputi ( 0, f ) ;              /* 8 xmin, ymin, xmax, ymax */
1682   fputi ( 0, f ) ;
1683   fputi ( f->w-1, f ) ;
1684   fputi ( f->h-1, f ) ;
1685   fputi ( f->xres, f ) ;        /* 4 x and y dpi */
1686   fputi ( f->yres, f ) ;
1687   memset ( buf, 0, 48 ) ;       /* 48 palette */
1688   fwrite ( buf, 1, 48, f->f ) ;
1689   putc ( 0, f->f ) ;            /* 1 reserved */
1690   putc ( 1, f->f ) ;            /* 1 planes per pixel  */
1691   fputi ( (f->w+15)/16*2, f ) ; /* 2 bytes per line */
1692   memset ( buf, 0, 60 ) ;       /* 60 zero */
1693   fwrite ( buf, 1, 60, f->f ) ;
1694 }
1695
1696 /* Write a PCX-compressed scan line. */
1697
1698 void  pcxwrite ( OFILE *of, uchar *p, int nb )
1699 {
1700   int c, n, runc ;
1701   FILE *f = of->f ;
1702
1703   runc = *p++ ;
1704   n = 1 ;
1705
1706   for ( nb-- ; nb > 0 ; nb-- ) {
1707     c = *p++ ;
1708     if ( c == runc && n < 63 ) { /* continue run */
1709       n++ ;
1710     } else {            /* terminate run */
1711       if ( n > 1 || ( ( runc & 0xc0 ) == 0xc0 ) ) /* output as run */
1712         putc ( n | 0xc0, f ) ;
1713       putc ( runc, f ) ;
1714       runc = c ;        /* start new run */
1715       n = 1 ;
1716     }
1717   }
1718
1719   /* last run */
1720
1721   if ( n > 1 || ( ( runc & 0xc0 ) == 0xc0 ) ) /* output as run */
1722     putc ( n | 0xc0, f ) ;
1723   putc ( runc, f ) ;
1724
1725 }
1726
1727
1728 /* Begin/end output pages.  If not starting first page (0), terminate
1729    previous page.  If output filename pattern is defined, [re-]opens that
1730    file.  If not terminating last page (page==EOF), writes file header.
1731    Returns 0 or 2 on errors. */
1732
1733 int nextopage ( OFILE *f, int page )
1734 {
1735   int err = 0 ;
1736   int i, nb=0 ;
1737   uchar *p, codes [ ( RTCEOL * EOLBITS ) / 8 + 3 ] ;
1738   
1739   if ( f->f ) { /* terminate previous page */
1740
1741     switch ( f->format ) {
1742     case O_PBM:
1743       break ;
1744     case O_PGM:
1745       break ;
1746     case O_FAX:
1747     case O_TIFF_FAX:
1748       for ( p = codes, i=0 ; i<RTCEOL ; i++ ) 
1749         p = putcode ( &f->e, EOLCODE, EOLBITS, p ) ;
1750       nb = putcode ( &f->e, 0, 0, p ) - codes ;
1751       fwrite ( codes, 1, nb, f->f ) ;
1752       f->bytes += nb ;
1753       if ( f->format == O_TIFF_FAX ) tiffinit ( f ) ;
1754       break ;
1755     case O_TIFF_RAW:
1756       tiffinit(f) ;             /* rewind & update TIFF header */
1757       break ;
1758     case O_PCL:
1759       fprintf ( f->f, PCLEND ) ;
1760       break ;
1761     case O_PS:
1762       fprintf ( f->f, PSPAGEEND ) ;
1763       if ( f->fname || page<0 ) fprintf ( f->f, PSEND, f->lastpageno ) ;
1764       break ;
1765     case O_PCX:
1766     case O_PCX_RAW:
1767       fseek ( f->f, 0, SEEK_SET ) ;
1768       pcxinit ( f ) ;
1769       break ;
1770     }
1771
1772     if ( ferror ( f->f ) ) {
1773       err = msg ("ES2output error:" ) ;
1774     } else {
1775       msg ( "F+ wrote %s as %dx%d pixel %.fx%.f dpi %s page", 
1776            f->cfname, f->w, f->h, f->xres, f->yres, 
1777            oformatname [f->format] ) ;
1778       
1779       switch ( f->format ) {
1780       case O_PS: 
1781         msg ( "F  (%d lines)", f->pslines ) ;
1782         break ;
1783       case O_TIFF_RAW:
1784       case O_TIFF_FAX:
1785         msg ( "F  (%d bytes)", f->bytes ) ;
1786         break ;
1787       default:
1788         msg ( "F " ) ;
1789         break ;
1790       }
1791
1792     }
1793
1794   }
1795
1796   if ( ! err && page >= 0 ) {   /* open new file */
1797     if ( f->fname ) {
1798       sprintf ( f->cfname, f->fname, page+1, page+1, page+1 ) ;
1799
1800       if ( ! f->f )
1801         f->f = fopen ( f->cfname, ( f->format == O_PS ) ? "w" : "wb+" ) ;
1802       else
1803         f->f = freopen ( f->cfname, ( f->format == O_PS ) ? "w" : "wb+", f->f ) ;
1804
1805       if ( ! f->f ) {
1806         err = msg ("ES2can't open output file %s:", f->cfname ) ;
1807       }
1808     } else {
1809       f->f = stdout ;
1810       strcpy ( f->cfname, "standard output" ) ;
1811     }
1812   }
1813
1814   /* start new page */
1815
1816   if ( ! err && page >= 0 ) {
1817     switch ( f->format ) {
1818     case  O_PBM:
1819       fprintf ( f->f, "P4 %d %d\n", f->w, f->h ) ;
1820       break ;
1821     case  O_PGM:
1822       fprintf ( f->f, "P5 %d %d %d\n", f->w/4, f->h/4, 255 ) ;
1823       break ;
1824     case O_FAX:
1825     case O_TIFF_FAX:
1826       if ( f->format == O_TIFF_FAX ) tiffinit ( f ) ;
1827       p = putcode ( &f->e, EOLCODE, EOLBITS, codes ) ;
1828       nb = p - codes ;
1829       fwrite ( codes, 1, nb, f->f ) ;
1830       break ;
1831     case O_TIFF_RAW:
1832       tiffinit ( f ) ;
1833       break ;
1834     case O_PCL:
1835       fprintf ( f->f, PCLBEGIN, (int) f->xres ) ;
1836       break ;
1837     case O_PS:
1838       psinit ( f, ( f->fname || page==0 ), page+1, f->w, f->h, f->w/8 ) ;
1839       break ;
1840     case O_PCX:
1841     case O_PCX_RAW:
1842       fseek ( f->f, 0, SEEK_SET ) ;
1843       pcxinit ( f ) ;
1844       break ;
1845     }
1846
1847     if ( ferror ( f->f ) ) err = msg ("ES2output error:" ) ;
1848   }
1849
1850   /* only count lines/bytes for those formats that don't have
1851      headers or where we will update the headers on closing */
1852
1853   switch ( f->format ) {
1854   case O_FAX:
1855   case O_TIFF_FAX:
1856   case O_PCX:
1857   case O_PCX_RAW:
1858     f->h = 0 ;
1859     f->bytes = nb ;
1860     break ;
1861   }
1862
1863   return err ;
1864 }
1865
1866
1867 /* Output scan line of nr runs no times to output file f. */
1868
1869 void writeline ( OFILE *f, short *runs, int nr, int no )
1870 {
1871   int nb = 0 ;
1872   uchar *p, buf [ MAXCODES ] ;
1873
1874   /* if line to be output, convert to right format */
1875
1876   if ( no > 0 )
1877     switch ( f->format ) {
1878     case O_PBM:
1879     case O_PGM:
1880     case O_PCL:
1881     case O_PS:
1882     case O_TIFF_RAW:
1883     case O_PCX:
1884     case O_PCX_RAW:
1885       nb = runtobit ( runs, nr, buf ) ;
1886       break ;
1887     case O_FAX:
1888     case O_TIFF_FAX:
1889       break ;
1890     }
1891   
1892   /* output `no' times. */
1893     
1894   while ( no-- > 0 ) {
1895     switch ( f->format ) {
1896     case O_PCX_RAW:
1897     case O_TIFF_RAW:
1898     case O_PBM:
1899       fwrite ( buf, 1, nb, f->f ) ;
1900       break ;
1901     case O_PGM:
1902       pgmwrite ( f, buf, nb ) ;
1903       break ;
1904     case O_TIFF_FAX:
1905     case O_FAX:
1906       p = runtocode ( &f->e, runs, nr, buf ) ;
1907       p = putcode ( &f->e, EOLCODE, EOLBITS, p ) ;
1908       nb = p - buf ;
1909       fwrite ( buf, 1, nb, f->f ) ;
1910       break ;
1911     case O_PCL:
1912       pclwrite ( f, buf, nb ) ;
1913       break ;
1914     case O_PS:
1915       pswrite ( f, buf, nb ) ;
1916       break ;
1917     case O_PCX:
1918       pcxwrite ( f, buf, nb ) ;
1919       break ;
1920     }
1921
1922   /* only count lines/bytes for those formats that don't have
1923      headers or where we will update the headers on closing */
1924
1925     switch ( f->format ) {
1926     case O_FAX:
1927     case O_TIFF_FAX:
1928     case O_TIFF_RAW:
1929     case O_PCX:
1930     case O_PCX_RAW:
1931       f->h++ ;
1932       f->bytes += nb ;
1933       break ;
1934     }
1935     
1936   }
1937 }
1938
1939
1940 /* Initialize new output file. If fname is NULL, stdout will be used for
1941    all images. */
1942
1943 void newOFILE ( OFILE *f, int format, char *fname, 
1944                float xres, float yres, int w, int h )
1945 {
1946   f->f = 0 ;
1947   f->format = format ;
1948   f->fname = fname ;
1949   f->xres = xres ;
1950   f->yres = yres ;
1951   f->w = w ;
1952   f->h = h ;
1953   f->bytes = 0 ;
1954   newENCODER ( &f->e ) ;
1955 }
1956
1957 /* Read a bitmap to use as a font and fill in the font data.  If
1958    the file name is null, empty, or there are errors, the font is
1959    initialized to the built-in font. Returns 0 if OK, 2 on
1960    errors. */
1961
1962 int readfont ( char *fname, faxfont *font )
1963 {
1964   int err=0, i, j, n=0, nr, nb, fontok=0, pels ;
1965   char *fnames [2] = { 0, 0 } ;
1966   short runs [ MAXRUNS ] ;
1967   IFILE f;
1968
1969   if ( fname && *fname ) {
1970
1971     fnames[0] = fname ;
1972     
1973     newIFILE ( &f, fnames ) ;
1974     
1975     if ( nextipage ( &f, 0 ) ) {
1976       err = msg ( "E2 can't open font file %s", fnames[0] ) ;
1977     }
1978     
1979     nb = 0 ;
1980     while ( ! err && ( nr = readline ( &f, runs, &pels ) ) >= 0 ) {
1981       if ( nb+pels/8 < MAXFONTBUF ) {
1982         nb += runtobit ( runs, nr, font->buf+nb ) ;
1983       } else {
1984         err = msg ("E2font file %s too large (max %d bytes)", 
1985                    fnames[0], MAXFONTBUF ) ;
1986       }
1987     }
1988     
1989     if ( ! err && nb != f.page->w * f.page->h / 8 )
1990       err = msg ( "E2 read %d bytes of font data for %dx%d bitmap",
1991                  nb, f.page->w, f.page->h ) ;
1992     
1993     if ( ! err && ( f.page->w / 256 > MAXFONTW || f.page->h > MAXFONTH ) ) {
1994       err = msg ( "E2font size (%dx%d) too large", f.page->w, f.page->h ) ;
1995     }
1996     
1997     if ( err ) {
1998       font->w = font->h = 0 ;
1999     } else {
2000       font->w = f.page->w / 256 ;
2001       font->h = f.page->h ;
2002       for ( i=0 ; i<256 ; i++ ) font->offset[i] = i*font->w ;
2003       msg ("Iread %dx%d font %s (%d bytes)", font->w, font->h, fname, nb ) ;
2004       fontok = 1 ;
2005     }
2006
2007     if ( f.f ) {
2008       fclose ( f.f ) ;
2009       f.f = 0 ;
2010     }
2011   }    
2012
2013   if ( ! fontok ) {                /* use built-in font */
2014
2015     font->w = STDFONTW ;
2016     font->h = STDFONTH ;
2017
2018     for ( i=j=0 ; j<STDFONTBUF ; i++ )     /* expand bit map */
2019       if ( stdfont [ i ] == 0 )
2020         for ( n = stdfont [ ++i ] ; n > 0 ; n-- ) 
2021           font->buf [ j++ ] = 0 ;
2022       else
2023         font->buf [ j++ ] = stdfont [ i ] ;
2024
2025     if ( i != 1980 ) err = msg ( "E2can't happen(readfont)" ) ;
2026
2027     for ( i=0 ; i<256 ; i++ ) font->offset[i] = i*font->w ;
2028   }
2029
2030   return err ;
2031 }
2032
2033
2034 /* Initialize bit reversal lookup tables (note that the
2035    `normalbits' array is the one actually used for the bit
2036    reversal.  */
2037
2038 void initbittab ( void )
2039 {
2040   int i ;
2041   for ( i=0 ; i<256 ; i++ ) 
2042     normalbits [ reversebits [ i ] = i ] = 
2043       ( i& 1 ? 128:0 ) | ( i& 2 ? 64:0 ) | ( i& 4 ? 32:0 ) | ( i&  8 ? 16:0 ) |
2044       ( i&16 ?   8:0 ) | ( i&32 ?  4:0 ) | ( i&64 ?  2:0 ) | ( i&128 ?  1:0 ) ;
2045 }
2046
2047
2048                    /* T.4 Encoding/Decoding */
2049
2050 /* Table-lookup decoder for variable-bit-length codewords.  The table index
2051    is the N most recently undecoded bits with the first (oldest) undecoded
2052    bit as the MS bit.  If the N bits uniquely identify a codeword then the
2053    indexed 'code' member identifies the code, otherwise it is zero.  The
2054    'bits' member gives the number of bits to be considered decoded (to be
2055    removed from the bit stream) and the 'next' element is a pointer to the
2056    table to use for decoding the next part of the bit sequence.
2057
2058    For T.4 decoding the longest T.4 codeword is 13 bits. The implementation
2059    below uses two tables of 512 elements (N=9 bits) for each colour.
2060    Codewords longer than 9 bits require a second lookup.  Since all
2061    codewords longer than than 9 bits have a 4-bit zero prefix it is
2062    possible to use only one secondary 9-bit lookup table by dropping only
2063    the first 4 bits after the first lookup. The code indentifier is the run
2064    length + 1. A separate table is used for decoding the variable-length
2065    FILL patterns.
2066
2067    For undefined codewords, one bit is skipped and decoding continues at
2068    the white code table. */
2069
2070 /* the lookup tables for each colour and the fill lookup table */
2071
2072 dtab tw1 [ 512 ], tw2 [ 512 ], tb1 [ 512 ], tb2 [ 512 ], fill [ 512 ] ;
2073 char tabinit=0 ;
2074
2075 /* Add code cword shifted left by shift to decoding table tab. */
2076
2077 void addcode ( dtab *tab, int cword, int shift, 
2078               short code, short bits, dtab *next )
2079 {
2080   int i, n = 1 << shift ;
2081   
2082   for ( i = cword << shift ; n-- > 0 ; i++ ) {
2083     tab[i].code = code ;
2084     tab[i].bits = bits ;
2085     tab[i].next = next ;
2086   }
2087 }
2088
2089 /* Initialize the decoding table for one colour using the codes in the T.4
2090    table p0.  t1 and t2 are the two decoding tables and ot is the first
2091    table of the other colour. */
2092
2093 void init1dtab ( t4tab *p0, dtab *t1, dtab *t2, dtab *ot )
2094 {
2095   t4tab *p ;
2096   for ( p = p0 ; p->code ; p++ ) 
2097     if ( p->bits <= 9 ) {
2098       addcode ( t1, p->code, 9 - p->bits, p->rlen + 1, p->bits,   
2099                ( p - p0 ) > 63 ? t1 : ot ) ;
2100     } else {
2101       addcode ( t1, p->code >> ( p->bits - 9 ), 0, 0, 4, t2 ) ;
2102       addcode ( t2, p->code, 13 - p->bits, p->rlen + 1, p->bits - 4, 
2103                ( p - p0 ) > 63 ? t1 : ot ) ;
2104     }
2105 }
2106
2107
2108 /* Initialize a T.4 decoder.   */
2109
2110 void newDECODER ( DECODER *d )
2111 {
2112   int i ;
2113
2114   if ( ! tabinit ) {
2115
2116     /* undefined codes */
2117
2118     addcode ( tw1,  0, 9, 0, 1, tw1 ) ;
2119     addcode ( tw2,  0, 9, 0, 1, tw1 ) ;
2120     addcode ( tb1,  0, 9, 0, 1, tw1 ) ;
2121     addcode ( tb2,  0, 9, 0, 1, tw1 ) ;
2122     addcode ( fill, 0, 9, 0, 1, tw1 ) ;
2123   
2124     /* fill and EOL */
2125
2126     addcode ( tw1, 0, 0, 0, 4, tw2 ) ;
2127     addcode ( tw2, 0, 2, 0, 7, fill ) ;
2128     addcode ( tb1, 0, 0, 0, 4, tb2 ) ;
2129     addcode ( tb2, 0, 2, 0, 7, fill ) ;
2130
2131     addcode ( fill, 0, 0, 0, 9, fill ) ;
2132     for ( i=0 ; i<=8 ; i++ )
2133       addcode ( fill, 1, i, -1, 9-i, tw1 ) ;
2134
2135     /* white and black runs */
2136     
2137     init1dtab ( wtab, tw1, tw2, tb1 ) ;
2138     init1dtab ( btab, tb1, tb2, tw1 ) ;
2139
2140     tabinit=1 ;
2141   }
2142
2143   /* initialize decoder to starting state */
2144
2145   d->x = 0 ;
2146   d->shift = -9 ;
2147   d->tab = tw1 ;
2148   d->eolcnt = 0 ;
2149 }
2150
2151       /* T.4 coding table and default font for efax/efix */
2152
2153 /* T.4 1-D run-length coding tables. codes must be in run length
2154    order for runtocode(). */
2155
2156 t4tab wtab [ ( 64 + 27 + 13 ) + 1 ] = { /* runs of white */
2157
2158 /*  Terminating White Codes */
2159
2160 {53,8,0},    {7,6,1},     {7,4,2},     {8,4,3},     {11,4,4},    {12,4,5},
2161 {14,4,6},    {15,4,7},    {19,5,8},    {20,5,9},    {7,5,10},    {8,5,11},
2162 {8,6,12},    {3,6,13},    {52,6,14},   {53,6,15},   {42,6,16},   {43,6,17},
2163 {39,7,18},   {12,7,19},   {8,7,20},    {23,7,21},   {3,7,22},    {4,7,23},
2164 {40,7,24},   {43,7,25},   {19,7,26},   {36,7,27},   {24,7,28},   {2,8,29},
2165 {3,8,30},    {26,8,31},   {27,8,32},   {18,8,33},   {19,8,34},   {20,8,35},
2166 {21,8,36},   {22,8,37},   {23,8,38},   {40,8,39},   {41,8,40},   {42,8,41},
2167 {43,8,42},   {44,8,43},   {45,8,44},   {4,8,45},    {5,8,46},    {10,8,47},
2168 {11,8,48},   {82,8,49},   {83,8,50},   {84,8,51},   {85,8,52},   {36,8,53},
2169 {37,8,54},   {88,8,55},   {89,8,56},   {90,8,57},   {91,8,58},   {74,8,59},
2170 {75,8,60},   {50,8,61},   {51,8,62},   {52,8,63},   
2171
2172 /*  Make Up White Codes */
2173
2174 {27,5,64},   {18,5,128},  {23,6,192},  {55,7,256},  {54,8,320},  {55,8,384},
2175 {100,8,448}, {101,8,512}, {104,8,576}, {103,8,640}, {204,9,704}, {205,9,768},
2176 {210,9,832}, {211,9,896}, {212,9,960}, {213,9,1024},{214,9,1088},{215,9,1152},
2177 {216,9,1216},{217,9,1280},{218,9,1344},{219,9,1408},{152,9,1472},{153,9,1536},
2178 {154,9,1600},{24,6,1664}, {155,9,1728},
2179
2180 /*  Extended Make Up Codes (Black and White) */
2181
2182 {8,11,1792}, {12,11,1856},{13,11,1920},{18,12,1984},{19,12,2048},{20,12,2112},
2183 {21,12,2176},{22,12,2240},{23,12,2304},{28,12,2368},{29,12,2432},{30,12,2496},
2184 {31,12,2560},
2185
2186 {0,0,0}  } ;
2187
2188 t4tab btab [ ( 64 + 27 + 13 ) + 1 ] = { /* runs of black */
2189
2190 /*  Terminating Black Codes */
2191
2192 {55,10,0},   {2,3,1},     {3,2,2},     {2,2,3},     {3,3,4},     {3,4,5},
2193 {2,4,6},     {3,5,7},     {5,6,8},     {4,6,9},     {4,7,10},    {5,7,11},
2194 {7,7,12},    {4,8,13},    {7,8,14},    {24,9,15},   {23,10,16},  {24,10,17},
2195 {8,10,18},   {103,11,19}, {104,11,20}, {108,11,21}, {55,11,22},  {40,11,23},
2196 {23,11,24},  {24,11,25},  {202,12,26}, {203,12,27}, {204,12,28}, {205,12,29},
2197 {104,12,30}, {105,12,31}, {106,12,32}, {107,12,33}, {210,12,34}, {211,12,35},
2198 {212,12,36}, {213,12,37}, {214,12,38}, {215,12,39}, {108,12,40}, {109,12,41},
2199 {218,12,42}, {219,12,43}, {84,12,44},  {85,12,45},  {86,12,46},  {87,12,47},
2200 {100,12,48}, {101,12,49}, {82,12,50},  {83,12,51},  {36,12,52},  {55,12,53},
2201 {56,12,54},  {39,12,55},  {40,12,56},  {88,12,57},  {89,12,58},  {43,12,59},
2202 {44,12,60},  {90,12,61},  {102,12,62}, {103,12,63}, 
2203
2204 /*  Make Up Black Codes */
2205
2206 {15,10,64},  {200,12,128},{201,12,192},{91,12,256}, {51,12,320}, {52,12,384},
2207 {53,12,448}, {108,13,512},{109,13,576},{74,13,640}, {75,13,704}, {76,13,768},
2208 {77,13,832}, {114,13,896},{115,13,960},{116,13,1024},{117,13,1088},
2209 {118,13,1152},
2210 {119,13,1216},{82,13,1280},{83,13,1344},{84,13,1408},{85,13,1472},{90,13,1536},
2211 {91,13,1600},{100,13,1664},{101,13,1728},
2212
2213 /*  Extended Make Up Codes (Black and White) */
2214
2215 {8,11,1792}, {12,11,1856},{13,11,1920},{18,12,1984},{19,12,2048},{20,12,2112},
2216 {21,12,2176},{22,12,2240},{23,12,2304},{28,12,2368},{29,12,2432},{30,12,2496},
2217 {31,12,2560},
2218
2219 {0,0,0}  } ;
2220
2221
2222 /* The built-in 8x16 font.  Runs of zeroes are coded as 0
2223    followed by the repetition count. */
2224
2225 uchar stdfont [ 1980 ] = {
2226 0,255,0,255,0,194,8,4,12,10,18,0,3,16,4,8,20,8,4,8,20,0,1,10,8,4,
2227 4,10,18,0,2,16,4,8,20,4,0,68,20,0,1,8,0,2,12,6,48,0,5,2,0,43,14,32,
2228 56,0,2,12,0,1,32,0,1,2,0,1,14,0,1,32,8,4,32,56,0,14,6,8,48,0,40,8,
2229 0,1,18,0,6,30,0,4,4,0,11,4,8,18,20,18,12,0,2,8,8,20,20,4,8,20,20,
2230 0,1,20,4,8,10,20,18,0,2,8,8,20,20,8,0,1,24,8,4,8,10,20,12,0,2,8,4,
2231 8,20,16,8,8,20,54,10,8,4,8,10,20,0,2,16,4,8,20,4,0,1,20,0,33,12,20,
2232 18,28,48,12,12,8,8,8,0,4,2,28,8,28,28,4,62,28,62,28,28,0,5,60,28,
2233 12,60,14,56,62,30,14,34,62,62,33,16,33,34,12,60,12,60,30,127,34,33,
2234 65,34,34,62,8,32,8,8,0,1,24,0,1,32,0,1,2,0,1,16,0,1,32,8,4,32,8,0,
2235 7,16,0,6,8,8,8,0,36,4,14,0,1,34,8,12,18,28,24,0,3,28,0,1,24,0,1,28,
2236 28,8,0,1,30,0,2,8,28,0,1,100,100,98,0,6,18,31,14,0,8,56,0,7,13,0,
2237 5,32,36,4,8,20,20,20,18,0,2,4,8,20,20,8,16,20,20,8,20,4,8,20,20,20,
2238 0,2,8,8,20,20,8,32,20,0,33,12,20,18,42,73,18,24,8,8,42,8,0,3,4,34,
2239 24,34,34,12,32,34,2,34,34,0,2,2,0,1,16,2,34,12,34,18,36,32,16,18,
2240 34,8,8,34,16,51,50,18,34,18,34,32,8,34,33,73,34,34,2,8,16,8,8,0,1,
2241 24,0,1,32,0,1,2,0,1,16,0,1,32,0,2,32,8,0,7,16,0,6,8,8,8,0,36,15,16,
2242 65,34,8,18,0,1,34,4,0,3,34,0,1,36,8,2,2,0,2,58,0,2,56,34,0,1,36,36,
2243 18,0,1,12,12,12,12,12,12,24,18,62,62,62,62,62,62,62,62,36,34,12,12,
2244 12,12,12,0,1,18,34,34,34,34,34,32,36,0,5,12,0,10,52,0,6,8,0,6,32,
2245 0,34,12,0,1,63,40,74,18,0,1,16,4,20,8,0,3,4,34,40,2,2,20,32,32,2,
2246 34,34,24,24,4,0,1,8,2,78,18,34,32,34,32,16,32,34,8,8,36,16,51,50,
2247 33,34,33,34,32,8,34,33,73,20,34,4,8,16,8,20,0,2,28,44,14,30,28,62,
2248 30,44,56,60,34,8,82,44,28,44,30,22,30,62,34,34,65,34,34,62,8,8,8,
2249 0,35,12,20,16,62,34,8,16,0,1,77,4,0,3,93,0,1,24,8,2,12,0,1,34,58,
2250 0,2,8,34,0,1,40,40,100,4,12,12,12,12,12,12,40,32,32,32,32,32,8,8,
2251 8,8,34,50,18,18,18,18,18,34,35,34,34,34,34,34,60,40,28,28,28,28,28,
2252 28,54,14,28,28,28,28,56,56,56,56,2,44,28,28,28,28,28,8,29,34,34,34,
2253 34,34,44,34,0,33,12,0,1,18,24,52,12,0,1,16,4,42,8,0,3,8,34,8,2,2,
2254 36,60,32,4,34,34,24,24,8,127,4,2,82,18,34,32,34,32,16,32,34,8,8,40,
2255 16,45,42,33,34,33,34,48,8,34,33,73,20,20,4,8,8,8,20,0,2,34,50,16,
2256 34,34,16,34,50,8,4,36,8,109,50,34,50,34,24,32,16,34,34,73,34,34,2,
2257 4,8,16,57,0,34,12,36,16,34,20,0,1,40,0,1,81,28,18,127,0,1,89,0,2,
2258 127,12,2,0,1,34,58,28,0,1,8,34,36,40,40,24,4,18,18,18,18,18,18,40,
2259 32,32,32,32,32,8,8,8,8,34,50,33,33,33,33,33,20,37,34,34,34,34,20,
2260 34,40,34,34,34,34,34,34,9,16,34,34,34,34,8,8,8,8,30,50,34,34,34,34,
2261 34,0,1,34,34,34,34,34,34,50,34,0,33,12,0,1,18,12,8,25,0,1,16,4,8,
2262 127,0,1,127,0,1,8,34,8,4,12,68,2,60,8,28,30,0,2,16,0,1,2,28,82,18,
2263 60,32,34,60,30,32,62,8,8,56,16,45,42,33,34,33,60,28,8,34,18,85,8,
2264 20,8,8,8,8,34,0,2,2,34,32,34,34,16,34,34,8,4,40,8,73,34,34,34,34,
2265 16,32,16,34,34,73,20,34,4,24,8,12,78,0,35,36,60,34,62,0,1,36,0,1,
2266 81,36,36,1,28,85,0,2,8,16,2,0,1,34,26,28,0,1,8,34,18,18,22,106,0,
2267 1,18,18,18,18,18,18,47,32,60,60,60,60,8,8,8,8,122,42,33,33,33,33,
2268 33,8,45,34,34,34,34,20,34,36,2,2,2,2,2,2,9,32,34,34,34,34,8,8,8,8,
2269 34,34,34,34,34,34,34,127,38,34,34,34,34,34,34,34,0,33,8,0,1,63,10,
2270 22,37,0,1,16,4,0,1,8,0,3,8,34,8,8,2,126,2,34,8,34,2,0,2,8,127,4,16,
2271 86,63,34,32,34,32,16,34,34,8,8,36,16,45,38,33,60,33,36,6,8,34,18,
2272 54,20,8,16,8,8,8,34,0,2,30,34,32,34,62,16,34,34,8,4,56,8,73,34,34,
2273 34,34,16,28,16,34,20,85,8,20,8,4,8,16,0,35,8,36,16,34,8,8,18,0,1,
2274 81,26,72,1,0,1,34,0,2,8,30,28,0,1,34,10,28,0,1,8,28,9,22,17,22,4,
2275 63,63,63,63,63,63,120,32,32,32,32,32,8,8,8,8,34,42,33,33,33,33,33,
2276 20,41,34,34,34,34,8,34,34,30,30,30,30,30,30,63,32,62,62,62,62,8,8,
2277 8,8,34,34,34,34,34,34,34,0,1,42,34,34,34,34,20,34,20,0,35,18,10,41,
2278 34,0,1,16,4,0,1,8,0,3,16,34,8,16,2,4,2,34,16,34,2,0,2,4,0,1,8,0,1,
2279 73,33,34,32,34,32,16,34,34,8,8,34,16,33,38,33,32,33,34,2,8,34,18,
2280 34,20,8,16,8,4,8,0,3,34,34,32,34,32,16,38,34,8,4,36,8,73,34,34,34,
2281 34,16,2,16,34,20,34,20,20,16,8,8,8,0,35,12,20,16,62,62,8,10,0,1,77,
2282 0,1,36,1,0,1,28,0,6,34,10,0,4,18,42,34,42,28,33,33,33,33,33,33,72,
2283 32,32,32,32,32,8,8,8,8,34,38,33,33,33,33,33,34,49,34,34,34,34,8,60,
2284 34,34,34,34,34,34,34,72,32,32,32,32,32,8,8,8,8,34,34,34,34,34,34,
2285 34,8,50,34,34,34,34,20,34,20,0,33,12,0,1,18,42,73,34,0,1,8,8,0,1,
2286 8,12,0,1,24,16,34,8,32,34,4,34,34,16,34,34,24,24,2,0,1,16,16,32,33,
2287 34,16,36,32,16,18,34,8,8,33,16,33,34,18,32,18,34,2,8,34,12,34,34,
2288 8,32,8,4,8,0,3,34,34,16,38,34,16,26,34,8,4,34,8,73,34,34,34,38,16,
2289 2,16,38,8,34,34,8,32,8,8,8,0,35,12,15,16,65,8,8,4,0,1,34,0,1,18,0,
2290 5,127,0,3,54,10,0,4,36,79,68,79,32,33,33,33,33,33,33,72,16,32,32,
2291 32,32,8,8,8,8,36,38,18,18,18,18,18,0,1,18,34,34,34,34,8,32,34,34,
2292 34,34,34,34,34,72,16,34,34,34,34,8,8,8,8,34,34,34,34,34,34,34,8,34,
2293 38,38,38,38,8,34,8,0,33,12,0,1,18,28,6,29,0,1,8,8,0,2,12,0,1,24,32,
2294 28,8,62,28,4,28,28,16,28,28,24,24,0,3,16,28,33,60,14,56,62,16,14,
2295 34,62,112,33,30,33,34,12,32,12,34,60,8,28,12,34,34,8,62,8,2,8,0,3,
2296 29,60,14,26,28,16,2,34,8,4,33,8,73,34,28,60,26,16,60,14,26,8,34,34,
2297 8,62,8,8,8,0,35,12,4,62,0,1,8,8,36,0,1,28,0,11,42,10,0,5,66,71,66,
2298 32,33,33,33,33,33,33,79,14,62,62,62,62,62,62,62,62,56,34,12,12,12,
2299 12,12,0,1,44,28,28,28,28,8,32,36,29,29,29,29,29,29,55,14,28,28,28,
2300 28,8,8,8,8,28,34,28,28,28,28,28,0,1,92,26,26,26,26,8,60,8,0,36,8,
2301 0,3,6,48,0,2,24,0,2,32,0,11,48,0,21,6,0,9,14,2,56,0,1,127,0,7,2,0,
2302 2,4,0,5,32,2,0,7,16,0,1,6,8,48,0,35,12,0,4,8,24,0,13,32,10,0,1,4,
2303 0,6,32,0,7,4,0,31,4,0,21,16,32,16,0,81,3,0,21,28,0,2,56,0,5,32,2,
2304 0,7,48,0,39,12,0,19,32,0,2,24,0,6,30,0,7,24,0,31,24,0,21,48,32,48,
2305 0,255,0,1
2306 } ;