--- netpbm-free-10.0.orig/GNUmakefile
+++ netpbm-free-10.0/GNUmakefile
@@ -233,15 +233,13 @@
 	for i in urt shhopt buildtools; do \
 	    $(MAKE) -C $$i -f $(SRCDIR)/$$i/Makefile clean ; \
 	done
-	mkdir -p lib/static lib/shared
 	-rm lib/*/*
 
 .PHONY: distclean
 distclean: clean
 	rm -f Makefile.config
 
-build-env: 
-	mkdir -p lib/static lib/shared
+shhopt/netpbm-shhopt.h:
 	ln -sf shhopt.h shhopt/netpbm-shhopt.h
 
 # The following endif is for the else block that contains virtually the
--- netpbm-free-10.0.orig/HISTORY
+++ netpbm-free-10.0/HISTORY
@@ -72,6 +72,18 @@
 CHANGE HISTORY 
 --------------
 
+04.01.16 ABa
+
+added st4topgm. Thanks to Justin Pryzby <justinpryzby@users.sourceforge.net>
+
+winicontoppm can now handle 24/32 bpp. Thanks to Lee Benfield <lee@benf.org>.
+
+Fixed bug in pnmnorm with too large values. Thanks to Adam M. Costello"
+  <bug.amc+1@nicemice.net> #129452
+
+Fixed bug in ppmtobpm with invalid bpp-values. Thanks to
+  YAMASHITA Junji <ysjj@unixuser.org> #227125
+
 04.01.04 ABa
 
 Export now pm_canonstr, pm_openColornameFile, pm_colorget, pm_rgbnorm,
--- netpbm-free-10.0.orig/buildtools/depend.pl
+++ netpbm-free-10.0/buildtools/depend.pl
@@ -15,18 +15,16 @@
 
 foreach $i ('ppm', 'pbm', 'pgm', 'pnm') {
 	foreach $j (@$i) {
-#		foreach $l ('shared', 'static') {
-#		print "lib/shared/$j.o: lib/shared\n";
-		print "lib/shared/$j.o: $i/$j.c\n";
+		print "lib/shared/$j.o: $i/$j.c shhopt/netpbm-shhopt.h\n";
+		print "\tmkdir -p lib/shared\n";
 		print "\t\$(CC) -c \$(INCLUDE) -I \$(SRCDIR)/include/ ".
 			"-I \$(SRCDIR)/shhopt/ ".
 			"\$(CFLAGS) -fPIC -D_REENTRANT \$(CDEBUG) -o \$@ \$<\n\n";
-#		print "lib/static/$j.o: lib/static\n";
-		print "lib/static/$j.o: $i/$j.c\n";
+		print "lib/static/$j.o: $i/$j.c shhopt/netpbm-shhopt.h\n";
+		print "\tmkdir -p lib/static\n";
 		print "\t\$(CC) -c \$(INCLUDE) -I \$(SRCDIR)/include/ ".
 			"-I \$(SRCDIR)/shhopt/ ".
 			"\$(CFLAGS) -D_REENTRANT \$(CDEBUG) -o \$@ \$<\n\n";
-#		}
 		print "lib/static/lib$i.a: lib/static/$j.o\n";
 		print "lib/static/libnetpbm.a: lib/static/$j.o\n";
 		print "lib/shared/lib$i.so.9.$min{$i}: lib/shared/$j.o\n";
@@ -39,18 +37,22 @@
 print "lib/shared/libpbm.so.9.$min{'pbm'}: lib/shared/shhopt.o\n";
 print "lib/shared/libnetpbm.so.10.0: lib/shared/shhopt.o\n";
 
-print "lib/shared/shhopt.o: shhopt/shhopt.c\n";
+print "lib/shared/shhopt.o: shhopt/shhopt.c shhopt/netpbm-shhopt.h\n";
+print "\tmkdir -p lib/shared\n";
 print "\t\$(CC) -c \$(INCLUDE) -I \$(SRCDIR)/include/ ".
 	"-I \$(SRCDIR)/shhopt/ ".
 	"\$(CFLAGS) -fPIC -D_REENTRANT \$(CDEBUG) -o \$@ \$<\n\n";
-print "lib/static/shhopt.o: shhopt/shhopt.c\n";
+print "lib/static/shhopt.o: shhopt/shhopt.c shhopt/netpbm-shhopt.h\n";
+print "\tmkdir -p lib/static\n";
 print "\t\$(CC) -c \$(INCLUDE) -I \$(SRCDIR)/include/ ".
 	"-I \$(SRCDIR)/shhopt/ ".
 	"\$(CFLAGS) -D_REENTRANT \$(CDEBUG) -o \$@ \$<\n\n";
 
-print "lib/static/libpbmvms.o: pbm/libpbmvms.c\n";
+print "lib/static/libpbmvms.o: pbm/libpbmvms.c shhopt/netpbm-shhopt.h\n";
+print "\tmkdir -p lib/static\n";
 print "\t\$(CC) -c \$(INCLUDE) \$(CFLAGS) \$(CDEBUG) -o \$@ \$<\n\n";
-print "lib/shared/libpbmvms.o: pbm/libpbmvms.c\n";
+print "lib/shared/libpbmvms.o: pbm/libpbmvms.c shhopt/netpbm-shhopt.h\n";
+print "\tmkdir -p lib/shared\n";
 print "\t\$(CC) -c \$(INCLUDE) \$(CFLAGS) \$(CDEBUG) -o \$@ \$<\n\n";
 
 
--- netpbm-free-10.0.orig/debian/changelog
+++ netpbm-free-10.0/debian/changelog
@@ -1,3 +1,74 @@
+netpbm-free (2:10.0-8sarge2) stable-security; urgency=high
+
+  * Non-maintainer upload by the Security Team
+  * Applied and backported patches by Greg Roelofs to fix buffer overflows
+    [pnm/pnmtopng.c, CVE-2005-3632]
+
+ -- Martin Schulze <joey@infodrom.org>  Fri, 18 Nov 2005 12:43:32 +0100
+
+netpbm-free (2:10.0-8sarge1) stable-security; urgency=critical
+
+  * Security update for buffer overflow in pnmtopng (CAN-2005-2978)
+
+ -- Noah Meyerhans <noahm@debian.org>  Thu, 29 Sep 2005 20:09:36 -0400
+
+netpbm-free (2:10.0-8) unstable; urgency=low
+
+  * add missing report for windows icon files in icontopbm; until now, we
+    detected them, but didn't report them. Thanks, Steve, for pointing it out.
+    Closes: #275663.
+
+ -- Andreas Barth <aba@amd>  Sun, 10 Oct 2004 11:49:32 +0200
+
+netpbm-free (2:10.0-7) unstable; urgency=medium
+
+  * really include the fix of #238372.
+
+ -- Andreas Barth <aba@not.so.argh.org>  Sun, 05 Sep 2004 16:31:28 +0200
+
+netpbm-free (2:10.0-6) unstable; urgency=high
+
+  * add warning in icontopbm when used on a windows icon. Closes: #268676.
+  * ppmlabel manpage improved; thanks to Richard Hosker. Closes: #265366.
+  * pnmtops supports 4-level grayscale again; thanks to Wayne Schlitt.
+    Closes: #248652.
+  * no need to depend on essential sed. Closes: #263787.
+  * add warning about pnmtofits/signed data; thanks to Justin Pryzby.
+    For details, see #268239.
+  * fix inconsistency error in pnmtopng; thanks to Ross J. Reedstrom.
+    Closes: #238372.
+
+ -- Andreas Barth <aba@not.so.argh.org>  Sun, 29 Aug 2004 17:16:57 +0200
+
+netpbm-free (2:10.0-5) unstable; urgency=low
+
+  * build-depends against libtiff4.
+  * fix typo in ppmtowinicon. Closes: #261999.
+
+ -- Andreas Barth <aba@not.so.argh.org>  Thu, 29 Jul 2004 20:25:46 +0200
+
+netpbm-free (2:10.0-4) unstable; urgency=low
+
+  * gif is free again! So added ppmtogif.
+
+ -- Andreas Barth <aba@not.so.argh.org>  Thu, 08 Jul 2004 20:06:39 +0200
+
+netpbm-free (2:10.0-3) unstable; urgency=low
+
+  * removed subtle build error with sudo
+
+ -- Andreas Barth <aba@not.so.argh.org>  Tue,  3 Feb 2004 19:27:10 +0100
+  
+netpbm-free (2:10.0-2) unstable; urgency=low
+
+  * Really included st4topgm this time.
+  * winicontoppm can now handle icons > 256 colors. Closes: #153917
+  * fixed manpage of ppmtowinicon. Closes: #215756
+  * pnmnorm can now handle 16-bit samples. Closes: #129452
+  * ppmtobmp uses correct bpp-values. Closes: #227125
+
+ -- Andreas Barth <aba@not.so.argh.org>  Sun, 18 Jan 2004 19:34:48 +0100
+
 netpbm-free (2:10.0-1) unstable; urgency=low
 
   * ppmtompeg cares about buffering now. Closes: #218295
--- netpbm-free-10.0.orig/debian/control
+++ netpbm-free-10.0/debian/control
@@ -1,17 +1,17 @@
 Source: netpbm-free
 Section: graphics
 Priority: optional
-Maintainer: A. Barth (sponsored by Steve McIntyre) <93sam-sponsoring-aba@klecker.debian.org>
-Uploaders: Steve McIntyre <93sam@debian.org>, Andreas Barth <aba@not.so.argh.org>
+Maintainer: Andreas Barth <aba@not.so.argh.org>
+Uploaders: Steve McIntyre <93sam@debian.org>
 Standards-Version: 3.6.1.0
-Build-Depends: libtiff3g-dev, libjpeg62-dev, debhelper (>= 4), libpng12-dev, zlib1g-dev, flex, sed
+Build-Depends: libtiff4-dev, libjpeg62-dev, debhelper (>= 4), libpng12-dev, zlib1g-dev, flex
 
 Package: netpbm
 Architecture: any
 Depends: bc, libnetpbm10 (>= ${Source-Version}), ${shlibs:Depends}
 Recommends: gs | gs-aladdin
 Conflicts: netpbm-nonfree (<= 1:19940301.1-3), pnmtopng, pbmwbmp, netpbm-dev (<= 2:9.10), ucbmpeg (<= 1r2-6)
-Replaces: pnmtopng, pbmwbmp, netpbm-dev, netpbm-nonfree (<= 19940301.1-5)
+Replaces: pnmtopng, pbmwbmp, netpbm-dev, netpbm-nonfree
 Provides: pnmtopng, pbmwbmp
 Description: Graphics conversion tools
  Netpbm is a toolkit for manipulation of graphic images, including
--- netpbm-free-10.0.orig/debian/copyright
+++ netpbm-free-10.0/debian/copyright
@@ -347,6 +347,7 @@
 sldtoppm:      (H) 1991      John Walker <kelvin@autodesk.com>
 spctoppm:      (A) 1991      Jef Poskanzer and Steve Belczyk
 sputoppm:      (A) 1991      Jef Poskanzer and Steve Belczyk
+st4topgm:      (A) 2003      Justin Pryzby <justinpryzby@users.sf.net>
 tifftopnm:     (A) 1990      Sun Microsystems, Inc, Jef Poskanzer
 tgatoppm:      (A) 1989      Jef Poskanzer
 thinkjettopbm: (A) 2001      W. Eric Norum <eric.norum@usask.ca>
--- netpbm-free-10.0.orig/mainttools/re-source-bryan
+++ netpbm-free-10.0/mainttools/re-source-bryan
@@ -6,7 +6,7 @@
 	rm -rf movedir;
 fi
 
-cp -avl netpbm-10.0 movedir
+cp -avl $1 movedir
 cd movedir
 find -name 'Makefile*' -exec rm '{}' ';'
 find -type l -exec rm '{}' ';'
@@ -37,5 +37,6 @@
 mv converter/other/x1* pnm/
 mv pnm/fiasco/fiascotopnm.c pnm/fiasco/dwfa.c
 mv pnm/fiasco/pnmtofiasco.c pnm/fiasco/cwfa.c
+mv ppm/ppmtompeg/ppmtompeg.c ppm/ppmtompeg/main.c
 
 find . -type f -printf '%f %P\n' | sort > ../files-10.0
--- netpbm-free-10.0.orig/pbm/icontopbm.1
+++ netpbm-free-10.0/pbm/icontopbm.1
@@ -10,8 +10,12 @@
 .IX Sun
 .IX "Sun icon format"
 Produces a portable bitmap as output.
+
+For windows icons (this format is used for "favicon.ico" on web pages) please
+see winicontoppm.
+
 .SH "SEE ALSO"
-pbmtoicon(1), pbm(5)
+pbmtoicon(1), pbm(5), winicontoppm(1).
 .SH AUTHOR
 Copyright (C) 1988 by Jef Poskanzer.
 .\" Permission to use, copy, modify, and distribute this software and its
--- netpbm-free-10.0.orig/pbm/icontopbm.c
+++ netpbm-free-10.0/pbm/icontopbm.c
@@ -82,19 +82,46 @@
     char variable[81], ch;
     int status, value, i, data_length, gotsome;
 
+    /*
+     *
+     * Problem is: if the first two shorts are 0 and 1, then somebody
+     * gave us a windows icon file. We should recognize that ...
+     *
+     */
+    int winicon=0;
+
     gotsome = 0;
     *width = *height = -1;
     for ( ; ; )
 	{
 	while ( ( ch = getc( file ) ) == ',' || ch == '\n' || ch == '\t' ||
 		ch == ' ' )
-	    ;
+	    winicon=-1;
+
+#define CHECKWIN \
+	if ( \
+		((winicon==0) && (ch==0)) || \
+		((winicon==1) && (ch==0)) || \
+		((winicon==2) && (ch==1)) || \
+		((winicon==3) && (ch==0)) \
+	)  \
+	    winicon++; \
+	else \
+	    winicon=-1; \
+	if (winicon==4) { \
+	    fprintf(stderr, "This seems to be a windows icon file, please try winicontoppm\n"); \
+	    exit(1); \
+	}
+
+	CHECKWIN
+
 	for ( i = 0;
 	      ch != '=' && ch != ',' && ch != '\n' && ch != '\t' && ch != ' ';
 	      i++ )
 	    {
 	    variable[i] = ch;
 	    ch = getc( file );
+	    CHECKWIN
 	    }
 	variable[i] = '\0';
 
--- netpbm-free-10.0.orig/pbm/pbmfilters.1
+++ netpbm-free-10.0/pbm/pbmfilters.1
@@ -538,6 +538,9 @@
 .B ppmtoeyuv
 convert a portable pixmap into a Berkeley YUV file
 .TP
+.B ppmtogif
+convert a portable pixmap into a GIF file
+.TP
 .B ppmtoicr
 convert a portable pixmap into NCSA ICR format 
 .TP
@@ -652,6 +655,9 @@
 .B sputoppm
 convert an Atari uncompressed Spectrum file into a portable pixmap
 .TP
+.B st4topgm
+convert an SBIG ST4 format file into a portable graymap
+.TP
 .B tgatoppm
 convert TrueVision Targa file into a portable pixmap
 .TP
@@ -903,6 +909,7 @@
 sldtoppm(1),
 spctoppm(1),
 sputoppm(1),
+st4topgm(1),
 tgatoppm(1),
 thinkjettopbm(1),
 tifftopnm(1),
--- netpbm-free-10.0.orig/pbm/thinkjettopbm.c
+++ netpbm-free-10.0/pbm/thinkjettopbm.c
@@ -0,0 +1,1904 @@
+
+#line 3 "<stdout>"
+
+#define  YY_INT_ALIGNED short int
+
+/* A lexical scanner generated by flex */
+
+#define FLEX_SCANNER
+#define YY_FLEX_MAJOR_VERSION 2
+#define YY_FLEX_MINOR_VERSION 5
+#define YY_FLEX_SUBMINOR_VERSION 31
+#if YY_FLEX_SUBMINOR_VERSION > 0
+#define FLEX_BETA
+#endif
+
+/* First, we deal with  platform-specific or compiler-specific issues. */
+
+/* begin standard C headers. */
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <stdlib.h>
+
+/* end standard C headers. */
+
+/* flex integer type definitions */
+
+#ifndef FLEXINT_H
+#define FLEXINT_H
+
+/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
+
+#if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L
+#include <inttypes.h>
+typedef int8_t flex_int8_t;
+typedef uint8_t flex_uint8_t;
+typedef int16_t flex_int16_t;
+typedef uint16_t flex_uint16_t;
+typedef int32_t flex_int32_t;
+typedef uint32_t flex_uint32_t;
+#else
+typedef signed char flex_int8_t;
+typedef short int flex_int16_t;
+typedef int flex_int32_t;
+typedef unsigned char flex_uint8_t; 
+typedef unsigned short int flex_uint16_t;
+typedef unsigned int flex_uint32_t;
+#endif /* ! C99 */
+
+/* Limits of integral types. */
+#ifndef INT8_MIN
+#define INT8_MIN               (-128)
+#endif
+#ifndef INT16_MIN
+#define INT16_MIN              (-32767-1)
+#endif
+#ifndef INT32_MIN
+#define INT32_MIN              (-2147483647-1)
+#endif
+#ifndef INT8_MAX
+#define INT8_MAX               (127)
+#endif
+#ifndef INT16_MAX
+#define INT16_MAX              (32767)
+#endif
+#ifndef INT32_MAX
+#define INT32_MAX              (2147483647)
+#endif
+#ifndef UINT8_MAX
+#define UINT8_MAX              (255U)
+#endif
+#ifndef UINT16_MAX
+#define UINT16_MAX             (65535U)
+#endif
+#ifndef UINT32_MAX
+#define UINT32_MAX             (4294967295U)
+#endif
+
+#endif /* ! FLEXINT_H */
+
+#ifdef __cplusplus
+
+/* The "const" storage-class-modifier is valid. */
+#define YY_USE_CONST
+
+#else	/* ! __cplusplus */
+
+#if __STDC__
+
+#define YY_USE_CONST
+
+#endif	/* __STDC__ */
+#endif	/* ! __cplusplus */
+
+#ifdef YY_USE_CONST
+#define yyconst const
+#else
+#define yyconst
+#endif
+
+/* Returned upon end-of-file. */
+#define YY_NULL 0
+
+/* Promotes a possibly negative, possibly signed char to an unsigned
+ * integer for use as an array index.  If the signed char is negative,
+ * we want to instead treat it as an 8-bit unsigned char, hence the
+ * double cast.
+ */
+#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
+
+/* Enter a start condition.  This macro really ought to take a parameter,
+ * but we do it the disgusting crufty way forced on us by the ()-less
+ * definition of BEGIN.
+ */
+#define BEGIN (yy_start) = 1 + 2 *
+
+/* Translate the current start state into a value that can be later handed
+ * to BEGIN to return to the state.  The YYSTATE alias is for lex
+ * compatibility.
+ */
+#define YY_START (((yy_start) - 1) / 2)
+#define YYSTATE YY_START
+
+/* Action number for EOF rule of a given start state. */
+#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
+
+/* Special action meaning "start processing a new file". */
+#define YY_NEW_FILE yyrestart(yyin  )
+
+#define YY_END_OF_BUFFER_CHAR 0
+
+/* Size of default input buffer. */
+#ifndef YY_BUF_SIZE
+#define YY_BUF_SIZE 16384
+#endif
+
+#ifndef YY_TYPEDEF_YY_BUFFER_STATE
+#define YY_TYPEDEF_YY_BUFFER_STATE
+typedef struct yy_buffer_state *YY_BUFFER_STATE;
+#endif
+
+extern int yyleng;
+
+extern FILE *yyin, *yyout;
+
+#define EOB_ACT_CONTINUE_SCAN 0
+#define EOB_ACT_END_OF_FILE 1
+#define EOB_ACT_LAST_MATCH 2
+
+    #define YY_LESS_LINENO(n)
+    
+/* Return all but the first "n" matched characters back to the input stream. */
+#define yyless(n) \
+	do \
+		{ \
+		/* Undo effects of setting up yytext. */ \
+        int yyless_macro_arg = (n); \
+        YY_LESS_LINENO(yyless_macro_arg);\
+		*yy_cp = (yy_hold_char); \
+		YY_RESTORE_YY_MORE_OFFSET \
+		(yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
+		YY_DO_BEFORE_ACTION; /* set up yytext again */ \
+		} \
+	while ( 0 )
+
+#define unput(c) yyunput( c, (yytext_ptr)  )
+
+/* The following is because we cannot portably get our hands on size_t
+ * (without autoconf's help, which isn't available because we want
+ * flex-generated scanners to compile on their own).
+ */
+
+#ifndef YY_TYPEDEF_YY_SIZE_T
+#define YY_TYPEDEF_YY_SIZE_T
+typedef unsigned int yy_size_t;
+#endif
+
+#ifndef YY_STRUCT_YY_BUFFER_STATE
+#define YY_STRUCT_YY_BUFFER_STATE
+struct yy_buffer_state
+	{
+	FILE *yy_input_file;
+
+	char *yy_ch_buf;		/* input buffer */
+	char *yy_buf_pos;		/* current position in input buffer */
+
+	/* Size of input buffer in bytes, not including room for EOB
+	 * characters.
+	 */
+	yy_size_t yy_buf_size;
+
+	/* Number of characters read into yy_ch_buf, not including EOB
+	 * characters.
+	 */
+	int yy_n_chars;
+
+	/* Whether we "own" the buffer - i.e., we know we created it,
+	 * and can realloc() it to grow it, and should free() it to
+	 * delete it.
+	 */
+	int yy_is_our_buffer;
+
+	/* Whether this is an "interactive" input source; if so, and
+	 * if we're using stdio for input, then we want to use getc()
+	 * instead of fread(), to make sure we stop fetching input after
+	 * each newline.
+	 */
+	int yy_is_interactive;
+
+	/* Whether we're considered to be at the beginning of a line.
+	 * If so, '^' rules will be active on the next match, otherwise
+	 * not.
+	 */
+	int yy_at_bol;
+
+    int yy_bs_lineno; /**< The line count. */
+    int yy_bs_column; /**< The column count. */
+    
+	/* Whether to try to fill the input buffer when we reach the
+	 * end of it.
+	 */
+	int yy_fill_buffer;
+
+	int yy_buffer_status;
+
+#define YY_BUFFER_NEW 0
+#define YY_BUFFER_NORMAL 1
+	/* When an EOF's been seen but there's still some text to process
+	 * then we mark the buffer as YY_EOF_PENDING, to indicate that we
+	 * shouldn't try reading from the input source any more.  We might
+	 * still have a bunch of tokens to match, though, because of
+	 * possible backing-up.
+	 *
+	 * When we actually see the EOF, we change the status to "new"
+	 * (via yyrestart()), so that the user can continue scanning by
+	 * just pointing yyin at a new input file.
+	 */
+#define YY_BUFFER_EOF_PENDING 2
+
+	};
+#endif /* !YY_STRUCT_YY_BUFFER_STATE */
+
+/* Stack of input buffers. */
+static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */
+static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */
+static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */
+
+/* We provide macros for accessing buffer states in case in the
+ * future we want to put the buffer states in a more general
+ * "scanner state".
+ *
+ * Returns the top of the stack, or NULL.
+ */
+#define YY_CURRENT_BUFFER ( (yy_buffer_stack) \
+                          ? (yy_buffer_stack)[(yy_buffer_stack_top)] \
+                          : NULL)
+
+/* Same as previous macro, but useful when we know that the buffer stack is not
+ * NULL or when we need an lvalue. For internal use only.
+ */
+#define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)]
+
+/* yy_hold_char holds the character lost when yytext is formed. */
+static char yy_hold_char;
+static int yy_n_chars;		/* number of characters read into yy_ch_buf */
+int yyleng;
+
+/* Points to current character in buffer. */
+static char *yy_c_buf_p = (char *) 0;
+static int yy_init = 1;		/* whether we need to initialize */
+static int yy_start = 0;	/* start state number */
+
+/* Flag which is used to allow yywrap()'s to do buffer switches
+ * instead of setting up a fresh yyin.  A bit of a hack ...
+ */
+static int yy_did_buffer_switch_on_eof;
+
+void yyrestart (FILE *input_file  );
+void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer  );
+YY_BUFFER_STATE yy_create_buffer (FILE *file,int size  );
+void yy_delete_buffer (YY_BUFFER_STATE b  );
+void yy_flush_buffer (YY_BUFFER_STATE b  );
+void yypush_buffer_state (YY_BUFFER_STATE new_buffer  );
+void yypop_buffer_state (void );
+
+static void yyensure_buffer_stack (void );
+static void yy_load_buffer_state (void );
+static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file  );
+
+#define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER )
+
+YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size  );
+YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str  );
+YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,int len  );
+
+void *yyalloc (yy_size_t  );
+void *yyrealloc (void *,yy_size_t  );
+void yyfree (void *  );
+
+#define yy_new_buffer yy_create_buffer
+
+#define yy_set_interactive(is_interactive) \
+	{ \
+	if ( ! YY_CURRENT_BUFFER ){ \
+        yyensure_buffer_stack (); \
+		YY_CURRENT_BUFFER_LVALUE =    \
+            yy_create_buffer(yyin,YY_BUF_SIZE ); \
+	} \
+	YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
+	}
+
+#define yy_set_bol(at_bol) \
+	{ \
+	if ( ! YY_CURRENT_BUFFER ){\
+        yyensure_buffer_stack (); \
+		YY_CURRENT_BUFFER_LVALUE =    \
+            yy_create_buffer(yyin,YY_BUF_SIZE ); \
+	} \
+	YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
+	}
+
+#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
+
+/* Begin user sect3 */
+
+typedef unsigned char YY_CHAR;
+
+FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0;
+
+typedef int yy_state_type;
+
+extern int yylineno;
+
+int yylineno = 1;
+
+extern char *yytext;
+#define yytext_ptr yytext
+
+static yy_state_type yy_get_previous_state (void );
+static yy_state_type yy_try_NUL_trans (yy_state_type current_state  );
+static int yy_get_next_buffer (void );
+static void yy_fatal_error (yyconst char msg[]  );
+
+/* Done after the current pattern has been matched and before the
+ * corresponding action - sets up yytext.
+ */
+#define YY_DO_BEFORE_ACTION \
+	(yytext_ptr) = yy_bp; \
+	yyleng = (size_t) (yy_cp - yy_bp); \
+	(yy_hold_char) = *yy_cp; \
+	*yy_cp = '\0'; \
+	(yy_c_buf_p) = yy_cp;
+
+#define YY_NUM_RULES 10
+#define YY_END_OF_BUFFER 11
+/* This struct is not used in this scanner,
+   but its presence is necessary. */
+struct yy_trans_info
+	{
+	flex_int32_t yy_verify;
+	flex_int32_t yy_nxt;
+	};
+static yyconst flex_int16_t yy_accept[34] =
+    {   0,
+        0,    0,    0,    0,    0,    0,   11,    9,    9,   10,
+        4,   10,    1,    0,    0,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,    8,    0,    3,    5,    5,    7,
+        6,    2,    0
+    } ;
+
+static yyconst flex_int32_t yy_ec[256] =
+    {   0,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    2,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    3,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    4,    1,    1,
+        1,    5,    1,    1,    1,    6,    1,    7,    7,    7,
+        7,    7,    7,    7,    7,    7,    7,    1,    1,    1,
+        1,    1,    1,    1,    8,    9,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,   10,    1,    1,    1,   11,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,   12,    1,    1,
+
+        1,    1,    1,    1,    1,    1,    1,   13,    1,    1,
+        1,    1,    1,   14,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1
+    } ;
+
+static yyconst flex_int32_t yy_meta[15] =
+    {   0,
+        1,    2,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1
+    } ;
+
+static yyconst flex_int16_t yy_base[38] =
+    {   0,
+       35,   34,    0,    5,    0,    0,   36,   39,    0,   39,
+       39,   30,   39,   21,    0,    1,   26,   25,    2,   24,
+       21,   15,    9,   11,   39,   12,   39,   39,   10,   39,
+       39,   39,   39,   23,   25,   27,    0
+    } ;
+
+static yyconst flex_int16_t yy_def[38] =
+    {   0,
+       34,   34,   35,   35,   36,   36,   33,   33,   33,   33,
+       33,   33,   33,   33,   33,   33,   33,   33,   33,   33,
+       33,   37,   33,   33,   33,   33,   33,   33,   37,   33,
+       33,   33,    0,   33,   33,   33,   33
+    } ;
+
+static yyconst flex_int16_t yy_nxt[54] =
+    {   0,
+       28,   11,   12,   14,   15,   11,   11,   12,   24,   25,
+       11,   18,   20,   19,   21,   23,   29,   24,   26,   30,
+       31,   29,   32,    8,    8,   10,   10,   13,   13,   27,
+       26,   23,   22,   17,   16,   33,    9,    9,    7,   33,
+       33,   33,   33,   33,   33,   33,   33,   33,   33,   33,
+       33,   33,   33
+    } ;
+
+static yyconst flex_int16_t yy_chk[54] =
+    {   0,
+       37,    3,    3,    9,    9,    3,    4,    4,   19,   19,
+        4,   15,   16,   15,   16,   23,   29,   24,   26,   23,
+       24,   22,   26,   34,   34,   35,   35,   36,   36,   21,
+       20,   18,   17,   14,   12,    7,    2,    1,   33,   33,
+       33,   33,   33,   33,   33,   33,   33,   33,   33,   33,
+       33,   33,   33
+    } ;
+
+static yy_state_type yy_last_accepting_state;
+static char *yy_last_accepting_cpos;
+
+extern int yy_flex_debug;
+int yy_flex_debug = 0;
+
+/* The intent behind this definition is that it'll catch
+ * any uses of REJECT which flex missed.
+ */
+#define REJECT reject_used_but_not_detected
+#define yymore() yymore_used_but_not_detected
+#define YY_MORE_ADJ 0
+#define YY_RESTORE_YY_MORE_OFFSET
+char *yytext;
+#line 1 "../pbm/thinkjettopbm.l"
+/*
+ * $Id: thinkjettopbm.l,v 1.2 2003/08/14 19:38:51 aba-guest Exp $
+ *
+ * Simple FLEX scanner to convert HP ThinkJet graphics image
+ * to PBM format.
+ *
+ * Implements a small subset of ThinkJet commands.
+ *
+ * Copyright (C) 2001 by W. Eric Norum
+ *
+ * Department of Electrical Engineering
+ * University of Saskatchewan
+ * Saskatoon, Saskatchewan, CANADA
+ * eric.norum@usask.ca
+ *
+ *  Permission to use, copy, modify, and distribute this software and
+ *  its documentation for any purpose and without fee is hereby granted,
+ *  provided that the above copyright notice appear in all copies and
+ *  that both that copyright notice and this permission notice appear in
+ *  supporting documentation.  This software is provided "as is" without
+ *  express or implied warranty.
+ *
+ *  Modified 2001.04.05 by Bryan Henderson for inclusion in the Netpbm
+ *  package.  Now uses Netpbm libraries and, for consistency with other
+ *  Netpbm programs, does not have PGM output option.
+ */
+#line 30 "../pbm/thinkjettopbm.l"
+
+#include <stdio.h>
+#include <stdarg.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+#include "pbm.h"
+
+static int yylex(void);
+static int yywrap(void);
+
+struct RowInfo {
+    int     length;    /* length, in bytes */
+    char    *bits;     /* Bitmap */
+};
+
+static int maxRowLength;
+static int rowCount;
+static int rowCapacity;
+static struct RowInfo *rows;
+
+static int column;
+
+const char *progname;
+int debugFlag;
+static void debug (const char *format, ...);
+
+
+#line 516 "<stdout>"
+
+#define INITIAL 0
+#define RASTERMODE 1
+#define ROWMODE 2
+
+#ifndef YY_NO_UNISTD_H
+/* Special case for "unistd.h", since it is non-ANSI. We include it way
+ * down here because we want the user's section 1 to have been scanned first.
+ * The user has a chance to override it with an option.
+ */
+#include <unistd.h>
+#endif
+
+#ifndef YY_EXTRA_TYPE
+#define YY_EXTRA_TYPE void *
+#endif
+
+/* Macros after this point can all be overridden by user definitions in
+ * section 1.
+ */
+
+#ifndef YY_SKIP_YYWRAP
+#ifdef __cplusplus
+extern "C" int yywrap (void );
+#else
+extern int yywrap (void );
+#endif
+#endif
+
+    static void yyunput (int c,char *buf_ptr  );
+    
+#ifndef yytext_ptr
+static void yy_flex_strncpy (char *,yyconst char *,int );
+#endif
+
+#ifdef YY_NEED_STRLEN
+static int yy_flex_strlen (yyconst char * );
+#endif
+
+#ifndef YY_NO_INPUT
+
+#ifdef __cplusplus
+static int yyinput (void );
+#else
+static int input (void );
+#endif
+
+#endif
+
+/* Amount of stuff to slurp up with each read. */
+#ifndef YY_READ_BUF_SIZE
+#define YY_READ_BUF_SIZE 8192
+#endif
+
+/* Copy whatever the last rule matched to the standard output. */
+#ifndef ECHO
+/* This used to be an fputs(), but since the string might contain NUL's,
+ * we now use fwrite().
+ */
+#define ECHO (void) fwrite( yytext, yyleng, 1, yyout )
+#endif
+
+/* Gets input and stuffs it into "buf".  number of characters read, or YY_NULL,
+ * is returned in "result".
+ */
+#ifndef YY_INPUT
+#define YY_INPUT(buf,result,max_size) \
+	if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
+		{ \
+		int c = '*'; \
+		size_t n; \
+		for ( n = 0; n < max_size && \
+			     (c = getc( yyin )) != EOF && c != '\n'; ++n ) \
+			buf[n] = (char) c; \
+		if ( c == '\n' ) \
+			buf[n++] = (char) c; \
+		if ( c == EOF && ferror( yyin ) ) \
+			YY_FATAL_ERROR( "input in flex scanner failed" ); \
+		result = n; \
+		} \
+	else \
+		{ \
+		errno=0; \
+		while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
+			{ \
+			if( errno != EINTR) \
+				{ \
+				YY_FATAL_ERROR( "input in flex scanner failed" ); \
+				break; \
+				} \
+			errno=0; \
+			clearerr(yyin); \
+			} \
+		}\
+\
+
+#endif
+
+/* No semi-colon after return; correct usage is to write "yyterminate();" -
+ * we don't want an extra ';' after the "return" because that will cause
+ * some compilers to complain about unreachable statements.
+ */
+#ifndef yyterminate
+#define yyterminate() return YY_NULL
+#endif
+
+/* Number of entries by which start-condition stack grows. */
+#ifndef YY_START_STACK_INCR
+#define YY_START_STACK_INCR 25
+#endif
+
+/* Report a fatal error. */
+#ifndef YY_FATAL_ERROR
+#define YY_FATAL_ERROR(msg) yy_fatal_error( msg )
+#endif
+
+/* end tables serialization structures and prototypes */
+
+/* Default declaration of generated scanner - a define so the user can
+ * easily add parameters.
+ */
+#ifndef YY_DECL
+#define YY_DECL_IS_OURS 1
+
+extern int yylex (void);
+
+#define YY_DECL int yylex (void)
+#endif /* !YY_DECL */
+
+/* Code executed at the beginning of each rule, after yytext and yyleng
+ * have been set up.
+ */
+#ifndef YY_USER_ACTION
+#define YY_USER_ACTION
+#endif
+
+/* Code executed at the end of each rule. */
+#ifndef YY_BREAK
+#define YY_BREAK break;
+#endif
+
+#define YY_RULE_SETUP \
+	YY_USER_ACTION
+
+/** The main scanner function which does all the work.
+ */
+YY_DECL
+{
+	register yy_state_type yy_current_state;
+	register char *yy_cp, *yy_bp;
+	register int yy_act;
+    
+#line 63 "../pbm/thinkjettopbm.l"
+
+
+#line 672 "<stdout>"
+
+	if ( (yy_init) )
+		{
+		(yy_init) = 0;
+
+#ifdef YY_USER_INIT
+		YY_USER_INIT;
+#endif
+
+		if ( ! (yy_start) )
+			(yy_start) = 1;	/* first start state */
+
+		if ( ! yyin )
+			yyin = stdin;
+
+		if ( ! yyout )
+			yyout = stdout;
+
+		if ( ! YY_CURRENT_BUFFER ) {
+			yyensure_buffer_stack ();
+			YY_CURRENT_BUFFER_LVALUE =
+				yy_create_buffer(yyin,YY_BUF_SIZE );
+		}
+
+		yy_load_buffer_state( );
+		}
+
+	while ( 1 )		/* loops until end-of-file is reached */
+		{
+		yy_cp = (yy_c_buf_p);
+
+		/* Support of yytext. */
+		*yy_cp = (yy_hold_char);
+
+		/* yy_bp points to the position in yy_ch_buf of the start of
+		 * the current run.
+		 */
+		yy_bp = yy_cp;
+
+		yy_current_state = (yy_start);
+yy_match:
+		do
+			{
+			register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];
+			if ( yy_accept[yy_current_state] )
+				{
+				(yy_last_accepting_state) = yy_current_state;
+				(yy_last_accepting_cpos) = yy_cp;
+				}
+			while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+				{
+				yy_current_state = (int) yy_def[yy_current_state];
+				if ( yy_current_state >= 34 )
+					yy_c = yy_meta[(unsigned int) yy_c];
+				}
+			yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
+			++yy_cp;
+			}
+		while ( yy_base[yy_current_state] != 39 );
+
+yy_find_action:
+		yy_act = yy_accept[yy_current_state];
+		if ( yy_act == 0 )
+			{ /* have to back up */
+			yy_cp = (yy_last_accepting_cpos);
+			yy_current_state = (yy_last_accepting_state);
+			yy_act = yy_accept[yy_current_state];
+			}
+
+		YY_DO_BEFORE_ACTION;
+
+do_action:	/* This label is used only to access EOF actions. */
+
+		switch ( yy_act )
+	{ /* beginning of action switch */
+			case 0: /* must back up */
+			/* undo the effects of YY_DO_BEFORE_ACTION */
+			*yy_cp = (yy_hold_char);
+			yy_cp = (yy_last_accepting_cpos);
+			yy_current_state = (yy_last_accepting_state);
+			goto yy_find_action;
+
+case 1:
+/* rule 1 can match eol */
+YY_RULE_SETUP
+#line 65 "../pbm/thinkjettopbm.l"
+{
+                        rows[rowCount].bits[column++] = yytext[0]; 
+                        if (column >= rows[rowCount].length) {
+                            rowCount++;
+                            debug ("Done %d-byte row %d.\n", column, rowCount);
+                            BEGIN (RASTERMODE);
+                        }
+                        }
+	YY_BREAK
+case 2:
+YY_RULE_SETUP
+#line 74 "../pbm/thinkjettopbm.l"
+{
+                            int l;
+                            if (rowCount >= rowCapacity) {
+				overflow_add(rowCapacity, 100);
+                                rowCapacity += 100;
+				overflow2(rowCapacity, sizeof *rows);
+                                rows = realloc (rows, rowCapacity * sizeof *rows);
+                                if (rows == NULL)
+                                    pm_error ("Out of memory.");
+                            }
+                            l = atoi (yytext+3);
+                            rows[rowCount].length = l;
+                            rows[rowCount].bits = malloc (l);
+                            if (rows[rowCount].bits == NULL)
+                                pm_error ("Out of memory.");
+                            if (l > maxRowLength)
+                                maxRowLength = l;
+                            debug ("Start %d-byte row.\n", l);
+                            column = 0;
+                            BEGIN (ROWMODE);
+                            }
+	YY_BREAK
+case 3:
+YY_RULE_SETUP
+#line 96 "../pbm/thinkjettopbm.l"
+{
+                       debug ("Match <esc>*rB\n");
+                       BEGIN (0);
+                       }
+	YY_BREAK
+case 4:
+/* rule 4 can match eol */
+YY_RULE_SETUP
+#line 101 "../pbm/thinkjettopbm.l"
+{ pm_error ("Unexpected character (%#x) in raster mode.\n", yytext[0]); }
+	YY_BREAK
+case 5:
+YY_RULE_SETUP
+#line 103 "../pbm/thinkjettopbm.l"
+{ debug ("Match <esc>&l\n"); }
+	YY_BREAK
+case 6:
+YY_RULE_SETUP
+#line 104 "../pbm/thinkjettopbm.l"
+{ debug ("Match <esc>*r#S\n"); }
+	YY_BREAK
+case 7:
+YY_RULE_SETUP
+#line 105 "../pbm/thinkjettopbm.l"
+{ debug ("Match <esc>*r#w\n"); }
+	YY_BREAK
+case 8:
+YY_RULE_SETUP
+#line 106 "../pbm/thinkjettopbm.l"
+{
+                       debug ("Match <esc>*rA\n");
+                       BEGIN (RASTERMODE);
+                       }
+	YY_BREAK
+case 9:
+/* rule 9 can match eol */
+YY_RULE_SETUP
+#line 111 "../pbm/thinkjettopbm.l"
+{ /* Silently consume all other characters */ }
+	YY_BREAK
+case 10:
+YY_RULE_SETUP
+#line 113 "../pbm/thinkjettopbm.l"
+ECHO;
+	YY_BREAK
+#line 841 "<stdout>"
+case YY_STATE_EOF(INITIAL):
+case YY_STATE_EOF(RASTERMODE):
+case YY_STATE_EOF(ROWMODE):
+	yyterminate();
+
+	case YY_END_OF_BUFFER:
+		{
+		/* Amount of text matched not including the EOB char. */
+		int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1;
+
+		/* Undo the effects of YY_DO_BEFORE_ACTION. */
+		*yy_cp = (yy_hold_char);
+		YY_RESTORE_YY_MORE_OFFSET
+
+		if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
+			{
+			/* We're scanning a new file or input source.  It's
+			 * possible that this happened because the user
+			 * just pointed yyin at a new source and called
+			 * yylex().  If so, then we have to assure
+			 * consistency between YY_CURRENT_BUFFER and our
+			 * globals.  Here is the right place to do so, because
+			 * this is the first action (other than possibly a
+			 * back-up) that will match for the new input source.
+			 */
+			(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
+			YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
+			YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
+			}
+
+		/* Note that here we test for yy_c_buf_p "<=" to the position
+		 * of the first EOB in the buffer, since yy_c_buf_p will
+		 * already have been incremented past the NUL character
+		 * (since all states make transitions on EOB to the
+		 * end-of-buffer state).  Contrast this with the test
+		 * in input().
+		 */
+		if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
+			{ /* This was really a NUL. */
+			yy_state_type yy_next_state;
+
+			(yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text;
+
+			yy_current_state = yy_get_previous_state(  );
+
+			/* Okay, we're now positioned to make the NUL
+			 * transition.  We couldn't have
+			 * yy_get_previous_state() go ahead and do it
+			 * for us because it doesn't know how to deal
+			 * with the possibility of jamming (and we don't
+			 * want to build jamming into it because then it
+			 * will run more slowly).
+			 */
+
+			yy_next_state = yy_try_NUL_trans( yy_current_state );
+
+			yy_bp = (yytext_ptr) + YY_MORE_ADJ;
+
+			if ( yy_next_state )
+				{
+				/* Consume the NUL. */
+				yy_cp = ++(yy_c_buf_p);
+				yy_current_state = yy_next_state;
+				goto yy_match;
+				}
+
+			else
+				{
+				yy_cp = (yy_c_buf_p);
+				goto yy_find_action;
+				}
+			}
+
+		else switch ( yy_get_next_buffer(  ) )
+			{
+			case EOB_ACT_END_OF_FILE:
+				{
+				(yy_did_buffer_switch_on_eof) = 0;
+
+				if ( yywrap( ) )
+					{
+					/* Note: because we've taken care in
+					 * yy_get_next_buffer() to have set up
+					 * yytext, we can now set up
+					 * yy_c_buf_p so that if some total
+					 * hoser (like flex itself) wants to
+					 * call the scanner after we return the
+					 * YY_NULL, it'll still work - another
+					 * YY_NULL will get returned.
+					 */
+					(yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ;
+
+					yy_act = YY_STATE_EOF(YY_START);
+					goto do_action;
+					}
+
+				else
+					{
+					if ( ! (yy_did_buffer_switch_on_eof) )
+						YY_NEW_FILE;
+					}
+				break;
+				}
+
+			case EOB_ACT_CONTINUE_SCAN:
+				(yy_c_buf_p) =
+					(yytext_ptr) + yy_amount_of_matched_text;
+
+				yy_current_state = yy_get_previous_state(  );
+
+				yy_cp = (yy_c_buf_p);
+				yy_bp = (yytext_ptr) + YY_MORE_ADJ;
+				goto yy_match;
+
+			case EOB_ACT_LAST_MATCH:
+				(yy_c_buf_p) =
+				&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)];
+
+				yy_current_state = yy_get_previous_state(  );
+
+				yy_cp = (yy_c_buf_p);
+				yy_bp = (yytext_ptr) + YY_MORE_ADJ;
+				goto yy_find_action;
+			}
+		break;
+		}
+
+	default:
+		YY_FATAL_ERROR(
+			"fatal flex scanner internal error--no action found" );
+	} /* end of action switch */
+		} /* end of scanning one token */
+} /* end of yylex */
+
+/* yy_get_next_buffer - try to read in a new buffer
+ *
+ * Returns a code representing an action:
+ *	EOB_ACT_LAST_MATCH -
+ *	EOB_ACT_CONTINUE_SCAN - continue scanning from current position
+ *	EOB_ACT_END_OF_FILE - end of file
+ */
+static int yy_get_next_buffer (void)
+{
+    	register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
+	register char *source = (yytext_ptr);
+	register int number_to_move, i;
+	int ret_val;
+
+	if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] )
+		YY_FATAL_ERROR(
+		"fatal flex scanner internal error--end of buffer missed" );
+
+	if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
+		{ /* Don't try to fill the buffer, so this is an EOF. */
+		if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 )
+			{
+			/* We matched a single character, the EOB, so
+			 * treat this as a final EOF.
+			 */
+			return EOB_ACT_END_OF_FILE;
+			}
+
+		else
+			{
+			/* We matched some text prior to the EOB, first
+			 * process it.
+			 */
+			return EOB_ACT_LAST_MATCH;
+			}
+		}
+
+	/* Try to read more data. */
+
+	/* First move last chars to start of buffer. */
+	number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1;
+
+	for ( i = 0; i < number_to_move; ++i )
+		*(dest++) = *(source++);
+
+	if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
+		/* don't do the read, it's not guaranteed to return an EOF,
+		 * just force an EOF
+		 */
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0;
+
+	else
+		{
+			size_t num_to_read =
+			YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
+
+		while ( num_to_read <= 0 )
+			{ /* Not enough room in the buffer - grow it. */
+
+			/* just a shorter name for the current buffer */
+			YY_BUFFER_STATE b = YY_CURRENT_BUFFER;
+
+			int yy_c_buf_p_offset =
+				(int) ((yy_c_buf_p) - b->yy_ch_buf);
+
+			if ( b->yy_is_our_buffer )
+				{
+				int new_size = b->yy_buf_size * 2;
+
+				if ( new_size <= 0 )
+					b->yy_buf_size += b->yy_buf_size / 8;
+				else
+					b->yy_buf_size *= 2;
+
+				b->yy_ch_buf = (char *)
+					/* Include room in for 2 EOB chars. */
+					yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2  );
+				}
+			else
+				/* Can't grow it, we don't own it. */
+				b->yy_ch_buf = 0;
+
+			if ( ! b->yy_ch_buf )
+				YY_FATAL_ERROR(
+				"fatal error - scanner input buffer overflow" );
+
+			(yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset];
+
+			num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
+						number_to_move - 1;
+
+			}
+
+		if ( num_to_read > YY_READ_BUF_SIZE )
+			num_to_read = YY_READ_BUF_SIZE;
+
+		/* Read in more data. */
+		YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
+			(yy_n_chars), num_to_read );
+
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
+		}
+
+	if ( (yy_n_chars) == 0 )
+		{
+		if ( number_to_move == YY_MORE_ADJ )
+			{
+			ret_val = EOB_ACT_END_OF_FILE;
+			yyrestart(yyin  );
+			}
+
+		else
+			{
+			ret_val = EOB_ACT_LAST_MATCH;
+			YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
+				YY_BUFFER_EOF_PENDING;
+			}
+		}
+
+	else
+		ret_val = EOB_ACT_CONTINUE_SCAN;
+
+	(yy_n_chars) += number_to_move;
+	YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR;
+	YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR;
+
+	(yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
+
+	return ret_val;
+}
+
+/* yy_get_previous_state - get the state just before the EOB char was reached */
+
+    static yy_state_type yy_get_previous_state (void)
+{
+	register yy_state_type yy_current_state;
+	register char *yy_cp;
+    
+	yy_current_state = (yy_start);
+
+	for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp )
+		{
+		register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 6);
+		if ( yy_accept[yy_current_state] )
+			{
+			(yy_last_accepting_state) = yy_current_state;
+			(yy_last_accepting_cpos) = yy_cp;
+			}
+		while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+			{
+			yy_current_state = (int) yy_def[yy_current_state];
+			if ( yy_current_state >= 34 )
+				yy_c = yy_meta[(unsigned int) yy_c];
+			}
+		yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
+		}
+
+	return yy_current_state;
+}
+
+/* yy_try_NUL_trans - try to make a transition on the NUL character
+ *
+ * synopsis
+ *	next_state = yy_try_NUL_trans( current_state );
+ */
+    static yy_state_type yy_try_NUL_trans  (yy_state_type yy_current_state )
+{
+	register int yy_is_jam;
+    	register char *yy_cp = (yy_c_buf_p);
+
+	register YY_CHAR yy_c = 6;
+	if ( yy_accept[yy_current_state] )
+		{
+		(yy_last_accepting_state) = yy_current_state;
+		(yy_last_accepting_cpos) = yy_cp;
+		}
+	while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+		{
+		yy_current_state = (int) yy_def[yy_current_state];
+		if ( yy_current_state >= 34 )
+			yy_c = yy_meta[(unsigned int) yy_c];
+		}
+	yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
+	yy_is_jam = (yy_current_state == 33);
+
+	return yy_is_jam ? 0 : yy_current_state;
+}
+
+    static void yyunput (int c, register char * yy_bp )
+{
+	register char *yy_cp;
+    
+    yy_cp = (yy_c_buf_p);
+
+	/* undo effects of setting up yytext */
+	*yy_cp = (yy_hold_char);
+
+	if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
+		{ /* need to shift things up to make room */
+		/* +2 for EOB chars. */
+		register int number_to_move = (yy_n_chars) + 2;
+		register char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[
+					YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2];
+		register char *source =
+				&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move];
+
+		while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
+			*--dest = *--source;
+
+		yy_cp += (int) (dest - source);
+		yy_bp += (int) (dest - source);
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars =
+			(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size;
+
+		if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
+			YY_FATAL_ERROR( "flex scanner push-back overflow" );
+		}
+
+	*--yy_cp = (char) c;
+
+	(yytext_ptr) = yy_bp;
+	(yy_hold_char) = *yy_cp;
+	(yy_c_buf_p) = yy_cp;
+}
+
+#ifndef YY_NO_INPUT
+#ifdef __cplusplus
+    static int yyinput (void)
+#else
+    static int input  (void)
+#endif
+
+{
+	int c;
+    
+	*(yy_c_buf_p) = (yy_hold_char);
+
+	if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR )
+		{
+		/* yy_c_buf_p now points to the character we want to return.
+		 * If this occurs *before* the EOB characters, then it's a
+		 * valid NUL; if not, then we've hit the end of the buffer.
+		 */
+		if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
+			/* This was really a NUL. */
+			*(yy_c_buf_p) = '\0';
+
+		else
+			{ /* need more input */
+			int offset = (yy_c_buf_p) - (yytext_ptr);
+			++(yy_c_buf_p);
+
+			switch ( yy_get_next_buffer(  ) )
+				{
+				case EOB_ACT_LAST_MATCH:
+					/* This happens because yy_g_n_b()
+					 * sees that we've accumulated a
+					 * token and flags that we need to
+					 * try matching the token before
+					 * proceeding.  But for input(),
+					 * there's no matching to consider.
+					 * So convert the EOB_ACT_LAST_MATCH
+					 * to EOB_ACT_END_OF_FILE.
+					 */
+
+					/* Reset buffer status. */
+					yyrestart(yyin );
+
+					/*FALLTHROUGH*/
+
+				case EOB_ACT_END_OF_FILE:
+					{
+					if ( yywrap( ) )
+						return EOF;
+
+					if ( ! (yy_did_buffer_switch_on_eof) )
+						YY_NEW_FILE;
+#ifdef __cplusplus
+					return yyinput();
+#else
+					return input();
+#endif
+					}
+
+				case EOB_ACT_CONTINUE_SCAN:
+					(yy_c_buf_p) = (yytext_ptr) + offset;
+					break;
+				}
+			}
+		}
+
+	c = *(unsigned char *) (yy_c_buf_p);	/* cast for 8-bit char's */
+	*(yy_c_buf_p) = '\0';	/* preserve yytext */
+	(yy_hold_char) = *++(yy_c_buf_p);
+
+	return c;
+}
+#endif	/* ifndef YY_NO_INPUT */
+
+/** Immediately switch to a different input stream.
+ * @param input_file A readable stream.
+ * 
+ * @note This function does not reset the start condition to @c INITIAL .
+ */
+    void yyrestart  (FILE * input_file )
+{
+    
+	if ( ! YY_CURRENT_BUFFER ){
+        yyensure_buffer_stack ();
+		YY_CURRENT_BUFFER_LVALUE =
+            yy_create_buffer(yyin,YY_BUF_SIZE );
+	}
+
+	yy_init_buffer(YY_CURRENT_BUFFER,input_file );
+	yy_load_buffer_state( );
+}
+
+/** Switch to a different input buffer.
+ * @param new_buffer The new input buffer.
+ * 
+ */
+    void yy_switch_to_buffer  (YY_BUFFER_STATE  new_buffer )
+{
+    
+	/* TODO. We should be able to replace this entire function body
+	 * with
+	 *		yypop_buffer_state();
+	 *		yypush_buffer_state(new_buffer);
+     */
+	yyensure_buffer_stack ();
+	if ( YY_CURRENT_BUFFER == new_buffer )
+		return;
+
+	if ( YY_CURRENT_BUFFER )
+		{
+		/* Flush out information for old buffer. */
+		*(yy_c_buf_p) = (yy_hold_char);
+		YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
+		}
+
+	YY_CURRENT_BUFFER_LVALUE = new_buffer;
+	yy_load_buffer_state( );
+
+	/* We don't actually know whether we did this switch during
+	 * EOF (yywrap()) processing, but the only time this flag
+	 * is looked at is after yywrap() is called, so it's safe
+	 * to go ahead and always set it.
+	 */
+	(yy_did_buffer_switch_on_eof) = 1;
+}
+
+static void yy_load_buffer_state  (void)
+{
+    	(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
+	(yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
+	yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
+	(yy_hold_char) = *(yy_c_buf_p);
+}
+
+/** Allocate and initialize an input buffer state.
+ * @param file A readable stream.
+ * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
+ * 
+ * @return the allocated buffer state.
+ */
+    YY_BUFFER_STATE yy_create_buffer  (FILE * file, int  size )
+{
+	YY_BUFFER_STATE b;
+    
+	b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state )  );
+	if ( ! b )
+		YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
+
+	b->yy_buf_size = size;
+
+	/* yy_ch_buf has to be 2 characters longer than the size given because
+	 * we need to put in 2 end-of-buffer characters.
+	 */
+	b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2  );
+	if ( ! b->yy_ch_buf )
+		YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
+
+	b->yy_is_our_buffer = 1;
+
+	yy_init_buffer(b,file );
+
+	return b;
+}
+
+/** Destroy the buffer.
+ * @param b a buffer created with yy_create_buffer()
+ * 
+ */
+    void yy_delete_buffer (YY_BUFFER_STATE  b )
+{
+    
+	if ( ! b )
+		return;
+
+	if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
+		YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
+
+	if ( b->yy_is_our_buffer )
+		yyfree((void *) b->yy_ch_buf  );
+
+	yyfree((void *) b  );
+}
+
+#ifndef __cplusplus
+extern int isatty (int );
+#endif /* __cplusplus */
+    
+/* Initializes or reinitializes a buffer.
+ * This function is sometimes called more than once on the same buffer,
+ * such as during a yyrestart() or at EOF.
+ */
+    static void yy_init_buffer  (YY_BUFFER_STATE  b, FILE * file )
+
+{
+	int oerrno = errno;
+    
+	yy_flush_buffer(b );
+
+	b->yy_input_file = file;
+	b->yy_fill_buffer = 1;
+
+    /* If b is the current buffer, then yy_init_buffer was _probably_
+     * called from yyrestart() or through yy_get_next_buffer.
+     * In that case, we don't want to reset the lineno or column.
+     */
+    if (b != YY_CURRENT_BUFFER){
+        b->yy_bs_lineno = 1;
+        b->yy_bs_column = 0;
+    }
+
+        b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
+    
+	errno = oerrno;
+}
+
+/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
+ * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
+ * 
+ */
+    void yy_flush_buffer (YY_BUFFER_STATE  b )
+{
+    	if ( ! b )
+		return;
+
+	b->yy_n_chars = 0;
+
+	/* We always need two end-of-buffer characters.  The first causes
+	 * a transition to the end-of-buffer state.  The second causes
+	 * a jam in that state.
+	 */
+	b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
+	b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
+
+	b->yy_buf_pos = &b->yy_ch_buf[0];
+
+	b->yy_at_bol = 1;
+	b->yy_buffer_status = YY_BUFFER_NEW;
+
+	if ( b == YY_CURRENT_BUFFER )
+		yy_load_buffer_state( );
+}
+
+/** Pushes the new state onto the stack. The new state becomes
+ *  the current state. This function will allocate the stack
+ *  if necessary.
+ *  @param new_buffer The new state.
+ *  
+ */
+void yypush_buffer_state (YY_BUFFER_STATE new_buffer )
+{
+    	if (new_buffer == NULL)
+		return;
+
+	yyensure_buffer_stack();
+
+	/* This block is copied from yy_switch_to_buffer. */
+	if ( YY_CURRENT_BUFFER )
+		{
+		/* Flush out information for old buffer. */
+		*(yy_c_buf_p) = (yy_hold_char);
+		YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
+		YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
+		}
+
+	/* Only push if top exists. Otherwise, replace top. */
+	if (YY_CURRENT_BUFFER)
+		(yy_buffer_stack_top)++;
+	YY_CURRENT_BUFFER_LVALUE = new_buffer;
+
+	/* copied from yy_switch_to_buffer. */
+	yy_load_buffer_state( );
+	(yy_did_buffer_switch_on_eof) = 1;
+}
+
+/** Removes and deletes the top of the stack, if present.
+ *  The next element becomes the new top.
+ *  
+ */
+void yypop_buffer_state (void)
+{
+    	if (!YY_CURRENT_BUFFER)
+		return;
+
+	yy_delete_buffer(YY_CURRENT_BUFFER );
+	YY_CURRENT_BUFFER_LVALUE = NULL;
+	if ((yy_buffer_stack_top) > 0)
+		--(yy_buffer_stack_top);
+
+	if (YY_CURRENT_BUFFER) {
+		yy_load_buffer_state( );
+		(yy_did_buffer_switch_on_eof) = 1;
+	}
+}
+
+/* Allocates the stack if it does not exist.
+ *  Guarantees space for at least one push.
+ */
+static void yyensure_buffer_stack (void)
+{
+	int num_to_alloc;
+    
+	if (!(yy_buffer_stack)) {
+
+		/* First allocation is just for 2 elements, since we don't know if this
+		 * scanner will even need a stack. We use 2 instead of 1 to avoid an
+		 * immediate realloc on the next call.
+         */
+		num_to_alloc = 1;
+		(yy_buffer_stack) = (struct yy_buffer_state**)yyalloc
+								(num_to_alloc * sizeof(struct yy_buffer_state*)
+								);
+		
+		memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*));
+				
+		(yy_buffer_stack_max) = num_to_alloc;
+		(yy_buffer_stack_top) = 0;
+		return;
+	}
+
+	if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){
+
+		/* Increase the buffer to prepare for a possible push. */
+		int grow_size = 8 /* arbitrary grow size */;
+
+		num_to_alloc = (yy_buffer_stack_max) + grow_size;
+		(yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc
+								((yy_buffer_stack),
+								num_to_alloc * sizeof(struct yy_buffer_state*)
+								);
+
+		/* zero only the new slots.*/
+		memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*));
+		(yy_buffer_stack_max) = num_to_alloc;
+	}
+}
+
+/** Setup the input buffer state to scan directly from a user-specified character buffer.
+ * @param base the character buffer
+ * @param size the size in bytes of the character buffer
+ * 
+ * @return the newly allocated buffer state object. 
+ */
+YY_BUFFER_STATE yy_scan_buffer  (char * base, yy_size_t  size )
+{
+	YY_BUFFER_STATE b;
+    
+	if ( size < 2 ||
+	     base[size-2] != YY_END_OF_BUFFER_CHAR ||
+	     base[size-1] != YY_END_OF_BUFFER_CHAR )
+		/* They forgot to leave room for the EOB's. */
+		return 0;
+
+	b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state )  );
+	if ( ! b )
+		YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
+
+	b->yy_buf_size = size - 2;	/* "- 2" to take care of EOB's */
+	b->yy_buf_pos = b->yy_ch_buf = base;
+	b->yy_is_our_buffer = 0;
+	b->yy_input_file = 0;
+	b->yy_n_chars = b->yy_buf_size;
+	b->yy_is_interactive = 0;
+	b->yy_at_bol = 1;
+	b->yy_fill_buffer = 0;
+	b->yy_buffer_status = YY_BUFFER_NEW;
+
+	yy_switch_to_buffer(b  );
+
+	return b;
+}
+
+/** Setup the input buffer state to scan a string. The next call to yylex() will
+ * scan from a @e copy of @a str.
+ * @param str a NUL-terminated string to scan
+ * 
+ * @return the newly allocated buffer state object.
+ * @note If you want to scan bytes that may contain NUL values, then use
+ *       yy_scan_bytes() instead.
+ */
+YY_BUFFER_STATE yy_scan_string (yyconst char * yy_str )
+{
+    
+	return yy_scan_bytes(yy_str,strlen(yy_str) );
+}
+
+/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
+ * scan from a @e copy of @a bytes.
+ * @param bytes the byte buffer to scan
+ * @param len the number of bytes in the buffer pointed to by @a bytes.
+ * 
+ * @return the newly allocated buffer state object.
+ */
+YY_BUFFER_STATE yy_scan_bytes  (yyconst char * bytes, int  len )
+{
+	YY_BUFFER_STATE b;
+	char *buf;
+	yy_size_t n;
+	int i;
+    
+	/* Get memory for full buffer, including space for trailing EOB's. */
+	n = len + 2;
+	buf = (char *) yyalloc(n  );
+	if ( ! buf )
+		YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
+
+	for ( i = 0; i < len; ++i )
+		buf[i] = bytes[i];
+
+	buf[len] = buf[len+1] = YY_END_OF_BUFFER_CHAR;
+
+	b = yy_scan_buffer(buf,n );
+	if ( ! b )
+		YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
+
+	/* It's okay to grow etc. this buffer, and we should throw it
+	 * away when we're done.
+	 */
+	b->yy_is_our_buffer = 1;
+
+	return b;
+}
+
+#ifndef YY_EXIT_FAILURE
+#define YY_EXIT_FAILURE 2
+#endif
+
+static void yy_fatal_error (yyconst char* msg )
+{
+    	(void) fprintf( stderr, "%s\n", msg );
+	exit( YY_EXIT_FAILURE );
+}
+
+/* Redefine yyless() so it works in section 3 code. */
+
+#undef yyless
+#define yyless(n) \
+	do \
+		{ \
+		/* Undo effects of setting up yytext. */ \
+        int yyless_macro_arg = (n); \
+        YY_LESS_LINENO(yyless_macro_arg);\
+		yytext[yyleng] = (yy_hold_char); \
+		(yy_c_buf_p) = yytext + yyless_macro_arg; \
+		(yy_hold_char) = *(yy_c_buf_p); \
+		*(yy_c_buf_p) = '\0'; \
+		yyleng = yyless_macro_arg; \
+		} \
+	while ( 0 )
+
+/* Accessor  methods (get/set functions) to struct members. */
+
+/** Get the current line number.
+ * 
+ */
+int yyget_lineno  (void)
+{
+        
+    return yylineno;
+}
+
+/** Get the input stream.
+ * 
+ */
+FILE *yyget_in  (void)
+{
+        return yyin;
+}
+
+/** Get the output stream.
+ * 
+ */
+FILE *yyget_out  (void)
+{
+        return yyout;
+}
+
+/** Get the length of the current token.
+ * 
+ */
+int yyget_leng  (void)
+{
+        return yyleng;
+}
+
+/** Get the current token.
+ * 
+ */
+
+char *yyget_text  (void)
+{
+        return yytext;
+}
+
+/** Set the current line number.
+ * @param line_number
+ * 
+ */
+void yyset_lineno (int  line_number )
+{
+    
+    yylineno = line_number;
+}
+
+/** Set the input stream. This does not discard the current
+ * input buffer.
+ * @param in_str A readable stream.
+ * 
+ * @see yy_switch_to_buffer
+ */
+void yyset_in (FILE *  in_str )
+{
+        yyin = in_str ;
+}
+
+void yyset_out (FILE *  out_str )
+{
+        yyout = out_str ;
+}
+
+int yyget_debug  (void)
+{
+        return yy_flex_debug;
+}
+
+void yyset_debug (int  bdebug )
+{
+        yy_flex_debug = bdebug ;
+}
+
+/* yylex_destroy is for both reentrant and non-reentrant scanners. */
+int yylex_destroy  (void)
+{
+    
+    /* Pop the buffer stack, destroying each element. */
+	while(YY_CURRENT_BUFFER){
+		yy_delete_buffer(YY_CURRENT_BUFFER  );
+		YY_CURRENT_BUFFER_LVALUE = NULL;
+		yypop_buffer_state();
+	}
+
+	/* Destroy the stack itself. */
+	yyfree((yy_buffer_stack) );
+	(yy_buffer_stack) = NULL;
+
+    return 0;
+}
+
+/*
+ * Internal utility routines.
+ */
+
+#ifndef yytext_ptr
+static void yy_flex_strncpy (char* s1, yyconst char * s2, int n )
+{
+	register int i;
+    	for ( i = 0; i < n; ++i )
+		s1[i] = s2[i];
+}
+#endif
+
+#ifdef YY_NEED_STRLEN
+static int yy_flex_strlen (yyconst char * s )
+{
+	register int n;
+    	for ( n = 0; s[n]; ++n )
+		;
+
+	return n;
+}
+#endif
+
+void *yyalloc (yy_size_t  size )
+{
+	return (void *) malloc( size );
+}
+
+void *yyrealloc  (void * ptr, yy_size_t  size )
+{
+	/* The cast to (char *) in the following accommodates both
+	 * implementations that use char* generic pointers, and those
+	 * that use void* generic pointers.  It works with the latter
+	 * because both ANSI C and C++ allow castless assignment from
+	 * any pointer type to void*, and deal with argument conversions
+	 * as though doing an assignment.
+	 */
+	return (void *) realloc( (char *) ptr, size );
+}
+
+void yyfree (void * ptr )
+{
+	free( (char *) ptr );	/* see yyrealloc() for (char *) cast */
+}
+
+#define YYTABLES_NAME "yytables"
+
+#undef YY_NEW_FILE
+#undef YY_FLUSH_BUFFER
+#undef yy_set_bol
+#undef yy_new_buffer
+#undef yy_set_interactive
+#undef yytext_ptr
+#undef YY_DO_BEFORE_ACTION
+
+#ifdef YY_DECL_IS_OURS
+#undef YY_DECL_IS_OURS
+#undef YY_DECL
+#endif
+#line 113 "../pbm/thinkjettopbm.l"
+
+
+
+/*
+ * Application entry point
+ */
+int
+main (int argc, char **argv)
+{
+    int c;
+    char *cp;
+    int bad = 0;
+    extern int optind;
+
+    pbm_init( &argc, argv );
+
+    if ((cp = strrchr (argv[0], '/')) != NULL)
+        progname = cp + 1;
+    else
+        progname = argv[0];
+    while ((c = getopt (argc, argv, "d")) != EOF) {
+        switch (c) {
+        case 'd':
+            debugFlag++;
+            break;
+
+        default:
+            bad = 1;
+            break;
+        }
+    }
+    if (optind == (argc - 1)) {
+        if (freopen (argv[optind], "rb", stdin) == NULL) {
+            pm_error ("Can't open `%s'.  Errno = %d (%s).\n", 
+                      argv[optind], errno, strerror (errno));
+        }
+    }
+    else if (optind != argc)
+        bad = 1;
+    if (bad) {
+        pm_error ("Usage: %s [-d] [thinkjet_file]\n", progname);
+    }
+    yylex ();
+    return 0;
+}
+
+/*
+ * Finish at end of file
+ */
+static int 
+yywrap (void)
+{
+    int row;
+    unsigned char * packed_bitrow;
+
+    debug ("Got %d rows, %d columns\n", rowCount, maxRowLength);
+
+    /*
+     * Quite simple since ThinkJet bit arrangement matches PBM
+     */
+
+    overflow2(maxRowLength, 8);
+    pbm_writepbminit(stdout, maxRowLength*8, rowCount, 0);
+
+    packed_bitrow = malloc(maxRowLength);
+    if (packed_bitrow == NULL) pm_error("Out of memory");
+
+    for (row = 0 ; row < rowCount ; row++) {
+        int col;
+        for (col = 0 ; col < rows[row].length ; col++) 
+            packed_bitrow[col] = rows[row].bits[col];
+        for (        ; col < maxRowLength;      col++)
+            packed_bitrow[col] = 0;
+        pbm_writepbmrow_packed(stdout, packed_bitrow, maxRowLength*8, 0);
+    }
+    free(packed_bitrow);
+    return 1;
+}
+
+/*
+ * Print debugging message
+ */
+static void
+debug (const char *format, ...)
+{
+    va_list args;
+
+    if (debugFlag) {
+        fprintf (stderr, "%s: ", progname);
+        va_start (args, format);
+        vfprintf (stderr, format, args);
+        va_end (args);
+    }
+}
+
+
--- netpbm-free-10.0.orig/pgm/Makefile
+++ netpbm-free-10.0/pgm/Makefile
@@ -7,7 +7,7 @@
 PORTBINARIES =	asciitopgm bioradtopgm fstopgm hipstopgm \
 		lispmtopgm pbmtopgm pgmbentley pgmenhance pgmhist \
 		pgmnoise pgmramp pgmslice pgmtofs pgmtolispm \
-		pgmtopbm psidtopgm sbigtopgm
+		pgmtopbm psidtopgm sbigtopgm st4topgm
 MATHBINARIES =	pgmcrater pgmedge pgmtexture rawtopgm pgmkernel
 BINARIES =	$(PORTBINARIES) $(MATHBINARIES)
 
--- netpbm-free-10.0.orig/pgm/st4topgm.1
+++ netpbm-free-10.0/pgm/st4topgm.1
@@ -0,0 +1,27 @@
+.TH st4topgm 1 "2003-12-15" netpbm
+.IX st4topgm
+.SH NAME
+st4topgm \- convert an SBIG ST4 format file into a portable graymap
+.SH SYNOPSIS
+.B st4topgm
+.RI [ st4file ]
+.SH DESCRIPTION
+Reads an an image file in the native format used by the SBIG ST-4
+astronomical CCD camera, and produces a portable graymap as output.
+Additional information on SBIG cameras and documentation of the file
+format is available at the Web site:
+.B http://www.sbig.com/
+.SH "SEE ALSO"
+.BR pgm (5)
+.BR sbigtopgm (1)
+
+.SH AUTHOR
+Copyright (C) 2003 by Justin Pryzby <justinpryzby@users.sf.net>.
+
+.SH COPYRIGHT
+Permission to use, copy, modify, and distribute this software and its
+documentation for any purpose and without fee is hereby granted,
+provided that the above copyright notice appear in all copies and that
+both that copyright notice and this permission notice appear in
+supporting documentation.  This software is provided "as is" without
+express or implied warranty.
--- netpbm-free-10.0.orig/pgm/st4topgm.c
+++ netpbm-free-10.0/pgm/st4topgm.c
@@ -0,0 +1,140 @@
+/*
+ * st4topgm.c
+ * Justin Pryzby <justinpryzby@users.sf.net>
+ * Mon Dec 15 17:51:29 EST 2003
+ *
+ * Convert an image from an SBIG ST-4 astronomical CCD camera to pgm.
+ * See [http://www.sbig.com/].  Use sbigtopgm for all other SBIG
+ * cameras.
+ *
+ * Copyright (C) 2003 by Justin Pryzby <justinpryzby@users.sf.net>
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose and without fee is hereby granted, provided
+ * that the above copyright notice appear in all copies and that both that
+ * copyright notice and this permission notice appear in supporting
+ * documentation.  This software is provided "as is" without express or
+ * implied warranty.
+ */
+
+#include <string.h>
+#include "pgm.h"
+
+/* 192x166, a 192*165 image plus a "line" of metadata. */
+#define	FSIZE	31872
+#define	ROWS	165
+#define	COLS	192
+#define	MAXVAL	255
+
+int main(int argc, char **argv);
+void read_foot(FILE *fp);
+void trim_comment0(char *comment);
+void trim_comment1(char *comment);
+
+int main(int argc, char **argv)
+{
+	FILE *fp;
+	int row,col;
+	gray *grayrow;
+
+	pgm_init(&argc, argv);
+
+	if (argc>2) pm_usage("[st4file]");
+	else if (argc==1) fp=pm_openr_seekable("-");
+	else fp=pm_openr_seekable(argv[1]);
+
+	fseek(fp, 0, SEEK_END);
+	if (ftell(fp)!=FSIZE) pm_error("Incorrect file size.");
+
+	pgm_writepgminit(stdout, COLS, ROWS, MAXVAL, 0);
+	grayrow = pgm_allocrow(COLS);
+
+	fseek(fp, 31680, SEEK_SET);
+	read_foot(fp);
+
+	/*
+	 * Okay, the file is of the correct size, and read_foot has
+	 * confirmed the constant-position, constant value byte.  We
+	 * accept the file as valid.
+	 */
+	fseek(fp, 0, SEEK_SET);
+
+	/* Data. */
+	for (row=0; row<ROWS; row++) {
+		for (col=0; col<COLS; col++) {
+			grayrow[col]=fgetc(fp);
+		}
+
+		pgm_writepgmrow(stdout, grayrow, COLS, MAXVAL, 0);
+	}
+
+	pgm_freerow(grayrow);
+	
+	pm_close(fp);
+	pm_close(stdout);
+
+	return 0;
+}
+
+
+/* 
+ * Read the footer, which is stored in the following form.
+ * 1:       'v'.
+ * 2-79:    Freeform comment.
+ * 80-89:   Exposure time in 1/100s of a second.
+ * 90-99:   Focal length in inches.
+ * 100-109: Aperture area in square inches.
+ * 110-119: Calibration factor.
+ * 120-192: Reserved.
+ */
+void read_foot(FILE *fp)
+{
+	char buf[192];
+
+	fread(buf, 192, 1, fp);
+
+	/*
+	 * The only constant byte at a known constant offset, and thus
+	 * serves as one of our two checks of the file type.  (The other
+	 * check being the file size).
+	 */
+	if (buf[0]!='v') pm_error("Invalid file format.");
+
+	memmove(buf, buf+1, 78);
+	buf[78]=0;
+	trim_comment0(buf);
+	fprintf(stderr, "Comment:                 %80s\n", buf);
+
+	memcpy(buf, buf+79, 10);
+	buf[10]=0;
+	trim_comment1(buf);
+	fprintf(stderr, "Exposure time (1/100 s): %80s\n", buf);
+
+	memcpy(buf, buf+89, 10);
+	trim_comment1(buf);
+	fprintf(stderr, "Focal length (in):       %80s\n", buf);
+
+	memcpy(buf, buf+99, 10);
+	trim_comment1(buf);
+	fprintf(stderr, "Aperture area (sq in):   %80s\n", buf);
+
+	memcpy(buf, buf+109, 10);
+	trim_comment1(buf);
+	fprintf(stderr, "Calibration factor:      %80s\n", buf);
+}
+
+/*
+ * Trim up to 79 trailing spaces from the given string.
+ */
+void trim_comment0(char *comment)
+{
+	for ( ; comment[strlen(comment)-1]==' '; comment[strlen(comment)-1]=0);
+}
+
+/*
+ * Trim up to 79 leading spaces from the given string.
+ */
+void trim_comment1(char *comment)
+{
+	for ( ; 32==*comment; memmove(comment, comment+1, strlen(comment)));
+}
--- netpbm-free-10.0.orig/pnm/pnmnorm.c
+++ netpbm-free-10.0/pnm/pnmnorm.c
@@ -296,20 +296,29 @@
     if (bvalue > 0)
         for (i = 0; i <= bvalue-1; ++i)
             newIntensity[i] = 0;
-    {
+
+    if (wvalue > bvalue) {
         /* Map the middle intensities to 0..maxval */
-        unsigned int const range = wvalue - bvalue;
-        unsigned int val;
+        /* Size: wvalue, bvalue are xelval, so the diff fits also in xelval */
+        xelval const range = wvalue - bvalue;
+        /* As val is at maximum (wvalue - bvalue - 1) * maxval <
+         * xelval_max * xelval_max this fits into double
+         */
+        double val;
         /* The following for loop is a hand optimization of this one:
            for (i = bvalue; i <= wvalue; ++i)
            newIntensity[i] = (i-bvalue)*maxval/range);
            (with proper rounding)
+           the rounding is aequivalent to (i-bvalue)*maxval/range + .5
+           <=> ((i-bvalue)*maxval + .5*range)/range, so we set the starting
+           point to range/2
         */
-        for (i = bvalue, val = maxval/2; 
+        for (i = bvalue, val = range/2; 
              i <= wvalue; 
              ++i, val += maxval)
             newIntensity[i] = val / range;
-        }
+    }
+
     /* Map the highest intensities to maxval */
     for (i = wvalue+1; i <= maxval; ++i)
         newIntensity[i] = maxval;
--- netpbm-free-10.0.orig/pnm/pnmtofits.1
+++ netpbm-free-10.0/pnm/pnmtofits.1
@@ -28,6 +28,10 @@
 .B \-max
 can be used to set DATAMAX, DATAMIN, BSCALE and BZERO in the FITS
 header, but do not cause the data to be rescaled.
+.SH BUGS
+.PP
+FITS uses signed data, and this program outputs unsigned values. If you
+run into this problem, you might use "-min 32768".
 .SH "SEE ALSO"
 fitstopnm(1), pgm(5)
 .SH AUTHOR
--- netpbm-free-10.0.orig/pnm/pnmtopng.c
+++ netpbm-free-10.0/pnm/pnmtopng.c
@@ -212,7 +212,7 @@
                       unsigned int * const bestMatchP) {
     
     unsigned int paletteIndex;
-    unsigned int bestIndex;
+    unsigned int bestIndex = 0;
     unsigned int bestMatch;
 
     bestMatch = UINT_MAX;
@@ -222,7 +222,7 @@
         unsigned int match = 
             SQR(PPM_GETR(thisColor) - PPM_GETR(targetColor)) +
             SQR(PPM_GETG(thisColor) - PPM_GETG(targetColor)) +
-            SQR(PPM_GETB(thisColor) - PPM_GETG(targetColor));
+            SQR(PPM_GETB(thisColor) - PPM_GETB(targetColor));
 
         if (match < bestMatch) {
             bestMatch = match;
@@ -316,6 +316,7 @@
 }
 
 
+#define TEXTLINE_MAX 1024  /* some URLs are > 256 chars long */
 
 #ifdef __STDC__
 static void read_text (png_info *info_ptr, FILE *tfp)
@@ -325,21 +326,25 @@
 FILE *tfp;
 #endif
 {
-  char textline[256];
+  char textline[TEXTLINE_MAX];
   int textpos;
   int i, j;
-  int c;
+  int ch;
   char *cp;
 
+  overflow2 (MAXCOMMENTS, (int)sizeof(png_text));
   info_ptr->text = (png_text *)malloc2 (MAXCOMMENTS, sizeof (png_text));
   if(info_ptr->text == NULL)
   	pm_error("out of memory");
   j = 0;
   textpos = 0;
-  while ((c = getc (tfp)) != EOF) {
-    if (c != '\n' && c != EOF) {
+  /* loop over bytes in text file until hit EOF */
+  do {
+    /* any line >= TEXTLINE_MAX bytes long: truncate and treat as EOF */
+    ch = (textpos < TEXTLINE_MAX)? getc(tfp) : EOF;
+    if (ch != '\n' && ch != EOF) {
       overflow_add(textpos, 1);
-      textline[textpos++] = c;
+      textline[textpos++] = ch;
     } else {
       overflow_add(textpos, 1);
       textline[textpos++] = '\0';
@@ -361,7 +366,7 @@
           while (textline[i] != ' ' && textline[i] != '\t' && textline[i] != '\n')
             *(cp++) = textline[i++];
         }
-        *(cp++) = '\0';
+	*cp = '\0';	/* end of info_ptr->text[j].key */
         cp = malloc (textpos);
         info_ptr->text[j].text = cp;
         while (textline[i] == ' ' || textline[i] == '\t')
@@ -371,21 +376,27 @@
         j++;
       } else {
         j--;
+	if (info_ptr->text[j].text_length + textpos <= 0) {
+	  /* malloc() would overflow:  terminate now; lose comment */
+	  ch = EOF;
+	  break;
+	}
         overflow_add(info_ptr->text[j].text_length, textpos);
         cp = malloc (info_ptr->text[j].text_length + textpos);
         strcpy (cp, info_ptr->text[j].text);
-        strcat (cp, "\n");
-        info_ptr->text[j].text = cp;
+	cp[ info_ptr->text[j].text_length ] = '\n';
         i = 0;
         while (textline[i] == ' ' || textline[i] == '\t')
         i++;
-        strcat (cp, &textline[i]);
+        strcpy (cp + info_ptr->text[j].text_length + 1, &textline[i]);
+	free (info_ptr->text[j].text);
+	info_ptr->text[j].text = cp;
         info_ptr->text[j].text_length = strlen (cp);
         j++;
       }
       textpos = 0;
     }
-  } /* end while */
+  } while (ch != EOF);
   info_ptr->num_text = j;
 }
 
@@ -736,9 +747,9 @@
        alpha_color_pair_count is the total number of elements, i.e. the
        total number of combinations color and alpha.
     */
-    gray *alphas_of_color[MAXCOLORS];
-    unsigned int alphas_first_index[MAXCOLORS];
-    unsigned int alphas_of_color_cnt[MAXCOLORS];
+    gray *alphas_of_color[MAXCOLORS+1];
+    unsigned int alphas_first_index[MAXCOLORS+1];
+    unsigned int alphas_of_color_cnt[MAXCOLORS+1];
 
     for (color_index = 0 ; color_index < colors + 1 ; ++color_index) {
         alphas_of_color[color_index] = 
@@ -797,7 +808,7 @@
         *tooBigP = FALSE;
 
         bot_idx = 0;
-        top_idx = alphas_first_index[colors] + alphas_of_color_cnt[colors] - 1;
+        top_idx = alphas_first_index[colors-1] + alphas_of_color_cnt[colors-1] - 1;
 
         /* remap palette indices so opaque entries are last */
         for (colorIndex = 0;  colorIndex < colors;  ++colorIndex) {
@@ -889,6 +900,8 @@
         *transSizeP = 1;
         if (verbose) {
             pixel const p = palette_pnm[0];
+            pm_message("Requested transparent color (%u, %u, %u)." ,
+                       PPM_GETR(transColor), PPM_GETG(transColor), PPM_GETB(transColor));
             pm_message("Making all occurences of color (%u, %u, %u) "
                        "transparent.",
                        PPM_GETR(p), PPM_GETG(p), PPM_GETB(p));
@@ -1079,7 +1092,7 @@
       /* The color part of the color/alpha palette passed to the PNG
          compressor 
       */
-  unsigned int palette_size;
+  unsigned int palette_size = MAXCOLORS;
 
   gray trans_pnm[MAXCOLORS];
   png_byte  trans[MAXCOLORS];
--- netpbm-free-10.0.orig/pnm/pnmtops.c
+++ netpbm-free-10.0/pnm/pnmtops.c
@@ -607,7 +607,7 @@
     unsigned int const bitsRequiredByMaxval = pm_maxvaltobits(input_maxval);
 
     if (bitsRequiredByMaxval <= 2)
-        *bitspersampleP = 1;
+        *bitspersampleP = bitsRequiredByMaxval;
     else if (bitsRequiredByMaxval > 2 && bitsRequiredByMaxval <= 4)
         *bitspersampleP = 4;
     else 
--- netpbm-free-10.0.orig/ppm/Makefile
+++ netpbm-free-10.0/ppm/Makefile
@@ -29,7 +29,7 @@
 		ppmtoyuvsplit ppmtv ppmtoneo \
 		qrttoppm rawtoppm rgb3toppm sldtoppm spctoppm \
 		sputoppm tgatoppm winicontoppm ximtoppm xpmtoppm xvminitoppm \
-		yuvtoppm yuvsplittoppm
+		yuvtoppm yuvsplittoppm ppmtogif
 
 #		picttoppm 
 # We don't build vidtoppm by default, because it requires special libraries
--- netpbm-free-10.0.orig/ppm/ppmlabel.1
+++ netpbm-free-10.0/ppm/ppmlabel.1
@@ -140,6 +140,10 @@
 background, it should probably fill the space between the lines
 with the background colour.  This is tricky to get right when the
 text is rotated to a non-orthogonal angle.
+.PP
+The -size, -x, and -y options MUST precede the -text option specifying
+the string they apply to, or they will be silently ignored in favor of
+the defaults.
 .SH "SEE ALSO"
 .PD
 .BR ppmmake (1),
--- netpbm-free-10.0.orig/ppm/ppmtobmp.c
+++ netpbm-free-10.0/ppm/ppmtobmp.c
@@ -1,5 +1,5 @@
 /*\
- * $Id: ppmtobmp.c,v 1.2 2003/08/14 19:38:51 aba-guest Exp $
+ * $Id: ppmtobmp.c,v 1.4 2004/01/17 09:10:18 aba-guest Exp $
  *
  * ppmtobmp.c - Converts from a PPM file to a Microsoft Windows or OS/2
  * .BMP file.
@@ -17,6 +17,12 @@
  * without express or implied warranty.
  *
  * $Log: ppmtobmp.c,v $
+ * Revision 1.4  2004/01/17 09:10:18  aba-guest
+ * tab -> space
+ *
+ * Revision 1.3  2004/01/17 08:20:56  aba-guest
+ * fixed bbp-values
+ *
  * Revision 1.2  2003/08/14 19:38:51  aba-guest
  * First part to 9.25 update; could now be really broken
  *
@@ -496,6 +502,12 @@
 }
 
 
+#define adjust_minimum_bpp(bpp) \
+        ((bpp <= 1) ? 1 : \
+        (bpp <= 4) ? 4 : \
+        (bpp <= 8) ? 8 : \
+         24)
+
 
 static void
 analyze_colors(const pixel ** const pixels, 
@@ -538,7 +550,7 @@
         *minimum_bpp_p = 24;
         *cht_p = NULL;
     } else {
-        *minimum_bpp_p = pm_maxvaltobits(*colors_p-1);
+        *minimum_bpp_p = adjust_minimum_bpp(pm_maxvaltobits(*colors_p-1));
         pm_message("%d colors found", *colors_p);
         /*
          * Now scale the maxval to 255 as required by BMP format.
--- netpbm-free-10.0.orig/ppm/ppmtowinicon.1
+++ netpbm-free-10.0/ppm/ppmtowinicon.1
@@ -32,13 +32,22 @@
 .SH OPTIONS
 .TP
 .B \-andpgms
-If this option is given, every other file is read as an alpha mask to
-be used by windows for transparancy data for the previous image.
-(These are set to blank by default).  The alpha mask is a PGM image,
-where any value less than or equal to the maxval means transparent,
-and anything greater than the maxval means opaque.  Note that as with
-all Netpbm programs, you may use a PBM file here and it will be used
-as if it were the equivalent PGM.
+If this option is given, every second file is read as an "and mask" to be
+used by windows for transparency data for the previous image. (These are
+set to fully opaque by default). The and mask is a PGM image, where any
+pixel with maxval intensity means opaque and any other pixel means not
+opaque. Note that as with all Netpbm programs, you may use a PBM file here
+and it will be used as if it were the equivalent PGM.
+
+The and mask is like an alpha mask, except for what it signifies in the
+"not opaque" areas. In the usual case, the foreground image is black in
+those areas, and in that case the areas are fully transparent -- the
+background shows through the icon. But in general, a not opaque pixel
+signifies that the background and foreground should be merged as follows:
+The intensities of the color components in the forgeground and background
+are represented as binary numbers, then corresponding bits of the
+background and foreground intensities are exlusive-or'ed together. So there
+is a sort of reverse video effect. 
 
 .TP
 .B \-output output.ico
--- netpbm-free-10.0.orig/ppm/ppmtowinicon.c
+++ netpbm-free-10.0/ppm/ppmtowinicon.c
@@ -1,6 +1,6 @@
 /* ppmtowinicon.c - read portable pixmap file(s) and write a MS Windows .ico
 **
-** Copyright (C) 2000 by Lee Benfield - lee@recoil.org
+** Copyright (C) 2000 by Lee Benfield - lee@benf.org
 **
 ** Permission to use, copy, modify, and distribute this software and its
 ** documentation for any purpose and without fee is hereby granted, provided
@@ -14,12 +14,12 @@
  * Changelog
  *
  * 2002/01/25 - Use pbm instead of ppm for alpha maps and fix alpha
- *		sense. (black = transparent, white = opaque).
- *		Option renamed to -andpbms; -andppms retained
- *		for compatibility.
- *		ppmtowinicon should now be the true reverse of winicontoppm.
- *		Filled some "ignored" fields in ICO output for maximum
- *		compatibility.  MVB.
+ *      sense. (black = transparent, white = opaque).
+ *      Option renamed to -andpbms; -andppms retained
+ *      for compatibility.
+ *      ppmtowinicon should now be the true reverse of winicontoppm.
+ *      Filled some "ignored" fields in ICO output for maximum
+ *      compatibility.  MVB.
  *
  * 2000/05/24 - using colorhash_table instead of a straight array search
  *              Though it's a little slower for files due to the low # of
@@ -28,6 +28,8 @@
 
 #include <string.h>
 #include <math.h>
+#include <string.h>
+
 #include "winico.h"
 #include "ppm.h"
 #include "ppmcmap.h"
@@ -45,8 +47,8 @@
 static int      file_offset = 0;    /* not actually used, but useful for debug. */
 static int      readFromStdin = 0;
 static char     er_write[] = "%s: write error";
-static char *   infname  = "";
-static char *   outfname = "-";
+static const char *   infname  = "";
+static const char *   outfname = "-";
 static FILE *   ofp;
 static FILE *   ifp;
 
@@ -55,7 +57,7 @@
    
    if (putc(v, ofp) == EOF)
      {
-	pm_error(er_write, outfname);
+    pm_error(er_write, outfname);
      }
 }
    
@@ -64,7 +66,7 @@
    
    if (pm_writelittleshort(ofp, v) == -1)
      {
-	pm_error(er_write, outfname);
+    pm_error(er_write, outfname);
      }
    
 }
@@ -74,7 +76,7 @@
    
    if (pm_writelittlelong(ofp, v) == -1)
      {
-	pm_error(er_write, outfname);
+    pm_error(er_write, outfname);
      }
    
 }
@@ -89,12 +91,6 @@
    PutByte(v);
 }
 
-static void 
-writeU1String (char * const string, int const length) {
-   fwrite(string,sizeof(u1),length,ofp);
-   file_offset += length;
-}
-
 static  void 
 writeU2 (u2 const v) {
    file_offset +=2;
@@ -110,6 +106,10 @@
 static MS_Ico 
 createIconFile (void) {
    MS_Ico MSIconData = malloc( sizeof (* MSIconData) );
+
+   if (MSIconData == NULL)
+       pm_error("out of memory");
+
    MSIconData->reserved     = 0;
    MSIconData->type         = 1;
    MSIconData->count        = 0;
@@ -131,12 +131,16 @@
    int xBytes,y,x;
    int wt = cols;
    u1 ** rowData;
+   if (icBitmap == NULL)
+        pm_error("out of memory");
    wt >>= 3;
    if (wt & 3) {
       wt = (wt & ~3) + 4;
    }
    xBytes = wt;
    rowData = malloc2 ( rows , sizeof (char *));
+   if (rowData == NULL)
+        pm_error("out of memory");
    icBitmap->xBytes = xBytes;
    icBitmap->data   = rowData;
    overflow2(xBytes, rows);
@@ -145,25 +149,27 @@
       u1 * row = malloc2 ( xBytes, sizeof (u1));
       int byteOn = 0;
       int bitOn = 128;
+      if (row == NULL)
+          pm_error("out of memory");
       memset (row, 0, xBytes);
       rowData[rows-y-1] = row;
       /* 
        * Check there's a bit array, otherwise we're just faking this...
        */
       if (ba) {
-	 for (x=0;x<cols;x++) {
+         for (x=0;x<cols;x++) {
             /* Black (bit clear) is transparent in PGM alpha maps,
              * in ICO bit *set* is transparent.
              */
             if (ba[y][x] <= maxval/2) row[byteOn] |= bitOn;
 
-	    if (bitOn == 1) {
-	       byteOn++;
-	       bitOn = 128;
-	    } else {
-	       bitOn >>= 1;
-	    }
-	 }
+            if (bitOn == 1) {
+               byteOn++;
+               bitOn = 128;
+            } else {
+               bitOn >>= 1;
+            }
+         }
       }
    }
    return icBitmap;
@@ -192,46 +198,53 @@
    int xBytes,y,x;
    int wt = cols;
    u1 ** rowData;
+   if (icBitmap == NULL)
+        pm_error("out of memory");
    wt >>= 3;
    if (wt & 3) {
       wt = (wt & ~3) + 4;
    }
    xBytes = wt;
    rowData = malloc2 ( rows,  sizeof (char *));
+   if (rowData == NULL)
+        pm_error("out of memory");
    icBitmap->xBytes = xBytes;
    icBitmap->data   = rowData;
+   overflow2(xBytes, rows);
    icBitmap->size   = xBytes * rows;
    for (y=0;y<rows;y++) {
       u1 * row = malloc2 ( xBytes , sizeof (u1));
       int byteOn = 0;
       int bitOn = 128;
       int value;
+      if (row == NULL)
+         pm_error("out of memory");
       memset (row, 0, xBytes);
       rowData[rows-y-1] = row;
       /* 
        * Check there's a pixel array, otherwise we're just faking this...
        */
       if (pa) {
-	 for (x=0;x<cols;x++) {
-	    /*
-	     * So we've got a colorhash_table with two colors in it.
-	     * Which is black?!
-	     * 
-	     * Unless the hashing function changes, 0's black.
-	     */
-	    value = ppm_lookupcolor(cht, &pa[y][x]);
-	    if (!value) {
-	       /* leave black. */
-	    } else {
-	       row[byteOn] |= bitOn;
-	    }
-	    if (bitOn == 1) {
-	       byteOn++;
-	       bitOn = 128;
-	    } else {
-	       bitOn >>= 1;
-	    }
-	 }
+         for (x=0;x<cols;x++) {
+            /*
+             * So we've got a colorhash_table with two colors in it.
+             * Which is black?!
+             * 
+             * Unless the hashing function changes, 0's black.
+             */
+            value = ppm_lookupcolor(cht, &pa[y][x]);
+            if (!value) {
+               /* leave black. */
+            } else {
+               row[byteOn] |= bitOn;
+            }
+            if (bitOn == 1) {
+               byteOn++;
+               bitOn = 128;
+            } else {
+               bitOn >>= 1;
+            }
+         }
       }
    }
    return icBitmap;
@@ -249,45 +262,50 @@
    int xBytes,y,x;
    int wt = cols;
    u1 ** rowData;
+   if (icBitmap == NULL)
+        pm_error("out of memory");
    wt >>= 1;
    if (wt & 3) {
       wt = (wt & ~3) + 4;
    }
    xBytes = wt;
    rowData = malloc2 ( rows , sizeof (char *));
+   if (rowData == NULL)
+        pm_error("out of memory");
    icBitmap->xBytes = xBytes;
    icBitmap->data   = rowData;
    overflow2(xBytes, rows);
    icBitmap->size   = xBytes * rows;
-   overflow2(xBytes, rows);
 
    for (y=0;y<rows;y++) {
       u1 * row = malloc2 ( xBytes, sizeof (u1));
       int byteOn = 0;
       int nibble = 1;   /* high nibble = 1, low nibble = 0; */
       int value;
+      if (row == NULL)
+         pm_error("out of memory");
       memset (row, 0, xBytes);
       rowData[rows-y-1] = row;
       /* 
        * Check there's a pixel array, otherwise we're just faking this...
        */
       if (pa) {
-	 for (x=0;x<cols;x++) {
-	    value = ppm_lookupcolor(cht, &pa[y][x]);
-	    /*
-	     * Shift it, if we're putting it in the high nibble.
-	     */
-	    if (nibble) {
-	       value <<= 4;
-	    }
-	    row[byteOn] |= value;
-	    if (nibble) {
-	       nibble = 0;
-	    } else {
-	       nibble = 1;
-	       byteOn++;
-	    }
-	 }
+         for (x=0;x<cols;x++) {
+            value = ppm_lookupcolor(cht, &pa[y][x]);
+            /*
+             * Shift it, if we're putting it in the high nibble.
+             */
+            if (nibble) {
+               value <<= 4;
+            }
+            row[byteOn] |= value;
+            if (nibble) {
+               nibble = 0;
+            } else {
+               nibble = 1;
+               byteOn++;
+            }
+         }
       }
    }
    return icBitmap;
@@ -306,27 +324,33 @@
    int xBytes,y,x;
    int wt = cols;
    u1 ** rowData;
+   if (icBitmap == NULL)
+        pm_error("out of memory");
    if (wt & 3) {
       wt = (wt & ~3) + 4;
    }
    xBytes = wt;
    rowData = malloc2 ( rows,  sizeof (char *));
+   if (rowData == NULL)
+        pm_error("out of memory");
    icBitmap->xBytes = xBytes;
    icBitmap->data   = rowData;
-   icBitmap->size   = xBytes * rows;
    overflow2(xBytes, rows);
+   icBitmap->size   = xBytes * rows;
 
    for (y=0;y<rows;y++) {
       u1 * row = malloc2 ( xBytes, sizeof (u1));
+      if (row == NULL)
+         pm_error("out of memory");
       memset (row, 0, xBytes);
       rowData[rows-y-1] = row;
       /* 
        * Check there's a pixel array, otherwise we're just faking this...
        */
       if (pa) {
-	 for (x=0;x<cols;x++) {
-	    row[x] = ppm_lookupcolor(cht, &pa[y][x]);
-	 }
+         for (x=0;x<cols;x++) {
+            row[x] = ppm_lookupcolor(cht, &pa[y][x]);
+         }
       }
    }
    return icBitmap;
@@ -338,6 +362,9 @@
 createInfoHeader(IC_Entry const entry, ICON_bmp const xbmp,
                  ICON_bmp const abmp) {
    IC_InfoHeader ih  = malloc ( sizeof (* ih) );
+   if (ih == NULL)
+       pm_error("out of memory");
+
    ih->size          = 40;
    ih->width         = entry->width;
    ih->height        = entry->height * 2;  
@@ -358,7 +385,12 @@
 createCleanPalette(void) {
    IC_Palette palette = malloc ( sizeof (* palette) );
    int x;
-   palette->colors = malloc(MAXCOLORS * sizeof(IC_Color *));
+   if (palette == NULL)
+        pm_error("out of memory");
+   palette->colors = malloc2 (MAXCOLORS, sizeof(IC_Color *));
+   if (palette->colors == NULL)
+        pm_error("out of memory");
+
    for (x=0;x<MAXCOLORS;x++ ){
       palette->colors[x] = NULL;
    }
@@ -371,10 +403,13 @@
 addColorToPalette(IC_Palette const palette, int const i,
                   int const r, int const g, int const b) {
    palette->colors[i] = malloc ( sizeof (* palette->colors[i]) );
-   palette->colors[i]->red      = r;
-   palette->colors[i]->green    = g;
-   palette->colors[i]->blue     = b;
-   palette->colors[i]->reserved = 0;
+    if (palette->colors[i] == NULL)
+        pm_error("out of memory");
+
+    palette->colors[i]->red      = r;
+    palette->colors[i]->green    = g;
+    palette->colors[i]->blue     = b;
+    palette->colors[i]->reserved = 0;
 }
 
 
@@ -405,8 +440,8 @@
 
 
 static void 
-addEntryToIcon (MS_Ico const MSIconData, char * const xorPPM,
-                char * const andPGM) {
+addEntryToIcon (MS_Ico const MSIconData, const char * const xorPPM,
+                const char * const andPGM) {
 
    IC_Entry entry = malloc ( sizeof (* entry) );
    FILE * xorfile;
@@ -425,6 +460,9 @@
    
    pixval xorMaxval;
    gray andMaxval;
+   if (entry == NULL)
+       pm_error("out of memory");
+
    /*
     * Read the xor PPM.
     */
@@ -450,28 +488,28 @@
    xorChv = ppm_computecolorhist(xorPPMarray, xorCols, xorRows, MAXCOLORS, 
                                  &colors);
    if (xorChv == (colorhist_vector) 0)
-     pm_error("%s has too many colors - try doing a 'ppmquant %d'"
-	      , xorPPM, MAXCOLORS);
+     pm_error("%s has too many colors - try doing a 'pnmquant %d'"
+          , xorPPM, MAXCOLORS);
    if (verbose) pm_message("%d colors found", colors);
 
    if (verbose && (xorMaxval > 255))
        pm_message("maxval is not 255 - automatically rescaling colors");
    for (i = 0; i < colors; ++i)
      {
-	if (xorMaxval == 255)
-	  {
-	     addColorToPalette(palette,i,
-			       PPM_GETR(xorChv[i].color),
-			       PPM_GETG(xorChv[i].color),
-			       PPM_GETB(xorChv[i].color));
-	  }
-	else
-	  {
-	     addColorToPalette(palette,i,
-			       PPM_GETR(xorChv[i].color) * 255 / xorMaxval,
-			       PPM_GETG(xorChv[i].color) * 255 / xorMaxval,
-			       PPM_GETB(xorChv[i].color) * 255 / xorMaxval);
-	  }
+    if (xorMaxval == 255)
+      {
+         addColorToPalette(palette,i,
+                   PPM_GETR(xorChv[i].color),
+                   PPM_GETG(xorChv[i].color),
+                   PPM_GETB(xorChv[i].color));
+      }
+    else
+      {
+         addColorToPalette(palette,i,
+                   PPM_GETR(xorChv[i].color) * 255 / xorMaxval,
+                   PPM_GETG(xorChv[i].color) * 255 / xorMaxval,
+                   PPM_GETB(xorChv[i].color) * 255 / xorMaxval);
+      }
      }
    
    /* And make a hash table for fast lookup. */
@@ -643,7 +681,7 @@
    for (x=0;x<MSIconData->count;x++) {
       writeIC_InfoHeader(MSIconData->entries[x]->ih);
       for (y=0;y<(MSIconData->entries[x]->color_count);y++) {
-	 writeIC_Color(MSIconData->entries[x]->colors[y]);
+     writeIC_Color(MSIconData->entries[x]->colors[y]);
       }
       if (verbose) pm_message("writing xor bitmap\n");
       writeBitmap(MSIconData->entries[x]->xorBitmapOut,
@@ -660,88 +698,82 @@
 
 
 int 
-main (int argc, char ** argv) {
-   MS_Ico MSIconData = createIconFile();
-   int iconOn = 1;
-   int argn;
-   int offset;
-   char * usage = "[-andppms] [-output output.ico] [icon1.ppm icon2.ppm ... ]";
-   
-   /*
-    * usage:
-    * 
-    * ppmtowinicon [-andppms] icon1.ppm [icon2.ppm icon3.ppm ... ] output.ico
-    * 
-    * Use -a flag if you supply your own and bitmaps.
-    */
-   ppm_init ( &argc, argv);
-   /*
-    * Parse command line arguments.
-    */
-   argn = 1;
-   while (argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0') {
-      if (pm_keymatch(argv[argn], "-verbose", 2))
-	verbose++;
-      else if (pm_keymatch(argv[argn], "-andpgms", 2) 
-               || pm_keymatch(argv[argn], "-andppms", 2)) {
-	readAndMaps++;
-      }
-      else if (pm_keymatch(argv[argn], "-output", 2)) {
-	 if (argc - argn > 1) {
-	    outfname = argv[argn+1];
-	    argn++;
-	 } else {
-	    pm_error ("-output must be supplied a filename");
-	 }
-      }
-      else pm_usage(usage);
-      ++argn;
-   }
+main(int argc, char ** argv) {
+    MS_Ico MSIconData = createIconFile();
+    int iconOn = 1;
+    int argn;
+    int offset;
+   
+    ppm_init ( &argc, argv);
+    /*
+     * Parse command line arguments.
+     */
+    argn = 1;
+    while (argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0') {
+        if (pm_keymatch(argv[argn], "-verbose", 2))
+            verbose++;
+        else if (pm_keymatch(argv[argn], "-andpgms", 2) 
+                 || pm_keymatch(argv[argn], "-andppms", 2)) {
+            readAndMaps++;
+        }
+        else if (pm_keymatch(argv[argn], "-output", 2)) {
+            if (argc - argn > 1) {
+                outfname = argv[argn+1];
+                argn++;
+            } else {
+                pm_error ("-output must be supplied a filename");
+            }
+        }
+        else pm_error("Invalid option '%s'", argv[argn]);
+        ++argn;
+    }
    
-   if (argn < argc) {
-      /*
-       * If there's cmd line args left over, fine. 
-       * Use them later.
-       */
-   } else {
-      ifp = stdin;
-      infname = "noname";
-      readFromStdin++;
-   }
+    if (argn < argc) {
+        /*
+         * If there's cmd line args left over, fine. 
+         * Use them later.
+         */
+    } else {
+        ifp = stdin;
+        infname = "noname";
+        readFromStdin++;
+    }
 
    
-   if (readFromStdin) {
-      addEntryToIcon(MSIconData, "-", "");
-      if (verbose) pm_message ("Added entry from stdin.\n");
-   } else {
-      /*
-       * If we're not using fake and maps, then we skip 1 each time.
-       */
-      for ( iconOn = argn; iconOn < argc ; iconOn += (readAndMaps ? 2 : 1) ) {
-	 char * xorPPM;
-	 char * andPPM;
-	 xorPPM = argv[iconOn];
-	 andPPM = (readAndMaps ? argv[iconOn+1] : "");
-	 addEntryToIcon(MSIconData, xorPPM, andPPM);
-      }
-   }
-   /*
-    * Now we have to go through and calculate the offsets.
-    * The first infoheader starts at 6 + count*16 bytes.
-    */
-   offset = (MSIconData->count * 16) + 6;
-   for ( iconOn = 0; iconOn < MSIconData->count; iconOn++ ) {
-      IC_Entry entry = MSIconData->entries[iconOn];
-      entry->file_offset = offset;
-      /* 
-       * Increase the offset by the size of this offset & data.
-       * this includes the size of the color data.
-       */
-      offset += entry->size_in_bytes;
-   }
-   /*
-    * And now, we have to actually SAVE the .ico!
-    */
-   writeMS_Ico(MSIconData,argv[argc-1]);
-   return 0;
+    if (readFromStdin) {
+        addEntryToIcon(MSIconData, "-", "");
+        if (verbose) pm_message ("Added entry from stdin.\n");
+    } else {
+        /*
+         * If we're not using fake and maps, then we skip 1 each time.
+         */
+        for ( iconOn = argn; 
+              iconOn < argc ; 
+              iconOn += (readAndMaps ? 2 : 1) ) {
+            const char * xorPPM;
+            const char * andPPM;
+            xorPPM = argv[iconOn];
+            andPPM = (readAndMaps ? argv[iconOn+1] : "");
+            addEntryToIcon(MSIconData, xorPPM, andPPM);
+        }
+    }
+    /*
+     * Now we have to go through and calculate the offsets.
+     * The first infoheader starts at 6 + count*16 bytes.
+     */
+    offset = (MSIconData->count * 16) + 6;
+    for ( iconOn = 0; iconOn < MSIconData->count; iconOn++ ) {
+        IC_Entry entry = MSIconData->entries[iconOn];
+        entry->file_offset = offset;
+        /* 
+         * Increase the offset by the size of this offset & data.
+         * this includes the size of the color data.
+         */
+        offset += entry->size_in_bytes;
+    }
+    /*
+     * And now, we have to actually SAVE the .ico!
+     */
+    writeMS_Ico(MSIconData,argv[argc-1]);
+    return 0;
 }
--- netpbm-free-10.0.orig/ppm/winicontoppm.1
+++ netpbm-free-10.0/ppm/winicontoppm.1
@@ -41,6 +41,9 @@
 or
 .IB ppmdestfile _xor_1.ppm \fR.
 
+.B winicontoppm
+can convert images with 1, 4, 8, 24 or 32 bits per pixel (bpp).
+
 .IX WINICON
 .SH OPTIONS
 .TP
@@ -65,7 +68,7 @@
 .BR ppm (5)
 
 .SH AUTHOR
-Copyright (C) 2000 by Lee Benfield.
+Copyright (C) 2000, 2003 by Lee Benfield.
 .\" Permission to use, copy, modify, and distribute this software and
 .\" its documentation for any purpose and without fee is hereby granted,
 .\" provided that the above copyright notice appear in all copies and
--- netpbm-free-10.0.orig/ppm/winicontoppm.c
+++ netpbm-free-10.0/ppm/winicontoppm.c
@@ -1,6 +1,6 @@
 /* winicontoppm.c - read a MS Windows .ico file and write portable pixmap(s)
 **
-** Copyright (C) 2000 by Lee Benfield - lee@recoil.org
+** Copyright (C) 2000,2003 by Lee Benfield - lee@benf.org
 **
 ** Permission to use, copy, modify, and distribute this software and its
 ** documentation for any purpose and without fee is hereby granted, provided
@@ -8,28 +8,108 @@
 ** copyright notice and this permission notice appear in supporting
 ** documentation.  This software is provided "as is" without express or
 ** implied warranty.
+**
+** Changes:
+** 
+** 03/2003 - Added 24+32 bpp support.
 */
 
 #include <string.h>
 #include <math.h>
+#include <assert.h>
+
 #include "ppm.h"
 #include "winico.h"
 
 #define MAJVERSION 0
-#define MINVERSION 3
+#define MINVERSION 4
+
+int asprintf(char **strp, const char *fmt, ...);
 
-static int      writeToFile = 0;
-static int      verbose = 0;
-static int      allicons = 0;
-static int      writeands = 0;
-static int      bestqual = 0;
-static int      multippm = 0;
-static int      file_offset = 0;    /* not actually used, but useful for debug */
-static char     er_read[] = "%s: read error";
-static char *   infname;
-static char *   outfname;
+static int file_offset = 0;    /* not actually used, but useful for debug */
+static const char     er_read[] = "%s: read error";
+static const char *   infname;
 static FILE *   ifp;
 
+struct cmdlineInfo {
+    /* All the information the user supplied in the command line,
+       in a form easy for the program to use.
+    */
+    const char * inputFilespec;
+    const char * outputFilespec;
+    unsigned int allicons;
+    unsigned int bestqual;
+    unsigned int writeands;
+    unsigned int multippm;
+    unsigned int verbose;
+};
+
+
+
+
+static void
+parseCommandLine ( int argc, char ** argv,
+                   struct cmdlineInfo *cmdlineP ) {
+/*----------------------------------------------------------------------------
+   parse program command line described in Unix standard form by argc
+   and argv.  Return the information in the options as *cmdlineP.  
+
+   If command line is internally inconsistent (invalid options, etc.),
+   issue error message to stderr and abort program.
+
+   Note that the strings we return are stored in the storage that
+   was passed to us as the argv array.  We also trash *argv.
+-----------------------------------------------------------------------------*/
+    optEntry *option_def = malloc(100*sizeof(optEntry));
+        /* Instructions to optParseOptions3 on how to parse our options.
+         */
+    optStruct3 opt;
+
+    unsigned int option_def_index;
+
+    option_def_index = 0;   /* incremented by OPTENT3 */
+    OPTENT3(0, "allicons",     OPT_FLAG,   NULL,                  
+            &cmdlineP->allicons,       0 );
+    OPTENT3(0, "bestqual",     OPT_FLAG,   NULL,                  
+            &cmdlineP->bestqual,       0 );
+    OPTENT3(0, "writeands",    OPT_FLAG,   NULL,                  
+            &cmdlineP->writeands,      0 );
+    OPTENT3(0, "multippm",     OPT_FLAG,   NULL,                  
+            &cmdlineP->multippm,       0 );
+    OPTENT3(0, "verbose",      OPT_FLAG,   NULL,                  
+            &cmdlineP->verbose,        0 );
+
+    opt.opt_table = option_def;
+    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */
+
+    pm_optParseOptions3( &argc, argv, opt, sizeof(opt), 0);
+        /* Uses and sets argc, argv, and some of *cmdlineP and others. */
+
+
+    if (argc-1 < 1) 
+        cmdlineP->inputFilespec = "-";
+    else
+        cmdlineP->inputFilespec = argv[1];
+
+    if (argc-1 < 2) {
+        cmdlineP->outputFilespec = "-";
+        
+        if (cmdlineP->writeands || cmdlineP->allicons)
+            pm_error("If you specify the -writeands or -allicons option, "
+                     "you must also specify an output file name argument.");
+    } else
+        cmdlineP->outputFilespec = argv[2];
+
+    if (argc-1 > 2)
+        pm_error("Too many arguments (%d).  Input filespec and "
+                 "output filespec are the only possible arguments.",
+                 argc-1);
+}
+
+
+
+
 static int 
 GetByte(void) {
     int v;
@@ -86,7 +166,7 @@
     overflow_add(length,1);
     fread(string,sizeof(u1),length,ifp);
     string[length] = 0;
-    file_offset += length;
+    file_offset += length * sizeof(u1);
     return string;
 }
 
@@ -114,19 +194,18 @@
     entry->bitcount      = readU2();
     entry->size_in_bytes = readU4();
     entry->file_offset   = readU4();
-
-    /*
-     * Spec says 0 color count is really 256.
-     */
-    if (entry->color_count == 0) entry->color_count = 256;
-   
+    entry->colors        = NULL;
+    entry->ih            = NULL;
+    entry->xorBitmap     = NULL;
+    entry->andBitmap     = NULL;
+    
     return entry;
 }
 
 
 
 static IC_InfoHeader 
-readInfoHeader (void) 
+readInfoHeader (IC_Entry entry) 
 {
     IC_InfoHeader ih = malloc ( sizeof (* ih) );
     ih->size            = readU4();
@@ -140,6 +219,13 @@
     ih->y_pixels_per_m  = readU4();
     ih->colors_used     = readU4();
     ih->colors_important = readU4();
+    
+    if (!entry->bitcount) entry->bitcount = ih->bitcount;
+    if (entry->color_count == 0 && 
+        entry->bitcount <= 8) entry->color_count = 256;
+    if (ih->compression) {
+        pm_error("Can't handle compressed icons");
+    }
     return ih;
 }
 
@@ -190,7 +276,8 @@
         int xOrVal = 128;
         u1 * row = readU1String(xBytes);
         for (x = 0; x< width; x++) {
-            *(bitmap+((height-tmp-1)*width) + (x)) = (row[rowByte] & xOrVal) / xOrVal;
+            *(bitmap+((height-tmp-1)*width) + (x)) = 
+                (row[rowByte] & xOrVal) / xOrVal;
             if (xOrVal == 1) {
                 xOrVal = 128;
                 rowByte++;
@@ -198,6 +285,7 @@
                 xOrVal >>= 1;
             }
         }
+        free(row);
     }
     return bitmap;
 }
@@ -227,13 +315,15 @@
              * 2 nibbles, 2 values.
              */
             if (bottom) {
-                *(bitmap+((height-tmp-1)*width) + (x)) = (row[rowByte] & 0xF0) >> 4;
+                *(bitmap+((height-tmp-1)*width) + (x)) = 
+                    (row[rowByte] & 0xF0) >> 4;
             } else {
                 *(bitmap+((height-tmp-1)*width) + (x)) = (row[rowByte] & 0xF);
                 rowByte++;
             }
             bottom = !bottom;
         }
+    free(row);
     }
     return bitmap;
 }
@@ -262,15 +352,40 @@
             *(bitmap+((height-tmp-1)*width) + (x)) = row[rowByte];
             rowByte++;
         }
+        free(row);
     }
     return bitmap;
 }
-   
 
+/*
+ * Read a true color bitmap. (24/32 bits)
+ * 
+ * The output routine deplanarizes it for us, we keep it flat here.
+ */
+static u1 *
+readXBitmap (int width, int height, int bpp)
+{
+    int tmp = 0;
+    int bytes = bpp >> 3;
+    u1 * bitmap = malloc3 (sizeof(u1)*bytes, width, height);
+    /* remember - bmp (dib) stored upside down, so reverse */
+    u1 * bitcurptr = bitmap + (bytes * width * (height-1) ) * (sizeof (u1));
+    unsigned int xBytes = width * bytes;
+    overflow2(bytes,sizeof(u1));
+
+    if (bitmap == NULL)
+        pm_error("out of memory");
+
+    for (tmp = 0;tmp < height; tmp++, bitcurptr -= xBytes) {
+        u1 * row = readU1String(xBytes);
+        memcpy(bitcurptr, row, xBytes);
+        free(row);
+    }
+    return bitmap;
+}
 
 static MS_Ico 
-readIconFile (void) 
-{
+readIconFile (bool const verbose) {
     int iter,iter2;
 
     MS_Ico MSIconData= malloc( sizeof (* MSIconData) );
@@ -302,37 +417,55 @@
     /* After that, we have to read in the infoheader, color map (if
      * any) and the actual bit/pix maps for the icons.  
      */
-    if (verbose) fprintf (stderr,"#\tColors\tBPP\tWidth\tHeight\n");
+    if (verbose) 
+        fprintf (stderr,"#\tColors\tBPP\tWidth\tHeight\n");
     for (iter = 0;iter < MSIconData->count ; iter++ ) {
         int bpp;
-        MSIconData->entries[iter]->ih = readInfoHeader ();
-        MSIconData->entries[iter]->colors = 
-            malloc2 (MSIconData->entries[iter]->color_count,
-                    sizeof(IC_Color *));
-        for (iter2 = 0;
-             iter2 < MSIconData->entries[iter]->color_count ; 
-             iter2++ ) {
-            MSIconData->entries[iter]->colors[iter2] = readICColor();
+        MSIconData->entries[iter]->ih =
+            readInfoHeader (MSIconData->entries[iter]);
+       
+        /* What's the bits per pixel? */
+        bpp = MSIconData->entries[iter]->bitcount; 
+        /* Read the palette, if appropriate */
+        switch (bpp) {
+        case 24:
+        case 32:
+            /* 24/32 bpp icon has no palette */
+            break;
+        default:
+            MSIconData->entries[iter]->colors = 
+                malloc2 (MSIconData->entries[iter]->color_count,
+                sizeof(IC_Color *));
+            if (MSIconData->entries[iter]->colors == NULL)
+                pm_error("out of memory");
+
+            for (iter2 = 0;
+                 iter2 < MSIconData->entries[iter]->color_count ; 
+                 iter2++ ) {
+                MSIconData->entries[iter]->colors[iter2] = readICColor();
+            }
+            break;
         }
-        /* What's the bits per pixel?  Bit confusing, since there's a
-         * field in entry, and in the infoheader.  I'll use both but
-         * let the entry field take precedence.  
-         */
-        bpp = MSIconData->entries[iter]->bitcount ? 
-            MSIconData->entries[iter]->bitcount : 
-            MSIconData->entries[iter]->ih->bitcount;
-        if (verbose) 
+        if (verbose) {
+            char cols_text[10];
+            sprintf (cols_text, "%d", MSIconData->entries[iter]->color_count);
             fprintf (stderr,
-                     "%d\t%d\t%d\t%d\t%d\n", iter,
-                     MSIconData->entries[iter]->color_count, 
+                     "%d\t%s\t%d\t%d\t%d\n", iter,
+                     MSIconData->entries[iter]->color_count ? 
+                     cols_text : "TRUE",
                      bpp, MSIconData->entries[iter]->width, 
                      MSIconData->entries[iter]->height);
+        }
         /* Pixels are stored bottom-up, left-to-right. Pixel lines are
          * padded with zeros to end on a 32bit (4byte) boundary. Every
          * line will have the same number of bytes. Color indices are
          * zero based, meaning a pixel color of 0 represents the first
          * color table entry, a pixel color of 255 (if there are that
          * many) represents the 256th entry.  
+         * 
+         * 24+32 bit (16 is an abomination, which I'll avoid, and expect
+         * no-one to mind) are stored 1byte/plane with a spare (alpha?)
+         * byte for 32 bit.
          */
         {
             /*
@@ -354,8 +487,14 @@
                     read8Bitmap(MSIconData->entries[iter]->width,
                                 MSIconData->entries[iter]->height);
                 break;
+            case 24:
+            case 32:
+                MSIconData->entries[iter]->xorBitmap = 
+                    readXBitmap(MSIconData->entries[iter]->width,
+                                MSIconData->entries[iter]->height,bpp);
+                break;
             default:
-                pm_error("Uncatered bit depth %d\n",bpp);
+                pm_error("Uncatered bit depth %d",bpp);
             }
             /*
              * Read AND Bitmap
@@ -372,15 +511,13 @@
 
 
 static char * 
-trimOutputName (char * inputName)
+trimOutputName(const char inputName[])
 {
     /*
      * Just trim off the final ".ppm", if there is one, else return as is.
      * oh, for =~ ... :)
      */
-    char * outFile = malloc ( sizeof (char) * (strlen (inputName) + 1));
-    overflow_add(strlen(inputName), 1);
-    strcpy(outFile, inputName);
+    char * outFile = strdup(inputName);
     if (!strcmp (outFile + (strlen (outFile) - 4), ".ppm")) {
         *(outFile + (strlen (outFile) - 4)) = 0;
     }
@@ -412,12 +549,13 @@
     return best;
 }
 
-
-
 static void
-writeXors(bool const writeToFile, FILE * const multiOutF,
-          char outputFileBase[], IC_Entry const entry,
-          int const entryNum, bool const multiple, bool const xor) {
+writeXors(FILE *   const multiOutF,
+          char           outputFileBase[], 
+          IC_Entry const entry,
+          int      const entryNum,
+          bool     const multiple, 
+          bool     const xor) {
 /*----------------------------------------------------------------------------
    Write an "xor" image (i.e. the main image) out.
 
@@ -435,24 +573,25 @@
     FILE * outF;
     pixel ** ppm_array;
     int row;
+    int pel_size;
     char *outputFile;
+    int maxval;
+    int forcetext;
 
-    overflow_add(strlen(outputFileBase),20);
-    outputFile = malloc(sizeof(char) * (strlen (outputFileBase) + 20));
-
-    if (multiOutF)
+    if (multiOutF) {
         outF = multiOutF;
-    else {
-        if (writeToFile) {
+        outputFile = strdup("");
+    } else {
+        if (outputFileBase) {
             if (multiple) {
-                sprintf(outputFile, "%s%s_%d.ppm",
-                        outputFileBase,(xor ? "_xor" : ""), entryNum);
+                asprintf(&outputFile, "%s%s_%d.ppm",
+                          outputFileBase,(xor ? "_xor" : ""), entryNum);
             } else { 
-                sprintf(outputFile, "%s%s.ppm",
-                        outputFileBase,(xor ? "_xor" : ""));
+                asprintf(&outputFile, "%s%s.ppm",
+                          outputFileBase,(xor ? "_xor" : ""));
             }
         } else
-            strcpy(outputFile, "-");
+            outputFile = strdup("-");
         
         outF = pm_openw(outputFile);
     }
@@ -465,20 +604,39 @@
     for (row=0; row < entry->height; row++) {
         u1 * xorRow;
         int col;
-        xorRow = entry->xorBitmap + row * entry->width;
-        for (col=0; col < entry->width; col++) {
-            int colorIndex;
-            IC_Color color;
-            colorIndex  = xorRow[col];
-            color = entry->colors[colorIndex];
-            PPM_ASSIGN(ppm_array[row][col],
-                       color->red,color->green,color->blue);
+        switch (entry->bitcount) {
+        case 24:
+        case 32:
+            pel_size = entry->bitcount >> 3;
+            xorRow = entry->xorBitmap + row * entry->width * pel_size;
+            for (col=0; col < entry->width*pel_size;col+=pel_size) {
+                PPM_ASSIGN(ppm_array[row][col/pel_size],
+                           xorRow[col+2],xorRow[col+1],xorRow[col]);
+            }
+            break;
+        default:
+            xorRow = entry->xorBitmap + row * entry->width;
+            for (col=0; col < entry->width; col++) {
+                int colorIndex;
+                IC_Color color;
+                colorIndex  = xorRow[col];
+                color = entry->colors[colorIndex];
+                PPM_ASSIGN(ppm_array[row][col],
+                           color->red,color->green,color->blue);
+            }
+            break;
         }
     }    
+    
+    maxval = 255;
+    forcetext = 0;
+
     ppm_writeppm(outF,ppm_array,entry->width, entry->height, 
-                 (pixval) 255, 0);
+                 (pixval) maxval, forcetext);
     ppm_freearray(ppm_array,entry->height);
 
+    free(outputFile);
+    
     if (!multiOutF) 
         pm_close(outF);
 }
@@ -490,7 +648,7 @@
           char outputFileBase[], IC_Entry const entry, int const entryNum, 
           bool multiple) {
 /*----------------------------------------------------------------------------
-   Write an "and" image (i.e. the alpha mask) out.
+   Write the "and" image (i.e. the alpha mask) of the image 'IC_Entry' out.
 
    'multiple' means this is one of multiple images that are being written.
    'entryNum' is the sequence number within the winicon file of the image
@@ -511,13 +669,12 @@
     else {
         char *outputFile;
 
-        overflow_add(strlen(outputFileBase),20);
-        outputFile =  malloc ( sizeof (char) * (strlen (outputFileBase) + 20));
+        assert(outputFileBase);
 
-        if (allicons) 
-            sprintf(outputFile, "%s_and_%d.pbm", outputFileBase, entryNum);
+        if (multiple) 
+            asprintf(&outputFile, "%s_and_%d.pbm", outputFileBase, entryNum);
         else 
-            sprintf(outputFile, "%s_and.pbm", outputFileBase);
+            asprintf(&outputFile, "%s_and.pbm", outputFileBase);
         outF = pm_openw(outputFile);
         free(outputFile);
     }
@@ -535,28 +692,29 @@
 
     pbm_freearray(pbm_array, entry->height);
     if (!multiOutF)
-        pm_close (outF);	 
+        pm_close (outF);     
 }
 
 
 
 static void
-openMultiXor(char outputFileBase[], FILE ** const multiOutFP) {
+openMultiXor(char          outputFileBase[], 
+             bool    const writeands,
+             FILE ** const multiOutFP) {
 
     char *outputFile;
 
-    overflow_add(strlen(outputFileBase),20);
-    outputFile =  malloc ( sizeof (char) * (strlen (outputFileBase) + 20));
+    if (outputFileBase) {
+        asprintf(&outputFile, "%s%s.ppm",
+                  outputFileBase, (writeands ? "_xor" : ""));
+    } else
+        outputFile = strdup("-");
+
     /*
      * Open the output file now, it'll stay open the whole time.
      */
-    if (writeToFile) {
-        sprintf(outputFile, "%s%s.ppm",
-                outputFileBase, (writeands ? "_xor" : ""));
-    } else {
-        sprintf(outputFile,"-");
-    }
     *multiOutFP = pm_openw(outputFile);
+
     free(outputFile);
 }
 
@@ -567,84 +725,65 @@
 
     char *outputFile;
 
-    overflow_add(strlen(outputFileBase),20);
-    outputFile =  malloc ( sizeof (char) * (strlen (outputFileBase) + 20));
-    
-    sprintf(outputFile, "%s_and.pbm", outputFileBase);
+    assert(outputFileBase);
+
+    asprintf(&outputFile, "%s_and.pbm", outputFileBase);
     
     *multiAndOutFP = pm_openw(outputFile);
+
     free(outputFile);
 }
 
+static void free_iconentry(IC_Entry entry) {
+    int x;
+    if (entry->colors && entry->color_count) {
+        for (x=0;x<entry->color_count;x++) free(entry->colors[x]);
+        free(entry->colors);
+    }
+    if (entry->andBitmap) free(entry->andBitmap);
+    if (entry->xorBitmap) free(entry->xorBitmap);
+    if (entry->ih) free(entry->ih);
+    free(entry);
+}
 
+static void free_icondata(MS_Ico MSIconData)
+{
+    int x;
+    for (x=0;x<MSIconData->count;x++) {
+    free_iconentry(MSIconData->entries[x]);
+    }
+    free(MSIconData);
+}
 
 
-int main (int argc, char *argv[]) {
+int 
+main(int argc, char *argv[]) {
 
-    int argn;
+    struct cmdlineInfo cmdline;
     int startEntry, endEntry;
-    char * usage = "[-writeands] [-allicons|-bestqual] [-multippm] "
-        "[-verbose] [iconfile] [ppmdestfile]";
     MS_Ico MSIconData;
     char * outputFileBase;
-    char * outputFile;
     FILE * multiOutF;
     FILE * multiAndOutF;
    
     ppm_init (&argc, argv);
-    /*
-     * Parse command line arguments.
-     */
-    argn = 1;
-    while (argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0') {
-        if (pm_keymatch(argv[argn], "-verbose", 2))
-            verbose++;
-        else if (pm_keymatch(argv[argn], "-allicons", 2))
-            allicons++;
-        else if (pm_keymatch(argv[argn], "-bestqual", 2))
-            bestqual++;
-        else if (pm_keymatch(argv[argn], "-writeands", 2))
-            writeands++;
-        else if (pm_keymatch(argv[argn], "-multippm", 2))
-            multippm++;
-        else pm_usage(usage);
-        ++argn;
-    }
-   
-    if (bestqual && allicons) {
-        pm_message ("bestqual flag ignored.");
-        bestqual--;
-    }
-   
-    if (argn < argc) {
-        ifp = pm_openr(argv[argn]);
-        infname = argv[argn];
-        ++argn;
-    } else {
-        ifp = stdin;
-        infname = "noname";
-    }
-   
-    if (argn < argc && strcmp(argv[argn],"-")) {
-        outputFileBase = trimOutputName(argv[argn]);
-        outfname = argv[argn];
-        overflow_add(strlen(outputFileBase),20);
-        outputFile =  malloc ( sizeof (char) * (strlen (outputFileBase) + 20));
-        writeToFile++;
-        ++argn;
-    } else {
-        outfname = "noname";
-        if (allicons || writeands) {
-            pm_error("When using -allicons or -writeands, "
-                     "please supply an output filename.\n");
-        }
-        if (argn < argc) argn++;
-    }
-   
-    if (argn != argc)
-        pm_usage(usage);
+
+    parseCommandLine(argc, argv, &cmdline);
+
+    if (cmdline.bestqual && cmdline.allicons)
+        pm_message("-bestqual doesn't make sense with -allicons.  "
+                   "Ignoring -bestqual.");
    
-    MSIconData = readIconFile ();
+    if (strcmp(cmdline.outputFilespec, "-") == 0)
+        outputFileBase = NULL;
+    else
+        outputFileBase = trimOutputName(cmdline.outputFilespec);
+
+    ifp = pm_openr(cmdline.inputFilespec);
+
+    infname = cmdline.inputFilespec;
+
+    MSIconData = readIconFile(cmdline.verbose);
     /*
      * Now we've read the icon file in (Hopefully! :)
      * Go through each of the entries, and write out files of the
@@ -659,7 +798,7 @@
      * If allicons is set, we want everything, if not, just go through once.
      */
     startEntry = 0;
-    if (allicons) {
+    if (cmdline.allicons) {
         endEntry = MSIconData->count;
     } else {
         endEntry = 1;
@@ -667,17 +806,17 @@
     /*
      * If bestqual is set, find the icon with highest size & bpp.
      */
-    if (bestqual) {
+    if (cmdline.bestqual) {
         startEntry = getBestQualityIcon(MSIconData);
         endEntry = startEntry+1;
     }
    
-    if (multippm) 
-        openMultiXor(outputFileBase, &multiOutF);
+    if (cmdline.multippm) 
+        openMultiXor(outputFileBase, cmdline.writeands, &multiOutF);
     else
         multiOutF = NULL;
 
-    if (writeands && multippm) 
+    if (cmdline.writeands && cmdline.multippm) 
         openMultiAnd(outputFileBase, &multiAndOutF);
     else
         multiAndOutF = NULL;
@@ -688,17 +827,19 @@
         for (entryNum = startEntry ; entryNum < endEntry ; entryNum++ ) {
             IC_Entry const entry = MSIconData->entries[entryNum];
 
-            writeXors(writeToFile, multiOutF, outputFileBase, entry, entryNum, 
-                      allicons, writeands);
-            if (writeands)
+            writeXors(multiOutF, outputFileBase, entry, entryNum, 
+                      cmdline.allicons, cmdline.writeands);
+            if (cmdline.writeands)
                 writeAnds(multiAndOutF, outputFileBase, 
-                          entry, entryNum, allicons);
+                          entry, entryNum, cmdline.allicons);
         }
     }
     if (multiOutF)
-        pm_close (multiOutF);	 
+        pm_close (multiOutF);    
     if (multiAndOutF)
         pm_close(multiAndOutF);
+    
+    /* free up the image data here. */
+    free_icondata(MSIconData);
     return 0;
 }
-
--- netpbm-free-10.0.orig/ppm/ppmtogif.1
+++ netpbm-free-10.0/ppm/ppmtogif.1
@@ -0,0 +1,218 @@
+.TH ppmtogif 1 "20 May 2000"
+.IX ppmtogif
+.SH NAME
+ppmtogif - convert a portable pixmap into a GIF file
+.SH SYNOPSIS
+.B ppmtogif
+.RB [ -interlace ]
+.RB [ -sort ]
+.RB [ -map
+.IR mapfile ]
+.br
+.RB [ \-transparent
+.RB [ = ] \fIcolor ]
+.RB [ \-alpha
+.IR pgmfile ]
+.RB [ \-comment
+.IR text ]
+.RB [ \-nolzw ]
+.br
+.RI [ ppmfile ]
+.PP
+All options can be abbreviated to their shortest unique prefix.  You
+may use two hyphens instead of one to designate an option.  You may
+use either white space or equals signs between an option name and its
+value.
+
+.SH DESCRIPTION
+Reads a portable pixmap as input.  Produces a GIF file as output.
+
+This program creates only individual GIF images.  To combine multiple GIF
+images into an animated GIF, use 
+.BR gifsicle 
+(not part of the Netpbm package).
+
+.B ppmtogif
+creates either an original GIF87 format GIF file or the newer GIF89 format.
+It creates GIF89 when you request features that were new with GIF89, to wit
+the
+.B -transparent
+or
+.B -comment
+options.  Otherwise, it creates GIF87.  Really old GIF readers conceivably
+could not recognize GIF89.
+
+.IX GIF
+.SH OPTIONS
+.TP
+.B -interlace
+Produce an interlaced GIF file.
+.TP
+.B -sort
+Produces a GIF file with a sorted color map.
+.TP
+.B -map 
+.I mapfile
+
+Uses the colors found in the
+.I mapfile
+to create the colormap in the GIF file, instead of the colors from
+.I ppmfile.
+The
+.I mapfile
+can be any
+.I ppm
+file; all that matters is the colors in it. If the colors in
+.I ppmfile
+do not match those in
+.I mapfile
+, they are matched to a "best match." A (much) better result can be obtained by
+using the following filter in advance:
+
+.I ppmquant
+-floyd -map
+.I mapfile
+.TP
+.B \-transparent \fIcolor\fP
+.B ppmtogif
+marks the specified color as transparent in the GIF image.
+
+If you don't specify
+.BR -transparent ,
+.B ppmtogif
+does not mark any color transparent (except as indicated by the
+.B -alpha
+option).
+
+You specify the color as in
+.BR ppmmake (1).  E.g.
+.B red
+or
+.BR rgb:ff/00/0d .
+If the color you specify is not present in the image, 
+.B ppmtogif
+selects instead the color in the image that is closest to the one you
+specify.  Closeness is measured as a cartesian distance between colors
+in RGB space.  If multiple colors are equidistant, 
+.B ppmtogif
+chooses one of them arbitrarily.
+
+However, if you prefix your color specification with "=", e.g.
+
+.B -transparent==red
+
+Only the exact color you specify will be transparent.  If that color does
+not appear in the image, there will be no transparency.  
+.B ppmtogif
+issues an information message when this is the case.
+
+You cannot specify both 
+.B -transparent
+and
+.BR -alpha .
+
+.TP
+.B -alpha= \fIpgmfile
+This option names a PGM file that contains an alpha mask for the image.
+.B ppmtogif
+Creates fully transparent pixels wherever the alpha
+mask indicates transparency greater than 50%.  The color of those pixels
+is that specified by the 
+.B -alphacolor
+option, or black by default.
+
+To do this, 
+.B ppmtogif
+creates an entry in the GIF colormap in addition to the entries for colors
+that are actually in the image.  It marks that colormap entry as transparent
+and uses that colormap index in the output image to create a transparent
+pixel.
+
+The alpha image must be the same dimensions as the input image, but may
+have any maxval.  White means opaque and black means transparent.
+
+You cannot specify both 
+.B -transparent
+and
+.BR -alpha .
+
+.TP
+.B -alphacolor
+See 
+.BR -alpha .
+
+.TP
+.B \-comment \fItext\fP
+Include a comment in the GIF output with comment text 
+.IR text .
+Without this option, there are no comments in the output.
+
+.TP
+.B \-nolzw 
+This option causes the GIF output, and thus 
+.BR ppmtogif ,
+not to use LZW (Lempel-Ziv) compression.  As a result, the image file is
+larger and no royalties are owed to the holder of the patent on LZW.
+See the section LICENSE below.
+
+LZW is a method for combining the information from multiple pixels into a
+single GIF code.  With the 
+.B \-nolzw
+option, 
+.B ppmtogif
+creates one GIF code per pixel, so it is not doing any compression and not
+using LZW.  However, any GIF decoder, whether it uses an LZW decompressor
+or not, will correctly decode this uncompressed format.  An LZW decompressor
+would see this as a particular case of LZW compression.
+
+Note that if someone uses an LZW decompressor such as the one in 
+.B ppmtogif
+or pretty much any graphics display program to process the output of
+.B ppmtogif -nolzw 
+he is then using the LZW patent.  But the patent holder has expressed
+far less interest in enforcing the patent on decoding than on encoding.
+
+.SH "SEE ALSO"
+.BR giftopnm (1), 
+.BR ppmquant (1), 
+.BR pngtopnm (1),
+.BR gifsicle (1)
+<http://www.lcdf.org/gifsicle>,
+.BR ppm (5).
+.SH AUTHOR
+Based on GIFENCOD by David Rowley <mgardi@watdcsu.waterloo.edu>.
+Lempel-Ziv compression based on "compress".
+
+The non-LZW format is generated by code based on 
+.B djpeg
+by the Independent Jpeg Group.
+
+Copyright (C) 1989 by Jef Poskanzer.
+.\" Permission to use, copy, modify, and distribute this software and its
+.\" documentation for any purpose and without fee is hereby granted, provided
+.\" that the above copyright notice appear in all copies and that both that
+.\" copyright notice and this permission notice appear in supporting
+.\" documentation.  This software is provided "as is" without express or
+.\" implied warranty.
+.\"
+.\" The Graphics Interchange Format(c) is the Copyright property of
+.\" CompuServe Incorporated.  GIF(sm) is a Service Mark property of
+.\" CompuServe Incorporated.
+
+.SH LICENSE
+If you use
+.BR ppmtogif 
+without the 
+.B -nolzw
+option, you are using a patent on the LZW compression method which is
+owned by Unisys, and in all probability you do not have a license from
+Unisys to do so.  Unisys typically asks $5000 for a license for
+trivial use of the patent.  Unisys has never enforced the patent
+against trivial users.  The patent expires in 2003.
+
+Rumor has it that IBM also owns a patent covering 
+.BR ppmtogif .
+
+A replacement for the GIF format that does not require any patents to use
+is the PNG format.
+
--- netpbm-free-10.0.orig/ppm/ppmtogif.c
+++ netpbm-free-10.0/ppm/ppmtogif.c
@@ -0,0 +1,1380 @@
+/* ppmtogif.c - read a portable pixmap and produce a GIF file
+**
+** Based on GIFENCOD by David Rowley <mgardi@watdscu.waterloo.edu>.A
+** Lempel-Zim compression based on "compress".
+**
+** Modified by Marcel Wijkstra <wijkstra@fwi.uva.nl>
+**
+** The non-LZW GIF generation stuff was adapted from the Independent
+** JPEG Group's djpeg on 2001.09.29.  The uncompressed output subroutines
+** are derived directly from the corresponding subroutines in djpeg's
+** wrgif.c source file.  It's copyright notice say:
+
+ * Copyright (C) 1991-1997, Thomas G. Lane.
+ * This file is part of the Independent JPEG Group's software.
+ * For conditions of distribution and use, see the accompanying README file.
+ *
+   The reference README file is README.JPEG in the Netpbm package.
+**
+** Copyright (C) 1989 by Jef Poskanzer.
+**
+** Permission to use, copy, modify, and distribute this software and its
+** documentation for any purpose and without fee is hereby granted, provided
+** that the above copyright notice appear in all copies and that both that
+** copyright notice and this permission notice appear in supporting
+** documentation.  This software is provided "as is" without express or
+** implied warranty.
+**
+** The Graphics Interchange Format(c) is the Copyright property of
+** CompuServe Incorporated.  GIF(sm) is a Service Mark property of
+** CompuServe Incorporated.
+*/
+
+/* TODO: merge the LZW and uncompressed subroutines.  They are separate
+   only because they had two different lineages and the code is too
+   complicated for me quickly to rewrite it.
+*/
+#include "ppm.h"
+#include "ppmcmap.h"
+
+#define MAXCMAPSIZE 256
+
+/*
+ * a code_int must be able to hold 2**BITS values of type int, and also -1
+ */
+typedef int             code_int;
+
+#ifdef SIGNED_COMPARE_SLOW
+typedef unsigned long int count_int;
+typedef unsigned short int count_short;
+#else /*SIGNED_COMPARE_SLOW*/
+typedef long int          count_int;
+#endif /*SIGNED_COMPARE_SLOW*/
+
+struct cmap {
+    /* This is the information for the GIF colormap (aka palette). */
+
+    int red[MAXCMAPSIZE], green[MAXCMAPSIZE], blue[MAXCMAPSIZE];
+        /* These arrays arrays map a color index, as is found in
+           the raster part of the GIF, to an intensity value for the indicated
+           RGB component.
+        */
+    int perm[MAXCMAPSIZE], permi[MAXCMAPSIZE];
+        /* perm[i] is the position in the sorted colormap of the color which
+           is at position i in the unsorted colormap.  permi[] is the inverse
+           function of perm[].
+        */
+    int cmapsize;
+        /* Number of entries in the GIF colormap.  I.e. number of colors
+           in the image, plus possibly one fake transparency color.
+        */
+    int transparent;
+        /* color index number in GIF palette of the color that is to be
+           transparent.  -1 if no color is transparent.
+        */
+    colorhash_table cht;
+        /* A hash table that relates a PPM pixel value to to a pre-sort
+           GIF colormap index.
+        */
+    pixval maxval;
+        /* The maxval for the colors in 'cht'. */
+};
+
+struct gif_dest {
+    /* This structure controls output of uncompressed GIF raster */
+
+    /* State for packing variable-width codes into a bitstream */
+    int n_bits;         /* current number of bits/code */
+    int maxcode;        /* maximum code, given n_bits */
+    int cur_accum;      /* holds bits not yet output */
+    int cur_bits;       /* # of bits in cur_accum */
+
+    /* State for GIF code assignment */
+    int ClearCode;      /* clear code (doesn't change) */
+    int EOFCode;        /* EOF code (ditto) */
+    int code_counter;   /* counts output symbols */
+};
+
+static void BumpPixel ARGS(( void ));
+static void Putword ARGS(( int w, FILE* fp ));
+static void writeerr ARGS(( void ));
+
+struct cmdline_info {
+    /* All the information the user supplied in the command line,
+       in a form easy for the program to use.
+    */
+    char *input_filespec;  /* Filespec of input file */
+    char *alpha_filespec;  /* Filespec of alpha file; NULL if none */
+    char *alphacolor;      /* -alphacolor option value or default */
+    unsigned int interlace; /* -interlace option value */
+    unsigned int sort;     /* -sort option value */
+    char *mapfile;         /* -mapfile option value.  NULL if none. */
+    char *transparent;     /* -transparent option value.  NULL if none. */
+    char *comment;         /* -comment option value; NULL if none */
+    unsigned int nolzw;    /* -nolzw option */
+};
+
+
+static void
+parse_command_line(int argc, char ** argv,
+                   struct cmdline_info *cmdline_p) {
+/*----------------------------------------------------------------------------
+   Note that the file spec array we return is stored in the storage that
+   was passed to us as the argv array.
+-----------------------------------------------------------------------------*/
+    optStruct3 opt;  /* set by OPTENT3 */
+    optEntry *option_def = malloc(100*sizeof(optEntry));
+    unsigned int option_def_index;
+
+    option_def_index = 0;   /* incremented by OPTENT3 */
+    OPTENT3(0,   "interlace",   OPT_FLAG,   
+            NULL,                       &cmdline_p->interlace, 0);
+    OPTENT3(0,   "sort",        OPT_FLAG,   
+            NULL,                       &cmdline_p->sort, 0);
+    OPTENT3(0,   "nolzw",       OPT_FLAG,   
+            NULL,                       &cmdline_p->nolzw, 0);
+    OPTENT3(0,   "mapfile",     OPT_STRING, 
+            &cmdline_p->mapfile,        NULL, 0);
+    OPTENT3(0,   "transparent", OPT_STRING, 
+            &cmdline_p->transparent,    NULL, 0);
+    OPTENT3(0,   "comment",     OPT_STRING, 
+            &cmdline_p->comment,        NULL, 0);
+    OPTENT3(0,   "alpha",       OPT_STRING, 
+            &cmdline_p->alpha_filespec, NULL, 0);
+    OPTENT3(0,   "alphacolor",  OPT_STRING, 
+            &cmdline_p->alphacolor,     NULL, 0);
+    
+    /* Set the defaults */
+    cmdline_p->mapfile = NULL;
+    cmdline_p->transparent = NULL;  /* no transparency */
+    cmdline_p->comment = NULL;      /* no comment */
+    cmdline_p->alpha_filespec = NULL;      /* no alpha file */
+    cmdline_p->alphacolor = "rgb:0/0/0";      
+        /* We could say "black" here, but then we depend on the color names
+           database existing.
+        */
+
+    opt.opt_table = option_def;
+    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
+    opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */
+
+    pm_optParseOptions3(&argc, argv, opt, sizeof(opt), 0);
+        /* Uses and sets argc, argv, and some of *cmdline_p and others. */
+
+    if (argc-1 == 0) 
+        cmdline_p->input_filespec = "-";
+    else if (argc-1 != 1)
+        pm_error("Program takes zero or one argument (filename).  You "
+                 "specified %d", argc-1);
+    else
+        cmdline_p->input_filespec = argv[1];
+
+    if (cmdline_p->alpha_filespec && cmdline_p->transparent)
+        pm_error("You cannot specify both -alpha and -transparent.");
+}
+
+
+
+static int __inline__ sqr(const int x) {
+    return x*x;
+}
+
+
+static int __inline__
+closestcolor(const pixel color, pixval const maxval, struct cmap * cmapP) {
+/*----------------------------------------------------------------------------
+   Return the pre-sort colormap index of the color in the colormap *cmapP
+   that is closest to the color 'color', whose maxval is 'maxval'.
+
+   Also add 'color' to the colormap hash, with the colormap index we
+   are returning.  Caller must ensure that the color is not already in
+   there.
+-----------------------------------------------------------------------------*/
+    int i,r,g,b;
+    int imin,dmin;
+
+    r=(int)PPM_GETR(color)*255/maxval;
+    g=(int)PPM_GETG(color)*255/maxval;
+    b=(int)PPM_GETB(color)*255/maxval;
+
+    dmin = sqr(255)*3;
+    imin = 0;
+    for (i=0;i < cmapP->cmapsize; i++) {
+        int d;
+        d=sqr(r-cmapP->red[i])+sqr(g-cmapP->green[i])+sqr(b-cmapP->blue[i]);
+        if (d<dmin) {
+            dmin=d;
+            imin=i; 
+        } 
+    }
+    ppm_addtocolorhash(cmapP->cht,&color,cmapP->permi[imin]);
+    return cmapP->permi[imin];
+}
+
+
+
+static __inline__ int
+GetPixel(pixel ** const pixels, pixval const input_maxval,
+         gray ** const alpha, gray const alpha_threshold, 
+         struct cmap * const cmapP,
+         int const x, int const y) {
+/*----------------------------------------------------------------------------
+   Return the colormap index of the pixel at location (x,y) in the PPM
+   raster 'pixels', using colormap *cmapP.
+-----------------------------------------------------------------------------*/
+    int colorindex;
+
+    if (alpha && alpha[y][x] < alpha_threshold)
+        colorindex = cmapP->transparent;
+    else {
+        int presort_colorindex;
+
+        presort_colorindex = ppm_lookupcolor(cmapP->cht, &pixels[y][x]);
+        if (presort_colorindex == -1)
+            presort_colorindex = 
+                closestcolor(pixels[y][x], input_maxval, cmapP);
+        colorindex = cmapP->perm[presort_colorindex];
+    }
+    return colorindex;
+}
+
+
+#define TRUE 1
+#define FALSE 0
+
+static int Width, Height;
+static int curx, cury;
+static long CountDown;
+static int Pass = 0;
+static int Interlace;
+
+/*
+ * Bump the 'curx' and 'cury' to point to the next pixel
+ */
+static void
+BumpPixel()
+{
+        /*
+         * Bump the current X position
+         */
+        ++curx;
+
+        /*
+         * If we are at the end of a scan line, set curx back to the beginning
+         * If we are interlaced, bump the cury to the appropriate spot,
+         * otherwise, just increment it.
+         */
+        if( curx == Width ) {
+                curx = 0;
+
+                if( !Interlace )
+                        ++cury;
+                else {
+                     switch( Pass ) {
+
+                       case 0:
+                          cury += 8;
+                          if( cury >= Height ) {
+                                ++Pass;
+                                cury = 4;
+                          }
+                          break;
+
+                       case 1:
+                          cury += 8;
+                          if( cury >= Height ) {
+                                ++Pass;
+                                cury = 2;
+                          }
+                          break;
+
+                       case 2:
+                          cury += 4;
+                          if( cury >= Height ) {
+                             ++Pass;
+                             cury = 1;
+                          }
+                          break;
+
+                       case 3:
+                          cury += 2;
+                          break;
+                        }
+                }
+        }
+}
+
+
+
+static __inline__ int
+GIFNextPixel(pixel ** const pixels, pixval const input_maxval,
+             gray ** const alpha, gray const alpha_threshold, 
+             struct cmap * const cmapP) {
+/*----------------------------------------------------------------------------
+   Return the pre-sort color index (index into the unsorted GIF color map)
+   of the next pixel to be processed from the input image.
+
+   'alpha_threshold' is the gray level such that a pixel in the alpha
+   map whose value is less that that represents a transparent pixel
+   in the output.
+-----------------------------------------------------------------------------*/
+    int r;
+
+    if( CountDown == 0 )
+        return EOF;
+    
+    --CountDown;
+    
+    r = GetPixel(pixels, input_maxval, alpha, alpha_threshold, cmapP, 
+                 curx, cury);
+    
+    BumpPixel();
+    
+    return r;
+}
+
+
+
+static void
+write_transparent_color_index_extension(FILE *fp, const int Transparent) {
+/*----------------------------------------------------------------------------
+   Write out extension for transparent color index.
+-----------------------------------------------------------------------------*/
+
+    fputc( '!', fp );
+    fputc( 0xf9, fp );
+    fputc( 4, fp );
+    fputc( 1, fp );
+    fputc( 0, fp );
+    fputc( 0, fp );
+    fputc( Transparent, fp );
+    fputc( 0, fp );
+}
+
+
+
+static void
+write_comment_extension(FILE *fp, const char comment[]) {
+/*----------------------------------------------------------------------------
+   Write out extension for a comment
+-----------------------------------------------------------------------------*/
+    char *segment;
+    
+    fputc('!', fp);   /* Identifies an extension */
+    fputc(0xfe, fp);  /* Identifies a comment */
+
+    /* Write it out in segments no longer than 255 characters */
+    for (segment = (char *) comment; 
+         segment < comment+strlen(comment); 
+         segment += 255) {
+
+        const int length_this_segment = min(255, strlen(segment));
+
+        fputc(length_this_segment, fp);
+
+        fwrite(segment, 1, length_this_segment, fp);
+    }
+
+    fputc(0, fp);   /* No more comment blocks in this extension */
+}
+
+
+
+/***************************************************************************
+ *
+ *  GIFCOMPR.C       - GIF Image compression routines
+ *
+ *  Lempel-Ziv compression based on 'compress'.  GIF modifications by
+ *  David Rowley (mgardi@watdcsu.waterloo.edu)
+ *
+ ***************************************************************************/
+
+/*
+ * General DEFINEs
+ */
+
+#define BITS    12
+
+#define HSIZE  5003            /* 80% occupancy */
+
+#ifdef NO_UCHAR
+ typedef char   char_type;
+#else /*NO_UCHAR*/
+ typedef        unsigned char   char_type;
+#endif /*NO_UCHAR*/
+
+/*
+ *
+ * GIF Image compression - modified 'compress'
+ *
+ * Based on: compress.c - File compression ala IEEE Computer, June 1984.
+ *
+ * By Authors:  Spencer W. Thomas       (decvax!harpo!utah-cs!utah-gr!thomas)
+ *              Jim McKie               (decvax!mcvax!jim)
+ *              Steve Davies            (decvax!vax135!petsd!peora!srd)
+ *              Ken Turkowski           (decvax!decwrl!turtlevax!ken)
+ *              James A. Woods          (decvax!ihnp4!ames!jaw)
+ *              Joe Orost               (decvax!vax135!petsd!joe)
+ *
+ */
+#include <ctype.h>
+
+#define ARGVAL() (*++(*argv) || (--argc && *++argv))
+
+static int n_bits;                        /* number of bits/code */
+static int maxbits = BITS;                /* user settable max # bits/code */
+static code_int maxcode;                  /* maximum code, given n_bits */
+static code_int maxmaxcode = (code_int)1 << BITS; /* should NEVER generate this code */
+#ifdef COMPATIBLE               /* But wrong! */
+# define MAXCODE(n_bits)        ((code_int) 1 << (n_bits) - 1)
+#else /*COMPATIBLE*/
+# define MAXCODE(n_bits)        (((code_int) 1 << (n_bits)) - 1)
+#endif /*COMPATIBLE*/
+
+static count_int htab [HSIZE];
+static unsigned short codetab [HSIZE];
+#define HashTabOf(i)       htab[i]
+#define CodeTabOf(i)    codetab[i]
+
+static code_int hsize = HSIZE;                 /* for dynamic table sizing */
+
+/*
+ * To save much memory, we overlay the table used by compress() with those
+ * used by decompress().  The tab_prefix table is the same size and type
+ * as the codetab.  The tab_suffix table needs 2**BITS characters.  We
+ * get this from the beginning of htab.  The output stack uses the rest
+ * of htab, and contains characters.  There is plenty of room for any
+ * possible stack (stack used to be 8000 characters).
+ */
+
+#define tab_prefixof(i) CodeTabOf(i)
+#define tab_suffixof(i)        ((char_type*)(htab))[i]
+#define de_stack               ((char_type*)&tab_suffixof((code_int)1<<BITS))
+
+static code_int free_ent = 0;                  /* first unused entry */
+
+/*
+ * block compression parameters -- after all codes are used up,
+ * and compression rate changes, start over.
+ */
+static int clear_flg = 0;
+
+static int offset;
+static long int in_count = 1;            /* length of input */
+static long int out_count = 0;           /* # of codes output (for debugging) */
+
+/*
+ * compress stdin to stdout
+ *
+ * Algorithm:  use open addressing double hashing (no chaining) on the
+ * prefix code / next character combination.  We do a variant of Knuth's
+ * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
+ * secondary probe.  Here, the modular division first probe is gives way
+ * to a faster exclusive-or manipulation.  Also do block compression with
+ * an adaptive reset, whereby the code table is cleared when the compression
+ * ratio decreases, but after the table fills.  The variable-length output
+ * codes are re-sized at this point, and a special CLEAR code is generated
+ * for the decompressor.  Late addition:  construct the table according to
+ * file size for noticeable speed improvement on small files.  Please direct
+ * questions about this implementation to ames!jaw.
+ */
+
+static int g_init_bits;
+static FILE* g_outfile;
+
+static int ClearCode;
+static int EOFCode;
+
+/***************************************************************************
+*                          BYTE OUTPUTTER                 
+***************************************************************************/
+
+static char accum[256];
+    /* The current packet, under construction */
+static int a_count;
+    /* Number of characters so far in the current packet */
+
+static void
+char_init() {
+    a_count = 0;
+}
+
+
+
+static void
+flush_char() {
+/*----------------------------------------------------------------------------
+   Write the current packet to the output file, then reset the current 
+   packet to empty.
+-----------------------------------------------------------------------------*/
+    if( a_count > 0 ) {
+        fputc( a_count, g_outfile );
+        fwrite( accum, 1, a_count, g_outfile );
+        a_count = 0;
+    }
+}
+
+
+
+static void
+char_out( int const c ) {
+/*----------------------------------------------------------------------------
+   Add a character to the end of the current packet, and if it is 254
+   character, flush the packet to the output file.
+-----------------------------------------------------------------------------*/
+    accum[ a_count++ ] = c;
+    if( a_count >= 254 )
+        flush_char();
+}
+
+
+
+static unsigned long const masks[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F,
+                                       0x001F, 0x003F, 0x007F, 0x00FF,
+                                       0x01FF, 0x03FF, 0x07FF, 0x0FFF,
+                                       0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };
+
+static void
+output( code_int const code, FILE * const outfile ) {
+/*----------------------------------------------------------------------------
+   Output one GIF code to the file.
+
+   The code is represented as cur_bits+n_bits/8 bytes in the file.
+
+ * Inputs:
+ *      code:   A n_bits-bit integer.  If == -1, then EOF.  This assumes
+ *              that n_bits =< (long)wordsize - 1.
+ * Assumptions:
+ *      Chars are 8 bits long.
+ * Algorithm:
+ *      Maintain a BITS character long buffer (so that 8 codes will
+ * fit in it exactly).  Use the VAX insv instruction to insert each
+ * code in turn.  When the buffer fills up empty it and start over.
+
+-----------------------------------------------------------------------------*/
+    static unsigned long cur_accum = 0;
+    static int cur_bits = 0;
+
+    g_outfile = outfile;
+
+    cur_accum &= masks[ cur_bits ];
+
+    if( cur_bits > 0 )
+        cur_accum |= ((long)code << cur_bits);
+    else
+        cur_accum = code;
+
+    cur_bits += n_bits;
+
+    while( cur_bits >= 8 ) {
+        char_out( (unsigned int)(cur_accum & 0xff) );
+        cur_accum >>= 8;
+        cur_bits -= 8;
+    }
+
+    /*
+     * If the next entry is going to be too big for the code size,
+     * then increase it, if possible.
+     */
+   if ( free_ent > maxcode || clear_flg ) {
+
+            if( clear_flg ) {
+
+                maxcode = MAXCODE (n_bits = g_init_bits);
+                clear_flg = 0;
+
+            } else {
+
+                ++n_bits;
+                if ( n_bits == maxbits )
+                    maxcode = maxmaxcode;
+                else
+                    maxcode = MAXCODE(n_bits);
+            }
+        }
+
+    if( code == EOFCode ) {
+        /*
+         * At EOF, write the rest of the buffer.
+         */
+        while( cur_bits > 0 ) {
+                char_out( (unsigned int)(cur_accum & 0xff) );
+                cur_accum >>= 8;
+                cur_bits -= 8;
+        }
+
+        flush_char();
+
+        fflush( g_outfile );
+
+        if( ferror( g_outfile ) )
+                writeerr();
+    }
+}
+
+
+
+static void
+cl_hash(hsize)          /* reset code table */
+register count_int hsize;
+{
+
+        register count_int *htab_p = htab+hsize;
+
+        register long i;
+        register long m1 = -1;
+
+        i = hsize - 16;
+        do {                            /* might use Sys V memset(3) here */
+                *(htab_p-16) = m1;
+                *(htab_p-15) = m1;
+                *(htab_p-14) = m1;
+                *(htab_p-13) = m1;
+                *(htab_p-12) = m1;
+                *(htab_p-11) = m1;
+                *(htab_p-10) = m1;
+                *(htab_p-9) = m1;
+                *(htab_p-8) = m1;
+                *(htab_p-7) = m1;
+                *(htab_p-6) = m1;
+                *(htab_p-5) = m1;
+                *(htab_p-4) = m1;
+                *(htab_p-3) = m1;
+                *(htab_p-2) = m1;
+                *(htab_p-1) = m1;
+                htab_p -= 16;
+        } while ((i -= 16) >= 0);
+
+        for ( i += 16; i > 0; --i )
+                *--htab_p = m1;
+}
+
+
+/*
+ * Clear out the hash table
+ */
+static void
+cl_block (FILE * const outfile)     /* table clear for block compress */
+{
+
+        cl_hash ( (count_int) hsize );
+        free_ent = ClearCode + 2;
+        clear_flg = 1;
+
+        output( (code_int)ClearCode, outfile );
+}
+
+
+
+static void
+write_raster_LZW(pixel ** const pixels, pixval const input_maxval,
+                 gray ** const alpha, gray const alpha_maxval, 
+                 struct cmap * const cmapP, 
+                 int const init_bits, FILE * const outfile) {
+/*----------------------------------------------------------------------------
+   Write the raster to file 'outfile'.
+
+   The raster to write is 'pixels', which has maxval 'input_maxval',
+   modified by alpha mask 'alpha', which has maxval 'alpha_maxval'.
+
+   Use the colormap 'cmapP' to generate the raster ('pixels' is 
+   composed of RGB samples; the GIF raster is colormap indices).
+
+   Write the raster using LZW compression.
+-----------------------------------------------------------------------------*/
+
+    code_int ent;
+    code_int disp;
+    code_int hsize_reg;
+    int hshift;
+    bool eof;
+    gray const alpha_threshold = (alpha_maxval + 1) / 2;
+        /* gray levels below this in the alpha mask indicate transparent
+           pixels in the output image.
+        */
+    
+    /*
+     * Set up the globals:  g_init_bits - initial number of bits
+     *                      g_outfile   - pointer to output file
+     */
+    g_init_bits = init_bits;
+
+    /*
+     * Set up the necessary values
+     */
+    offset = 0;
+    out_count = 0;
+    clear_flg = 0;
+    in_count = 1;
+    maxcode = MAXCODE(n_bits = g_init_bits);
+
+    ClearCode = (1 << (init_bits - 1));
+    EOFCode = ClearCode + 1;
+    free_ent = ClearCode + 2;
+
+    char_init();
+
+    ent = GIFNextPixel(pixels, input_maxval, alpha, alpha_threshold, cmapP);
+
+    {
+        long fcode;
+        hshift = 0;
+        for ( fcode = (long) hsize;  fcode < 65536L; fcode *= 2L )
+            ++hshift;
+        hshift = 8 - hshift;                /* set hash code range bound */
+    }
+    hsize_reg = hsize;
+    cl_hash( (count_int) hsize_reg);            /* clear hash table */
+
+    output( (code_int)ClearCode, outfile );
+
+    eof = FALSE;
+    while (!eof) {
+        int gifpixel;
+            /* The value for the pixel in the GIF image.  I.e. the colormap
+               index.  Or -1 to indicate "no more pixels."
+            */
+        gifpixel = GIFNextPixel(pixels, 
+                                input_maxval, alpha, alpha_threshold, cmapP);
+        if (gifpixel == EOF) eof = TRUE;
+        if (!eof) {
+            long const fcode = (long) (((long) gifpixel << maxbits) + ent);
+            code_int i;
+                /* xor hashing */
+
+            ++in_count;
+
+            i = (((code_int)gifpixel << hshift) ^ ent);    
+
+            if ( HashTabOf (i) == fcode ) {
+                ent = CodeTabOf (i);
+                continue;
+            } else if ( (long)HashTabOf (i) < 0 )      /* empty slot */
+                goto nomatch;
+            disp = hsize_reg - i;        /* secondary hash (after G. Knott) */
+            if ( i == 0 )
+                disp = 1;
+        probe:
+            if ( (i -= disp) < 0 )
+                i += hsize_reg;
+
+            if ( HashTabOf (i) == fcode ) {
+                ent = CodeTabOf (i);
+                continue;
+            }
+            if ( (long)HashTabOf (i) > 0 )
+                goto probe;
+        nomatch:
+            output ( (code_int) ent, outfile );
+            ++out_count;
+            ent = gifpixel;
+            if ( free_ent < maxmaxcode ) {  /* } */
+                CodeTabOf (i) = free_ent++; /* code -> hashtable */
+                HashTabOf (i) = fcode;
+            } else
+                cl_block(outfile);
+        }
+    }
+    /*
+     * Put out the final code.
+     */
+    output( (code_int)ent, outfile );
+    ++out_count;
+    output( (code_int) EOFCode, outfile );
+}
+
+
+
+/* Routine to convert variable-width codes into a byte stream */
+
+static void
+output_uncompressed(struct gif_dest * const dinfo, int const code,
+                    FILE * const outfile) {
+
+    g_outfile = outfile;
+
+    /* Emit a code of n_bits bits */
+    /* Uses cur_accum and cur_bits to reblock into 8-bit bytes */
+    dinfo->cur_accum |= ((int) code) << dinfo->cur_bits;
+    dinfo->cur_bits += dinfo->n_bits;
+
+    while (dinfo->cur_bits >= 8) {
+        char_out(dinfo->cur_accum & 0xFF);
+        dinfo->cur_accum >>= 8;
+        dinfo->cur_bits -= 8;
+    }
+}
+
+
+static void
+write_raster_uncompressed_init (struct gif_dest * const dinfo, 
+                                int const i_bits, FILE * const outfile)
+/* Initialize pseudo-compressor */
+{
+  /* init all the state variables */
+  dinfo->n_bits = i_bits;
+  dinfo->maxcode = MAXCODE(dinfo->n_bits);
+  dinfo->ClearCode = (1 << (i_bits - 1));
+  dinfo->EOFCode = dinfo->ClearCode + 1;
+  dinfo->code_counter = dinfo->ClearCode + 2;
+  /* init output buffering vars */
+  dinfo->cur_accum = 0;
+  dinfo->cur_bits = 0;
+  /* GIF specifies an initial Clear code */
+  output_uncompressed(dinfo, dinfo->ClearCode, outfile);
+}
+
+
+static void
+write_raster_uncompressed_pixel (struct gif_dest * const dinfo, 
+                                 int const c, FILE * const outfile)
+/* Accept and "compress" one pixel value.
+ * The given value must be less than n_bits wide.
+ */
+{
+  /* Output the given pixel value as a symbol. */
+  output_uncompressed(dinfo, c, outfile);
+  /* Issue Clear codes often enough to keep the reader from ratcheting up
+   * its symbol size.
+   */
+  if (dinfo->code_counter < dinfo->maxcode) {
+    dinfo->code_counter++;
+  } else {
+    output_uncompressed(dinfo, dinfo->ClearCode, outfile);
+    dinfo->code_counter = dinfo->ClearCode + 2;	/* reset the counter */
+  }
+}
+
+
+static void
+write_raster_uncompressed_term (struct gif_dest * const dinfo,
+                                FILE * const outfile)
+/* Clean up at end */
+{
+  /* Send an EOF code */
+  output_uncompressed(dinfo, dinfo->EOFCode, outfile);
+  /* Flush the bit-packing buffer */
+  if (dinfo->cur_bits > 0) {
+    char_out(dinfo->cur_accum & 0xFF);
+  }
+  /* Flush the packet buffer */
+  flush_char();
+}
+
+
+
+static void
+write_raster_uncompressed(pixel ** const pixels, pixval const input_maxval,
+                          gray ** const alpha, gray const alpha_maxval, 
+                          struct cmap * const cmapP, 
+                          int const init_bits, FILE * const outfile) {
+/*----------------------------------------------------------------------------
+   Write the raster to file 'outfile'.
+   
+   Same as write_raster_LZW(), except written out one code per
+   pixel (plus some clear codes), so no compression.  And no use
+   of the LZW patent.
+-----------------------------------------------------------------------------*/
+    gray const alpha_threshold = (alpha_maxval + 1) / 2;
+        /* gray levels below this in the alpha mask indicate transparent
+           pixels in the output image.
+        */
+    bool eof;
+
+    struct gif_dest gif_dest;
+
+    write_raster_uncompressed_init(&gif_dest, init_bits, outfile);
+
+    g_outfile = outfile;
+
+    eof = FALSE;
+    while (!eof) {
+        int gifpixel;
+            /* The value for the pixel in the GIF image.  I.e. the colormap
+               index.  Or -1 to indicate "no more pixels."
+            */
+        gifpixel = GIFNextPixel(pixels, 
+                                input_maxval, alpha, alpha_threshold, cmapP);
+        if (gifpixel == EOF) eof = TRUE;
+        if (!eof) {
+            write_raster_uncompressed_pixel(&gif_dest, gifpixel, outfile);
+        }
+    }
+    write_raster_uncompressed_term(&gif_dest, outfile);
+}
+
+
+
+static void
+writeerr()
+{
+        pm_error( "error writing output file" );
+}
+
+/******************************************************************************
+ *
+ * GIF Specific routines
+ *
+ ******************************************************************************/
+
+static void
+writeGifHeader(FILE * const fp,
+               int const Width, int const Height, 
+               int const GInterlace, int const Background, 
+               int const BitsPerPixel, struct cmap * const cmapP,
+               const char comment[]) {
+
+    int B;
+    int const Resolution = BitsPerPixel;
+    int const ColorMapSize = 1 << BitsPerPixel;
+
+    /* Calculate number of bits we are expecting */
+    CountDown = (long)Width * (long)Height;
+
+    /* Indicate which pass we are on (if interlace) */
+    Pass = 0;
+
+    /* Set up the current x and y position */
+    curx = cury = 0;
+
+    /* Write the Magic header */
+    if (cmapP->transparent != -1 || comment)
+        fwrite("GIF89a", 1, 6, fp);
+    else
+        fwrite("GIF87a", 1, 6, fp);
+
+    /* Write out the screen width and height */
+    Putword( Width, fp );
+    Putword( Height, fp );
+
+    /* Indicate that there is a global colour map */
+    B = 0x80;       /* Yes, there is a color map */
+
+    /* OR in the resolution */
+    B |= (Resolution - 1) << 5;
+
+    /* OR in the Bits per Pixel */
+    B |= (BitsPerPixel - 1);
+
+    /* Write it out */
+    fputc( B, fp );
+
+    /* Write out the Background color */
+    fputc( Background, fp );
+
+    /* Byte of 0's (future expansion) */
+    fputc( 0, fp );
+
+    {
+        /* Write out the Global Color Map */
+        int i;
+        for( i=0; i < ColorMapSize; ++i ) {
+            fputc( cmapP->red[i], fp );
+            fputc( cmapP->green[i], fp );
+            fputc( cmapP->blue[i], fp );
+        }
+    }
+        
+    if ( cmapP->transparent >= 0 ) 
+        write_transparent_color_index_extension(fp, cmapP->transparent);
+
+    if ( comment )
+        write_comment_extension(fp, comment);
+}
+
+
+
+static void
+GIFEncode(FILE * const fp, 
+          pixel ** const pixels, pixval const input_maxval,
+          int const GWidth, int const GHeight, 
+          gray ** const alpha, gray const alpha_maxval,
+          int const GInterlace, int const Background, 
+          int const BitsPerPixel, struct cmap * const cmapP,
+          const char comment[], bool const nolzw) {
+
+    int const LeftOfs = 0;
+    int const TopOfs = 0;
+    int InitCodeSize;
+    
+    writeGifHeader(fp, GWidth, GHeight, GInterlace, Background,
+                   BitsPerPixel, cmapP, comment);
+
+    /* Write an Image separator */
+    fputc( ',', fp );
+
+    /* Write the Image header */
+
+    Putword( LeftOfs, fp );
+    Putword( TopOfs, fp );
+    Putword( GWidth, fp );
+    Putword( GHeight, fp );
+
+    /* Write out whether or not the image is interlaced */
+    if( GInterlace )
+        fputc( 0x40, fp );
+    else
+        fputc( 0x00, fp );
+
+    /* The initial code size */
+    if( BitsPerPixel <= 1 )
+        InitCodeSize = 2;
+    else
+        InitCodeSize = BitsPerPixel;
+
+    /* Write out the initial code size */
+    fputc( InitCodeSize, fp );
+
+    /* Set some global variables for BumpPixel() */
+    Interlace = GInterlace;
+    Width = GWidth;
+    Height = GHeight;
+
+    /* Write the actual raster */
+    if (nolzw)
+        write_raster_uncompressed(pixels, 
+                                  input_maxval, alpha, alpha_maxval, cmapP, 
+                                  InitCodeSize+1, fp);
+    else
+        write_raster_LZW(pixels, 
+                         input_maxval, alpha, alpha_maxval, cmapP, 
+                         InitCodeSize+1, fp);
+
+    /* Write out a Zero-length packet (to end the series) */
+    fputc( 0, fp );
+
+    /* Write the GIF file terminator */
+    fputc( ';', fp );
+
+    /* And close the file */
+    fclose( fp );
+}
+
+/*
+ * Write out a word to the GIF file
+ */
+static void
+Putword(int const w, FILE * const fp) {
+
+    fputc( w & 0xff, fp );
+    fputc( (w / 256) & 0xff, fp );
+}
+
+
+static int
+compute_transparent(const char colorarg[], 
+                    struct cmap * const cmapP) {
+/*----------------------------------------------------------------------------
+   Figure out the color index (index into the colormap) of the color
+   that is to be transparent in the GIF.
+
+   colorarg[] is the string that specifies the color the user wants to
+   be transparent (e.g. "red", "#fefefe").  Its maxval is the maxval
+   of the colormap.  'cmap' is the full colormap except that its
+   'transparent' component isn't valid.
+
+   colorarg[] is a standard Netpbm color specification, except that
+   may have a "=" prefix, which means it specifies a particular exact
+   color, as opposed to without the "=", which means "the color that
+   is closest to this and actually in the image."
+
+   Return -1 if colorarg[] specifies an exact color and that color is not
+   in the image.  Also issue an informational message.
+-----------------------------------------------------------------------------*/
+    int retval;
+
+    const char *colorspec;
+    bool exact;
+    int presort_colorindex;
+    pixel transcolor;
+
+    if (colorarg[0] == '=') {
+        colorspec = &colorarg[1];
+        exact = TRUE;
+    } else {
+        colorspec = colorarg;
+        exact = FALSE;
+    }
+        
+    transcolor = ppm_parsecolor((char*)colorspec, cmapP->maxval);
+    presort_colorindex = ppm_lookupcolor(cmapP->cht, &transcolor);
+    
+    if (presort_colorindex != -1)
+        retval = cmapP->perm[presort_colorindex];
+    else if (!exact)
+        retval = cmapP->perm[closestcolor(transcolor, cmapP->maxval, cmapP)];
+    else {
+        retval = -1;
+        pm_message(
+            "Warning: specified transparent color does not occur in image.");
+    }
+    return retval;
+}
+
+
+
+static void
+sort_colormap(int const sort, struct cmap * const cmapP) {
+/*----------------------------------------------------------------------------
+   Sort (in place) the colormap *cmapP.
+
+   Create the perm[] and permi[] mappings for the colormap.
+
+   'sort' is logical:  true means to sort the colormap by red intensity,
+   then by green intensity, then by blue intensity.  False means a null
+   sort -- leave it in the same order in which we found it.
+-----------------------------------------------------------------------------*/
+    int * const Red = cmapP->red;
+    int * const Blue = cmapP->blue;
+    int * const Green = cmapP->green;
+    int * const perm = cmapP->perm;
+    int * const permi = cmapP->permi;
+    unsigned int const cmapsize = cmapP->cmapsize;
+    
+    int i;
+
+    for (i=0; i < cmapsize; i++)
+        permi[i] = i;
+
+    if (sort) {
+        pm_message("sorting colormap");
+        for (i=0; i < cmapsize; i++) {
+            int j;
+            for (j=i+1; j < cmapsize; j++)
+                if (((Red[i]*MAXCMAPSIZE)+Green[i])*MAXCMAPSIZE+Blue[i] >
+                    ((Red[j]*MAXCMAPSIZE)+Green[j])*MAXCMAPSIZE+Blue[j]) {
+                    int tmp;
+                    
+                    tmp=permi[i]; permi[i]=permi[j]; permi[j]=tmp;
+                    tmp=Red[i]; Red[i]=Red[j]; Red[j]=tmp;
+                    tmp=Green[i]; Green[i]=Green[j]; Green[j]=tmp;
+                    tmp=Blue[i]; Blue[i]=Blue[j]; Blue[j]=tmp; } }
+    }
+
+    for (i=0; i < cmapsize; i++)
+        perm[permi[i]] = i;
+}
+
+
+
+static void
+normalize_to_255(colorhist_vector const chv, struct cmap * const cmapP) {
+/*----------------------------------------------------------------------------
+   With a PPM color histogram vector 'chv' as input, produce a colormap
+   of integers 0-255 as output in *cmapP.
+-----------------------------------------------------------------------------*/
+    int i;
+    pixval const maxval = cmapP->maxval;
+
+    if ( maxval != 255 )
+        pm_message(
+            "maxval is not 255 - automatically rescaling colors" );
+
+    for ( i = 0; i < cmapP->cmapsize; ++i ) {
+        if ( maxval == 255 ) {
+            cmapP->red[i] = (int) PPM_GETR( chv[i].color );
+            cmapP->green[i] = (int) PPM_GETG( chv[i].color );
+            cmapP->blue[i] = (int) PPM_GETB( chv[i].color );
+        } else {
+            cmapP->red[i] = (int) PPM_GETR( chv[i].color ) * 255 / maxval;
+            cmapP->green[i] = (int) PPM_GETG( chv[i].color ) * 255 / maxval;
+            cmapP->blue[i] = (int) PPM_GETB( chv[i].color ) * 255 / maxval;
+        }
+    }
+}
+
+
+
+static void add_to_colormap(struct cmap * const cmapP, char * const
+                            colorspec, int * new_indexP) {
+/*----------------------------------------------------------------------------
+  Add a new entry to the colormap.  Make the color that specified by
+  'colorspec', and return the index of the new entry as *new_indexP.
+
+  'colorspec' is a color specification given by the user, e.g.
+  "red" or "rgb:ff/03.0d".  The maxval for this color specification is
+  that for the colormap *cmapP.
+-----------------------------------------------------------------------------*/
+    pixel const transcolor = ppm_parsecolor((char*)colorspec, cmapP->maxval);
+    
+    *new_indexP = cmapP->cmapsize++; 
+
+    cmapP->red[*new_indexP] = PPM_GETR(transcolor);
+    cmapP->green[*new_indexP] = PPM_GETG(transcolor); 
+    cmapP->blue[*new_indexP] = PPM_GETB(transcolor); 
+}
+
+
+
+static void
+colormap_from_file(char filespec[], unsigned int const maxcolors,
+                   colorhist_vector * const chvP, pixval * const maxvalP,
+                   int * const colorsP) {
+/*----------------------------------------------------------------------------
+   Read a colormap from the PPM file filespec[].  Return the color histogram
+   vector (which is practically a colormap) of the input image as *cvhP
+   and the maxval for that histogram as *maxvalP.
+-----------------------------------------------------------------------------*/
+    FILE *mapfile;
+    int cols, rows;
+    pixel ** colormap_ppm;
+
+    mapfile = pm_openr(filespec);
+    colormap_ppm = ppm_readppm(mapfile, &cols, &rows, maxvalP);
+    pm_close(mapfile);
+    
+    /* Figure out the colormap from the <mapfile>. */
+    pm_message("computing other colormap...");
+    *chvP = 
+        ppm_computecolorhist(colormap_ppm, cols, rows, maxcolors, colorsP);
+    
+    ppm_freearray(colormap_ppm, rows); 
+}
+
+
+static void
+get_alpha(char * const alpha_filespec, int const cols, int const rows,
+          gray *** const alphaP, gray * const maxvalP) {
+
+    if (alpha_filespec) {
+        int alpha_cols, alpha_rows;
+        *alphaP = pgm_readpgm(pm_openr(alpha_filespec),
+                              &alpha_cols, &alpha_rows, maxvalP);
+        if (alpha_cols != cols || alpha_rows != rows)
+            pm_error("alpha mask is not the same dimensions as the "
+                     "input file (alpha is %dW x %dH; image is %dW x %dH)",
+                     alpha_cols, alpha_rows, cols, rows);
+    } else 
+        *alphaP = NULL;
+}
+
+
+static void
+compute_ppm_colormap(pixel ** const pixels, int const cols, int const rows,
+                     int const input_maxval, bool const have_alpha, 
+                     char * const mapfile, colorhist_vector * const chvP,
+                     colorhash_table * const chtP,
+                     pixval * const colormap_maxvalP, 
+                     int * const colorsP) {
+/*----------------------------------------------------------------------------
+   Compute a colormap, PPM style, for the image 'pixels', which is
+   'cols' by 'rows' with maxval 'input_maxval'.  If 'mapfile' is
+   non-null, Use the colors in that (PPM) file for the color map
+   instead of the colors in 'pixels'.
+
+   Return the colormap as *chvP and *chtP.  Return the maxval for that
+   colormap as *colormap_maxvalP.
+
+   While we're at it, count the colors and validate that there aren't
+   too many.  Return the count as *colorsP.  In determining if there are
+   too many, allow one slot for a fake transparency color if 'have_alpha'
+   is true.  If there are too many, issue an error message and abort the
+   program.
+-----------------------------------------------------------------------------*/
+    unsigned int maxcolors;
+        /* The most colors we can tolerate in the image.  If we have
+           our own made-up entry in the colormap for transparency, it
+           isn't included in this count.
+        */
+
+    if (have_alpha)
+        maxcolors = MAXCMAPSIZE - 1;
+    else
+        maxcolors = MAXCMAPSIZE;
+
+    if (mapfile) {
+        /* Read the colormap from a separate colormap file. */
+        colormap_from_file(mapfile, maxcolors, chvP, colormap_maxvalP, 
+                           colorsP);
+    } else {
+        /* Figure out the color map from the input file */
+        pm_message("computing colormap...");
+        *chvP = ppm_computecolorhist(pixels, cols, rows, maxcolors, colorsP); 
+        *colormap_maxvalP = input_maxval;
+    }
+
+    if (*chvP == NULL)
+        pm_error("too many colors - try doing a 'ppmquant %d'", maxcolors);
+    pm_message("%d colors found", *colorsP);
+
+    /* And make a hash table for fast lookup. */
+    *chtP = ppm_colorhisttocolorhash(*chvP, *colorsP);
+}
+
+
+
+int
+main(int argc, char *argv[]) {
+    struct cmdline_info cmdline;
+    FILE* ifp;
+    int rows, cols;
+    int BitsPerPixel;
+    pixel ** pixels;   /* The input image, in PPM format */
+    pixval input_maxval;  /* Maxval for 'pixels' */
+    gray ** alpha;     /* The supplied alpha mask; NULL if none */
+    gray alpha_maxval; /* Maxval for 'alpha' */
+
+    struct cmap cmap;
+        /* The colormap, with all its accessories */
+    colorhist_vector chv;
+    int fake_transparent;
+        /* colormap index of the fake transparency color we're using to
+           implement the alpha mask.  Undefined if we're not doing an alpha
+           mask.
+        */
+
+    ppm_init( &argc, argv );
+
+    parse_command_line(argc, argv, &cmdline);
+
+    ifp = pm_openr(cmdline.input_filespec);
+
+    pixels = ppm_readppm(ifp, &cols, &rows, &input_maxval);
+
+    pm_close(ifp);
+
+    get_alpha(cmdline.alpha_filespec, cols, rows, &alpha, &alpha_maxval);
+
+    compute_ppm_colormap(pixels, cols, rows, input_maxval, (alpha != NULL), 
+                         cmdline.mapfile, 
+                         &chv, &cmap.cht, &cmap.maxval, &cmap.cmapsize);
+
+    /* Now turn the ppm colormap into the appropriate GIF colormap. */
+
+    normalize_to_255(chv, &cmap);
+
+    ppm_freecolorhist(chv);
+
+    if (alpha) {
+        /* Add a fake entry to the end of the colormap for transparency.  
+           Make its color black. 
+        */
+        add_to_colormap(&cmap, cmdline.alphacolor, &fake_transparent);
+    }
+    sort_colormap(cmdline.sort, &cmap);
+
+    BitsPerPixel = pm_maxvaltobits(cmap.cmapsize-1);
+
+    if (alpha) {
+        cmap.transparent = cmap.perm[fake_transparent];
+    } else {
+        if (cmdline.transparent)
+            cmap.transparent = 
+                compute_transparent(cmdline.transparent, &cmap);
+        else 
+            cmap.transparent = -1;
+    }
+    /* All set, let's do it. */
+    GIFEncode(stdout, pixels, input_maxval, cols, rows, 
+              alpha, alpha_maxval, 
+              cmdline.interlace, 0, BitsPerPixel, &cmap, cmdline.comment,
+              cmdline.nolzw);
+
+    ppm_freearray(pixels, rows);
+    if (alpha)
+        pgm_freearray(alpha, rows);
+
+    exit(0);
+}
+
+
