The Independent JPEG Group's JPEG software v5
diff --git a/CHANGELOG b/CHANGELOG
deleted file mode 100644
index ccbc6ea..0000000
--- a/CHANGELOG
+++ /dev/null
@@ -1,146 +0,0 @@
-CHANGELOG for Independent JPEG Group's JPEG software
-
-
-Version 4A 18-Feb-93
---------------------
-
-Substantial speedup for grayscale output from color JPEG file (suppress
-processing of chrominance components).  Lesser speedups in Huffman decoding
-and in compression quantization.
-
-Can switch stdin/stdout to binary mode with either fdopen() or setmode();
-this allows use of one-file command line style on a wider range of systems.
-Also added -outfile switch so that makefile test scripts don't have to depend
-on the command line style.
-
-New makefile.icc for Code Builder; makefile.sas is updated for SAS C 6.x.
-
-Hook added to allow surrounding application to read and write COM (comment)
-blocks.
-
-Bugfixes (DOS only): jmemdos.c code for accessing expanded memory only worked
-if struct fields are packed on byte boundaries.  This is not true by default
-for Microsoft C.  Furthermore, Microsoft C needs an _fheapmin() call to clean
-up the far heap correctly.
-
-
-Version 4  10-Dec-92
---------------------
-
-Revised user interface: switches now use names instead of single letters.
-(Old switch letters are acceptable abbreviations of new switch names, EXCEPT
-for djpeg's old -g, -D, -1 switches.)  cjpeg has several new switches.
-
-Provision for smoothing the input image added to cjpeg.  This helps a lot with
-converting dithered GIFs to JPEG.
-
-Decoder upsampling now uses interpolation instead of pixel replication; this
-improves rendering of sharp colored edges.
-
-The decompressor will now try to continue after detecting an error in the
-compressed data, instead of just aborting.  If the input file has restart
-markers, full synchronization will usually be regained at the next undamaged
-restart marker.  (But you're still out of luck if any of the header markers
-are corrupt.)
-
-Substantial improvements in speed; DCT accuracy improved too.
-
-Numerous minor changes to improve portability.  egetopt.c, which was by far
-the worst portability problem, is gone altogether.
-
-A few bugfixes, sigh (mostly affecting DOS implementations only).
-Bugfix: on DOS machines, cjpeg -o would fail on grayscale input files.
-Bugfix: one-pass quantization to more than 64 color levels would fail on
-16-bit-int machines.  This could only happen with quantized grayscale output.
-
-A couple of changes affect code that calls the JPEG subroutine library:
-
-1. The parameter struct tag names are now capitalized (Compress_info_struct,
-Compress_methods_struct, Decompress_info_struct, Decompress_methods_struct,
-and External_methods_struct).  This makes it easier to live with brain-damaged
-compilers with short identifier lengths.  (All identifiers used in the JPEG
-code are now unique within the first 16 characters.)
-
-2. If you are not calling jselerror(), you need to initialize three new fields
-in the emethods structure, typically as follows:
-    e_methods.num_warnings = 0; /* no warnings emitted yet */
-    e_methods.first_warning_level = 0; /* display first corrupt-data warning */
-    e_methods.more_warning_level = 3; /* but suppress additional ones */
-These fields control handling of corrupt-data warnings.
-
-
-Version 3  17-Mar-92
---------------------
-
-Memory manager is finally capable of swapping to temp files.  There are
-separate versions of jmemsys.c for no temp files (same behavior as older
-versions), simple temp files with or without tmpfile(), and a DOS-specific
-version (including special code for EMS and XMS).  This is probably much more
-system-dependent than any of the older code; some bugs may surface here.
-
-Hooks added for user interface to install progress monitoring routine
-(percent-done bar, etc).  See comments with dummy progress_monitor
-routines in jcdeflts.c, jddeflts.c.
-
-Two-pass color quantization (finally!).  This is now the default method when
-quantizing; say '-1' to djpeg for quick-and-ugly 1-pass method.  There is
-a test file for checking 2-pass quantization and GIF output.
-
-Fixed bug in jcopy_block_row that broke cjpeg -o option and djpeg -b option
-on MSDOS machines.
-
-Miscellaneous small speedups; notably, DCT computation rearranged so that
-GCC "inline" feature is no longer needed for good code quality.
-
-File config.c renamed ckconfig.c to avoid name conflict with /etc/config
-on Unix systems.
-
-Added example.c to document usage of JPEG subroutines better.
-
-Memory manager now knows how to release all storage during error exit ---
-avoids memory leak when using JPEG as subroutines.  This implies a couple
-small changes to the subroutine interface: the old free_defaults subroutines
-are no longer needed, but if you have a replacement error_exit method then it
-must call the new free_all method.  Also, jselvirtmem renamed to jselmemmgr.
-
-Code for reading Targa files with 32-bit pixels was incorrect.
-
-Colorspace conversion slightly faster and more accurate; because of
-this, old "test" files will no longer match bit-for-bit.
-
-
-Version 2  13-Dec-91
---------------------
-
-Documentation improved a little --- there are man pages now.
-Installation instructions moved from README to a separate file SETUP.
-
-New program config.c is provided to help you get the configuration options
-right.  This should make installation a lot more foolproof.
-
-Sense of djpeg -D switch reversed: dithering is now ON by default.
-
-RLE image file support added (thanks to Mike Lijewski).
-
-Targa image file support added (thanks to Lee Crocker).
-
-PPM input now accepts all PPM and PGM files.
-
-Bug fix: on machines where 'int' is 16 bits, high-Q-setting JPEG files
-were not decoded correctly.
-
-Numerous changes to improve portability.  There should be few or no compiler
-warnings now.
-
-Makefiles cleaned up; defaults now appropriate for production use rather than
-debugging.
-
-Subroutine interface cleaned up.  If you wrote code based on version 1's
-jcmain/jdmain, you'll need to change it, but it should get a little shorter
-and simpler.
-
-
-Version 1   7-Oct-91
---------------------
-
-Initial public release.
diff --git a/README b/README
index 99c4d36..c882ffb 100644
--- a/README
+++ b/README
@@ -1,51 +1,65 @@
 The Independent JPEG Group's JPEG software
 ==========================================
 
-README for release 4A of 18-Feb-93
-==================================
+README for release 5 of 24-Sep-94
+=================================
 
-This distribution contains a BETA TEST release of the Independent JPEG
+This distribution contains the fifth public release of the Independent JPEG
 Group's free JPEG software.  You are welcome to redistribute this software and
 to use it for any purpose, subject to the conditions under LEGAL ISSUES, below.
 
-For installation instructions, see file SETUP.
-
-For usage instructions, see file USAGE (or the cjpeg.1 and djpeg.1 manual
-pages; but USAGE contains a "hints" section not found in the manual pages).
-Useful information can also be found in the JPEG FAQ (Frequently Asked
-Questions) article; see ARCHIVE LOCATIONS below to obtain the FAQ article.
-
-This software is still undergoing revision.  Updated versions may be obtained
-by FTP or UUCP to UUNET and other archive sites; see ARCHIVE LOCATIONS below
-for details.
-
 Serious users of this software (particularly those incorporating it into
 larger programs) should contact jpeg-info@uunet.uu.net to be added to our
 electronic mailing list.  Mailing list members are notified of updates and
 have a chance to participate in technical discussions, etc.
 
-This software is the work of Tom Lane, Philip Gladstone, Luis Ortiz, Lee
-Crocker, George Phillips, Ge' Weijers, and other members of the Independent
-JPEG Group.
+This software is the work of Tom Lane, Philip Gladstone, Luis Ortiz, Jim
+Boucher, Lee Crocker, George Phillips, Davide Rossi, Ge' Weijers, and other
+members of the Independent JPEG Group.
+
+IJG is not associated with the official ISO JPEG standards committee.
 
 
-DISCLAIMER
-==========
+DOCUMENTATION ROADMAP
+=====================
 
-THIS SOFTWARE IS NOT COMPLETE NOR FULLY DEBUGGED.  It is not guaranteed to be
-useful for anything, nor to be compatible with subsequent releases, nor to be
-an accurate implementation of the JPEG standard.  (See LEGAL ISSUES for even
-more disclaimers.)
+This file contains the following sections:
 
-Despite that, we believe that this software is pretty good, and if you find
-any problems with it, we'd like to know about them.  Please report problems
-by e-mail to jpeg-info@uunet.uu.net.
+OVERVIEW            General description of JPEG and the IJG software.
+LEGAL ISSUES        Copyright, lack of warranty, terms of distribution.
+REFERENCES          Where to learn more about JPEG.
+ARCHIVE LOCATIONS   Where to find newer versions of this software.
+RELATED SOFTWARE    Other stuff you should get.
+FILE FORMAT WARS    Software *not* to get.
+TO DO               Plans for future IJG releases.
+
+Other documentation files in the distribution are:
+
+User documentation:
+  install.doc       How to configure and install the IJG software.
+  usage.doc         Usage instructions for cjpeg, djpeg, rdjpgcom, wrjpgcom.
+  *.1               Unix-style man pages for programs (same info as usage.doc).
+  change.log        Version-to-version change highlights.
+Programmer and internal documentation:
+  libjpeg.doc       How to use the JPEG library in your own programs.
+  example.c         Sample code for calling the JPEG library.
+  structure.doc     Overview of the JPEG library's internal structure.
+  filelist.doc      Road map of IJG files.
+  coderules.doc     Coding style rules --- please read if you contribute code.
+
+Please read at least the files install.doc and usage.doc.  Useful information
+can also be found in the JPEG FAQ (Frequently Asked Questions) article.  See
+ARCHIVE LOCATIONS below to find out where to obtain the FAQ article.
+
+If you want to understand how the JPEG code works, we suggest reading one or
+more of the REFERENCES, then looking at the documentation files (in roughly
+the order listed) before diving into the code.
 
 
-WHAT'S HERE
-===========
+OVERVIEW
+========
 
-This distribution contains C software to implement JPEG image compression and
+This package contains C software to implement JPEG image compression and
 decompression.  JPEG (pronounced "jay-peg") is a standardized compression
 method for full-color and gray-scale images.  JPEG is intended for compressing
 "real-world" scenes; cartoons and other non-realistic images are not its
@@ -57,19 +71,27 @@
 For more details, see the references, or just experiment with various
 compression settings.
 
-The software implements JPEG baseline and extended-sequential compression
+We provide a set of library routines for reading and writing JPEG image files,
+plus two simple applications "cjpeg" and "djpeg", which use the library to
+perform conversion between JPEG and some other popular image file formats.
+The library is intended to be reused in other applications.
+
+This software implements JPEG baseline and extended-sequential compression
 processes.  Provision is made for supporting all variants of these processes,
 although some uncommon parameter settings aren't implemented yet.  For legal
 reasons, we are not distributing code for the arithmetic-coding process; see
 LEGAL ISSUES.  At present we have made no provision for supporting the
 progressive, hierarchical, or lossless processes defined in the standard.
+(Support for progressive mode may be offered in a future release.)
 
 In order to support file conversion and viewing software, we have included
 considerable functionality beyond the bare JPEG coding/decoding capability;
 for example, the color quantization modules are not strictly part of JPEG
 decoding, but they are essential for output to colormapped file formats or
-colormapped displays.  These extra functions can be compiled out if not
-required for a particular application.
+colormapped displays.  These extra functions can be compiled out of the
+library if not required for a particular application.  We have also included
+two simple applications for inserting and extracting textual comments in
+JFIF files.
 
 The emphasis in designing this software has been on achieving portability and
 flexibility, while also making it fast enough to be useful.  In particular,
@@ -78,258 +100,31 @@
 package will someday be industrial-strength code, much remains to be done in
 performance tuning and in improving the capabilities of individual modules.
 
-
-This software can be used on several levels:
-
-* As canned software for JPEG compression and decompression.  Just edit the
-  Makefile and configuration files as needed (see file SETUP), compile and go.
-  Members of the Independent JPEG Group will improve the out-of-the-box
-  functionality and speed as time goes on.
-
-* As the basis for other JPEG programs.  For example, you could incorporate
-  the decompressor into a general image viewing package by replacing the
-  output module with write-to-screen functions.  For an implementation on
-  specific hardware, you might want to replace some of the inner loops with
-  assembly code.  For a non-command-line-driven system, you might want a
-  different user interface.  (Members of the group will be producing Macintosh
-  and Amiga versions with more appropriate user interfaces, for example.)
-
-* As a toolkit for experimentation with JPEG and JPEG-like algorithms.  Most
-  of the individual decisions you might want to mess with are packaged up into
-  separate modules.  For example, the details of color-space conversion and
-  subsampling techniques are each localized in one compressor and one
-  decompressor module.  You'd probably also want to extend the user interface
-  to give you more detailed control over the JPEG compression parameters.
-
-In particular, we welcome the use of this software as a component of commercial
-products; no royalty is required.
-
-
-ARCHIVE LOCATIONS
-=================
-
-[Version 4A is a beta-test release and will not be publicly archived.
-The following paragraphs refer to the most recent official release.]
-
-The "official" archive site for this software is ftp.uu.net (Internet
-address 137.39.1.9 or 192.48.96.9).  The most recent released version can
-always be found there in directory graphics/jpeg.  This particular version
-will be archived as jpegsrc.v4.tar.Z.  If you are on the Internet, you can
-retrieve files from UUNET by anonymous FTP.  If you don't have FTP access,
-UUNET's archives are also available via UUCP; contact postmaster@uunet.uu.net
-for information on retrieving files that way.
-
-Numerous Internet sites maintain copies of the UUNET files; in particular,
-you can probably find a copy at any site that archives comp.sources.misc
-submissions.  However, only ftp.uu.net is guaranteed to have the latest
-official version.
-
-You can also obtain this software from CompuServe, in the GRAPHSUPPORT forum
-(GO PICS), library 15; this version will be file jpsrc4.zip.  Again,
-CompuServe is not guaranteed to have the very latest version.
-
-The JPEG FAQ (Frequently Asked Questions) article is a useful source of
-general information about JPEG.  It is updated constantly and therefore
-is not included in this distribution.  The FAQ is posted every two weeks
-to Usenet newsgroups comp.graphics, news.answers, and other groups.  You
-can always obtain the latest version from the news.answers archive at
-rtfm.mit.edu (18.172.1.27).  By FTP, fetch /pub/usenet/news.answers/jpeg-faq.
-If you don't have FTP, send e-mail to mail-server@rtfm.mit.edu with body
-"send usenet/news.answers/jpeg-faq".
-
-
-SUPPORTING SOFTWARE
-===================
-
-You will probably want Jef Poskanzer's PBMPLUS image software, which provides
-many useful operations on PPM-format image files.  In particular, it can
-convert PPM images to and from a wide range of other formats.  You can FTP
-this free software from export.lcs.mit.edu (contrib/pbmplus*.tar.Z) or
-ftp.ee.lbl.gov (pbmplus*.tar.Z).  Unfortunately PBMPLUS is not nearly as
-portable as the JPEG software is; you are likely to have difficulty making it
-work on any non-Unix machine.
-
-If you are using X Windows you might want to use the xv or xloadimage viewers
-to save yourself the trouble of converting PPM to some other format.  Both of
-these can be found in the contrib directory at export.lcs.mit.edu.  Actually,
-xv version 2.00 and up incorporates our software and thus can read and write
-JPEG files directly.  (NOTE: since xv internally reduces all images to 8
-bits/pixel, a JPEG file written by xv will not be very high quality; and xv
-cannot fully exploit a 24-bit display.  These problems are expected to go away
-in the next xv release, planned for early 1993.  In the meantime, use
-xloadimage for 24-bit displays.)
-
-For DOS machines, Lee Crocker's free Piclab program is a useful companion to
-the JPEG software.  The latest version, currently 1.91, is available by FTP
-from SIMTEL20 and its various mirror sites, file <msdos.graphics>piclb191.zip.
-CompuServe also has it, in the same library as the JPEG software.
-
-
-SOFTWARE THAT'S NO HELP AT ALL
-==============================
-
-Handmade Software's shareware PC program GIF2JPG produces files that are
-totally incompatible with our programs.  They use a proprietary format that is
-an amalgam of GIF and JPEG representations.  However, you can force GIF2JPG
-to produce compatible files with its -j switch, and their decompression
-program JPG2GIF can read our files (at least ones produced with our default
-option settings).
-
-Some commercial JPEG implementations are also incompatible as of this writing,
-especially programs released before summer 1991.  The root of the problem is
-that the ISO JPEG committee failed to specify a concrete file format.  Some
-vendors "filled in the blanks" on their own, creating proprietary formats that
-no one else could read.  (For example, none of the early commercial JPEG
-implementations for the Macintosh were able to exchange compressed files.)
-
-The file format we have adopted is called JFIF (see REFERENCES).  This format
-has been agreed to by a number of major commercial JPEG vendors, and we expect
-that it will become the de facto standard.  JFIF is a minimal representation;
-work is also going forward to incorporate JPEG compression into the TIFF 6.0
-standard, for use in "high end" applications that need to record a lot of
-additional data about an image.  We intend to support TIFF 6.0 in the future.
-We hope that these two formats will be sufficient and that other, incompatible
-JPEG file formats will not proliferate.
-
-Indeed, part of the reason for developing and releasing this free software is
-to help force rapid convergence to de facto standards for JPEG file formats.
-SUPPORT STANDARD, NON-PROPRIETARY FORMATS: demand JFIF or TIFF 6.0!
-
-
-USING JPEG AS A SUBROUTINE IN A LARGER PROGRAM
-==============================================
-
-You can readily incorporate the JPEG compression and decompression routines in
-a larger program.  The file example.c provides a skeleton of the interface
-routines you'll need for this purpose.  Essentially, you replace jcmain.c (for
-compression) and/or jdmain.c (for decompression) with your own code.  Note
-that the fewer JPEG options you allow the user to twiddle, the less code you
-need; all the default options are set up automatically.  (Alternately, if you
-know a lot about JPEG or have a special application, you may want to twiddle
-the default options even more extensively than jcmain/jdmain do.)
-
-Most likely, you will want the uncompressed image to come from memory (for
-compression) or go to memory or the screen (for decompression).  For this
-purpose you must provide image reading or writing routines that match the
-interface used by the image file I/O modules (jrdXXX or jwrXXX); again,
-example.c shows a skeleton of what is required.  In this situation, you
-won't need any of the non-JPEG image file I/O modules used by cjpeg and djpeg.
-
-By default, any error detected inside the JPEG routines will cause a message
-to be printed on stderr, followed by exit().  You can override this behavior
-by supplying your own message-printing and/or error-exit routines; again,
-example.c shows how.
-
-We recommend you create libjpeg.a as shown in the Makefile, then link that
-with your surrounding program.  (If your linker is at all reasonable, only the
-code you actually need will get loaded.)  Include the files jconfig.h and
-jpegdata.h in C files that need to call the JPEG routines.
-
-CAUTION: some people have tried to compile JPEG and their surrounding code
-with different compilers, e.g., cc for JPEG and c++ or gcc for the rest.  This
-is a Real Bad Move and you will deserve what happens to you if you try it.
-(Hint: the parameter structures can get laid out differently with no warning.)
-
-Read our "architecture" file for more info.  If it seems to you that the
-software structure doesn't accommodate what you want to do, please contact
-the authors.
-
-Beginning with version 3, we will endeavor to hold the interface described by
-example.c constant, so that you can plug in updated versions of the JPEG code
-just by recompiling.  However, we can't guarantee this, especially if you
-choose to twiddle any JPEG options not listed in example.c.  Check the
-CHANGELOG when installing any new version, and compare example.c against the
-prior version.  Recompile your calling software (don't just relink), as we may
-add or subtract fields in the parameter structures.
-
-
-REFERENCES
-==========
-
-We highly recommend reading one or more of these references before trying to
-understand the innards of any JPEG software.
-
-The best short technical introduction to the JPEG compression algorithm is
-	Wallace, Gregory K.  "The JPEG Still Picture Compression Standard",
-	Communications of the ACM, April 1991 (vol. 34 no. 4), pp. 30-44.
-(Adjacent articles in that issue discuss MPEG motion picture compression,
-applications of JPEG, and related topics.)  If you don't have the CACM issue
-handy, a PostScript file containing a revised version of the article is
-available at ftp.uu.net, graphics/jpeg/wallace.ps.Z.  The file (actually a
-preprint for an article to appear in IEEE Trans. Consumer Electronics) omits
-the sample images that appeared in CACM, but it includes corrections and some
-added material.  Note: the Wallace article is copyright ACM and IEEE, and it
-may not be used for commercial purposes.
-
-A somewhat less technical, more leisurely introduction to JPEG can be found in
-"The Data Compression Book" by Mark Nelson, published by M&T Books (Redwood
-City, CA), 1991, ISBN 1-55851-216-0.  This book provides good explanations and
-example C code for a multitude of compression methods including JPEG.  It is
-an excellent source if you are comfortable reading C code but don't know much
-about data compression in general.  The book's JPEG sample code is far from
-industrial-strength, but when you are ready to look at a full implementation,
-you've got one here...
-
-A new textbook about JPEG is "JPEG Still Image Data Compression Standard" by
-William B. Pennebaker and Joan L. Mitchell, published by Van Nostrand
-Reinhold, 1993, ISBN 0-442-01272-1.  Price US$59.95.  This book includes the
-complete text of the ISO JPEG standards (DIS 10918-1 and draft DIS 10918-2).
-This is by far the most complete exposition of JPEG in existence, and I highly
-recommend it.  If you read the entire book, you will probably know more about
-JPEG than I do.
-
-The JPEG standard itself is not available electronically; you must order a
-paper copy through ISO.  (Unless you are concerned about having a certified
-official copy, I recommend buying the Pennebaker and Mitchell book instead;
-it's much cheaper and includes a great deal of useful explanatory material.)
-In the US, copies of the standard may be ordered from ANSI Sales at (212)
-642-4900.  It's not cheap: as of 1992, Part 1 is $95 and Part 2 is $47, plus
-7% shipping/handling.  The standard is divided into two parts, Part 1 being
-the actual specification, while Part 2 covers compliance testing methods.
-As of early 1992, Part 1 has Draft International Standard status.  It is
-titled "Digital Compression and Coding of Continuous-tone Still Images, Part
-1: Requirements and guidelines" and has document number ISO/IEC DIS 10918-1.
-Part 2 is still at Committee Draft status.  It is titled "Digital Compression
-and Coding of Continuous-tone Still Images, Part 2: Compliance testing" and
-has document number ISO/IEC CD 10918-2.  (NOTE: I'm told that the final
-version of Part 2 will differ considerably from the CD draft.)
-
-The JPEG standard does not specify all details of an interchangeable file
-format.  For the omitted details we follow the "JFIF" conventions, revision
-1.02.  A copy of the JFIF spec is available from:
-	Literature Department
-	C-Cube Microsystems, Inc.
-	399A West Trimble Road
-	San Jose, CA  95131
-	(408) 944-6300
-A PostScript version of this document is available at ftp.uu.net, file
-graphics/jpeg/jfif.ps.Z.  It can also be obtained by e-mail from the C-Cube
-mail server, netlib@c3.pla.ca.us.  Send the message "send jfif_ps from jpeg"
-to the server to obtain the JFIF document; send the message "help" if you have
-trouble.
-
-The TIFF 6.0 file format specification can be obtained by FTP from sgi.com
-(192.48.153.1), file graphics/tiff/TIFF6.ps.Z; or you can order a printed copy
-from Aldus Corp. at (206) 628-6593.  It should be noted that the TIFF 6.0 spec
-of 3-June-92 has a number of serious problems in its JPEG features.  A
-clarification note will probably be needed to ensure that TIFF JPEG files are
-compatible across different implementations.  The IJG does not intend to
-support TIFF 6.0 until these problems are resolved.
-
-If you want to understand this implementation, start by reading the
-"architecture" documentation file.  Please read "codingrules" if you want to
-contribute any code.
+We welcome the use of this software as a component of commercial products.
+No royalty is required, but we do ask for an acknowledgement in product
+documentation, as described under LEGAL ISSUES.
 
 
 LEGAL ISSUES
 ============
 
+In plain English:
+
+1. We don't promise that this software works.  (But if you find any bugs,
+   please let us know!)
+2. You can use this software for whatever you want.  You don't have to pay us.
+3. You may not pretend that you wrote this software.  If you use it in a
+   program, you must acknowledge somewhere in your documentation that
+   you've used the IJG code.
+
+In legalese:
+
 The authors make NO WARRANTY or representation, either express or implied,
 with respect to this software, its quality, accuracy, merchantability, or
 fitness for a particular purpose.  This software is provided "AS IS", and you,
 its user, assume the entire risk as to its quality and accuracy.
 
-This software is copyright (C) 1991, 1992, Thomas G. Lane.
+This software is copyright (C) 1991, 1992, 1993, 1994, Thomas G. Lane.
 All Rights Reserved except as specified below.
 
 Permission is hereby granted to use, copy, modify, and distribute this
@@ -346,6 +141,10 @@
 full responsibility for any undesirable consequences; the authors accept
 NO LIABILITY for damages of any kind.
 
+These conditions apply to any software derived from or based on the IJG code,
+not just to the unmodified library.  If you use our work, you ought to
+acknowledge us.
+
 Permission is NOT granted for the use of any IJG author's name or company name
 in advertising or publicity relating to this software or products derived from
 it.  This software may be referred to only as "the Independent JPEG Group's
@@ -362,44 +161,189 @@
 by the usual distribution terms of the Free Software Foundation; principally,
 that you must include source code if you redistribute it.  (See the file
 ansi2knr.c for full details.)  However, since ansi2knr.c is not needed as part
-of any program generated from the JPEG code, this does not limit you more than
+of any program generated from the IJG code, this does not limit you more than
 the foregoing paragraphs do.
 
+The configuration script "configure" was produced by GNU Autoconf.  Again,
+the FSF copyright terms apply only to configure, not to the IJG code; and
+again, that does not limit your use of the object code.
 
 It appears that the arithmetic coding option of the JPEG spec is covered by
-patents owned by IBM and AT&T, as well as a pending Japanese patent of
-Mitsubishi.  Hence arithmetic coding cannot legally be used without obtaining
-one or more licenses.  For this reason, support for arithmetic coding has been
-removed from the free JPEG software.  (Since arithmetic coding provides only a
-marginal gain over the unpatented Huffman mode, it is unlikely that very many
-implementors will support it.  If you do obtain the necessary licenses,
-contact jpeg-info@uunet.uu.net for a copy of our arithmetic coding modules.)
+patents owned by IBM, AT&T, and Mitsubishi.  Hence arithmetic coding cannot
+legally be used without obtaining one or more licenses.  For this reason,
+support for arithmetic coding has been removed from the free JPEG software.
+(Since arithmetic coding provides only a marginal gain over the unpatented
+Huffman mode, it is unlikely that very many implementations will support it.)
 So far as we are aware, there are no patent restrictions on the remaining
 code.
 
-
 We are required to state that
     "The Graphics Interchange Format(c) is the Copyright property of
     CompuServe Incorporated.  GIF(sm) is a Service Mark property of
     CompuServe Incorporated."
 
 
+REFERENCES
+==========
+
+We highly recommend reading one or more of these references before trying to
+understand the innards of the JPEG software.
+
+The best short technical introduction to the JPEG compression algorithm is
+	Wallace, Gregory K.  "The JPEG Still Picture Compression Standard",
+	Communications of the ACM, April 1991 (vol. 34 no. 4), pp. 30-44.
+(Adjacent articles in that issue discuss MPEG motion picture compression,
+applications of JPEG, and related topics.)  If you don't have the CACM issue
+handy, a PostScript file containing a revised version of Wallace's article is
+available at ftp.uu.net, graphics/jpeg/wallace.ps.gz.  The file (actually a
+preprint for an article to appear in IEEE Trans. Consumer Electronics) omits
+the sample images that appeared in CACM, but it includes corrections and some
+added material.  Note: the Wallace article is copyright ACM and IEEE, and it
+may not be used for commercial purposes.
+
+A somewhat less technical, more leisurely introduction to JPEG can be found in
+"The Data Compression Book" by Mark Nelson, published by M&T Books (Redwood
+City, CA), 1991, ISBN 1-55851-216-0.  This book provides good explanations and
+example C code for a multitude of compression methods including JPEG.  It is
+an excellent source if you are comfortable reading C code but don't know much
+about data compression in general.  The book's JPEG sample code is far from
+industrial-strength, but when you are ready to look at a full implementation,
+you've got one here...
+
+The best full description of JPEG is the textbook "JPEG Still Image Data
+Compression Standard" by William B. Pennebaker and Joan L. Mitchell, published
+by Van Nostrand Reinhold, 1993, ISBN 0-442-01272-1.  Price US$59.95, 638 pp.
+The book includes the complete text of the ISO JPEG standards (DIS 10918-1
+and draft DIS 10918-2).  This is by far the most complete exposition of JPEG
+in existence, and we highly recommend it.
+
+The JPEG standard itself is not available electronically; you must order a
+paper copy through ISO.  (Unless you feel a need to own a certified official
+copy, we recommend buying the Pennebaker and Mitchell book instead; it's much
+cheaper and includes a great deal of useful explanatory material.)  In the US,
+copies of the standard may be ordered from ANSI Sales at (212) 642-4900, or
+from Global Engineering Documents at (800) 854-7179.  (ANSI doesn't take
+credit card orders, but Global does.)  It's not cheap: as of 1992, ANSI was
+charging $95 for Part 1 and $47 for Part 2, plus 7% shipping/handling.  The
+standard is divided into two parts, Part 1 being the actual specification,
+while Part 2 covers compliance testing methods.  Part 1 is titled "Digital
+Compression and Coding of Continuous-tone Still Images, Part 1: Requirements
+and guidelines" and has document number ISO/IEC IS 10918-1.  As of mid-1994,
+Part 2 is still at Draft International Standard status.  It is titled "Digital
+Compression and Coding of Continuous-tone Still Images, Part 2: Compliance
+testing" and has document number ISO/IEC DIS 10918-2.  (The document number
+will change to IS 10918-2 when final approval is obtained.)  A Part 3,
+covering extensions, is likely to appear in draft form in late 1994.
+
+The JPEG standard does not specify all details of an interchangeable file
+format.  For the omitted details we follow the "JFIF" conventions, revision
+1.02.  A copy of the JFIF spec is available from:
+	Literature Department
+	C-Cube Microsystems, Inc.
+	1778 McCarthy Blvd.
+	Milpitas, CA 95035
+	phone (408) 944-6300,  fax (408) 944-6314
+A PostScript version of this document is available at ftp.uu.net, file
+graphics/jpeg/jfif.ps.gz.  It can also be obtained by e-mail from the C-Cube
+mail server, netlib@c3.pla.ca.us.  Send the message "send jfif_ps from jpeg"
+to the server to obtain the JFIF document; send the message "help" if you have
+trouble.
+
+The TIFF 6.0 file format specification can be obtained by FTP from sgi.com
+(192.48.153.1), file graphics/tiff/TIFF6.ps.Z; or you can order a printed copy
+from Aldus Corp. at (206) 628-6593.  It should be noted that the TIFF 6.0 spec
+of 3-June-92 has a number of serious problems in its JPEG features.  A
+redesign effort is currently underway to correct these problems; it is
+expected to result in a new, incompatible, spec.  IJG intends to support the
+corrected version of TIFF when the new spec is issued.
+
+
+ARCHIVE LOCATIONS
+=================
+
+The "official" archive site for this software is ftp.uu.net (Internet
+address 192.48.96.9).  The most recent released version can always be found
+there in directory graphics/jpeg.  This particular version will be archived
+as graphics/jpeg/jpegsrc.v5.tar.gz.  If you are on the Internet, you
+can retrieve files from ftp.uu.net by standard anonymous FTP.  If you don't
+have FTP access, UUNET's archives are also available via UUCP; contact
+help@uunet.uu.net for information on retrieving files that way.
+
+Numerous Internet sites maintain copies of the UUNET files; in particular,
+you can probably find a copy at any site that archives comp.sources.misc
+submissions.  However, only ftp.uu.net is guaranteed to have the latest
+official version.
+
+You can also obtain this software from CompuServe, in the GRAPHSUPPORT forum
+(GO GRAPHSUP); this version will be file jpsrc5.zip in library 15.  Again,
+CompuServe is not guaranteed to have the very latest version.
+
+The JPEG FAQ (Frequently Asked Questions) article is a useful source of
+general information about JPEG.  It is updated constantly and therefore
+is not included in this distribution.  The FAQ is posted every two weeks
+to Usenet newsgroups comp.graphics, news.answers, and other groups.  You
+can always obtain the latest version from the news.answers archive at
+rtfm.mit.edu (18.181.0.24).  By FTP, fetch /pub/usenet/news.answers/jpeg-faq.
+If you don't have FTP, send e-mail to mail-server@rtfm.mit.edu with body
+"send usenet/news.answers/jpeg-faq".
+
+
+RELATED SOFTWARE
+================
+
+Numerous viewing and image manipulation programs now support JPEG.  (Quite a
+few of them use this library to do so.)  The JPEG FAQ described above lists
+some of the more popular free and shareware viewers, and tells where to
+obtain them on Internet.
+
+If you are on a Unix machine, we highly recommend Jef Poskanzer's free
+PBMPLUS image software, which provides many useful operations on PPM-format
+image files.  In particular, it can convert PPM images to and from a wide
+range of other formats.  You can obtain this package by FTP from ftp.x.org
+(contrib/pbmplus*.tar.Z) or ftp.ee.lbl.gov (pbmplus*.tar.Z).  There is also
+a newer update of this package called NETPBM, available from
+wuarchive.wustl.edu under directory /graphics/graphics/packages/NetPBM/.
+Unfortunately PBMPLUS/NETPBM is not nearly as portable as the IJG software
+is; you are likely to have difficulty making it work on any non-Unix machine.
+
+A different free JPEG implementation, written by the PVRG group at Stanford,
+is available from havefun.stanford.edu in directory pub/jpeg.  This program
+is designed for research and experimentation rather than production use;
+it is slower, harder to use, and less portable than the IJG code, but it
+implements a larger subset of the JPEG standard.  In particular, it supports
+lossless JPEG.
+
+
+FILE FORMAT WARS
+================
+
+Some JPEG programs produce files that are not compatible with our library.
+The root of the problem is that the ISO JPEG committee failed to specify a
+concrete file format.  Some vendors "filled in the blanks" on their own,
+creating proprietary formats that no one else could read.  (For example, none
+of the early commercial JPEG implementations for the Macintosh were able to
+exchange compressed files.)
+
+The file format we have adopted is called JFIF (see REFERENCES).  This format
+has been agreed to by a number of major commercial JPEG vendors, and it has
+become the de facto standard.  JFIF is a minimal or "low end" representation.
+Work is also going forward to incorporate JPEG compression into the TIFF
+standard, for use in "high end" applications that need to record a lot of
+additional data about an image.  We intend to support TIFF in the future.
+We hope that these two formats will be sufficient and that other,
+incompatible JPEG file formats will not proliferate.
+
+Indeed, part of the reason for developing and releasing this free software is
+to help force rapid convergence to de facto standards for JPEG file formats.
+SUPPORT STANDARD, NON-PROPRIETARY FORMATS: demand JFIF or TIFF/JPEG!
+
+
 TO DO
 =====
 
-The next major release will probably be a significant rewrite to allow use of
-this code in conjunction with Sam Leffler's free TIFF library (assuming the
-bugs in the TIFF 6.0 specification get resolved).
+In future versions, we are considering supporting progressive JPEG
+compression, the upcoming JPEG Part 3 extensions, and other improvements.
 
-Many of the modules need fleshing out to provide more complete
-implementations, or to provide faster paths for common cases.
-Speeding things up is still high on our priority list.
-
-We'd appreciate it if people would compile and check out the code on as wide a
-variety of systems as possible, and report any portability problems
-encountered (with solutions, if possible).  Checks of file compatibility with
-other JPEG implementations would also be of interest.  Finally, we would
-appreciate code profiles showing where the most time is spent, especially on
-unusual systems.
+As always, speeding things up is high on our priority list.
 
 Please send bug reports, offers of help, etc. to jpeg-info@uunet.uu.net.
diff --git a/SETUP b/SETUP
deleted file mode 100644
index 85f0184..0000000
--- a/SETUP
+++ /dev/null
@@ -1,550 +0,0 @@
-SETUP instructions for the Independent JPEG Group's JPEG software
-=================================================================
-
-This file explains how to configure and compile the JPEG software.  We have
-tried to make this software extremely portable and flexible, so that it can be
-adapted to almost any environment.  The downside of this decision is that the
-installation process is not very automatic; you will need at least a little
-familiarity with C programming and program build procedures for your system.
-
-This file contains general instructions, then sections of specific hints for
-certain systems.  You may save yourself considerable time if you scan the
-whole file before starting to do anything.
-
-Before installing the software you must unpack the distributed source code.
-Since you are reading this file, you have probably already succeeded in this
-task.  However, there is one potential trap if you are on a non-Unix system:
-you may need to convert these files to the local standard text file format
-(for example, if you are on MS-DOS you probably have to convert LF end-of-line
-to CR/LF).  If so, apply the conversion to all the files EXCEPT those whose
-names begin with "test".  The test files contain binary data; if you change
-them in any way then the self-test will give bad results.
-
-
-STEP 1: PREPARE A MAKEFILE
-==========================
-
-First, select a makefile and copy it to "Makefile" (or whatever your version
-of make uses as the default makefile name; for example, "makefile.mak" for
-old versions of Borland C).  We include several standard makefiles in the
-distribution:
-
-	makefile.ansi:	for Unix systems with ANSI-compatible C compilers.
-	makefile.unix:	for Unix systems with non-ANSI C compilers.
-	makefile.mc5:	for Microsoft C 5.x under MS-DOS.
-	makefile.mc6:	for Microsoft C 6.x and up under MS-DOS.
-	makefile.bcc:	for Borland C (Turbo C) under MS-DOS.
-	makefile.icc:	for Intel's Code Builder C under MS-DOS.
-	makefile.manx:	for Manx Aztec C on Amigas.
-	makefile.sas:	for SAS C on Amigas.
-	makcjpeg.st:	project file for Atari ST/STE/TT Pure C or Turbo C.
-	makdjpeg.st:	project file for Atari ST/STE/TT Pure C or Turbo C.
-	makljpeg.st:	project file for Atari ST/STE/TT Pure C or Turbo C.
-	makefile.mms:	for VAX/VMS systems with MMS.
-	makefile.vms:	for VAX/VMS systems without MMS.
-
-If you don't see a makefile for your system, we recommend starting from either
-makefile.ansi or makefile.unix, depending on whether your compiler accepts
-ANSI C or not.  Actually you should start with makefile.ansi whenever your
-compiler supports ANSI-style function definitions; you don't need full ANSI
-compatibility.  The difference between the two makefiles is that makefile.unix
-preprocesses the source code to convert function definitions to old-style C.
-(Our thanks to Peter Deutsch of Aladdin Enterprises for the ansi2knr program.)
-
-If you don't know whether your compiler supports ANSI-style function
-definitions, then take a look at ckconfig.c.  It is a test program that will
-help you figure out this fact, as well as some other facts you'll need in
-later steps.  You must compile and execute ckconfig.c by hand; the makefiles
-don't provide any support for this.  ckconfig.c may not compile the first try
-(in fact, the whole idea is for it to fail if anything is going to).  If you
-get compile errors, fix them by editing ckconfig.c according to the directions
-given in ckconfig.c.  Once you get it to run, select a makefile according to
-the advice it prints out, and make any other changes it recommends.
-
-Look over the selected Makefile and adjust options as needed.  In particular
-you may want to change the CC and CFLAGS definitions.  For instance, if you
-are using GCC, set CC=gcc.  If you had to use any compiler switches to get
-ckconfig.c to work, make sure the same switches are in CFLAGS.
-
-If you are on a system that doesn't use makefiles, you'll need to set up
-project files (or whatever you do use) to compile all the source files and
-link them into executable files cjpeg and djpeg.  See the file lists in any of
-the makefiles to find out which files go into each program.  As a last resort,
-you can make a batch script that just compiles everything and links it all
-together; makefile.vms is an example of this (it's for VMS systems that have
-no make-like utility).
-
-
-STEP 2: EDIT JCONFIG.H
-======================
-
-Look over jconfig.h and adjust #defines to reflect the properties of your
-system and C compiler.  If you prefer, you can usually leave jconfig.h
-unmodified and add -Dsymbol switches to the Makefile's CFLAGS definition.
-(This is already done if you used a compiler-specific makefile in step 1.)
-However, putting the switches in the Makefile is a bad idea if you are going
-to incorporate the JPEG software into other programs --- you'd need to include
-the same -D switches in the other programs' Makefiles.  Better to change
-jconfig.h.
-
-If you have an ANSI-compliant C compiler, no changes should be necessary
-except perhaps for RIGHT_SHIFT_IS_UNSIGNED and TWO_FILE_COMMANDLINE.  For
-older compilers other changes may be needed, depending on what ANSI features
-are supported.
-
-If you don't know enough about C programming to understand the questions in
-jconfig.h, then use ckconfig.c to figure out what to change.  (See description
-of ckconfig.c in step 1.)
-
-A note about TWO_FILE_COMMANDLINE: defining this selects the command line
-syntax in which the input and output files are both named on the command line.
-If it's not defined, the output image goes to standard output, and the input
-can optionally come from standard input.  You MUST use two-file style on any
-system that doesn't cope well with binary data fed through stdin/stdout; this
-is true for most MS-DOS compilers, for example.  If you're not on a Unix
-system, it's probably safest to assume you need two-file style.  (But if your
-compiler provides either the Posix-standard fdopen() library routine or a
-Microsoft-compatible setmode() routine, you can use the Unix command line
-style, by defining USE_FDOPEN or USE_SETMODE respectively.)
-
-
-STEP 3: SELECT SYSTEM-DEPENDENT FILES
-=====================================
-
-A few places in the JPEG software are so system-dependent that we have to
-provide several different implementations and let you select the one you need.
-
-The only system-dependent file in the current version is jmemsys.c.  This file
-controls use of temporary files for big images that won't fit in main memory.
-You'll notice there is no file named jmemsys.c in the distribution; you must
-select one of the provided versions and copy, rename, or link it to jmemsys.c.
-Here are the provided versions:
-
-	jmemansi.c	This is a reasonably portable version that should
-			work on most ANSI and near-ANSI C compilers.  It uses
-			the ANSI-standard library routine tmpfile(), which not
-			all non-ANSI systems have.  On some systems tmpfile()
-			may put the temporary file in a non-optimal location;
-			if you don't like what it does, use jmemname.c.
-
-	jmemname.c	This version constructs the temp file name by itself.
-			For anything except a Unix machine, you'll need to
-			configure the select_file_name() routine appropriately;
-			see the comments near the head of jmemname.c.
-			If you use this version, define NEED_SIGNAL_CATCHER
-			in jconfig.h or in the Makefile to make sure the temp
-			files are removed if the program is aborted.
-
-	jmemnobs.c	(That stands for No Backing Store :-).  This will
-			compile on almost any system, but it assumes you
-			have enough main memory or virtual memory to hold
-			the biggest images you need to work with.
-
-	jmemdos.c	This should be used in most MS-DOS installations; see
-			the system-specific notes about MS-DOS for more info.
-			IMPORTANT: if you use this, also copy jmemdos.h to
-			jmemsys.h, replacing the standard version.  ALSO,
-			include the assembly file jmemdosa.asm in the programs.
-			(This last is already done if you used one of the
-			supplied MS-DOS-specific makefiles.)
-
-If you have plenty of (real or virtual) main memory, just use jmemnobs.c.
-"Plenty" means at least ten bytes for every pixel in the largest images
-you plan to process, so a lot of systems don't meet this criterion.
-If yours doesn't, try jmemansi.c first.  If that doesn't compile, you'll have
-to use jmemname.c; be sure to adjust select_file_name() for local conditions.
-You may also need to change unlink() to remove() in close_backing_store().
-
-Except with jmemnobs.c, you need to adjust the #define DEFAULT_MAX_MEM to a
-reasonable value for your system (either by editing jmemsys.c, or by adding
-a -D switch to the Makefile).  This value limits the amount of data space the
-program will attempt to allocate.  Code and static data space isn't counted,
-so the actual memory needs for cjpeg or djpeg are typically 100 to 150Kb more
-than the max-memory setting.  Larger max-memory settings reduce the amount of
-I/O needed to process a large image, but too large a value can result in
-"insufficient memory" failures.  On most Unix machines (and other systems with
-virtual memory), just set DEFAULT_MAX_MEM to several million and forget it.
-At the other end of the spectrum, for MS-DOS machines you probably can't go
-much above 300K to 400K.  (On MS-DOS the value refers to conventional memory;
-extended/expanded memory is handled separately by jmemdos.c.)
-
-
-STEP 4: MAKE
-============
-
-Now you should be able to "make" the software.
-
-If you have trouble with missing system include files or inclusion of the
-wrong ones, look at jinclude.h (or use ckconfig.c, if you are not a C expert).
-
-If your compiler complains about big_sarray_control and big_barray_control
-being undefined structures, you should be able to shut it up by adding
--DINCOMPLETE_TYPES_BROKEN to CFLAGS (or add #define INCOMPLETE_TYPES_BROKEN
-to jconfig.h).  If you don't have a getenv() library routine, define NO_GETENV.
-
-There are a fair number of routines that do not use all of their parameters;
-some compilers will issue warnings about this, which you can ignore.  Any
-other warning deserves investigation.
-
-
-STEP 5: TEST
-============
-
-As a quick test of functionality we've included a small sample image in
-several forms:
-	testorig.jpg	A reduced section of the well-known Lenna picture.
-	testimg.ppm	The output of djpeg testorig.jpg
-	testimg.gif	The output of djpeg -gif testorig.jpg
-	testimg.jpg	The output of cjpeg testimg.ppm
-(The two .jpg files aren't identical since JPEG is lossy.)  If you can
-generate duplicates of the testimg.* files then you probably have working
-programs.
-
-With most of the makefiles, "make test" will perform the necessary
-comparisons.  If you started with makefile.ansi or makefile.unix, and you
-defined TWO_FILE_COMMANDLINE, then change the makefile's test script to use
-two-file syntax (i.e., delete the ">" character from the invocations of cjpeg
-and djpeg).  The other makefiles will work with either command-line syntax.
-
-If you're using a makefile that doesn't provide the test option, run djpeg and
-cjpeg by hand to generate testout.ppm, testout.gif, and testout.jpg, then
-compare these to testimg.* with whatever binary file comparison tool you have.
-The files should be bit-for-bit identical.
-
-If the cjpeg test run fails with "Missing Huffman code table entry", it's a
-good bet that you needed to define RIGHT_SHIFT_IS_UNSIGNED.  Go back to step 2
-and run ckconfig.c.  (This is a good plan for any other test failure, too.)
-
-If you are using Unix (one-file) command line style on a non-Unix system,
-it's a good idea to check that binary I/O through stdin/stdout actually works.
-You should get the same results from "djpeg <testorig.jpg >out.ppm" as from
-"djpeg -outfile out.ppm  testorig.jpg".  Note that the non-Unix makefiles use
-the latter style and therefore do not exercise stdin/stdout.  If this test
-fails, try recompiling jcmain.c & jdmain.c with USE_SETMODE and/or USE_FDOPEN.
-
-If your choice of jmemsys.c was anything other than jmemnobs.c, you should
-test that temporary-file usage works.  Try "djpeg -gif -max 0 testorig.jpg"
-and make sure its output matches testimg.gif.  If you have any really large
-images handy, try compressing them with -optimize and/or decompressing with
--gif to make sure your DEFAULT_MAX_MEM setting is not too large.
-
-NOTE: this is far from an exhaustive test of the JPEG software; some modules,
-such as 1-pass color quantization, are not exercised at all.  It's just a quick
-test to give you some confidence that you haven't missed something major.
-
-
-STEP 6: INSTALLATION
-====================
-
-Once you're done with the above steps, you can install the software by copying
-the executable files (cjpeg and djpeg) to wherever you normally install
-programs.  On Unix systems, you'll also want to put cjpeg.1 and djpeg.1 in the
-corresponding manual directory.  (The makefiles don't support this step since
-there's such a wide variety of installation procedures on different systems.)
-
-To learn to use the programs, read the file USAGE (or manual pages cjpeg(1)
-and djpeg(1) on Unix).  Note that the man pages cjpeg.1/djpeg.1 only describe
-the Unix-style command line syntax; if you want to use these files with a
-version that uses two-file command line syntax, you'll have to modify the text
-accordingly.  The USAGE file describes both styles.
-
-
-OPTIMIZATION
-============
-
-Unless you own a Cray, you'll probably be interested in making the JPEG
-software go as fast as possible.  This section covers some machine-dependent
-optimizations you may want to try.  We suggest that before trying any of this,
-you first get the basic installation to pass the self-test (step 5 above).
-Repeat the self-test after any optimization to make sure that you haven't
-broken anything.
-
-The JPEG DCT routines perform a lot of multiplications.  These multiplications
-must yield 32-bit results, but none of their input values are more than 16
-bits wide.  On many machines, notably the 680x0 and 80x86 CPUs, a 16x16=>32
-bit multiply instruction is faster than a full 32x32=>32 bit multiply.
-Unfortunately there is no portable way to specify such a multiplication in C,
-but some compilers can generate one when you use the right combination of
-casts.  See the MULTIPLY macro definitions in jfwddct.c and jrevdct.c.
-If your compiler makes "int" be 32 bits and "short" be 16 bits, defining
-SHORTxSHORT_32 is fairly likely to work.  When experimenting with alternate
-definitions, be sure to test not only whether the code still works (use the
-self-test step), but also whether it is actually faster --- on some compilers,
-alternate definitions may compute the right answer, yet be slower than the
-default.  Timing cjpeg on a large PPM input file is the best way to check
-this, as the DCT will be the largest fraction of the runtime in that mode.
-(Note: some of the distributed compiler-specific makefiles already contain
--D switches to select an appropriate MULTIPLY definition.)
-
-If access to "short" arrays is slow on your machine, it may be a win to define
-type DCTELEM as int rather than as JCOEF (which is normally defined as short).
-This will cause the DCT routines to operate on int arrays instead of short
-arrays.  If shorts are slow and you have lots of memory to burn, you might
-even make JCOEF itself be int.
-
-If your compiler can compile function calls in-line, make sure the INLINE
-macro in jconfig.h is defined as the keyword that marks a function
-inline-able.  Some compilers have a switch that tells the compiler to inline
-any function it thinks is profitable (e.g., -finline-functions for gcc).
-Enabling such a switch is likely to make the compiled code bigger but faster.
-
-In general, it's worth trying the maximum optimization level of your compiler,
-and experimenting with any optional optimizations such as loop unrolling.
-(Unfortunately, far too many compilers have optimizer bugs ... be prepared to
-back off if the code fails self-test.)  If you do any experimentation along
-these lines, please report the optimal settings to jpeg-info@uunet.uu.net so
-we can mention them in future releases.  Be sure to specify your machine and
-compiler version.
-
-
-OPTIONAL STUFF
-==============
-
-Progress monitor:
-
-If you like, you can #define PROGRESS_REPORT (in jconfig.h or in the Makefile)
-to enable display of percent-done progress reports.  The routines provided in
-jcmain.c/jdmain.c merely print percentages to stderr, but you can customize
-them to do something fancier.
-
-Utah RLE file format support:
-
-We distribute the software with support for RLE image files (Utah Raster
-Toolkit format) disabled, because the RLE support won't compile without the
-Utah library.  If you have URT version 3.0, you can enable RLE support as
-follows:
-	1.  #define RLE_SUPPORTED in jconfig.h or in the Makefile.
-	2.  Add a -I option to CFLAGS in the Makefile for the directory
-	    containing the URT .h files (typically the "include"
-	    subdirectory of the URT distribution).
-	3.  Add -L... -lrle to LDLIBS in the Makefile, where ... specifies
-	    the directory containing the URT "librle.a" file (typically the
-	    "lib" subdirectory of the URT distribution).
-
-JPEG library:
-
-If you want to incorporate the JPEG code as subroutines in a larger program,
-we recommend that you make libjpeg.a, then link that into your surrounding
-program.  See file README for more info.
-
-CAUTION: When you use the JPEG code as subroutines, we recommend that you make
-any required configuration changes by modifying jconfig.h, not by adding -D
-switches to the Makefile.  Otherwise you must be sure to provide the same -D
-switches when compiling any program that includes the JPEG .h files, to ensure
-that the parameter structures are interpreted the same way.  (This is only
-critical for the first few symbols mentioned in jconfig.h, down through
-NEED_FAR_POINTERS.)
-
-Removing code:
-
-If you need to make a smaller version of the JPEG software, some optional
-functions can be removed at compile time.  See the xxx_SUPPORTED #defines in
-jconfig.h.  If at all possible, we recommend that you leave in decoder support
-for all valid JPEG files, to ensure that you can read anyone's output.
-Restricting your encoder, or removing optional functions like block smoothing,
-won't hurt compatibility.  Taking out support for image file formats that you
-don't use is the most painless way to make the programs smaller.
-
-
-NOTES FOR SPECIFIC SYSTEMS
-==========================
-
-We welcome reports on changes needed for systems not mentioned here.
-Submit 'em to jpeg-info@uunet.uu.net.  Also, if ckconfig.c is wrong about
-how to configure the JPEG software for your system, please let us know.
-
-
-Amiga:
-
-Makefiles are provided for Manx Aztec C and SAS C.  I have also heard from
-people who have compiled with the free DICE compiler, using makefile.ansi as a
-starting point (set "CC= dcc" and "CFLAGS= -c -DAMIGA -DTWO_FILE_COMMANDLINE
--DNEED_SIGNAL_CATCHER" in the makefile).  For all compilers, we recommend you
-use jmemname.c as the system-dependent memory manager.  Assuming you have
--DAMIGA in the makefile, jmemname.c will put temporary files in JPEGTMP:.
-Change jmemname.c if you don't like this.
-
-
-Atari:
-
-The project files provided should work as-is with Pure C.  For Turbo C, change
-library filenames "PC..." to "TC..." in the project files for cjpeg.ttp and
-djpeg.ttp.  Don't forget to select a jmemsys.c file, see Step 3 (we recommend
-jmemansi.c).  Also adjust the DEFAULT_MAX_MEM setting --- you probably want it
-to be a couple hundred K less than your normal free memory.  Note that you
-must make jpeg.lib before making cjpeg.ttp or cjpeg.ttp.  You'll have to
-perform the self-test (Step 5) by hand.
-
-There is a bug in some older versions of the Turbo C library which causes the
-space used by temporary files created with "tmpfile()" not to be freed after
-an abnormal program exit.  If you check your disk afterwards, you will find
-cluster chains that are allocated but not used by a file.  This should not
-happen in cjpeg or djpeg, since we enable a signal catcher to explicitly close
-temp files before exiting.  But if you use the JPEG library with your own
-code, be sure to supply a signal catcher, or else use a different
-system-dependent memory manager.
-
-
-Cray:
-
-Should you be so fortunate as to be running JPEG on a Cray YMP, there is a
-compiler bug in Cray's Standard C versions prior to 3.1.  You'll need to
-insert a line reading "#pragma novector" just before the loop	
-    for (i = 1; i <= (int) htbl->bits[l]; i++)
-      huffsize[p++] = (char) l;
-in fix_huff_tbl (in V4A, line 42 of jchuff.c and line 39 of jdhuff.c).  The
-usual symptom of not adding this line is a core-dump.  See Cray's SPR 48222.
-
-
-HP/Apollo DOMAIN:
-
-With system release 10.4 or later, makefile.ansi should work OK.  If you have
-version 10.3.anything, you need to figure out whether you have the ANSI C
-compiler (version 6.7 or later) and whether you've installed the ANSI C
-include files (if so, the first line of <stdio.h> will mention ANSI C).
-If you have the ANSI C compiler but not the ANSI C include files, use
-makefile.ansi and add -DNONANSI_INCLUDES to CFLAGS.  If you have both,
-then makefile.ansi should work as is.  If neither, use makefile.unix.
-
-
-HP-UX:
-
-If you have HP-UX 7.05 or later with the "software development" C compiler,
-then you can use makefile.ansi.  Add "-Aa" to the CFLAGS line in the makefile
-to make the compiler work in ANSI mode.  If you have a pre-7.05 system, or if
-you are using the non-ANSI C compiler delivered with a minimum HP-UX 8.0
-system, then you must use makefile.unix (and do NOT add -Aa).  Also, adding
-"-lmalloc" to LDLIBS is recommended if you have libmalloc.a (it seems not to
-be present in minimum 8.0).
-
-On HP 9000 series 800 machines, the HP C compiler is buggy in revisions prior
-to A.08.07.  If you get complaints about "not a typedef name", you'll have to
-convert the code to K&R style (i.e., use makefile.unix).
-
-
-Macintosh MPW:
-
-We don't directly support MPW in the current release, but Larry Rosenstein
-reports that the JPEG code can be ported without very much trouble.  There's
-useful notes and conversion scripts in his kit for porting PBMPLUS to MPW.
-You can obtain the kit by FTP to ftp.apple.com, file /pub/lsr/pbmplus-port*.
-
-
-Macintosh Think C:
-
-You'll have to prepare project files for cjpeg and djpeg; we don't include
-those in the distribution since they are not text files.  The COBJECTS and
-DOBJECTS lists in makefile.unix show which files should be included in each
-project.  Also add the ANSI and Unix C libraries in a separate segment.  You
-may need to divide the JPEG files into more than one segment; you can do this
-pretty much as you please.
-
-If you have Think C version 5.0 you need not modify jconfig.h; instead you
-should turn on both the ANSI Settings and Language Extensions option buttons
-(so that both __STDC__ and THINK_C are predefined).  With version 4.0 you must
-edit jconfig.h.  (You can #define HAVE_STDC to do the right thing for all
-options except const; you must also #define const.)
-
-jcmain and jdmain are set up to provide the usual command-line interface
-by means of Think's ccommand() library routine.  A more Mac-like interface
-is in the works.
-
-
-MS-DOS, generic comments:
-
-The JPEG code is designed to be compiled with 80x86 "small" or "medium" memory
-models (i.e., data pointers are 16 bits unless explicitly declared "far"; code
-pointers can be either size).  You should be able to use small model to
-compile cjpeg or djpeg by itself, but you will probably have to go to medium
-model if you include the JPEG code in a larger application.  This shouldn't
-hurt performance much.  You *will* take a noticeable performance hit if you
-compile in a large-data memory model, and you should avoid "huge" model if at
-all possible.  Be sure that NEED_FAR_POINTERS is defined by jconfig.h or by
-the Makefile if you use a small-data model; be sure it is NOT defined if you
-use a large-data memory model.  (As distributed, jconfig.h defines
-NEED_FAR_POINTERS if MSDOS is defined.)
-
-The DOS-specific memory manager, jmemdos.c, should be used if possible.
-(Be sure to install jmemdos.h and jmemdosa.asm along with it.)  If you
-can't use jmemdos.c for some reason --- for example, because you don't have
-a Microsoft-compatible assembler to assemble jmemdosa.asm --- you'll have
-to fall back to jmemansi.c or jmemname.c.  IMPORTANT: if you use either of
-the latter two files, you will have to compile in a large-data memory model
-in order to get the right stdio library.  Too bad.
-
-None of the above advice applies if you are using a 386 flat-memory-space
-environment, such as DJGPP or Watcom C.  (And you should use one if you have
-it, as performance will be much better than 8086-compatible code!)  For
-flat-memory-space compilers, do NOT define NEED_FAR_POINTERS, and do NOT use
-jmemdos.c.  Use jmemnobs.c if the environment supplies adequate virtual
-memory, otherwise use jmemansi.c or jmemname.c.
-
-Most MS-DOS compilers treat stdin/stdout as text files, so you must use
-two-file command line style.  But if your compiler has either fdopen() or
-setmode(), you can use one-file style if you like.  To do this, define
-USE_FDOPEN or USE_SETMODE so that stdin/stdout will be set to binary mode.
-(USE_SETMODE seems to work with more DOS compilers than USE_FDOPEN.)  You
-should test that I/O through stdin/stdout produces the same results as I/O
-to explicitly named files... the "make test" procedures in the DOS-specific
-makefiles do NOT use stdin/stdout.
-
-If you add more switches to CFLAGS in the DOS-specific makefiles, you are
-likely to run up against DOS' 128-byte command line length limit.  In that
-case, remove some "-Dsymbol" switches from CFLAGS and instead put
-corresponding "#define symbol" lines at the head of jinclude.h.
-
-
-MS-DOS, Borland C:
-
-Be sure to convert all the source files to DOS text format (CR/LF newlines).
-Although Borland C will often work OK with unmodified Unix (LF newlines)
-source files, sometimes it will give bogus compile errors.
-"Illegal character '#'" is the most common such error.
-
-Some versions of Borland's MAKE erroneously display the warning message about
-creating jmemsys.c, even after you have done so.  If this happens to you,
-delete the four lines beginning with "jmemsys.c:" from the Makefile.
-
-If you want one-file command line style, define USE_SETMODE.  fdopen() does
-not work correctly.
-
-
-MS-DOS, DJGPP:
-
-Use makefile.ansi and jmemnobs.c, and put "-UMSDOS" in CFLAGS to undo the
-compiler's automatic definition of MSDOS.  Also put either "-DUSE_SETMODE" or
-"-DTWO_FILE_COMMANDLINE" in CFLAGS, depending on whether you prefer one-file
-or two-file command line style.  You'll also need to put the object-file lists
-into response files in order to circumvent DOS's 128-byte command line length
-limit at the final linking step.
-
-
-MS-DOS, Microsoft C:
-
-Old versions of MS C fail with an "out of macro expansion space" error
-because they can't cope with the macro TRACEMS8 (defined in jpegdata.h).
-If this happens to you, the easiest solution is to change TRACEMS8 to
-expand to nothing.  You'll lose the ability to dump out JPEG coefficient
-tables with djpeg -debug -debug, but at least you can compile.
-
-Original MS C 6.0 is buggy; it compiles incorrect code unless you turn off
-optimization (remove -O from CFLAGS).  That problem seems to have been fixed
-in 6.00A and later versions.  6.00A still generates a bogus "conditional
-expression is constant" warning in jrdppm.c, but the emitted code seems OK.
-
-If you want one-file command line style, define USE_SETMODE.  fdopen() does
-not work correctly, at least not in 6.00A.
-
-
-SGI:
-
-Use makefile.ansi, but set "AR2= ar -ts" rather than "AR2= ranlib".  Also
-make any changes recommended by ckconfig.c.
-
-
-Sun:
-
-Don't forget to add -DBSD to CFLAGS.  If you are using GCC on SunOS 4.0.1 or
-earlier, you will need to add -DNONANSI_INCLUDES to CFLAGS (your compiler may
-be ANSI, but your system include files aren't).  I've gotten conflicting
-reports on whether this is still necessary on SunOS 4.1 or later.
diff --git a/USAGE b/USAGE
deleted file mode 100644
index 76044f8..0000000
--- a/USAGE
+++ /dev/null
@@ -1,308 +0,0 @@
-USAGE instructions for the Independent JPEG Group's JPEG software
-=================================================================
-
-INTRODUCTION
-
-This distribution contains software to implement JPEG image compression and
-decompression.  JPEG (pronounced "jay-peg") is a standardized compression
-method for full-color and gray-scale images.  JPEG is designed to handle
-"real-world" scenes, for example scanned photographs.  Cartoons, line
-drawings, and other non-realistic images are not JPEG's strong suit; on this
-sort of material you may get poor image quality and/or little compression.
-
-JPEG is lossy, meaning that the output image is not necessarily identical to
-the input image.  Hence you should not use JPEG if you have to have identical
-output bits.  However, on typical real-world images, very good compression
-levels can be obtained with no visible change, and amazingly high compression
-is possible if you can tolerate a low-quality image.  You can trade off image
-quality against file size by adjusting the compressor's "quality" setting.
-
-This file describes usage of the standard programs "cjpeg" and "djpeg" that
-can be built directly from the distributed C code.  See the README file for
-hints on incorporating the JPEG software into other programs.
-
-If you are on a Unix machine you may prefer to read the Unix-style manual
-pages in files cjpeg.1 and djpeg.1.  But also see the HINTS section below,
-which is not present in either manual page.
-
-NOTE: the switch syntax has been redesigned since the v3 release of
-cjpeg/djpeg.  Switch names are now words instead of single letters.
-
-
-GENERAL USAGE
-
-We provide two programs, cjpeg to compress an image file into JPEG format,
-and djpeg to decompress a JPEG file back into a conventional image format.
-
-On Unix-like systems, you say:
-	cjpeg [switches] [imagefile] >jpegfile
-or
-	djpeg [switches] [jpegfile]  >imagefile
-The programs read the specified input file, or standard input if none is
-named.  They always write to standard output (with trace/error messages to
-standard error).  These conventions are handy for piping images between
-programs.
-
-On most non-Unix systems, you say:
-	cjpeg [switches] imagefile jpegfile
-or
-	djpeg [switches] jpegfile  imagefile
-i.e., both the input and output files are named on the command line.  This
-style is a little more foolproof, and it loses no functionality if you don't
-have pipes.  (You can get this style on Unix too, if you prefer, by defining
-TWO_FILE_COMMANDLINE when you compile the programs; see SETUP.)
-
-You can also say:
-	cjpeg [switches] -outfile jpegfile  imagefile
-or
-	djpeg [switches] -outfile imagefile  jpegfile
-This syntax works on all systems, so it is useful for scripts.
-
-The currently supported image file formats are: PPM (PBMPLUS color format),
-PGM (PBMPLUS gray-scale format), GIF, Targa, and RLE (Utah Raster Toolkit
-format).  (RLE is supported only if the URT library is available.)
-cjpeg recognizes the input image format automatically, with the exception
-of some Targa-format files.  You have to tell djpeg which format to generate.
-
-The only JPEG file format currently supported is the JFIF format.  Support for
-the TIFF 6.0 JPEG format will probably be added at some future date.
-
-All switch names may be abbreviated; for example, -grayscale may be written
--gray or -gr.  Most of the "basic" switches can be abbreviated to as little as
-one letter.  Upper and lower case are equivalent (-GIF is the same as -gif).
-British spellings are also accepted (e.g., -greyscale), though for brevity
-these are not mentioned below.
-
-
-CJPEG DETAILS
-
-The basic command line switches for cjpeg are:
-
-	-quality N	Scale quantization tables to adjust image quality.
-			Quality is 0 (worst) to 100 (best); default is 75.
-			(See below for more info.)
-
-	-grayscale	Create monochrome JPEG file from color input.
-			Be sure to use this switch when compressing a grayscale
-			GIF file, because cjpeg isn't bright enough to notice
-			whether a GIF file uses only shades of gray.  By
-			saying -grayscale, you'll get a smaller JPEG file that
-			takes less time to process.
-
-	-optimize	Perform optimization of entropy encoding parameters.
-			Without this, default encoding parameters are used.
-			-optimize usually makes the JPEG file a little smaller,
-			but cjpeg runs somewhat slower and needs much more
-			memory.  Image quality and speed of decompression are
-			unaffected by -optimize.
-
-	-targa		Input file is Targa format.  Targa files that contain
-			an "identification" field will not be automatically
-			recognized by cjpeg; for such files you must specify
-			-targa to make cjpeg treat the input as Targa format.
-
-The -quality switch lets you trade off compressed file size against quality of
-the reconstructed image: the higher the quality setting, the larger the JPEG
-file, and the closer the output image will be to the original input.  Normally
-you want to use the lowest quality setting (smallest file) that decompresses
-into something visually indistinguishable from the original image.  For this
-purpose the quality setting should be between 50 and 95; the default of 75 is
-often about right.  If you see defects at -quality 75, then go up 5 or 10
-counts at a time until you are happy with the output image.  (The optimal
-setting will vary from one image to another.)
-
--quality 100 will generate a quantization table of all 1's, eliminating loss
-in the quantization step (but there is still information loss in subsampling,
-as well as roundoff error).  This setting is mainly of interest for
-experimental purposes.  Quality values above about 95 are NOT recommended for
-normal use; the compressed file size goes up dramatically for hardly any gain
-in output image quality.
-
-In the other direction, quality values below 50 will produce very small files
-of low image quality.  Settings around 5 to 10 might be useful in preparing an
-index of a large image library, for example.  Try -quality 2 (or so) for some
-amusing Cubist effects.  (Note: quality values below about 25 generate 2-byte
-quantization tables, which are considered optional in the JPEG standard.
-cjpeg emits a warning message when you give such a quality value, because
-some commercial JPEG programs may be unable to decode the resulting file.)
-
-Switches for advanced users:
-
-	-maxmemory N	Set limit for amount of memory to use in processing
-			large images.  Value is in thousands of bytes, or
-			millions of bytes if "M" is attached to the number.
-			For example, -max 4m selects 4000000 bytes.  If more
-			space is needed, temporary files will be used.
-
-	-restart N	Emit a JPEG restart marker every N MCU rows, or every
-			N MCU blocks if "B" is attached to the number.
-			-restart 0 (the default) means no restart markers.
-
-	-smooth N	Smooth the input image to eliminate dithering noise.
-			N, ranging from 1 to 100, indicates the strength of
-			smoothing.  0 (the default) means no smoothing.
-
-	-verbose	Enable debug printout.  More -v's give more printout.
-	or  -debug	Also, version information is printed at startup.
-
-The -restart option inserts extra markers that allow a JPEG decoder to
-resynchronize after a transmission error.  Without restart markers, any damage
-to a compressed file will usually ruin the image from the point of the error
-to the end of the image; with restart markers, the damage is usually confined
-to the portion of the image up to the next restart marker.  Of course, the
-restart markers occupy extra space.  We recommend -restart 1 for images that
-will be transmitted across unreliable networks such as Usenet.
-
-The -smooth option filters the input to eliminate fine-scale noise.  This is
-often useful when converting GIF files to JPEG: a moderate smoothing factor of
-10 to 50 gets rid of dithering patterns in the input file, resulting in a
-smaller JPEG file and a better-looking image.  Too large a smoothing factor
-will visibly blur the image, however.
-
-Switches for wizards:
-
-	-arithmetic	Use arithmetic coding rather than Huffman coding.
-			(Not currently supported for legal reasons.)
-
-	-nointerleave	Generate noninterleaved JPEG file (not yet supported).
-
-	-qtables file	Use the quantization tables given in the specified
-			file.  The file should contain one to four tables
-			(64 values each) as plain text.  Comments preceded by
-			'#' may be included in the file.  The tables are
-			implicitly numbered 0,1,etc.  If -quality N is also
-			specified, the values in the file are scaled according
-			to cjpeg's quality scaling curve.
-
-	-sample HxV[,...]	Set JPEG sampling factors.  If you specify
-			fewer H/V pairs than there are components, the
-			remaining components are set to 1x1 sampling.  The
-			default setting is equivalent to "-sample 2x2".
-
-The "wizard" switches are intended for experimentation with JPEG.  If you
-don't know what you are doing, DON'T USE THEM.  You can easily produce files
-with worse image quality and/or poorer compression than you'll get from the
-default settings.  Furthermore, these switches should not be used when making
-files intended for general use, because not all JPEG implementations will
-support unusual JPEG parameter settings.
-
-
-DJPEG DETAILS
-
-The basic command line switches for djpeg are:
-
-	-colors N	Reduce image to at most N colors.  This reduces the
-	or -quantize N	number of colors used in the output image, so that it
-			can be displayed on a colormapped display or stored in
-			a colormapped file format.  For example, if you have
-			an 8-bit display, you'd need to reduce to 256 or fewer
-			colors.  (-colors is the recommended name, -quantize
-			is provided only for backwards compatibility.)
-
-	-gif		Select GIF output format.  Since GIF does not support
-			more than 256 colors, -colors 256 is assumed (unless
-			you specify a smaller number of colors).
-
-	-pnm		Select PBMPLUS (PPM/PGM) output format (this is the
-			default format).  PGM is emitted if the JPEG file is
-			gray-scale or if -grayscale is specified; otherwise
-			PPM is emitted.
-
-	-rle		Select RLE output format.  (Requires URT library.)
-
-	-targa		Select Targa output format.  Gray-scale format is
-			emitted if the JPEG file is gray-scale or if
-			-grayscale is specified; otherwise, colormapped format
-			is emitted if -colors is specified; otherwise, 24-bit
-			full-color format is emitted.
-
-Switches for advanced users:
-
-	-blocksmooth	Perform cross-block smoothing.  This is slow, quite
-			memory-intensive, and only seems to improve the image
-			at very low quality settings (-quality 10 to 20 or so).
-			At normal quality settings it may make things worse.
-
-	-grayscale	Force gray-scale output even if JPEG file is color.
-			Useful for viewing on monochrome displays.
-
-	-maxmemory N	Set limit for amount of memory to use in processing
-			large images.  Value is in thousands of bytes, or
-			millions of bytes if "M" is attached to the number.
-			For example, -max 4m selects 4000000 bytes.  If more
-			space is needed, temporary files will be used.
-
-	-nodither	Do not use dithering in color quantization.
-			By default, Floyd-Steinberg dithering is applied when
-			quantizing colors, but on some images dithering may
-			result in objectionable "graininess".  If that
-			happens, you can turn off dithering with -nodither.
-			-nodither is ignored unless you also say -colors N.
-
-	-onepass	Use one-pass instead of two-pass color quantization.
-			The one-pass method is faster and needs less memory,
-			but it produces a lower-quality image.  -onepass is
-			ignored unless you also say -colors N.  Also,
-			the one-pass method is always used for gray-scale
-			output (the two-pass method is no improvement then).
-
-	-verbose	Enable debug printout.  More -v's give more printout.
-	or  -debug	Also, version information is printed at startup.
-
-
-HINTS
-
-Color GIF files are not the ideal input for JPEG; JPEG is really intended for
-compressing full-color (24-bit) images.  In particular, don't try to convert
-cartoons, line drawings, and other images that have only a few distinct
-colors.  GIF works great on these, JPEG does not.  If you want to convert a
-GIF to JPEG, you should experiment with cjpeg's -quality and -smooth options
-to get a satisfactory conversion.  -smooth 10 or so is often helpful.
-
-Avoid running an image through a series of JPEG compression/decompression
-cycles.  Image quality loss will accumulate; after ten or so cycles the image
-may be noticeably worse than it was after one cycle.  It's best to use a
-lossless format while manipulating an image, then convert to JPEG format when
-you are ready to file the image away.
-
-The -optimize option to cjpeg is worth using when you are making a "final"
-version for posting or archiving.  It's also a win when you are using low
-quality settings to make very small JPEG files; the percentage improvement
-is often a lot more than it is on larger files.
-
-When making images to be posted on Usenet, we recommend using cjpeg's option
--restart 1.  This option limits the damage done to a compressed image by
-netnews transmission errors.
-
-The default memory usage limit (-maxmemory) is set when the software is
-compiled.  If you get an "insufficient memory" error, try specifying a smaller
--maxmemory value, even -maxmemory 0 to use the absolute minimum space.  You
-may want to recompile with a smaller default value if this happens often.
-
-On machines that have "environment" variables, you can define the environment
-variable JPEGMEM to set the default memory limit.  The value is specified as
-described for the -maxmemory switch.  JPEGMEM overrides the default value
-specified when the program was compiled, and itself is overridden by an
-explicit -maxmemory switch.
-
-On MS-DOS machines, -maxmemory is the amount of main (conventional) memory to
-use.  (Extended or expanded memory is also used if available.)  Most
-DOS-specific versions of this software do their own memory space estimation
-and do not need -maxmemory.
-
-djpeg with two-pass color quantization requires a good deal of memory; on
-MS-DOS machines it may run out of memory even with -maxmemory 0.  In that case
-you can still decompress, with some loss of image quality, by specifying
--onepass for one-pass quantization.
-
-If more space is needed than will fit in the available main memory (as
-determined by -maxmemory), temporary files will be used.  (MS-DOS versions
-will try to get extended or expanded memory first.)  The temporary files are
-often rather large: in typical cases they occupy three bytes per pixel, for
-example 3*800*600 = 1.44Mb for an 800x600 image.  If you don't have enough
-free disk space, leave out -optimize (for cjpeg) or specify -onepass (for
-djpeg).  On MS-DOS, the temporary files are created in the directory named by
-the TMP or TEMP environment variable, or in the current directory if neither
-of those exist.  Amiga implementations put the temp files in the directory
-named by JPEGTMP:, so be sure to assign JPEGTMP: to a disk partition with
-adequate free space.
diff --git a/ansi2knr.1 b/ansi2knr.1
new file mode 100644
index 0000000..434ce8f
--- /dev/null
+++ b/ansi2knr.1
@@ -0,0 +1,19 @@
+.TH ANSI2KNR 1 "31 December 1990" 
+.SH NAME
+ansi2knr \- convert ANSI C to Kernighan & Ritchie C
+.SH SYNOPSIS
+.I ansi2knr
+input_file output_file
+.SH DESCRIPTION
+If no output_file is supplied, output goes to stdout.
+.br
+There are no error messages.
+.sp
+.I ansi2knr
+recognizes functions by seeing a non-keyword identifier at the left margin, followed by a left parenthesis, with a right parenthesis as the last character on the line.  It will recognize a multi-line header if the last character on each line but the last is a left parenthesis or comma.  These algorithms ignore whitespace and comments, except that the function name must be the first thing on the line.
+.sp
+The following constructs will confuse it:
+.br
+     - Any other construct that starts at the left margin and follows the above syntax (such as a macro or function call).
+.br
+     - Macros that tinker with the syntax of the function header.
diff --git a/ansi2knr.c b/ansi2knr.c
index 13310d9..3924215 100644
--- a/ansi2knr.c
+++ b/ansi2knr.c
@@ -1,24 +1,26 @@
-/* Copyright (C) 1989, 1991 Aladdin Enterprises.  All rights reserved.
-   Distributed by Free Software Foundation, Inc.
+/* Copyright (C) 1989, 1991, 1993 Aladdin Enterprises. All rights reserved. */
 
-This file is part of Ghostscript.
+/* ansi2knr.c */
+/* Convert ANSI function declarations to K&R syntax */
 
-Ghostscript is distributed in the hope that it will be useful, but
+/*
+ansi2knr is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY.  No author or distributor accepts responsibility
 to anyone for the consequences of using it or for whether it serves any
 particular purpose or works at all, unless he says so in writing.  Refer
-to the Ghostscript General Public License for full details.
+to the GNU General Public License for full details.
 
 Everyone is granted permission to copy, modify and redistribute
-Ghostscript, but only under the conditions described in the Ghostscript
+ansi2knr, but only under the conditions described in the GNU
 General Public License.  A copy of this license is supposed to have been
-given to you along with Ghostscript so you can know your rights and
+given to you along with ansi2knr so you can know your rights and
 responsibilities.  It should be in a file named COPYING.  Among other
 things, the copyright notice and this notice must be preserved on all
-copies.  */
+copies.
+*/
 
 /*
----------- Here is the GhostScript file COPYING, referred to above ----------
+---------- Here is the GNU GPL file COPYING, referred to above ----------
 ----- These terms do NOT apply to the JPEG software itself; see README ------
 
 		    GHOSTSCRIPT GENERAL PUBLIC LICENSE
@@ -163,28 +165,26 @@
 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) GHOSTSCRIPT, EVEN IF YOU
 HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, OR FOR ANY CLAIM
 BY ANY OTHER PARTY.
+
 -------------------- End of file COPYING ------------------------------
 */
 
 
-/* ansi2knr.c */
-/* Convert ANSI function declarations to K&R syntax */
-
 #include <stdio.h>
 #include <ctype.h>
 
 #ifdef BSD
 #include <strings.h>
-#define strchr index
 #else
 #ifdef VMS
-	extern char *strcat(), *strchr(), *strcpy(), *strupr();
-	extern int strcmp(), strlen(), strncmp();
+	extern int strlen(), strncmp();
 #else
 #include <string.h>
 #endif
 #endif
 
+/* malloc and free should be declared in stdlib.h, */
+/* but if you've got a K&R compiler, they probably aren't. */
 #ifdef MSDOS
 #include <malloc.h>
 #else
@@ -198,27 +198,35 @@
 #endif
 
 /* Usage:
-	ansi2knr input_file output_file
+	ansi2knr input_file [output_file]
  * If no output_file is supplied, output goes to stdout.
  * There are no error messages.
  *
  * ansi2knr recognizes functions by seeing a non-keyword identifier
  * at the left margin, followed by a left parenthesis,
  * with a right parenthesis as the last character on the line.
- * It will recognize a multi-line header if the last character
- * on each line but the last is a left parenthesis or comma.
+ * It will recognize a multi-line header provided that the last character
+ * of the last line of the header is a right parenthesis,
+ * and no intervening line ends with a left brace or a semicolon.
  * These algorithms ignore whitespace and comments, except that
  * the function name must be the first thing on the line.
  * The following constructs will confuse it:
-	- Any other construct that starts at the left margin and
-	    follows the above syntax (such as a macro or function call).
-	- Macros that tinker with the syntax of the function header.
+ *	- Any other construct that starts at the left margin and
+ *	    follows the above syntax (such as a macro or function call).
+ *	- Macros that tinker with the syntax of the function header.
  */
 
 /* Scanning macros */
 #define isidchar(ch) (isalnum(ch) || (ch) == '_')
 #define isidfirstchar(ch) (isalpha(ch) || (ch) == '_')
 
+/* Forward references */
+char *skipspace();
+int writeblanks();
+int test1();
+int convert1();
+
+/* The main program */
 main(argc, argv)
     int argc;
     char *argv[];
@@ -324,9 +332,9 @@
 	switch ( *bend )
 	   {
 	case ')': contin = 1; break;
-	case '(':
-	case ',': contin = -1; break;
-	default: return 0;		/* not a function */
+	case '{':
+	case ';': return 0;		/* not a function */
+	default: contin = -1;
 	   }
 	while ( isidchar(*p) ) p++;
 	endfn = p;
@@ -362,13 +370,16 @@
 convert1(buf, out)
     char *buf;
     FILE *out;
-{	char *endfn = strchr(buf, '(') + 1;
+{	char *endfn;
 	register char *p;
 	char **breaks;
 	unsigned num_breaks = 2;	/* for testing */
 	char **btop;
 	char **bp;
 	char **ap;
+	/* Pre-ANSI implementations don't agree on whether strchr */
+	/* is called strchr or index, so we open-code it here. */
+	for ( endfn = buf; *(endfn++) != '('; ) ;
 top:	p = endfn;
 	breaks = (char **)malloc(sizeof(char *) * num_breaks * 2);
 	if ( breaks == 0 )
diff --git a/architecture b/architecture
deleted file mode 100644
index bf3385f..0000000
--- a/architecture
+++ /dev/null
@@ -1,1195 +0,0 @@
-
-	JPEG SYSTEM ARCHITECTURE		1-DEC-92
-
-
-This file provides an overview of the "architecture" of the portable JPEG
-software; that is, the functions of the various modules in the system and the
-interfaces between modules.  For more precise details about any data structure
-or calling convention, see the header files.
-
-Important note: when I say "module" I don't mean "a C function", which is what
-some people seem to think the term means.  A separate C source file is closer
-to the mark.  Also, it is frequently the case that several different modules
-present a common interface to callers; the term "object" or "method" refers to
-this common interface (see "Poor man's object-oriented programming", below).
-
-JPEG-specific terminology follows the JPEG standard:
-  A "component" means a color channel, e.g., Red or Luminance.
-  A "sample" is a pixel component value (i.e., one number in the image data).
-  A "coefficient" is a frequency coefficient (a DCT transform output number).
-  The term "block" refers to an 8x8 group of samples or coefficients.
-  "MCU" (minimum coded unit) is the same as "MDU" of the R8 draft; i.e., an
-	interleaved set of blocks of size determined by the sampling factors,
-	or a single block in a noninterleaved scan.
-
-
-*** System requirements ***
-
-We must support compression and decompression of both Huffman and
-arithmetic-coded JPEG files.  Any set of compression parameters allowed by the
-JPEG spec should be readable for decompression.  (We can be more restrictive
-about what formats we can generate.)  (Note: for legal reasons no arithmetic
-coding implementation is currently included in the publicly available sources.
-However, the architecture still supports it.)
-
-We need to be able to handle both raw JPEG files (more specifically, the JFIF
-format) and JPEG-in-TIFF (C-cubed's format, and perhaps Kodak's).  Even if we
-don't implement TIFF ourselves, other people will want to use our code for
-that.  This means that generation and scanning of the file header has to be
-separated out.
-
-Perhaps we should be prepared to support the JPEG lossless mode (also referred
-to in the spec as spatial DPCM coding).  A lot of people seem to believe they
-need this... whether they really do is debatable, but the customer is always
-right.  On the other hand, there will not be much sharable code between the
-lossless and lossy modes!  At best, a lossless program could be derived from
-parts of the lossy version.  For now we will only worry about the lossy mode.
-
-I see no real value in supporting the JPEG progressive modes (note that
-spectral selection and successive approximation are two different progressive
-modes).  These are only of interest when painting the decompressed image in
-real-time, which nobody is going to do with a pure software implementation.
-
-There is some value in supporting the hierarchical mode, which allows for
-successive frames of higher resolution.  This could be of use for including
-"thumbnail" representations.  However, this appears to add a lot more
-complexity than it is worth.
-
-A variety of uncompressed image file formats and user interfaces must be
-supported.  These aspects therefore have to be kept separate from the rest of
-the system.  A particularly important issue is whether color quantization of
-the output is needed (i.e., whether a colormap is used).  We should be able to
-support both adaptive quantization (which requires two or more passes over the
-image) and nonadaptive (quantization to a prespecified colormap, which can be
-done in one pass).
-
-Memory usage is an important concern, since we will port this code to 80x86
-and other limited-memory machines.  For large intermediate structures, we
-should be able to use either virtual memory or temporary files.
-
-It should be possible to build programs that handle compression only,
-decompression only, or both, without much duplicate or unused code in any
-version.  (In particular, a decompression-only version should have no extra
-baggage.)
-
-
-*** Compression overview ***
-
-The *logical* steps needed in (non-lossless) JPEG compression are:
-
-1. Conversion from incoming image format to a standardized internal form
-   (either RGB or grayscale).
-
-2. Color space conversion (e.g., RGB to YCbCr).  This is a null step for
-   grayscale (unless we support mapping color inputs to grayscale, which
-   would most easily be done here).  Gamma adjustment may also be needed here.
-
-3. Downsampling (reduction of number of samples in some color components).
-   This step operates independently on each color component.
-
-4. MCU extraction (creation of a single sequence of 8x8 sample blocks).
-   This step and the following ones are performed once for each scan
-   in the output JPEG file, i.e., once if making an interleaved file and more
-   than once for a noninterleaved file.
-   Note: both this step and the previous one must deal with edge conditions
-   for pictures that aren't a multiple of the MCU dimensions.  Alternately,
-   we could expand the picture to a multiple of an MCU before doing these
-   two steps.  (The latter seems better and has been adopted below.)
-
-5. DCT transformation of each 8x8 block.
-
-6. Quantization scaling and zigzag reordering of the elements in each 8x8
-   block.
-
-7. Huffman or arithmetic encoding of the transformed block sequence.
-
-8. Output of the JPEG file with whatever headers/markers are wanted.
-
-Of course, the actual implementation will combine some of these logical steps
-for efficiency.  The trick is to keep these logical functions as separate as
-possible without losing too much performance.
-
-In addition to these logical pipeline steps, we need various modules that
-aren't part of the data pipeline.  These are:
-
-A. Overall control (sequencing of other steps & management of data passing).
-
-B. User interface; this will determine the input and output files, and supply
-   values for some compression parameters.  Note that this module is highly
-   platform-dependent.
-
-C. Compression parameter selection: some parameters should be chosen
-   automatically rather than requiring the user to find a good value.
-   The prototype only does this for the back-end (Huffman or arithmetic)
-   parameters, but further in the future, more might be done.  A
-   straightforward approach to selection is to try several values; this
-   requires being able to repeatedly apply some portion of the pipeline and
-   inspect the results (without actually outputting them).  Probably only
-   entropy encoding parameters can reasonably be done this way; optimizing
-   earlier steps would require too much data to be reprocessed (not to mention
-   the problem of interactions between parameters for different steps).
-   What other facilities do we need to support automatic parameter selection?
-
-D. A memory management module to deal with small-memory machines.  This must
-   create the illusion of virtual memory for certain large data structures
-   (e.g., the downsampled image or the transformed coefficients).
-   The interface to this must be defined to minimize the overhead incurred,
-   especially on virtual-memory machines where the module won't do much.
-
-In many cases we can arrange things so that a data stream is produced in
-segments by one module and consumed by another without the need to hold it all
-in (virtual) memory.  This is obviously not possible for any data that must be
-scanned more than once, so it won't work everywhere.
-
-The major variable at this level of detail is whether the JPEG file is to be
-interleaved or not; that affects the order of processing so fundamentally that
-the central control module must know about it.  Some of the other modules may
-need to know it too.  It would simplify life if we didn't need to support
-noninterleaved images, but that is not reasonable.
-
-Many of these steps operate independently on each color component; the
-knowledge of how many components there are, and how they are interleaved,
-ought to be confined to the central control module.  (Color space conversion
-and MCU extraction probably have to know it too.)
-
-
-*** Decompression overview ***
-
-Decompression is roughly the inverse process from compression, but there are
-some additional steps needed to produce a good output image.
-
-The *logical* steps needed in (non-lossless) JPEG decompression are:
-
-1. Scanning of the JPEG file, decoding of headers/markers etc.
-
-2. Huffman or arithmetic decoding of the coefficient sequence.
-
-3. Quantization descaling and zigzag reordering of the elements in each 8x8
-   block.
-
-4. MCU disassembly (conversion of a possibly interleaved sequence of 8x8
-   blocks back to separate components in pixel map order).
-
-5. (Optional)  Cross-block smoothing per JPEG section K.8 or a similar
-   algorithm.  (Steps 5-8 operate independently on each component.)
-
-6. Inverse DCT transformation of each 8x8 block.
-
-7. Upsampling.  At this point a pixel image of the original dimensions
-   has been recreated.
-
-8. Post-upsampling smoothing.  This can be combined with upsampling,
-   by using a convolution-like calculation to generate each output pixel
-   directly from one or more input pixels.
-
-9. Cropping to the original pixel dimensions (throwing away duplicated
-   pixels at the edges).  It is most convenient to do this now, as the
-   preceding steps are simplified by not having to worry about odd picture
-   sizes.
-
-10. Color space reconversion (e.g., YCbCr to RGB).  This is a null step for
-    grayscale.  (Note that mapping a color JPEG to grayscale output is most
-    easily done in this step.)  Gamma adjustment may also be needed here.
-
-11. Color quantization (only if a colormapped output format is requested).
-    NOTE: it is probably preferable to perform quantization in the internal
-    (JPEG) colorspace rather than the output colorspace.  Doing it that way,
-    color conversion need only be applied to the colormap entries, not to
-    every pixel; and quantization gets to operate in a non-gamma-corrected
-    space.  But the internal space may not be suitable for some algorithms.
-    The system design is such that only the color quantizer module knows
-    whether color conversion happens before or after quantization.
-
-12. Writing of the desired image format.
-
-As before, some of these will be combined into single steps.  When dealing
-with a noninterleaved JPEG file, steps 2-9 will be performed once for each
-scan; the resulting data will need to be buffered up so that steps 10-12 can
-process all the color components together.
-
-The same auxiliary modules are needed as before, except for compression
-parameter selection.  Note that rerunning a pipeline stage should never be
-needed during decompression.  This may allow a simpler control module.  The
-user interface might also be simpler since it need not supply any compression
-parameters.
-
-As before, not all of these steps require the whole image to be stored.
-Actually, two-pass color quantization is the only step that logically requires
-this; everything else could be done a few raster lines at a time (at least for
-interleaved images).  We might want to make color quantization be a separate
-program because of this fact.
-
-Again, many of the steps should be able to work on one color component in
-ignorance of the other components.
-
-
-*** Implications of noninterleaved formats ***
-
-Much of the work can be done in a single pass if an interleaved JPEG file
-format is used.  With a noninterleaved JPEG file, separating or recombining
-the components will force use of virtual memory (on a small-memory machine,
-we probably would want one temp file per color component).
-
-If any of the image formats we read or write are noninterleaved, the opposite
-condition might apply: processing a noninterleaved JPEG file would be more
-efficient.  Offhand, though, I can't think of any popular image formats that
-work that way; besides the win would only come if the same color space were
-used in JPEG and non-JPEG files.  It's not worth the complexity to make the
-system design accommodate that case efficiently.
-
-An argument against interleaving is that it makes the decompressor need more
-memory for cross-block smoothing (since the minimum processable chunk of the
-image gets bigger).  With images more than 1000 pixels across, 80x86 machines
-are likely to have difficulty in handling this feature.
-
-Another argument against interleaving is that the noninterleaved format allows
-a wider range of sampling factors, since the limit of ten blocks per MCU no
-longer applies.  We could get around this by blithely ignoring the spec's
-limit of ten blocks, but that seems like a bad idea (especially since it makes
-the above problem worse).
-
-The upshot is that we need to support both interleaved and noninterleaved JPEG
-formats, since for any given machine and picture size one may be much more
-efficient than the other.  However, the non-JPEG format we convert to or from
-will be assumed to be an interleaved format (i.e., it produces or stores all
-the components of a pixel together).
-
-I do not think it is necessary for the compressor to be able to output
-partially-interleaved formats (multiple scans, some of which interleave a
-subset of the components).  However, the decompressor must be able to read
-such files to conform to the spec.
-
-
-*** Data formats ***
-
-Pipeline steps that work on pixel sample values will use the following data
-structure:
-
-    typedef something JSAMPLE;		a pixel component value, 0..MAXJSAMPLE
-    typedef JSAMPLE *JSAMPROW;		ptr to a row of samples
-    typedef JSAMPROW *JSAMPARRAY;	ptr to a list of rows
-    typedef JSAMPARRAY *JSAMPIMAGE;	ptr to a list of color-component arrays
-
-The basic element type JSAMPLE will be one of unsigned char, (signed) char, or
-unsigned short.  Unsigned short will be used if samples wider than 8 bits are
-to be supported (this is a compile-time option).  Otherwise, unsigned char is
-used if possible.  If the compiler only supports signed chars, then it is
-necessary to mask off the value when reading.  Thus, all reads of sample
-values should be coded as "GETJSAMPLE(value)", where the macro will be defined
-as "((value)&0xFF)" on signed-char machines and "(value)" elsewhere.
-
-With these conventions, JSAMPLE values can be assumed to be >= 0.  This should
-simplify correct rounding during downsampling, etc.  The JPEG draft's
-specification that sample values run from -128..127 will be accommodated by
-subtracting 128 just as the sample value is copied into the source array for
-the DCT step (this will be an array of signed shorts or longs).  Similarly,
-during decompression the output of the IDCT step will be immediately shifted
-back to 0..255.  (NB: different values are required when 12-bit samples are in
-use.  The code should be written in terms of MAXJSAMPLE and CENTERJSAMPLE,
-which will be #defined as 255 and 128 respectively in an 8-bit implementation,
-and as 4095 and 2048 in a 12-bit implementation.)
-
-On compilers that don't support "unsigned short", signed short can be used for
-a 12-bit implementation.  To support lossless coding (which allows up to
-16-bit data precision) masking with 0xFFFF in GETJSAMPLE might be necessary.
-(But if "int" is 16 bits then using "unsigned int" is the best solution.)
-
-Notice that we use a pointer per row, rather than a two-dimensional JSAMPLE
-array.  This choice costs only a small amount of memory and has several
-benefits:
-
-* Code using the data structure doesn't need to know the allocated width of
-the rows.  This will simplify edge expansion/compression, since we can work
-in an array that's wider than the logical picture width.
-
-* The rows forming a component array may be allocated at different times
-without extra copying.  This will simplify working a few scanlines at a time,
-especially in smoothing steps that need access to the previous and next rows.
-
-* Indexing doesn't require multiplication; this is a performance win on many
-machines.
-
-Note that each color component is stored in a separate array; we don't use the
-traditional structure in which the components of a pixel are stored together.
-This simplifies coding of steps that work on each component independently,
-because they don't need to know how many components there are.  Furthermore,
-we can read or write each component to a temp file independently, which is
-helpful when dealing with noninterleaved JPEG files.
-
-A specific sample value will be accessed by code such as
-	GETJSAMPLE(image[colorcomponent][row][col])
-where col is measured from the image left edge, but row is measured from the
-first sample row currently in memory.  Either of the first two indexings can
-be precomputed by copying the relevant pointer.
-
-
-Pipeline steps that work on frequency-coefficient values will use the
-following data structure:
-
-    typedef short JCOEF;		a 16-bit signed integer
-    typedef JCOEF JBLOCK[64];		an 8x8 block of coefficients
-    typedef JBLOCK *JBLOCKROW;		ptr to one horizontal row of 8x8 blocks
-    typedef JBLOCKROW *JBLOCKARRAY;	ptr to a list of such rows
-    typedef JBLOCKARRAY *JBLOCKIMAGE;	ptr to a list of color component arrays
-
-The underlying type is always a 16-bit signed integer (this is "short" on all
-machines of interest, but let's use the typedef name anyway).  These are
-grouped into 8x8 blocks (we should use #defines DCTSIZE and DCTSIZE2 rather
-than "8" and "64").  The contents of a block may be either in "natural" or
-zigzagged order, and may be true values or divided by the quantization
-coefficients, depending on where the block is in the pipeline.
-
-Notice that the allocation unit is now a row of 8x8 blocks, corresponding to
-eight rows of samples.  Otherwise the structure is much the same as for
-samples, and for the same reasons.
-
-On machines where malloc() can't handle a request bigger than 64Kb, this data
-structure limits us to rows of less than 512 JBLOCKs, which would be a picture
-width of 4000 pixels.  This seems an acceptable restriction.
-
-
-On 80x86 machines, the bottom-level pointer types (JSAMPROW and JBLOCKROW)
-must be declared as "far" pointers, but the upper levels can be "near"
-(implying that the pointer lists are allocated in the DS segment).
-To simplify sharing code, we'll have a #define symbol FAR, which expands to
-the "far" keyword when compiling on 80x86 machines and to nothing elsewhere.
-
-
-The data arrays used as input and output of the DCT transform subroutine will
-be declared using a separate typedef; they could be arrays of "short", "int"
-or "long" independently of the above choices.  This would depend on what is
-needed to make the compiler generate correct and efficient multiply/add code
-in the DCT inner loops.  No significant speed or memory penalty will be paid
-to have a different representation than is used in the main image storage
-arrays, since some additional value-by-value processing is done at the time of
-creation or extraction of the DCT data anyway (e.g., add/subtract 128).
-
-
-*** Poor man's object-oriented programming ***
-
-It should be pretty clear by now that we have a lot of quasi-independent
-steps, many of which have several possible behaviors.  To avoid cluttering the
-code with lots of switch statements, we'll use a simple form of object-style
-programming to separate out the different possibilities.
-
-For example, Huffman and arithmetic coding will be implemented as two separate
-modules that present the same external interface; at runtime, the calling code
-will access the proper module indirectly through an "object".
-
-We can get the limited features we need while staying within portable C.  The
-basic tool is a function pointer.  An "object" is just a struct containing one
-or more function pointer fields, each of which corresponds to a method name in
-real object-oriented languages.  During initialization we fill in the function
-pointers with references to whichever module we have determined we need to use
-in this run.  Then invocation of the module is done by indirecting through a
-function pointer; on most architectures this is no more expensive (and
-possibly cheaper) than a switch, which would be the only other way of making
-the required run-time choice.  The really significant benefit, of course, is
-keeping the source code clean and well structured.
-
-For example, the interface for entropy decoding (Huffman or arithmetic
-decoding) might look like this:
-
-	struct function_ptr_struct {
-		...
-		/* Entropy decoding methods */
-		void (*prepare_for_scan) ();
-		void (*get_next_mcu) ();
-		...
-		};
-
-	typedef struct function_ptr_struct * function_ptrs;
-
-The struct pointer is what will actually be passed around.  A call site might
-look like this:
-
-	some_function (function_ptrs fptrs)
-	    {
-		...
-		(*fptrs->get_next_mcu) (...);
-		...
-	    }
-
-(It might be worth inventing some specialized macros to hide the rather ugly
-syntax for method definition and call.)  Note that the caller doesn't know how
-many different get_next_mcu procedures there are, what their real names are,
-nor how to choose which one to call.
-
-An important benefit of this scheme is that it is easy to provide multiple
-versions of any method, each tuned to a particular case.  While a lot of
-precalculation might be done to select an optimal implementation of a method,
-the cost per invocation is constant.  For example, the MCU extraction step
-might have a "generic" method, plus one or more "hardwired" methods for the
-most popular sampling factors; the hardwired methods would be faster because
-they'd use straight-line code instead of for-loops.  The cost to determine
-which method to use is paid only once, at startup, and the selection criteria
-are hidden from the callers of the method.
-
-This plan differs a little bit from usual object-oriented structures, in that
-only one instance of each object class will exist during execution.  The
-reason for having the class structure is that on different runs we may create
-different instances (choose to execute different modules).
-
-To minimize the number of object pointers that have to be passed around, it
-will be easiest to have just a few big structs containing all the method
-pointers.  We'll actually use two such structs, one for "system-dependent"
-methods (memory allocation and error handling) and one for everything else.
-
-Because of this choice, it's best not to think of an "object" as a specific
-data structure.  Rather, an "object" is just a group of related methods.
-There would typically be one or more C modules (source files) providing
-concrete implementations of those methods.  You can think of the term
-"method" as denoting the common interface presented by some set of functions,
-and "object" as denoting a group of common method interfaces, or the total
-shared interface behavior of a group of modules.
-
-
-*** Data chunk sizes ***
-
-To make the cost of this object-oriented style really minimal, we should make
-sure that each method call does a fair amount of computation.  To do that we
-should pass large chunks of data around; for example, the colorspace
-conversion method should process much more than one pixel per call.
-
-For many steps, the most natural unit of data seems to be an "MCU row".
-This consists of one complete horizontal strip of the image, as high as an
-MCU.  In a noninterleaved scan, an MCU row is always eight samples high (when
-looking at samples) or one 8x8 block high (when looking at coefficients).  In
-an interleaved scan, an MCU row consists of all the data for one horizontal
-row of MCUs; this may be from one to four blocks high (eight to thirty-two
-samples) depending on the sampling factors.  The height and width of an MCU
-row may be different in each component.  (Note that the height and width of an
-MCU row changes at the downsampling and upsampling steps.  An unsubsampled
-image has the same size in each component.  The preceding statements apply to
-the downsampled dimensions.)
-
-For example, consider a 1024-pixel-wide image using (2h:2v)(1h:1v)(1h:1v)
-subsampling.  In the noninterleaved case, an MCU row of Y would contain 8x1024
-samples or the same number of frequency coefficients, so it would occupy
-8K bytes (samples) or 16K bytes (coefficients).  An MCU row of Cb or Cr would
-contain 8x512 samples and occupy half as much space.  In the interleaved case,
-an MCU row would contain 16x1024 Y samples, 8x512 Cb and 8x512 Cr samples, so
-a total of 24K (samples) or 48K (coefficients) would be needed.  This is a
-reasonable amount of data to expect to retain in memory at one time.  (Bear in
-mind that we'll usually need to have several MCU rows resident in memory at
-once, at the inputs and outputs to various pipeline steps.)
-
-The worst case is probably (2h:4v)(1h:1v)(1h:1v) interleaving (this uses 10
-blocks per MCU, which is the maximum allowed by the spec).  An MCU will then
-contain 32 sample rows worth of Y, so it would occupy 40K or 80K bytes for a
-1024-pixel-wide image.  The most memory-intensive step is probably cross-block
-smoothing, for which we'd need 3 MCU rows of coefficients as input and another
-one as output; that would be 320K of working storage.  Anything much larger
-would not fit in an 80x86 machine.  (To decompress wider pictures on an 80x86,
-we'll have to skip cross-block smoothing or else use temporary files.)
-
-This unit is thus a reasonable-sized chunk for passing through the pipeline.
-Of course, its major advantage is that it is a natural chunk size for the MCU
-assembly and disassembly steps to work with.
-
-For the entropy (Huffman or arithmetic) encoding/decoding steps, the most
-convenient chunk is a single MCU: one 8x8 block if not interleaved, three to
-ten such blocks if interleaved.  The advantage of this is that when handling
-interleaved data, the blocks have the same sequence of component membership on
-each call.  (For example, Y,Y,Y,Y,Cb,Cr when using (2h:2v)(1h:1v)(1h:1v)
-subsampling.)  The code needs to know component membership so that it can
-apply the right set of compression coefficients to each block.  A prebuilt
-array describing this membership can be used during each call.  This chunk
-size also makes it easy to handle restart intervals: just count off one MCU
-per call and reinitialize when the count reaches zero (restart intervals are
-specified in numbers of MCU).
-
-For similar reasons, one MCU is also the best chunk size for the frequency
-coefficient quantization and dequantization steps.
-
-For downsampling and upsampling, the best chunk size is to have each call
-transform Vk sample rows from or to Vmax sample rows (Vk = this component's
-vertical sampling factor, Vmax = largest vertical sampling factor).  There are
-eight such chunks in each MCU row.  Using a whole MCU row as the chunk size
-would reduce function call overhead a fraction, but would imply more buffering
-to provide context for cross-pixel smoothing.
-
-
-*** Compression object structure ***
-
-I propose the following set of objects for the compressor.  Here an "object"
-is the common interface for one or more modules having comparable functions.
-
-Most of these objects can be justified as information-hiding modules.
-I've indicated what information is private to each object/module.
-
-Note that in all cases, the caller of a method is expected to have allocated
-any storage needed for it to return its result.  (Typically this storage can
-be re-used in successive calls, so malloc'ing and free'ing once per call is
-not reasonable.)  Also, much of the context required (compression parameters,
-image size, etc) will be passed around in large common data structures, which
-aren't described here; see the header files.  Notice that any object that
-might need to allocate working storage receives an "init" and a "term" call;
-"term" should be careful to free all allocated storage so that the JPEG system
-can be used multiple times during a program run.  (For the same reason,
-depending on static initialization of variables is a no-no.  The only
-exception to the free-all-allocated-storage rule is that storage allocated for
-the entire processing of an image need not be explicitly freed, since the
-memory manager's free_all cleanup will free it.)
-
-1. Input file conversion to standardized form.  This provides these methods:
-	input_init: read the file header, report image size & component count.
-	get_input_row: read one pixel row, return it in our standard format.
-	input_term: finish up at the end.
-   In implementations that support multiple input formats, input_init could
-   set up an appropriate get_input_row method depending on the format it
-   finds.  Note that in most applications, the selection and opening of the
-   input file will be under the control of the user interface module; and
-   indeed the user interface may have already read the input header, so that
-   all that input_init may have to do is return previously saved values.  The
-   behind-the-scenes interaction between this object and the user interface is
-   not specified by this architecture.
-   (Hides format of input image and mechanism used to read it.  This code is
-   likely to vary considerably from one implementation to another.  Note that
-   the color space and number of color components of the source are not hidden;
-   but they are used only by the next object.)
-
-2. Gamma and color space conversion.  This provides three methods:
-	colorin_init: initialization.
-	get_sample_rows: read, convert, and return a specified number of pixel
-			 rows (not more than remain in the picture).
-	colorin_term: finish up at the end.
-   The most efficient approach seems to be for this object to call
-   get_input_row directly, rather than being passed the input data; that way,
-   any intermediate storage required can be local to this object.
-   (get_sample_rows might tell get_input_row to read directly into its own
-   output area and then convert in place; or it may do something different.
-   For example, conversion in place wouldn't work if it is changing the number
-   of color components.)  The output of this step is in the standardized
-   sample array format shown previously.
-   (Hides all knowledge of color space semantics and conversion.  Remaining
-   modules only need to know the number of JPEG components.)
-
-3. Edge expansion: needs only a single method.
-	edge_expand: Given an NxM sample array, expand to a desired size (a
-		     multiple of the MCU dimensions) by duplicating the last
-		     row or column.  Repeat for each component.
-   Expansion will occur in place, so the caller must have pre-allocated enough
-   storage.  (I'm assuming that it is easier and faster to do this expansion
-   than it is to worry about boundary conditions in the next two steps.
-   Notice that vertical expansion will occur only once, at the bottom of the
-   picture, so only horizontal expansion by a few pixels is speed-critical.)
-   (This doesn't really hide any information, so maybe it could be a simple
-   subroutine instead of a method.  Depends on whether we want to be able to
-   use alternative, optimized methods.)
-
-4. Downsampling: this will be applied to one component at a time.
-	downsample_init: initialize (precalculate convolution factors, for
-			 example).  This will be called once per scan.
-	downsample: Given a sample array, reduce it to a smaller number of
-		    samples using specified sampling factors.
-	downsample_term: clean up at the end of a scan.
-   If the current component has vertical sampling factor Vk and the largest
-   sampling factor is Vmax, then the input is always Vmax sample rows (whose
-   width is a multiple of Hmax) and the output is always Vk sample rows.
-   Vmax additional rows above and below the nominal input rows are also passed
-   for use by partial-pixel-averaging sampling methods.  (Is this necessary?)
-   At the top and bottom of the image, these extra rows are copies of the
-   first or last actual input row.
-   (This hides whether and how cross-pixel averaging occurs.)
-
-5. MCU extraction (creation of a single sequence of 8x8 sample blocks).
-	extract_init: initialize as needed.  This will be called once per scan.
-	extract_MCUs: convert a sample array to a sequence of MCUs.
-	extract_term: clean up at the end of a scan.
-   Given one or more MCU rows worth of image data, extract sample blocks in the
-   appropriate order; pass these off to subsequent steps one MCU at a time.
-   The input must be a multiple of the MCU dimensions.  It will probably be
-   most convenient for the DCT transform, frequency quantization, and zigzag
-   reordering of each block to be done as simple subroutines of this step.
-   Once a transformed MCU has been completed, it'll be passed off to a
-   method call, which will be passed as a parameter to extract_MCUs.
-   That routine might either encode and output the MCU immediately, or buffer
-   it up for later output if we want to do global optimization of the entropy
-   encoding coefficients.  Note: when outputting a noninterleaved file this
-   object will be called separately for each component.  Direct output could
-   be done for the first component, but the others would have to be buffered.
-   (Again, an object mainly on the grounds that multiple instantiations might
-   be useful.)
-
-6. DCT transformation of each 8x8 block.  This probably doesn't have to be a
-   full-fledged method, but just a plain subroutine that will be called by MCU
-   extraction.  One 8x8 block will be processed per call.
-
-7. Quantization scaling and zigzag reordering of the elements in each 8x8
-   block.  (This can probably be a plain subroutine called once per block by
-   MCU extraction; hard to see a need for multiple instantiations here.)
-
-8. Entropy encoding (Huffman or arithmetic).
-	entropy_encode_init: prepare for one scan.
-	entropy_encode: accepts an MCU's worth of quantized coefficients,
-			encodes and outputs them.
-	entropy_encode_term: finish up at end of a scan (dump any buffered
-			     bytes, for example).
-   The data output by this module will be sent to the entropy_output method
-   provided by the pipeline controller.  (It will probably be worth using
-   buffering to pass multiple bytes per call of the output method.)  The
-   output method could be just write_jpeg_data, but might also be a dummy
-   routine that counts output bytes (for use during cut-and-try coefficient
-   optimization).
-   (This hides which entropy encoding method is in use.)
-
-9. JPEG file header construction.  This will provide these methods:
-	write_file_header: output the initial header.
-	write_scan_header: output scan header (called once per component
-			   if noninterleaved mode).
-	write_jpeg_data: the actual data output method for the preceding step.
-	write_scan_trailer: finish up after one scan.
-	write_file_trailer: finish up at end of file.
-   Note that compressed data is passed to the write_jpeg_data method, in case
-   a simple fwrite isn't appropriate for some reason.
-   (This hides which variant JPEG file format is being written.  Also, the
-   actual mechanism for writing the file is private to this object and the
-   user interface.)
-
-10. Pipeline control.  This object will provide the "main loop" that invokes
-    all the pipeline objects.  Note that we will need several different main
-    loops depending on the situation (interleaved output or not, global
-    optimization of encoding parameters or not, etc).  This object will do
-    most of the memory allocation, since it will provide the working buffers
-    that are the inputs and outputs of the pipeline steps.
-    (An object mostly to support multiple instantiations; however, overall
-    memory management and sequencing of operations are known only here.)
-
-11. Overall control.  This module will provide at least two routines:
-	jpeg_compress: the main entry point to the compressor.
-	per_scan_method_selection: called by pipeline controllers for
-				   secondary method selection passes.
-    jpeg_compress is invoked from the user interface after the UI has selected
-    the input and output files and obtained values for all compression
-    parameters that aren't dynamically determined.  jpeg_compress performs
-    basic initialization (e.g., calculating the size of MCUs), does the
-    "global" method selection pass, and finally calls the selected pipeline
-    control object.  (Per-scan method selections will be invoked by the
-    pipeline controller.)
-    Note that jpeg_compress can't be a method since it is invoked prior to
-    method selection.
-
-12. User interface; this is the architecture's term for "the rest of the
-    application program", i.e., that which invokes the JPEG compressor.  In a
-    standalone JPEG compression program the UI need be little more than a C
-    main() routine and argument parsing code; but we can expect that the JPEG
-    compressor may be incorporated into complex graphics applications, wherein
-    the UI is much more complex.  Much of the UI will need to be written
-    afresh for each non-Unix-like platform the compressor is ported to.
-    The UI is expected to supply input and output files and values for all
-    non-automatically-chosen compression parameters.  (Hence defaults are
-    determined by the UI; we should provide helpful routines to fill in
-    the recommended defaults.)  The UI must also supply error handling
-    routines and some mechanism for trace messages.
-    (This module hides the user interface provided --- command line,
-    interactive, etc.  Except for error/message handling, the UI calls the
-    portable JPEG code, not the other way around.)
-
-13. (Optional) Compression parameter selection control.
-	entropy_optimize: given an array of MCUs ready to be fed to entropy
-			  encoding, find optimal encoding parameters.
-    The actual optimization algorithm ought to be separated out as an object,
-    even though a special pipeline control method will be needed.  (The
-    pipeline controller only has to understand that the output of extract_MCUs
-    must be built up as a virtual array rather than fed directly to entropy
-    encoding and output.  This pipeline behavior may also be useful for future
-    implementation of hierarchical modes, etc.)
-    To minimize the amount of control logic in the optimization module, the
-    pipeline control doesn't actually hand over big-array pointers, but rather
-    an "iterator": a function which knows how to scan the stored image.
-    (This hides the details of the parameter optimization algorithm.)
-
-    The present design doesn't allow for multiple passes at earlier points
-    in the pipeline, but allowing that would only require providing some
-    new pipeline control methods; nothing else need change.
-
-14. A memory management object.  This will provide methods to allocate "small"
-    things and "big" things.  Small things have to fit in memory and you get
-    back direct pointers (this could be handled by direct calls to malloc, but
-    it's cleaner not to assume malloc is the right routine).  "Big" things
-    mean buffered images for multiple passes, noninterleaved output, etc.
-    In this case the memory management object will give you room for a few MCU
-    rows and you have to ask for access to the next few; dumping and reloading
-    in a temporary file will go on behind the scenes.  (All big objects are
-    image arrays containing either samples or coefficients, and will be
-    scanned top-to-bottom some number of times, so we can apply this access
-    model easily.)  On a platform with virtual memory, the memory manager can
-    treat small and big things alike: just malloc up enough virtual memory for
-    the whole image, and let the operating system worry about swapping the
-    image to disk.
-
-    Most of the actual calls on the memory manager will be made from pipeline
-    control objects; changing any data item from "small" to "big" status would
-    require a new pipeline control object, since it will contain the logic to
-    ask for a new chunk of a big thing.  Thus, one way in which pipeline
-    controllers will vary is in which structures they treat as big.
-
-    The memory manager will need to be told roughly how much space is going to
-    be requested overall, so that it can figure out how big a buffer is safe
-    to allocate for a "big" object.  (If it happens that you are dealing with
-    a small image, you'd like to decide to keep it all in memory!)  The most
-    flexible way of doing this is to divide allocation of "big" objects into
-    two steps.  First, there will be one or more "request" calls that indicate
-    the desired object sizes; then an "instantiate" call causes the memory
-    manager to actually construct the objects.  The instantiation must occur
-    before the contents of any big object can be accessed.
-
-    For 80x86 CPUs, we would like the code to be compilable under small or
-    medium model, meaning that pointers are 16 bits unless explicitly declared
-    FAR.  Hence space allocated by the "small" allocator must fit into the
-    64Kb default data segment, along with stack space and global/static data.
-    For normal JPEG operations we seem to need only about 32Kb of such space,
-    so we are within the target (and have a reasonable slop for the needs of
-    a surrounding application program).  However, some color quantization
-    algorithms need 64Kb or more of all-in-memory space in order to create
-    color histograms.  For this purpose, we will also support "medium" size
-    things.  These are semantically the same as "small" things but are
-    referenced through FAR pointers.
-
-    The following methods will be needed:
-	alloc_small:	allocate an object of given size; use for any random
-			data that's not an image array.
-	free_small:	release same.
-	alloc_medium:	like alloc_small, but returns a FAR pointer.  Use for
-			any object bigger than a couple kilobytes.
-	free_medium:	release same.
-	alloc_small_sarray: construct an all-in-memory image sample array.
-	free_small_sarray:  release same.
-	alloc_small_barray,
-	free_small_barray:  ditto for block (coefficient) arrays.
-	request_big_sarray:  request a virtual image sample array.  The size
-			     of the in-memory buffer will be determined by the
-			     memory manager, but it will always be a multiple
-			     of the passed-in MCU height.
-	request_big_barray:  ditto for block (coefficient) arrays.
-	alloc_big_arrays:  instantiate all the big arrays previously requested.
-			   This call will also pass some info about future
-			   memory demands, so that the memory manager can
-			   figure out how much space to leave unallocated.
-	access_big_sarray: obtain access to a specified portion of a virtual
-			   image sample array.
-	free_big_sarray:   release a virtual sample array.
-	access_big_barray,
-	free_big_barray:   ditto for block (coefficient) arrays.
-	free_all:	   release any remaining storage.  This is called
-			   before normal or error termination; the main reason
-			   why it must exist is to ensure that any temporary
-			   files will be deleted upon error termination.
-
-    alloc_big_arrays will be called by the pipeline controller, which does
-    most of the memory allocation anyway.  The only reason for having separate
-    request calls is to allow some of the other modules to get big arrays.
-    The pipeline controller is required to give an upper bound on total future
-    small-array requests, so that this space can be discounted.  (A fairly
-    conservative estimate will be adequate.)  Future small-object requests
-    aren't counted; the memory manager has to use a slop factor for those.
-    10K or so seems to be sufficient.  (In an 80x86, small objects aren't an
-    issue anyway, since they don't compete for far-heap space.  "Medium"-size
-    objects will have to be counted separately.)
-
-    The distinction between sample and coefficient array routines is annoying,
-    but it has to be maintained for machines in which "char *" is represented
-    differently from "int *".  On byte-addressable machines some of these
-    methods could perhaps point to the same code.
-
-    The array routines will operate on only 2-D arrays (one component at a
-    time), since different components may require different-size arrays.
-
-    (This object hides the knowledge of whether virtual memory is available,
-    as well as the actual interface to OS and library support routines.)
-
-Note that any given implementation will presumably contain only one
-instantiation of input file header reading, overall control, user interface,
-and memory management.  Thus these could be called as simple subroutines,
-without bothering with an object indirection.  This is essential for overall
-control (which has to initialize the object structure); for consistency we
-will impose objectness on the other three.
-
-
-*** Decompression object structure ***
-
-I propose the following set of objects for decompression.  The general
-comments at the top of the compression object section also apply here.
-
-1. JPEG file scanning.  This will provide these methods:
-	read_file_header: read the file header, determine which variant
-			  JPEG format is in use, read everything through SOF.
-	read_scan_header: read scan header (up through SOS).  This is called
-			  after read_file_header and again after each scan;
-			  it returns TRUE if it finds SOS, FALSE if EOI.
-	read_jpeg_data: fetch data for entropy decoder.
-	resync_to_restart: try to recover from bogus data (see below).
-	read_scan_trailer: finish up after one scan, prepare for another call
-			   of read_scan_header (may be a no-op).
-	read_file_trailer: finish up at end of file (probably a no-op).
-   The entropy decoder must deal with restart markers, but all other JPEG
-   marker types will be handled in this object; useful data from the markers
-   will be extracted into data structures available to subsequent routines.
-   Note that on exit from read_file_header, only the SOF-marker data should be
-   assumed valid (image size, component IDs, sampling factors); other data
-   such as Huffman tables may not appear until after the SOF.  The overall
-   image size and colorspace can be determined after read_file_header, but not
-   whether or how the data is interleaved.  (This hides which variant JPEG
-   file format is being read.  In particular, for JPEG-in-TIFF the read_header
-   routines might not be scanning standard JPEG markers at all; they could
-   extract the data from TIFF tags.  The user interface will already have
-   opened the input file and possibly read part of the header before
-   read_file_header is called.)
-
-   When reading a file with a nonzero restart interval, the entropy decoder
-   expects to see a correct sequence of restart markers.  In some cases, these
-   markers may be synthesized by the file-format module (a TIFF reader might
-   do so, for example, using tile boundary pointers to determine where the
-   restart intervals fall).  If the incoming data is corrupted, the entropy
-   decoder will read as far as the next JPEG marker, which may or may not be
-   the expected next restart marker.  If it isn't, resync_to_restart is called
-   to try to locate a good place to resume reading.  We make this heuristic a
-   file-format-dependent operation since some file formats may have special
-   info that's not available to the entropy decoder (again, TIFF is an
-   example).  Note that resync_to_restart is NOT called at the end of a scan;
-   it is read_scan_trailer's responsibility to resync there.
-
-   NOTE: for JFIF/raw-JPEG file format, the read_jpeg_data routine is actually
-   supplied by the user interface; the jrdjfif module uses read_jpeg_data
-   internally to scan the input stream.  This makes it possible for the user
-   interface module to single-handedly implement special applications like
-   reading from a non-stdio source.  For JPEG-in-TIFF format, the need for
-   random access will make it impossible for this to work; hence the TIFF
-   header module will override the UI-supplied read_jpeg_data routine.
-   Non-stdio input from a TIFF file will require extensive surgery to the TIFF
-   header module, if indeed it is practical at all.
-
-2. Entropy (Huffman or arithmetic) decoding of the coefficient sequence.
-	entropy_decode_init: prepare for one scan.
-	entropy_decode: decodes and returns an MCU's worth of quantized
-			coefficients per call.
-	entropy_decode_term: finish up after a scan (may be a no-op).
-   This will read raw data by calling the read_jpeg_data method (I don't see
-   any reason to provide a further level of indirection).
-   (This hides which entropy encoding method is in use.)
-
-3. Quantization descaling and zigzag reordering of the elements in each 8x8
-   block.  This will be folded into entropy_decode for efficiency reasons:
-   many of the coefficients are zeroes, and this can be exploited most easily
-   within entropy_decode since the encoding explicitly skips zeroes.
-
-4. MCU disassembly (conversion of a possibly interleaved sequence of 8x8
-   blocks back to separate components in pixel map order).
-	disassemble_init: initialize.  This will be called once per scan.
-	disassemble_MCU:  Given an MCU's worth of dequantized blocks,
-			  distribute them into the proper locations in a
-			  coefficient image array.
-	disassemble_term: clean up at the end of a scan.
-   Probably this should be called once per MCU row and should call the
-   entropy decoder repeatedly to obtain the row's data.  The output is
-   always a multiple of an MCU's dimensions.
-   (An object on the grounds that multiple instantiations might be useful.)
-
-5. Cross-block smoothing per JPEG section K.8 or a similar algorithm.
-	smooth_coefficients: Given three block rows' worth of a single
-			     component, emit a smoothed equivalent of the
-			     middle row.  The "above" and "below" pointers
-			     may be NULL if at top/bottom of image.
-   The pipeline controller will do the necessary buffering to provide the
-   above/below context.  Smoothing will be optional since a good deal of
-   extra memory is needed to buffer the additional block rows.
-   (This object hides the details of the smoothing algorithm.)
-
-6. Inverse DCT transformation of each 8x8 block.
-	reverse_DCT: given an MCU row's worth of blocks, perform inverse
-		     DCT on each block and output the results into an array
-		     of samples.
-   We put this method into the jdmcu module for symmetry with the division of
-   labor in compression.  Note that the actual IDCT code is a separate source
-   file.
-
-7. Upsampling and smoothing: this will be applied to one component at a
-   time.  Note that cross-pixel smoothing, which was a separate step in the
-   prototype code, will now be performed simultaneously with expansion.
-	upsample_init: initialize (precalculate convolution factors, for
-		       example).  This will be called once per scan.
-	upsample: Given a sample array, enlarge it by specified sampling
-		  factors.
-	upsample_term: clean up at the end of a scan.
-   If the current component has vertical sampling factor Vk and the largest
-   sampling factor is Vmax, then the input is always Vk sample rows (whose
-   width is a multiple of Hk) and the output is always Vmax sample rows.
-   Vk additional rows above and below the nominal input rows are also passed
-   for use in cross-pixel smoothing.  At the top and bottom of the image,
-   these extra rows are copies of the first or last actual input row.
-   (This hides whether and how cross-pixel smoothing occurs.)
-
-8. Cropping to the original pixel dimensions (throwing away duplicated
-   pixels at the edges).  This won't be a separate object, just an
-   adjustment of the nominal image size in the pipeline controller.
-
-9. Color space reconversion and gamma adjustment.
-	colorout_init: initialization.  This will be passed the component
-		       data from read_file_header, and will determine the
-		       number of output components.
-	color_convert: convert a specified number of pixel rows.  Input and
-		       output are image arrays of same size but possibly
-		       different numbers of components.
-	colorout_term: cleanup (probably a no-op except for memory dealloc).
-   In practice will usually be given an MCU row's worth of pixel rows, except
-   at the bottom where a smaller number of rows may be left over.  Note that
-   this object works on all the components at once.
-   When quantizing colors, color_convert may be applied to the colormap
-   instead of actual pixel data.  color_convert is called by the color
-   quantizer in this case; the pipeline controller calls color_convert
-   directly only when not quantizing.
-   (Hides all knowledge of color space semantics and conversion.  Remaining
-   modules only need to know the number of JPEG and output components.)
-
-10. Color quantization (used only if a colormapped output format is requested).
-    We use two different strategies depending on whether one-pass (on-the-fly)
-    or two-pass quantization is requested.  Note that the two-pass interface
-    is actually designed to let the quantizer make any number of passes.
-	color_quant_init: initialization, allocate working memory.  In 1-pass
-			  quantization, should call put_color_map.
-	color_quantize: convert a specified number of pixel rows.  Input
-			and output are image arrays of same size, but input
-			is N coefficients and output is only one.  (Used only
-			in 1-pass quantization.)
-	color_quant_prescan: prescan a specified number of pixel rows in
-			     2-pass quantization.
-	color_quant_doit: perform multi-pass color quantization.  Input is a
-			  "big" sample image, output is via put_color_map and
-			  put_pixel_rows.  (Used only in 2-pass quantization.)
-	color_quant_term: cleanup (probably a no-op except for memory dealloc).
-    The input to the color quantizer is always in the unconverted colorspace;
-    its output colormap must be in the converted colorspace.  The quantizer
-    has the choice of which space to work in internally.  It must call
-    color_convert either on its input data or on the colormap it sends to the
-    output module.
-    For one-pass quantization the image is simply processed by color_quantize,
-    a few rows at a time.  For two-pass quantization, the pipeline controller
-    accumulates the output of steps 1-8 into a "big" sample image.  The
-    color_quant_prescan method is invoked during this process so that the
-    quantizer can accumulate statistics.  (If the input file has multiple
-    scans, the prescan may be done during the final scan or as a separate
-    pass.)  At the end of the image, color_quant_doit is called; it must
-    create and output a colormap, then rescan the "big" image and pass mapped
-    data to the output module.  Additional scans of the image could be made
-    before the output pass is done (in fact, prescan could be a no-op).
-    As with entropy parameter optimization, the pipeline controller actually
-    passes an iterator function rather than direct access to the big image.
-    (Hides color quantization algorithm.)
-
-11. Writing of the desired image format.
-	output_init: produce the file header given data from read_file_header.
-	put_color_map: output colormap, if any (called by color quantizer).
-		       If used, must be called before any pixel data is output.
-	put_pixel_rows: output image data in desired format.
-	output_term: finish up at the end.
-    The actual timing of I/O may differ from that suggested by the routine
-    names; for instance, writing of the file header may be delayed until
-    put_color_map time if the actual number of colors is needed in the header.
-    Also, the colormap is available to put_pixel_rows and output_term as well
-    as put_color_map.
-    Note that whether colormapping is needed will be determined by the user
-    interface object prior to method selection.  In implementations that
-    support multiple output formats, the actual output format will also be
-    determined by the user interface.
-    (Hides format of output image and mechanism used to write it.  Note that
-    several other objects know the color model used by the output format.
-    The actual mechanism for writing the file is private to this object and
-    the user interface.)
-
-12. Pipeline control.  This object will provide the "main loop" that invokes
-    all the pipeline objects.  Note that we will need several different main
-    loops depending on the situation (interleaved input or not, whether to
-    apply cross-block smoothing or not, etc).  We may want to divvy up the
-    pipeline controllers into two levels, one that retains control over the
-    whole file and one that is invoked per scan.
-    This object will do most of the memory allocation, since it will provide
-    the working buffers that are the inputs and outputs of the pipeline steps.
-    (An object mostly to support multiple instantiations; however, overall
-    memory management and sequencing of operations are known only here.)
-
-13. Overall control.  This module will provide at least two routines:
-	jpeg_decompress: the main entry point to the decompressor.
-	per_scan_method_selection: called by pipeline controllers for
-				   secondary method selection passes.
-    jpeg_decompress is invoked from the user interface after the UI has
-    selected the input and output files and obtained values for all
-    user-specified options (e.g., output file format, whether to do block
-    smoothing).  jpeg_decompress calls read_file_header, performs basic
-    initialization (e.g., calculating the size of MCUs), does the "global"
-    method selection pass, and finally calls the selected pipeline control
-    object.  (Per-scan method selections will be invoked by the pipeline
-    controller.)
-    Note that jpeg_decompress can't be a method since it is invoked prior to
-    method selection.
-
-14. User interface; this is the architecture's term for "the rest of the
-    application program", i.e., that which invokes the JPEG decompressor.
-    The UI is expected to supply input and output files and values for all
-    operational parameters.  The UI must also supply error handling routines.
-    (This module hides the user interface provided --- command line,
-    interactive, etc.  Except for error handling, the UI calls the portable
-    JPEG code, not the other way around.)
-
-15. A memory management object.  This will be identical to the memory
-    management for compression (and will be the same code, in combined
-    programs).  See above for details.
-
-
-*** Initial method selection ***
-
-The main ugliness in this design is the portion of startup that will select
-which of several instantiations should be used for each of the objects.  (For
-example, Huffman or arithmetic for entropy encoding; one of several pipeline
-controllers depending on interleaving, the size of the image, etc.)  It's not
-really desirable to have a single chunk of code that knows the names of all
-the possible instantiations and the conditions under which to select each one.
-
-The best approach seems to be to provide a selector function for each object
-(group of related method calls).  This function knows about each possible
-instantiation of its object and how to choose the right one; but it doesn't
-know about any other objects.
-
-Note that there will be several rounds of method selection: at initial startup,
-after overall compression parameters are determined (after the file header is
-read, if decompressing), and one in preparation for each scan (this occurs
-more than once if the file is noninterleaved).  Each object method will need
-to be clearly identified as to which round sets it up.
-
-
-*** Implications of DNL marker ***
-
-Some JPEG files may use a DNL marker to postpone definition of the image
-height (this would be useful for a fax-like scanner's output, for instance).
-In these files the SOF marker claims the image height is 0, and you only
-find out the true image height at the end of the first scan.
-
-We could handle these files as follows:
-1. Upon seeing zero image height, replace it by 65535 (the maximum allowed).
-2. When the DNL is found, update the image height in the global image
-   descriptor.
-This implies that pipeline control objects must avoid making copies of the
-image height, and must re-test for termination after each MCU row.  This is
-no big deal.
-
-In situations where image-size data structures are allocated, this approach
-will result in very inefficient use of virtual memory or
-much-larger-than-necessary temporary files.  This seems acceptable for
-something that probably won't be a mainstream usage.  People might have to
-forgo use of memory-hogging options (such as two-pass color quantization or
-noninterleaved JPEG files) if they want efficient conversion of such files.
-(One could improve efficiency by demanding a user-supplied upper bound for the
-height, less than 65536; in most cases it could be much less.)
-
-Alternately, we could insist that DNL-using files be preprocessed by a
-separate program that reads ahead to the DNL, then goes back and fixes the SOF
-marker.  This is a much simpler solution and is probably far more efficient.
-Even if one wants piped input, buffering the first scan of the JPEG file
-needs a lot smaller temp file than is implied by the maximum-height method.
-For this approach we'd simply treat DNL as a no-op in the decompressor (at
-most, check that it matches the SOF image height).
-
-We will not worry about making the compressor capable of outputting DNL.
-Something similar to the first scheme above could be applied if anyone ever
-wants to make that work.
-
-
-*** Memory manager internal structure ***
-
-The memory manager contains the most potential for system dependencies.
-To isolate system dependencies as much as possible, we have broken the
-memory manager into two parts.  There is a reasonably system-independent
-"front end" (jmemmgr.c) and a "back end" that contains only the code
-likely to change across systems.  All of the memory management methods
-outlined above are implemented by the front end.  The back end provides
-the following routines for use by the front end (none of these routines
-are known to the rest of the JPEG code):
-
-jmem_init, jmem_term	system-dependent initialization/shutdown
-
-jget_small, jfree_small	interface to malloc and free library routines
-
-jget_large, jfree_large	interface to FAR malloc/free in MS-DOS machines;
-			otherwise same as jget_small/jfree_small
-
-jmem_available		estimate available memory
-
-jopen_backing_store	create a backing-store object
-
-read_backing_store,	manipulate a backing store object
-write_backing_store,
-close_backing_store
-
-On some systems there will be more than one type of backing-store object
-(specifically, in MS-DOS a backing store file might be an area of extended
-memory as well as a disk file).  jopen_backing_store is responsible for
-choosing how to implement a given object.  The read/write/close routines
-are method pointers in the structure that describes a given object; this
-lets them be different for different object types.
-
-It may be necessary to ensure that backing store objects are explicitly
-released upon abnormal program termination.  (For example, MS-DOS won't free
-extended memory by itself.)  To support this, we will expect the main program
-or surrounding application to arrange to call the free_all method upon
-abnormal termination; this may require a SIGINT signal handler, for instance.
-(We don't want to have the system-dependent module install its own signal
-handler, because that would pre-empt the surrounding application's ability
-to control signal handling.)
-
-
-*** Notes for MS-DOS implementors ***
-
-The standalone cjpeg and djpeg applications can be compiled in "small" memory
-model, at least at the moment; as the code grows we may be forced to switch to
-"medium" model.  (Small = both code and data pointers are near by default;
-medium = far code pointers, near data pointers.)  Medium model will slow down
-calls through method pointers, but I don't think this will amount to any
-significant speed penalty.
-
-When integrating the JPEG code into a larger application, it's a good idea to
-stay with a small-data-space model if possible.  An 8K stack is much more than
-sufficient for the JPEG code, and its static data requirements are less than
-1K.  When executed, it will typically malloc about 10K-20K worth of near heap
-space (and lots of far heap, but that doesn't count in this calculation).
-This figure will vary depending on image size and other factors, but figuring
-30K should be more than sufficient.  Thus you have about 25K available for
-other modules' static data and near heap requirements before you need to go to
-a larger memory model.  The C library's static data will account for several K
-of this, but that still leaves a good deal for your needs.  (If you are tight
-on space, you could reduce JPEG_BUF_SIZE from 4K to 1K to save 3K of near heap
-space.)
-
-As the code is improved, we will endeavor to hold the near data requirements
-to the range given above.  This does imply that certain data structures will
-be allocated as FAR although they would fit in near space if we assumed the
-JPEG code is stand-alone.  (The LZW tables in jrdgif/jwrgif are examples.)
-To make an optimal implementation, you might want to move these structures
-back to near heap if you know there is sufficient space.
-
-FAR data space may also be a tight resource when you are dealing with large
-images.  The most memory-intensive case is decompression with two-pass color
-quantization.  This requires a 128Kb color histogram plus strip buffers
-amounting to about 150 bytes per column for typical sampling ratios (eg, about
-96000 bytes for a 640-pixel-wide image).  You may not be able to process wide
-images if you have large data structures of your own.
-
-
-*** Potential optimizations ***
-
-For colormapped input formats it might be worthwhile to merge the input file
-reading and the colorspace conversion steps; in other words, do the colorspace
-conversion by hacking up the colormap before inputting the image body, rather
-than doing the conversion on each pixel independently.  Not clear if this is
-worth the uglification involved.  In the above design for the compressor, only
-the colorspace conversion step ever sees the output of get_input_row, so this
-sort of thing could be done via private agreement between those two modules.
-
-Level shift from 0..255 to -128..127 may be done either during colorspace
-conversion, or at the moment of converting an 8x8 sample block into the format
-used by the DCT step (which will be signed short or long int).  This could be
-selectable by a compile-time flag, so that the intermediate steps can work on
-either signed or unsigned chars as samples, whichever is most easily handled
-by the platform.  However, making sure that rounding is done right will be a
-lot easier if we can assume positive values.  At the moment I think that
-benefit is worth the overhead of "& 0xFF" when reading out sample values on
-signed-char-only machines.
diff --git a/cderror.h b/cderror.h
new file mode 100644
index 0000000..6479a4d
--- /dev/null
+++ b/cderror.h
@@ -0,0 +1,135 @@
+/*
+ * cderror.h
+ *
+ * Copyright (C) 1994, 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.
+ *
+ * This file defines the error and message codes for the cjpeg/djpeg
+ * applications.  These strings are not needed as part of the JPEG library
+ * proper.
+ * Edit this file to add new codes, or to translate the message strings to
+ * some other language.
+ */
+
+
+/* To define the enum list of message codes, include this file without
+ * defining JMAKE_MSG_TABLE.  To create the message string table, include it
+ * again with JMAKE_MSG_TABLE defined (this should be done in just one module).
+ */
+
+#ifdef JMAKE_MSG_TABLE
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define addon_message_table	cdMsgTable
+#endif
+
+const char * const addon_message_table[] = {
+
+#define JMESSAGE(code,string)	string ,
+
+#else /* not JMAKE_MSG_TABLE */
+
+typedef enum {
+
+#define JMESSAGE(code,string)	code ,
+
+#endif /* JMAKE_MSG_TABLE */
+
+JMESSAGE(JMSG_FIRSTADDONCODE=1000, NULL) /* Must be first entry! */
+
+#ifdef BMP_SUPPORTED
+JMESSAGE(JERR_BMP_BADCMAP, "Unsupported BMP colormap format")
+JMESSAGE(JERR_BMP_BADDEPTH, "Only 8- and 24-bit BMP files are supported")
+JMESSAGE(JERR_BMP_BADHEADER, "Invalid BMP file: bad header length")
+JMESSAGE(JERR_BMP_BADPLANES, "Invalid BMP file: biPlanes not equal to 1")
+JMESSAGE(JERR_BMP_COLORSPACE, "BMP output must be grayscale or RGB")
+JMESSAGE(JERR_BMP_COMPRESSED, "Sorry, compressed BMPs not yet supported")
+JMESSAGE(JERR_BMP_NOT, "Not a BMP file - does not start with BM")
+JMESSAGE(JTRC_BMP, "%ux%u 24-bit BMP image")
+JMESSAGE(JTRC_BMP_MAPPED, "%ux%u 8-bit colormapped BMP image")
+JMESSAGE(JTRC_BMP_OS2, "%ux%u 24-bit OS2 BMP image")
+JMESSAGE(JTRC_BMP_OS2_MAPPED, "%ux%u 8-bit colormapped OS2 BMP image")
+#endif /* BMP_SUPPORTED */
+
+#ifdef GIF_SUPPORTED
+JMESSAGE(JERR_GIF_BUG, "GIF output got confused")
+JMESSAGE(JERR_GIF_CODESIZE, "Bogus GIF codesize %d")
+JMESSAGE(JERR_GIF_COLORSPACE, "GIF output must be grayscale or RGB")
+JMESSAGE(JERR_GIF_IMAGENOTFOUND, "Too few images in GIF file")
+JMESSAGE(JERR_GIF_NOT, "Not a GIF file")
+JMESSAGE(JTRC_GIF, "%ux%ux%d GIF image")
+JMESSAGE(JTRC_GIF_BADVERSION,
+	 "Warning: unexpected GIF version number '%c%c%c'")
+JMESSAGE(JTRC_GIF_EXTENSION, "Ignoring GIF extension block of type 0x%02x")
+JMESSAGE(JTRC_GIF_NONSQUARE, "Caution: nonsquare pixels in input")
+JMESSAGE(JWRN_GIF_BADDATA, "Corrupt data in GIF file")
+JMESSAGE(JWRN_GIF_CHAR, "Bogus char 0x%02x in GIF file, ignoring")
+JMESSAGE(JWRN_GIF_ENDCODE, "Premature end of GIF image")
+JMESSAGE(JWRN_GIF_NOMOREDATA, "Ran out of GIF bits")
+#endif /* GIF_SUPPORTED */
+
+#ifdef PPM_SUPPORTED
+JMESSAGE(JERR_PPM_COLORSPACE, "PPM output must be grayscale or RGB")
+JMESSAGE(JERR_PPM_NONNUMERIC, "Nonnumeric data in PPM file")
+JMESSAGE(JERR_PPM_NOT, "Not a PPM file")
+JMESSAGE(JTRC_PGM, "%ux%u PGM image")
+JMESSAGE(JTRC_PGM_TEXT, "%ux%u text PGM image")
+JMESSAGE(JTRC_PPM, "%ux%u PPM image")
+JMESSAGE(JTRC_PPM_TEXT, "%ux%u text PPM image")
+#endif /* PPM_SUPPORTED */
+
+#ifdef RLE_SUPPORTED
+JMESSAGE(JERR_RLE_BADERROR, "Bogus error code from RLE library")
+JMESSAGE(JERR_RLE_COLORSPACE, "RLE output must be grayscale or RGB")
+JMESSAGE(JERR_RLE_DIMENSIONS, "Image dimensions (%ux%u) too large for RLE")
+JMESSAGE(JERR_RLE_EMPTY, "Empty RLE file")
+JMESSAGE(JERR_RLE_EOF, "Premature EOF in RLE header")
+JMESSAGE(JERR_RLE_MEM, "Insufficient memory for RLE header")
+JMESSAGE(JERR_RLE_NOT, "Not an RLE file")
+JMESSAGE(JERR_RLE_TOOMANYCHANNELS, "Cannot handle %d output channels for RLE")
+JMESSAGE(JERR_RLE_UNSUPPORTED, "Cannot handle this RLE setup")
+JMESSAGE(JTRC_RLE, "%ux%u full-color RLE file")
+JMESSAGE(JTRC_RLE_FULLMAP, "%ux%u full-color RLE file with map of length %d")
+JMESSAGE(JTRC_RLE_GRAY, "%ux%u grayscale RLE file")
+JMESSAGE(JTRC_RLE_MAPGRAY, "%ux%u grayscale RLE file with map of length %d")
+JMESSAGE(JTRC_RLE_MAPPED, "%ux%u colormapped RLE file with map of length %d")
+#endif /* RLE_SUPPORTED */
+
+#ifdef TARGA_SUPPORTED
+JMESSAGE(JERR_TGA_BADCMAP, "Unsupported Targa colormap format")
+JMESSAGE(JERR_TGA_BADPARMS, "Invalid or unsupported Targa file")
+JMESSAGE(JERR_TGA_COLORSPACE, "Targa output must be grayscale or RGB")
+JMESSAGE(JTRC_TGA, "%ux%u RGB Targa image")
+JMESSAGE(JTRC_TGA_GRAY, "%ux%u grayscale Targa image")
+JMESSAGE(JTRC_TGA_MAPPED, "%ux%u colormapped Targa image")
+#else
+JMESSAGE(JERR_TGA_NOTCOMP, "Targa support was not compiled")
+#endif /* TARGA_SUPPORTED */
+
+JMESSAGE(JERR_BAD_CMAP_FILE,
+	 "Color map file is invalid or of unsupported format")
+JMESSAGE(JERR_TOO_MANY_COLORS,
+	 "Output file format cannot handle %d colormap entries")
+JMESSAGE(JERR_UNGETC_FAILED, "ungetc failed")
+#ifdef TARGA_SUPPORTED
+JMESSAGE(JERR_UNKNOWN_FORMAT,
+	 "Unrecognized input file format --- perhaps you need -targa")
+#else
+JMESSAGE(JERR_UNKNOWN_FORMAT, "Unrecognized input file format")
+#endif
+JMESSAGE(JERR_UNSUPPORTED_FORMAT, "Unsupported output file format")
+
+#ifdef JMAKE_MSG_TABLE
+
+  NULL
+};
+
+#else /* not JMAKE_MSG_TABLE */
+
+  JMSG_LASTADDONCODE
+} ADDON_MESSAGE_CODE;
+
+#endif /* JMAKE_MSG_TABLE */
+
+#undef JMESSAGE
diff --git a/cdjpeg.h b/cdjpeg.h
new file mode 100644
index 0000000..35acc35
--- /dev/null
+++ b/cdjpeg.h
@@ -0,0 +1,124 @@
+/*
+ * cdjpeg.h
+ *
+ * Copyright (C) 1994, 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.
+ *
+ * This file contains common declarations for the sample applications
+ * cjpeg and djpeg.  It is NOT used by the core JPEG library.
+ */
+
+#define JPEG_CJPEG_DJPEG	/* define proper options in jconfig.h */
+#define JPEG_INTERNAL_OPTIONS	/* cjpeg.c,djpeg.c need to see xxx_SUPPORTED */
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jerror.h"		/* get library error codes too */
+#include "cderror.h"		/* get application-specific error codes */
+
+
+/*
+ * Object interface for cjpeg's source file decoding modules
+ */
+
+typedef struct cjpeg_source_struct * cjpeg_source_ptr;
+
+struct cjpeg_source_struct {
+  JMETHOD(void, start_input, (j_compress_ptr cinfo,
+			      cjpeg_source_ptr sinfo));
+  JMETHOD(JDIMENSION, get_pixel_rows, (j_compress_ptr cinfo,
+				       cjpeg_source_ptr sinfo));
+  JMETHOD(void, finish_input, (j_compress_ptr cinfo,
+			       cjpeg_source_ptr sinfo));
+
+  FILE *input_file;
+
+  JSAMPARRAY buffer;
+  JDIMENSION buffer_height;
+};
+
+
+/*
+ * Object interface for djpeg's output file encoding modules
+ */
+
+typedef struct djpeg_dest_struct * djpeg_dest_ptr;
+
+struct djpeg_dest_struct {
+  /* start_output is called after jpeg_start_decompress finishes.
+   * The color map will be ready at this time, if one is needed.
+   */
+  JMETHOD(void, start_output, (j_decompress_ptr cinfo,
+			       djpeg_dest_ptr dinfo));
+  /* Emit the specified number of pixel rows from the buffer. */
+  JMETHOD(void, put_pixel_rows, (j_decompress_ptr cinfo,
+				 djpeg_dest_ptr dinfo,
+				 JDIMENSION rows_supplied));
+  /* Finish up at the end of the image. */
+  JMETHOD(void, finish_output, (j_decompress_ptr cinfo,
+				djpeg_dest_ptr dinfo));
+
+  /* Target file spec; filled in by djpeg.c after object is created. */
+  FILE * output_file;
+
+  /* Output pixel-row buffer.  Created by module init or start_output.
+   * Width is cinfo->output_width * cinfo->output_components;
+   * height is buffer_height.
+   */
+  JSAMPARRAY buffer;
+  JDIMENSION buffer_height;
+};
+
+
+/*
+ * cjpeg/djpeg may need to perform extra passes to convert to or from
+ * the source/destination file format.  The JPEG library does not know
+ * about these passes, but we'd like them to be counted by the progress
+ * monitor.  We use an expanded progress monitor object to hold the
+ * additional pass count.
+ */
+
+struct cdjpeg_progress_mgr {
+  struct jpeg_progress_mgr pub;	/* fields known to JPEG library */
+  int completed_extra_passes;	/* extra passes completed */
+  int total_extra_passes;	/* total extra */
+  /* last printed percentage stored here to avoid multiple printouts */
+  int percent_done;
+};
+
+typedef struct cdjpeg_progress_mgr * cd_progress_ptr;
+
+
+/* Short forms of external names for systems with brain-damaged linkers. */
+
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+#define jinit_read_bmp		jIRdBMP
+#define jinit_write_bmp		jIWrBMP
+#define jinit_read_gif		jIRdGIF
+#define jinit_write_gif		jIWrGIF
+#define jinit_read_ppm		jIRdPPM
+#define jinit_write_ppm		jIWrPPM
+#define jinit_read_rle		jIRdRLE
+#define jinit_write_rle		jIWrRLE
+#define jinit_read_targa	jIRdTarga
+#define jinit_write_targa	jIWrTarga
+#define read_color_map		RdCMap
+#endif /* NEED_SHORT_EXTERNAL_NAMES */
+
+/* Module selection routines for I/O modules. */
+
+EXTERN cjpeg_source_ptr jinit_read_bmp JPP((j_compress_ptr cinfo));
+EXTERN djpeg_dest_ptr jinit_write_bmp JPP((j_decompress_ptr cinfo,
+					   boolean is_os2));
+EXTERN cjpeg_source_ptr jinit_read_gif JPP((j_compress_ptr cinfo));
+EXTERN djpeg_dest_ptr jinit_write_gif JPP((j_decompress_ptr cinfo));
+EXTERN cjpeg_source_ptr jinit_read_ppm JPP((j_compress_ptr cinfo));
+EXTERN djpeg_dest_ptr jinit_write_ppm JPP((j_decompress_ptr cinfo));
+EXTERN cjpeg_source_ptr jinit_read_rle JPP((j_compress_ptr cinfo));
+EXTERN djpeg_dest_ptr jinit_write_rle JPP((j_decompress_ptr cinfo));
+EXTERN cjpeg_source_ptr jinit_read_targa JPP((j_compress_ptr cinfo));
+EXTERN djpeg_dest_ptr jinit_write_targa JPP((j_decompress_ptr cinfo));
+
+/* Other global routines */
+
+EXTERN void read_color_map JPP((j_decompress_ptr cinfo, FILE * infile));
diff --git a/change.log b/change.log
new file mode 100644
index 0000000..ac2bbea
--- /dev/null
+++ b/change.log
@@ -0,0 +1,39 @@
+CHANGE LOG for Independent JPEG Group's JPEG software
+
+
+Version 5  24-Sep-94
+--------------------
+
+Version 5 represents a nearly complete redesign and rewrite of the IJG
+software.  Major user-visible changes include:
+  * Automatic configuration simplifies installation for most Unix systems.
+  * A range of speed vs. image quality tradeoffs are supported.
+    This includes resizing of an image during decompression: scaling down
+    by a factor of 1/2, 1/4, or 1/8 is handled very efficiently.
+  * New programs rdjpgcom and wrjpgcom allow insertion and extraction
+    of text comments in a JPEG file.
+
+The application programmer's interface to the library has changed completely.
+Notable improvements include:
+  * We have eliminated the use of callback routines for handling the
+    uncompressed image data.  The application now sees the library as a
+    set of routines that it calls to read or write image data on a
+    scanline-by-scanline basis.
+  * The application image data is represented in a conventional interleaved-
+    pixel format, rather than as a separate array for each color channel.
+    This can save a copying step in many programs.
+  * The handling of compressed data has been cleaned up: the application can
+    supply routines to source or sink the compressed data.  It is possible to
+    suspend processing on source/sink buffer overrun, although this is not
+    supported in all operating modes.
+  * All static state has been eliminated from the library, so that multiple
+    instances of compression or decompression can be active concurrently.
+  * JPEG abbreviated datastream formats are supported, ie, quantization and
+    Huffman tables can be stored separately from the image data.
+  * And not only that, but the documentation of the library has improved
+    considerably!
+
+
+The last widely used release before the version 5 rewrite was version 4A of
+18-Feb-93.  Change logs before that point have been discarded, since they
+are not of much interest after the rewrite.
diff --git a/cjpeg.1 b/cjpeg.1
index c76a912..80c2110 100644
--- a/cjpeg.1
+++ b/cjpeg.1
@@ -1,46 +1,10 @@
-.TH CJPEG 1 "4 November 1992"
+.TH CJPEG 1 "30 August 1994"
 .SH NAME
 cjpeg \- compress an image file to a JPEG file
 .SH SYNOPSIS
 .B cjpeg
 [
-.BI \-quality " N"
-]
-[
-.B \-grayscale
-]
-[
-.B \-optimize
-]
-[
-.B \-targa
-]
-[
-.BI \-maxmemory " N"
-]
-[
-.BI \-restart " N"
-]
-[
-.BI \-smooth " N"
-]
-[
-.B \-verbose
-]
-[
-.B \-debug
-]
-[
-.B \-arithmetic
-]
-[
-.B \-nointerleave
-]
-[
-.BI \-qtables " file"
-]
-[
-.BI \-sample " HxV[,...]"
+.I options
 ]
 [
 .I filename
@@ -52,7 +16,7 @@
 compresses the named image file, or the standard input if no file is
 named, and produces a JPEG/JFIF file on the standard output.
 The currently supported input file formats are: PPM (PBMPLUS color
-format), PGM (PBMPLUS gray-scale format), GIF, Targa, and RLE (Utah Raster
+format), PGM (PBMPLUS gray-scale format), BMP, GIF, Targa, and RLE (Utah Raster
 Toolkit format).  (RLE is supported only if the URT library is available.)
 .SH OPTIONS
 All switch names may be abbreviated; for example,
@@ -104,6 +68,7 @@
 to make
 .B cjpeg
 treat the input as Targa format.
+For most Targa files, you won't need this switch.
 .PP
 The
 .B \-quality
@@ -136,16 +101,25 @@
 considered optional in the JPEG standard.
 .B cjpeg
 emits a warning message when you give such a quality value, because some
-commercial JPEG programs may be unable to decode the resulting file.)
+commercial JPEG programs may be unable to decode the resulting file.  Use
+.B \-baseline
+if you need to ensure compatibility at low quality values.)
 .PP
 Switches for advanced users:
 .TP
-.BI \-maxmemory " N"
-Set limit for amount of memory to use in processing large images.  Value is
-in thousands of bytes, or millions of bytes if "M" is attached to the
-number.  For example,
-.B \-max 4m
-selects 4000000 bytes.  If more space is needed, temporary files will be used.
+.B \-dct int
+Use integer DCT method (default).
+.TP
+.B \-dct fast
+Use fast integer DCT (less accurate).
+.TP
+.B \-dct float
+Use floating-point DCT method.
+The floating-point method is the most accurate, but will be the slowest unless
+your machine has very fast floating-point hardware.  Also note that results of
+the floating-point method may vary slightly across machines, while the integer
+methods should give the same results everywhere.  The fast integer method is
+much less accurate than the other two.
 .TP
 .BI \-restart " N"
 Emit a JPEG restart marker every N MCU rows, or every N MCU blocks if "B" is
@@ -157,6 +131,16 @@
 Smooth the input image to eliminate dithering noise.  N, ranging from 1 to
 100, indicates the strength of smoothing.  0 (the default) means no smoothing.
 .TP
+.BI \-maxmemory " N"
+Set limit for amount of memory to use in processing large images.  Value is
+in thousands of bytes, or millions of bytes if "M" is attached to the
+number.  For example,
+.B \-max 4m
+selects 4000000 bytes.  If more space is needed, temporary files will be used.
+.TP
+.BI \-outfile " name"
+Send output image to the named file, not to standard output.
+.TP
 .B \-verbose
 Enable debug printout.  More
 .BR \-v 's
@@ -191,6 +175,10 @@
 Use arithmetic coding rather than Huffman coding.  (Not currently
 supported for legal reasons.)
 .TP
+.B \-baseline
+Force a baseline JPEG file to be generated.  This clamps quantization values
+to 8 bits even at low quality settings.
+.TP
 .B \-nointerleave
 Generate noninterleaved JPEG file (not yet supported).
 .TP
@@ -199,11 +187,15 @@
 contain one to four tables (64 values each) as plain text.  Comments preceded
 by '#' may be included in the file.  The tables are implicitly numbered
 0,1,etc.  If
-.B \-quality
-N is also specified, the values in the file are scaled according to
+.BI \-quality " N"
+is also specified, the values in the file are scaled according to
 .BR cjpeg 's
 quality scaling curve.
 .TP
+.BI \-qslots " N[,...]"
+Select which quantization table to use for each color component.  By default,
+table 0 is used for luminance and table 1 for chrominance components.
+.TP
 .BI \-sample " HxV[,...]"
 Set JPEG sampling factors.  If you specify fewer H/V pairs than there are
 components, the remaining components are set to 1x1 sampling.  The default
@@ -224,6 +216,34 @@
 .I 60 foo.ppm
 .B >
 .I foo.jpg
+.SH HINTS
+Color GIF files are not the ideal input for JPEG; JPEG is really intended for
+compressing full-color (24-bit) images.  In particular, don't try to convert
+cartoons, line drawings, and other images that have only a few distinct
+colors.  GIF works great on these, JPEG does not.  If you want to convert a
+GIF to JPEG, you should experiment with
+.BR cjpeg 's
+.B \-quality
+and
+.B \-smooth
+options to get a satisfactory conversion.
+.B \-smooth 10
+or so is often helpful.
+.PP
+Avoid running an image through a series of JPEG compression/decompression
+cycles.  Image quality loss will accumulate; after ten or so cycles the image
+may be noticeably worse than it was after one cycle.  It's best to use a
+lossless format while manipulating an image, then convert to JPEG format when
+you are ready to file the image away.
+.PP
+The
+.B \-optimize
+option to
+.B cjpeg
+is worth using when you are making a "final" version for posting or archiving.
+It's also a win when you are using low quality settings to make very small
+JPEG files; the percentage improvement is often a lot more than it is on
+larger files.
 .SH ENVIRONMENT
 .TP
 .B JPEGMEM
@@ -236,7 +256,9 @@
 itself is overridden by an explicit
 .BR \-maxmemory .
 .SH SEE ALSO
-.BR djpeg (1)
+.BR djpeg (1),
+.BR rdjpgcom (1),
+.BR wrjpgcom (1)
 .br
 .BR ppm (5),
 .BR pgm (5)
@@ -246,12 +268,12 @@
 .SH AUTHOR
 Independent JPEG Group
 .SH BUGS
-Arithmetic coding and interleaved output not yet supported.
+Arithmetic coding is not supported for legal reasons.
 .PP
-Not all variants of Targa file format are supported.
+Not all variants of BMP and Targa file formats are supported.
 .PP
 The
-.B -targa
+.B \-targa
 switch is not a bug, it's a feature.  (It would be a bug if the Targa format
 designers had not been clueless.)
 .PP
diff --git a/cjpeg.c b/cjpeg.c
new file mode 100644
index 0000000..33347f3
--- /dev/null
+++ b/cjpeg.c
@@ -0,0 +1,877 @@
+/*
+ * cjpeg.c
+ *
+ * Copyright (C) 1991-1994, 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.
+ *
+ * This file contains a command-line user interface for the JPEG compressor.
+ * It should work on any system with Unix- or MS-DOS-style command lines.
+ *
+ * Two different command line styles are permitted, depending on the
+ * compile-time switch TWO_FILE_COMMANDLINE:
+ *	cjpeg [options]  inputfile outputfile
+ *	cjpeg [options]  [inputfile]
+ * In the second style, output is always to standard output, which you'd
+ * normally redirect to a file or pipe to some other program.  Input is
+ * either from a named file or from standard input (typically redirected).
+ * The second style is convenient on Unix but is unhelpful on systems that
+ * don't support pipes.  Also, you MUST use the first style if your system
+ * doesn't do binary I/O to stdin/stdout.
+ * To simplify script writing, the "-outfile" switch is provided.  The syntax
+ *	cjpeg [options]  -outfile outputfile  inputfile
+ * works regardless of which command line style is used.
+ */
+
+#include "cdjpeg.h"		/* Common decls for cjpeg/djpeg applications */
+#define JMAKE_MSG_TABLE
+#include "cderror.h"		/* create message string table */
+#include "jversion.h"		/* for version message */
+
+#include <ctype.h>		/* to declare isupper(), tolower() */
+#ifdef NEED_SIGNAL_CATCHER
+#include <signal.h>		/* to declare signal() */
+#endif
+#ifdef USE_SETMODE
+#include <fcntl.h>		/* to declare setmode()'s parameter macros */
+/* If you have setmode() but not <io.h>, just delete this line: */
+#include <io.h>			/* to declare setmode() */
+#endif
+
+#ifdef USE_CCOMMAND		/* command-line reader for Macintosh */
+#ifdef __MWERKS__
+#include <SIOUX.h>              /* Metrowerks declares it here */
+#endif
+#ifdef THINK_C
+#include <console.h>		/* Think declares it here */
+#endif
+#endif
+
+#ifdef DONT_USE_B_MODE		/* define mode parameters for fopen() */
+#define READ_BINARY	"r"
+#define WRITE_BINARY	"w"
+#else
+#define READ_BINARY	"rb"
+#define WRITE_BINARY	"wb"
+#endif
+
+#ifndef EXIT_FAILURE		/* define exit() codes if not provided */
+#define EXIT_FAILURE  1
+#endif
+#ifndef EXIT_SUCCESS
+#ifdef VMS
+#define EXIT_SUCCESS  1		/* VMS is very nonstandard */
+#else
+#define EXIT_SUCCESS  0
+#endif
+#endif
+#ifndef EXIT_WARNING
+#ifdef VMS
+#define EXIT_WARNING  1		/* VMS is very nonstandard */
+#else
+#define EXIT_WARNING  2
+#endif
+#endif
+
+
+/*
+ * This routine determines what format the input file is,
+ * and selects the appropriate input-reading module.
+ *
+ * To determine which family of input formats the file belongs to,
+ * we may look only at the first byte of the file, since C does not
+ * guarantee that more than one character can be pushed back with ungetc.
+ * Looking at additional bytes would require one of these approaches:
+ *     1) assume we can fseek() the input file (fails for piped input);
+ *     2) assume we can push back more than one character (works in
+ *        some C implementations, but unportable);
+ *     3) provide our own buffering (breaks input readers that want to use
+ *        stdio directly, such as the RLE library);
+ * or  4) don't put back the data, and modify the input_init methods to assume
+ *        they start reading after the start of file (also breaks RLE library).
+ * #1 is attractive for MS-DOS but is untenable on Unix.
+ *
+ * The most portable solution for file types that can't be identified by their
+ * first byte is to make the user tell us what they are.  This is also the
+ * only approach for "raw" file types that contain only arbitrary values.
+ * We presently apply this method for Targa files.  Most of the time Targa
+ * files start with 0x00, so we recognize that case.  Potentially, however,
+ * a Targa file could start with any byte value (byte 0 is the length of the
+ * seldom-used ID field), so we provide a switch to force Targa input mode.
+ */
+
+static boolean is_targa;	/* records user -targa switch */
+
+
+LOCAL cjpeg_source_ptr
+select_file_type (j_compress_ptr cinfo, FILE * infile)
+{
+  int c;
+
+  if (is_targa) {
+#ifdef TARGA_SUPPORTED
+    return jinit_read_targa(cinfo);
+#else
+    ERREXIT(cinfo, JERR_TGA_NOTCOMP);
+#endif
+  }
+
+  if ((c = getc(infile)) == EOF)
+    ERREXIT(cinfo, JERR_INPUT_EMPTY);
+  if (ungetc(c, infile) == EOF)
+    ERREXIT(cinfo, JERR_UNGETC_FAILED);
+
+  switch (c) {
+#ifdef BMP_SUPPORTED
+  case 'B':
+    return jinit_read_bmp(cinfo);
+#endif
+#ifdef GIF_SUPPORTED
+  case 'G':
+    return jinit_read_gif(cinfo);
+#endif
+#ifdef PPM_SUPPORTED
+  case 'P':
+    return jinit_read_ppm(cinfo);
+#endif
+#ifdef RLE_SUPPORTED
+  case 'R':
+    return jinit_read_rle(cinfo);
+#endif
+#ifdef TARGA_SUPPORTED
+  case 0x00:
+    return jinit_read_targa(cinfo);
+#endif
+  default:
+    ERREXIT(cinfo, JERR_UNKNOWN_FORMAT);
+    break;
+  }
+
+  return NULL;			/* suppress compiler warnings */
+}
+
+
+/*
+ * Signal catcher to ensure that temporary files are removed before aborting.
+ * NB: for Amiga Manx C this is actually a global routine named _abort();
+ * we put "#define signal_catcher _abort" in jconfig.h.  Talk about bogus...
+ */
+
+#ifdef NEED_SIGNAL_CATCHER
+
+static j_common_ptr sig_cinfo;
+
+GLOBAL void
+signal_catcher (int signum)
+{
+  if (sig_cinfo != NULL) {
+    if (sig_cinfo->err != NULL) /* turn off trace output */
+      sig_cinfo->err->trace_level = 0;
+    jpeg_destroy(sig_cinfo);	/* clean up memory allocation & temp files */
+  }
+  exit(EXIT_FAILURE);
+}
+
+#endif
+
+
+/*
+ * Optional routine to display a percent-done figure on stderr.
+ */
+
+#ifdef PROGRESS_REPORT
+
+METHODDEF void
+progress_monitor (j_common_ptr cinfo)
+{
+  cd_progress_ptr prog = (cd_progress_ptr) cinfo->progress;
+  int total_passes = prog->pub.total_passes + prog->total_extra_passes;
+  int percent_done = (int) (prog->pub.pass_counter*100L/prog->pub.pass_limit);
+
+  if (percent_done != prog->percent_done) {
+    prog->percent_done = percent_done;
+    if (total_passes > 1) {
+      fprintf(stderr, "\rPass %d/%d: %3d%% ",
+	      prog->pub.completed_passes + prog->completed_extra_passes + 1,
+	      total_passes, percent_done);
+    } else {
+      fprintf(stderr, "\r %3d%% ", percent_done);
+    }
+    fflush(stderr);
+  }
+}
+
+#endif
+
+
+/*
+ * Argument-parsing code.
+ * The switch parser is designed to be useful with DOS-style command line
+ * syntax, ie, intermixed switches and file names, where only the switches
+ * to the left of a given file name affect processing of that file.
+ * The main program in this file doesn't actually use this capability...
+ */
+
+
+static const char * progname;	/* program name for error messages */
+static char * outfilename;	/* for -outfile switch */
+
+
+LOCAL void
+usage (void)
+/* complain about bad command line */
+{
+  fprintf(stderr, "usage: %s [switches] ", progname);
+#ifdef TWO_FILE_COMMANDLINE
+  fprintf(stderr, "inputfile outputfile\n");
+#else
+  fprintf(stderr, "[inputfile]\n");
+#endif
+
+  fprintf(stderr, "Switches (names may be abbreviated):\n");
+  fprintf(stderr, "  -quality N     Compression quality (0..100; 5-95 is useful range)\n");
+  fprintf(stderr, "  -grayscale     Create monochrome JPEG file\n");
+#ifdef ENTROPY_OPT_SUPPORTED
+  fprintf(stderr, "  -optimize      Optimize Huffman table (smaller file, but slow compression)\n");
+#endif
+#ifdef TARGA_SUPPORTED
+  fprintf(stderr, "  -targa         Input file is Targa format (usually not needed)\n");
+#endif
+  fprintf(stderr, "Switches for advanced users:\n");
+#ifdef DCT_ISLOW_SUPPORTED
+  fprintf(stderr, "  -dct int       Use integer DCT method%s\n",
+	  (JDCT_DEFAULT == JDCT_ISLOW ? " (default)" : ""));
+#endif
+#ifdef DCT_IFAST_SUPPORTED
+  fprintf(stderr, "  -dct fast      Use fast integer DCT (less accurate)%s\n",
+	  (JDCT_DEFAULT == JDCT_IFAST ? " (default)" : ""));
+#endif
+#ifdef DCT_FLOAT_SUPPORTED
+  fprintf(stderr, "  -dct float     Use floating-point DCT method%s\n",
+	  (JDCT_DEFAULT == JDCT_FLOAT ? " (default)" : ""));
+#endif
+  fprintf(stderr, "  -restart N     Set restart interval in rows, or in blocks with B\n");
+#ifdef INPUT_SMOOTHING_SUPPORTED
+  fprintf(stderr, "  -smooth N      Smooth dithered input (N=1..100 is strength)\n");
+#endif
+  fprintf(stderr, "  -maxmemory N   Maximum memory to use (in kbytes)\n");
+  fprintf(stderr, "  -outfile name  Specify name for output file\n");
+  fprintf(stderr, "  -verbose  or  -debug   Emit debug output\n");
+  fprintf(stderr, "Switches for wizards:\n");
+#ifdef C_ARITH_CODING_SUPPORTED
+  fprintf(stderr, "  -arithmetic    Use arithmetic coding\n");
+#endif
+  fprintf(stderr, "  -baseline      Force baseline output\n");
+#ifdef C_MULTISCAN_FILES_SUPPORTED
+  fprintf(stderr, "  -nointerleave  Create noninterleaved JPEG file\n");
+#endif
+  fprintf(stderr, "  -qtables file  Use quantization tables given in file\n");
+  fprintf(stderr, "  -qslots N[,...]    Set component quantization tables\n");
+  fprintf(stderr, "  -sample HxV[,...]  Set component sampling factors\n");
+  exit(EXIT_FAILURE);
+}
+
+
+LOCAL boolean
+keymatch (char * arg, const char * keyword, int minchars)
+/* Case-insensitive matching of (possibly abbreviated) keyword switches. */
+/* keyword is the constant keyword (must be lower case already), */
+/* minchars is length of minimum legal abbreviation. */
+{
+  register int ca, ck;
+  register int nmatched = 0;
+
+  while ((ca = *arg++) != '\0') {
+    if ((ck = *keyword++) == '\0')
+      return FALSE;		/* arg longer than keyword, no good */
+    if (isupper(ca))		/* force arg to lcase (assume ck is already) */
+      ca = tolower(ca);
+    if (ca != ck)
+      return FALSE;		/* no good */
+    nmatched++;			/* count matched characters */
+  }
+  /* reached end of argument; fail if it's too short for unique abbrev */
+  if (nmatched < minchars)
+    return FALSE;
+  return TRUE;			/* A-OK */
+}
+
+
+LOCAL int
+qt_getc (FILE * file)
+/* Read next char, skipping over any comments (# to end of line) */
+/* A comment/newline sequence is returned as a newline */
+{
+  register int ch;
+  
+  ch = getc(file);
+  if (ch == '#') {
+    do {
+      ch = getc(file);
+    } while (ch != '\n' && ch != EOF);
+  }
+  return ch;
+}
+
+
+LOCAL long
+read_qt_integer (FILE * file)
+/* Read an unsigned decimal integer from a quantization-table file */
+/* Swallows one trailing character after the integer */
+{
+  register int ch;
+  register long val;
+  
+  /* Skip any leading whitespace, detect EOF */
+  do {
+    ch = qt_getc(file);
+    if (ch == EOF)
+      return EOF;
+  } while (isspace(ch));
+  
+  if (! isdigit(ch)) {
+    fprintf(stderr, "%s: bogus data in quantization file\n", progname);
+    exit(EXIT_FAILURE);
+  }
+
+  val = ch - '0';
+  while (ch = qt_getc(file), isdigit(ch)) {
+    val *= 10;
+    val += ch - '0';
+  }
+  return val;
+}
+
+
+LOCAL void
+read_quant_tables (j_compress_ptr cinfo, char * filename, int scale_factor,
+		   boolean force_baseline)
+/* Read a set of quantization tables from the specified file.
+ * The file is plain ASCII text: decimal numbers with whitespace between.
+ * Comments preceded by '#' may be included in the file.
+ * There may be one to NUM_QUANT_TBLS tables in the file, each of 64 values.
+ * The tables are implicitly numbered 0,1,etc.
+ * NOTE: does not affect the qslots mapping, which will default to selecting
+ * table 0 for luminance (or primary) components, 1 for chrominance components.
+ * You must use -qslots if you want a different component->table mapping.
+ */
+{
+  /* ZIG[i] is the zigzag-order position of the i'th element of a DCT block */
+  /* read in natural order (left to right, top to bottom). */
+  static const int ZIG[DCTSIZE2] = {
+     0,  1,  5,  6, 14, 15, 27, 28,
+     2,  4,  7, 13, 16, 26, 29, 42,
+     3,  8, 12, 17, 25, 30, 41, 43,
+     9, 11, 18, 24, 31, 40, 44, 53,
+    10, 19, 23, 32, 39, 45, 52, 54,
+    20, 22, 33, 38, 46, 51, 55, 60,
+    21, 34, 37, 47, 50, 56, 59, 61,
+    35, 36, 48, 49, 57, 58, 62, 63
+    };
+  FILE * fp;
+  int tblno, i;
+  long val;
+  unsigned int table[DCTSIZE2];
+
+  if ((fp = fopen(filename, "r")) == NULL) {
+    fprintf(stderr, "%s: can't open %s\n", progname, filename);
+    exit(EXIT_FAILURE);
+  }
+  tblno = 0;
+
+  while ((val = read_qt_integer(fp)) != EOF) { /* read 1st element of table */
+    if (tblno >= NUM_QUANT_TBLS) {
+      fprintf(stderr, "%s: too many tables in file %s\n", progname, filename);
+      exit(EXIT_FAILURE);
+    }
+    table[0] = (unsigned int) val;
+    for (i = 1; i < DCTSIZE2; i++) {
+      if ((val = read_qt_integer(fp)) == EOF) {
+	fprintf(stderr, "%s: incomplete table in file %s\n", progname, filename);
+	exit(EXIT_FAILURE);
+      }
+      table[ZIG[i]] = (unsigned int) val;
+    }
+    jpeg_add_quant_table(cinfo, tblno, table, scale_factor, force_baseline);
+    tblno++;
+  }
+
+  fclose(fp);
+}
+
+
+LOCAL void
+set_quant_slots (j_compress_ptr cinfo, char *arg)
+/* Process a quantization-table-selectors parameter string, of the form
+ *     N[,N,...]
+ * If there are more components than parameters, the last value is replicated.
+ */
+{
+  int val = 0;			/* default table # */
+  int ci;
+  char ch;
+
+  for (ci = 0; ci < MAX_COMPONENTS; ci++) {
+    if (*arg) {
+      ch = ',';			/* if not set by sscanf, will be ',' */
+      if (sscanf(arg, "%d%c", &val, &ch) < 1)
+	usage();
+      if (ch != ',')
+	usage();		/* syntax check */
+      if (val < 0 || val >= NUM_QUANT_TBLS) {
+	fprintf(stderr, "JPEG quantization tables are numbered 0..%d\n",
+		NUM_QUANT_TBLS-1);
+	exit(EXIT_FAILURE);
+      }
+      cinfo->comp_info[ci].quant_tbl_no = val;
+      while (*arg && *arg++ != ',') /* advance to next segment of arg string */
+	;
+    } else {
+      /* reached end of parameter, set remaining components to last table */
+      cinfo->comp_info[ci].quant_tbl_no = val;
+    }
+  }
+}
+
+
+LOCAL void
+set_sample_factors (j_compress_ptr cinfo, char *arg)
+/* Process a sample-factors parameter string, of the form
+ *     HxV[,HxV,...]
+ * If there are more components than parameters, "1x1" is assumed.
+ */
+{
+  int ci, val1, val2;
+  char ch1, ch2;
+
+  for (ci = 0; ci < MAX_COMPONENTS; ci++) {
+    if (*arg) {
+      ch2 = ',';		/* if not set by sscanf, will be ',' */
+      if (sscanf(arg, "%d%c%d%c", &val1, &ch1, &val2, &ch2) < 3)
+	usage();
+      if ((ch1 != 'x' && ch1 != 'X') || ch2 != ',')
+	usage();		/* syntax check */
+      if (val1 <= 0 || val1 > 4 || val2 <= 0 || val2 > 4) {
+	fprintf(stderr, "JPEG sampling factors must be 1..4\n");
+	exit(EXIT_FAILURE);
+      }
+      cinfo->comp_info[ci].h_samp_factor = val1;
+      cinfo->comp_info[ci].v_samp_factor = val2;
+      while (*arg && *arg++ != ',') /* advance to next segment of arg string */
+	;
+    } else {
+      /* reached end of parameter, set remaining components to 1x1 sampling */
+      cinfo->comp_info[ci].h_samp_factor = 1;
+      cinfo->comp_info[ci].v_samp_factor = 1;
+    }
+  }
+}
+
+
+LOCAL int
+parse_switches (j_compress_ptr cinfo, int argc, char **argv,
+		int last_file_arg_seen, boolean for_real)
+/* Parse optional switches.
+ * Returns argv[] index of first file-name argument (== argc if none).
+ * Any file names with indexes <= last_file_arg_seen are ignored;
+ * they have presumably been processed in a previous iteration.
+ * (Pass 0 for last_file_arg_seen on the first or only iteration.)
+ * for_real is FALSE on the first (dummy) pass; we may skip any expensive
+ * processing.
+ */
+{
+  int argn;
+  char * arg;
+  int quality;			/* -quality parameter */
+  int q_scale_factor;		/* scaling percentage for -qtables */
+  boolean force_baseline;
+  char * qtablefile = NULL;	/* saves -qtables filename if any */
+  char * qslotsarg = NULL;	/* saves -qslots parm if any */
+  char * samplearg = NULL;	/* saves -sample parm if any */
+
+  /* Set up default JPEG parameters. */
+  /* Note that default -quality level need not, and does not,
+   * match the default scaling for an explicit -qtables argument.
+   */
+  quality = 75;			/* default -quality value */
+  q_scale_factor = 100;		/* default to no scaling for -qtables */
+  force_baseline = FALSE;	/* by default, allow 16-bit quantizers */
+  is_targa = FALSE;
+  outfilename = NULL;
+  cinfo->err->trace_level = 0;
+
+  /* Scan command line options, adjust parameters */
+
+  for (argn = 1; argn < argc; argn++) {
+    arg = argv[argn];
+    if (*arg != '-') {
+      /* Not a switch, must be a file name argument */
+      if (argn <= last_file_arg_seen) {
+	outfilename = NULL;	/* -outfile applies to just one input file */
+	continue;		/* ignore this name if previously processed */
+      }
+      break;			/* else done parsing switches */
+    }
+    arg++;			/* advance past switch marker character */
+
+    if (keymatch(arg, "arithmetic", 1)) {
+      /* Use arithmetic coding. */
+#ifdef C_ARITH_CODING_SUPPORTED
+      cinfo->arith_code = TRUE;
+#else
+      fprintf(stderr, "%s: sorry, arithmetic coding not supported\n",
+	      progname);
+      exit(EXIT_FAILURE);
+#endif
+
+    } else if (keymatch(arg, "baseline", 1)) {
+      /* Force baseline output (8-bit quantizer values). */
+      force_baseline = TRUE;
+
+    } else if (keymatch(arg, "dct", 2)) {
+      /* Select DCT algorithm. */
+      if (++argn >= argc)	/* advance to next argument */
+	usage();
+      if (keymatch(argv[argn], "int", 1)) {
+	cinfo->dct_method = JDCT_ISLOW;
+      } else if (keymatch(argv[argn], "fast", 2)) {
+	cinfo->dct_method = JDCT_IFAST;
+      } else if (keymatch(argv[argn], "float", 2)) {
+	cinfo->dct_method = JDCT_FLOAT;
+      } else
+	usage();
+
+    } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
+      /* Enable debug printouts. */
+      /* On first -d, print version identification */
+      static boolean printed_version = FALSE;
+
+      if (! printed_version) {
+	fprintf(stderr, "Independent JPEG Group's CJPEG, version %s\n%s\n",
+		JVERSION, JCOPYRIGHT);
+	printed_version = TRUE;
+      }
+      cinfo->err->trace_level++;
+
+    } else if (keymatch(arg, "grayscale", 2) || keymatch(arg, "greyscale",2)) {
+      /* Force a monochrome JPEG file to be generated. */
+      jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
+
+    } else if (keymatch(arg, "maxmemory", 3)) {
+      /* Maximum memory in Kb (or Mb with 'm'). */
+      long lval;
+      char ch = 'x';
+
+      if (++argn >= argc)	/* advance to next argument */
+	usage();
+      if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
+	usage();
+      if (ch == 'm' || ch == 'M')
+	lval *= 1000L;
+      cinfo->mem->max_memory_to_use = lval * 1000L;
+
+    } else if (keymatch(arg, "nointerleave", 3)) {
+      /* Create noninterleaved file. */
+#ifdef C_MULTISCAN_FILES_SUPPORTED
+      cinfo->interleave = FALSE;
+#else
+      fprintf(stderr, "%s: sorry, multiple-scan support was not compiled\n",
+	      progname);
+      exit(EXIT_FAILURE);
+#endif
+
+    } else if (keymatch(arg, "optimize", 1) || keymatch(arg, "optimise", 1)) {
+      /* Enable entropy parm optimization. */
+#ifdef ENTROPY_OPT_SUPPORTED
+      cinfo->optimize_coding = TRUE;
+#else
+      fprintf(stderr, "%s: sorry, entropy optimization was not compiled\n",
+	      progname);
+      exit(EXIT_FAILURE);
+#endif
+
+    } else if (keymatch(arg, "outfile", 4)) {
+      /* Set output file name. */
+      if (++argn >= argc)	/* advance to next argument */
+	usage();
+      outfilename = argv[argn];	/* save it away for later use */
+
+    } else if (keymatch(arg, "quality", 1)) {
+      /* Quality factor (quantization table scaling factor). */
+      if (++argn >= argc)	/* advance to next argument */
+	usage();
+      if (sscanf(argv[argn], "%d", &quality) != 1)
+	usage();
+      /* Change scale factor in case -qtables is present. */
+      q_scale_factor = jpeg_quality_scaling(quality);
+
+    } else if (keymatch(arg, "qslots", 2)) {
+      /* Quantization table slot numbers. */
+      if (++argn >= argc)	/* advance to next argument */
+	usage();
+      qslotsarg = argv[argn];
+      /* Must delay setting qslots until after we have processed any
+       * colorspace-determining switches, since jpeg_set_colorspace sets
+       * default quant table numbers.
+       */
+
+    } else if (keymatch(arg, "qtables", 2)) {
+      /* Quantization tables fetched from file. */
+      if (++argn >= argc)	/* advance to next argument */
+	usage();
+      qtablefile = argv[argn];
+      /* We postpone actually reading the file in case -quality comes later. */
+
+    } else if (keymatch(arg, "restart", 1)) {
+      /* Restart interval in MCU rows (or in MCUs with 'b'). */
+      long lval;
+      char ch = 'x';
+
+      if (++argn >= argc)	/* advance to next argument */
+	usage();
+      if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
+	usage();
+      if (lval < 0 || lval > 65535L)
+	usage();
+      if (ch == 'b' || ch == 'B') {
+	cinfo->restart_interval = (unsigned int) lval;
+	cinfo->restart_in_rows = 0; /* else prior '-restart n' overrides me */
+      } else {
+	cinfo->restart_in_rows = (int) lval;
+	/* restart_interval will be computed during startup */
+      }
+
+    } else if (keymatch(arg, "sample", 2)) {
+      /* Set sampling factors. */
+      if (++argn >= argc)	/* advance to next argument */
+	usage();
+      samplearg = argv[argn];
+      /* Must delay setting sample factors until after we have processed any
+       * colorspace-determining switches, since jpeg_set_colorspace sets
+       * default sampling factors.
+       */
+
+    } else if (keymatch(arg, "smooth", 2)) {
+      /* Set input smoothing factor. */
+      int val;
+
+      if (++argn >= argc)	/* advance to next argument */
+	usage();
+      if (sscanf(argv[argn], "%d", &val) != 1)
+	usage();
+      if (val < 0 || val > 100)
+	usage();
+      cinfo->smoothing_factor = val;
+
+    } else if (keymatch(arg, "targa", 1)) {
+      /* Input file is Targa format. */
+      is_targa = TRUE;
+
+    } else {
+      usage();			/* bogus switch */
+    }
+  }
+
+  /* Post-switch-scanning cleanup */
+
+  if (for_real) {
+
+    /* Set quantization tables for selected quality. */
+    /* Some or all may be overridden if -qtables is present. */
+    jpeg_set_quality(cinfo, quality, force_baseline);
+
+    if (qtablefile != NULL)	/* process -qtables if it was present */
+      read_quant_tables(cinfo, qtablefile, q_scale_factor, force_baseline);
+
+    if (qslotsarg != NULL)	/* process -qslots if it was present */
+      set_quant_slots(cinfo, qslotsarg);
+
+    if (samplearg != NULL)	/* process -sample if it was present */
+      set_sample_factors(cinfo, samplearg);
+
+  }
+
+  return argn;			/* return index of next arg (file name) */
+}
+
+
+/*
+ * The main program.
+ */
+
+GLOBAL int
+main (int argc, char **argv)
+{
+  struct jpeg_compress_struct cinfo;
+  struct jpeg_error_mgr jerr;
+#ifdef PROGRESS_REPORT
+  struct cdjpeg_progress_mgr progress;
+#endif
+  int file_index;
+  cjpeg_source_ptr src_mgr;
+  FILE * input_file;
+  FILE * output_file;
+  JDIMENSION num_scanlines;
+
+  /* On Mac, fetch a command line. */
+#ifdef USE_CCOMMAND
+  argc = ccommand(&argv);
+#endif
+
+  progname = argv[0];
+  if (progname == NULL || progname[0] == 0)
+    progname = "cjpeg";		/* in case C library doesn't provide it */
+
+  /* Initialize the JPEG compression object with default error handling. */
+  cinfo.err = jpeg_std_error(&jerr);
+  jpeg_create_compress(&cinfo);
+  /* Add some application-specific error messages (from cderror.h) */
+  jerr.addon_message_table = addon_message_table;
+  jerr.first_addon_message = JMSG_FIRSTADDONCODE;
+  jerr.last_addon_message = JMSG_LASTADDONCODE;
+
+  /* Now safe to enable signal catcher. */
+#ifdef NEED_SIGNAL_CATCHER
+  sig_cinfo = (j_common_ptr) &cinfo;
+  signal(SIGINT, signal_catcher);
+#ifdef SIGTERM			/* not all systems have SIGTERM */
+  signal(SIGTERM, signal_catcher);
+#endif
+#endif
+
+  /* Initialize JPEG parameters.
+   * Much of this may be overridden later.
+   * In particular, we don't yet know the input file's color space,
+   * but we need to provide some value for jpeg_set_defaults() to work.
+   */
+
+  cinfo.in_color_space = JCS_RGB; /* arbitrary guess */
+  jpeg_set_defaults(&cinfo);
+
+  /* Scan command line to find file names.
+   * It is convenient to use just one switch-parsing routine, but the switch
+   * values read here are ignored; we will rescan the switches after opening
+   * the input file.
+   */
+
+  file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);
+
+#ifdef TWO_FILE_COMMANDLINE
+  /* Must have either -outfile switch or explicit output file name */
+  if (outfilename == NULL) {
+    if (file_index != argc-2) {
+      fprintf(stderr, "%s: must name one input and one output file\n",
+	      progname);
+      usage();
+    }
+    outfilename = argv[file_index+1];
+  } else {
+    if (file_index != argc-1) {
+      fprintf(stderr, "%s: must name one input and one output file\n",
+	      progname);
+      usage();
+    }
+  }
+#else
+  /* Unix style: expect zero or one file name */
+  if (file_index < argc-1) {
+    fprintf(stderr, "%s: only one input file\n", progname);
+    usage();
+  }
+#endif /* TWO_FILE_COMMANDLINE */
+
+  /* Open the input file. */
+  if (file_index < argc) {
+    if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
+      fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
+      exit(EXIT_FAILURE);
+    }
+  } else {
+    /* default input file is stdin */
+#ifdef USE_SETMODE		/* need to hack file mode? */
+    setmode(fileno(stdin), O_BINARY);
+#endif
+#ifdef USE_FDOPEN		/* need to re-open in binary mode? */
+    if ((input_file = fdopen(fileno(stdin), READ_BINARY)) == NULL) {
+      fprintf(stderr, "%s: can't open stdin\n", progname);
+      exit(EXIT_FAILURE);
+    }
+#else
+    input_file = stdin;
+#endif
+  }
+
+  /* Open the output file. */
+  if (outfilename != NULL) {
+    if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
+      fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
+      exit(EXIT_FAILURE);
+    }
+  } else {
+    /* default output file is stdout */
+#ifdef USE_SETMODE		/* need to hack file mode? */
+    setmode(fileno(stdout), O_BINARY);
+#endif
+#ifdef USE_FDOPEN		/* need to re-open in binary mode? */
+    if ((output_file = fdopen(fileno(stdout), WRITE_BINARY)) == NULL) {
+      fprintf(stderr, "%s: can't open stdout\n", progname);
+      exit(EXIT_FAILURE);
+    }
+#else
+    output_file = stdout;
+#endif
+  }
+
+#ifdef PROGRESS_REPORT
+  /* Enable progress display, unless trace output is on */
+  if (jerr.trace_level == 0) {
+    progress.pub.progress_monitor = progress_monitor;
+    progress.completed_extra_passes = 0;
+    progress.total_extra_passes = 0;
+    progress.percent_done = -1;
+    cinfo.progress = &progress.pub;
+  }
+#endif
+
+  /* Figure out the input file format, and set up to read it. */
+  src_mgr = select_file_type(&cinfo, input_file);
+  src_mgr->input_file = input_file;
+
+  /* Read the input file header to obtain file size & colorspace. */
+  (*src_mgr->start_input) (&cinfo, src_mgr);
+
+  /* Now that we know input colorspace, fix colorspace-dependent defaults */
+  jpeg_default_colorspace(&cinfo);
+
+  /* Adjust default compression parameters by re-parsing the options */
+  file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);
+
+  /* Specify data destination for compression */
+  jpeg_stdio_dest(&cinfo, output_file);
+
+  /* Start compressor */
+  jpeg_start_compress(&cinfo, TRUE);
+
+  /* Process data */
+  while (cinfo.next_scanline < cinfo.image_height) {
+    num_scanlines = (*src_mgr->get_pixel_rows) (&cinfo, src_mgr);
+    (void) jpeg_write_scanlines(&cinfo, src_mgr->buffer, num_scanlines);
+  }
+
+  /* Finish compression and release memory */
+  (*src_mgr->finish_input) (&cinfo, src_mgr);
+  jpeg_finish_compress(&cinfo);
+  jpeg_destroy_compress(&cinfo);
+
+#ifdef PROGRESS_REPORT
+  /* Clear away progress display */
+  if (jerr.trace_level == 0) {
+    fprintf(stderr, "\r                \r");
+    fflush(stderr);
+  }
+#endif
+
+  /* All done. */
+  exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
+  return 0;			/* suppress no-return-value warnings */
+}
diff --git a/ckconfig.c b/ckconfig.c
index 687d2c6..34baf79 100644
--- a/ckconfig.c
+++ b/ckconfig.c
@@ -1,7 +1,7 @@
 /*
  * ckconfig.c
  *
- * Copyright (C) 1991, 1992, Thomas G. Lane.
+ * Copyright (C) 1991-1994, 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.
  */
@@ -11,12 +11,8 @@
  * software for installation on a particular system.  The idea is to try to
  * compile and execute this program.  If your compiler fails to compile the
  * program, make changes as indicated in the comments below.  Once you can
- * compile the program, run it, and it will tell you how to set the various
- * switches in jconfig.h and in your Makefile.
- *
- * This could all be done automatically if we could assume we were on a Unix
- * system, but we don't want to assume that, so you'll have to edit and
- * recompile this program until it works.
+ * compile the program, run it, and it will produce a "jconfig.h" file for
+ * your system.
  *
  * As a general rule, each time you try to compile this program,
  * pay attention only to the *first* error message you get from the compiler.
@@ -31,66 +27,58 @@
 
 
 /* First we must see if your system has the include files we need.
- * We start out with the assumption that your system follows the ANSI
- * conventions for include files.  If you get any error in the next dozen
- * lines, undefine INCLUDES_ARE_ANSI.
+ * We start out with the assumption that your system has all the ANSI-standard
+ * include files.  If you get any error trying to include one of these files,
+ * undefine the corresponding HAVE_xxx symbol.
  */
 
-#define INCLUDES_ARE_ANSI	/* replace 'define' by 'undef' if error here */
-
-#ifdef INCLUDES_ARE_ANSI	/* this will be skipped if you undef... */
-#include <stdio.h>		/* If you ain't got this, you ain't got C. */
-#ifdef __SASC			/* Amiga SAS C provides size_t in stddef.h. */
-#include <stddef.h>		/* (They are wrong...) */
-#endif
-#include <string.h>		/* size_t might be here too. */
-typedef size_t my_size_t;	/* The payoff: do we have size_t now? */
-#include <stdlib.h>		/* Check other ANSI includes we use. */
+#define HAVE_STDDEF_H		/* replace 'define' by 'undef' if error here */
+#ifdef HAVE_STDDEF_H		/* next line will be skipped if you undef... */
+#include <stddef.h>
 #endif
 
-
-/* If your system doesn't follow the ANSI conventions, we have to figure out
- * what it does follow.  If you didn't get an error before this line, you can
- * ignore everything down to "#define HAVE_ANSI_DEFINITIONS".
- */
-
-#ifndef INCLUDES_ARE_ANSI	/* skip these tests if INCLUDES_ARE_ANSI */
+#define HAVE_STDLIB_H		/* same thing for stdlib.h */
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
+#endif
 
 #include <stdio.h>		/* If you ain't got this, you ain't got C. */
 
-/* jinclude.h will try to include <sys/types.h> if you don't set
- * INCLUDES_ARE_ANSI.  We need to test whether that include file is provided.
- * If you get an error here, undefine HAVE_TYPES_H.
- */
-
-#define HAVE_TYPES_H
-
-#ifdef HAVE_TYPES_H
-#include <sys/types.h>
-#endif
-
 /* We have to see if your string functions are defined by
- * strings.h (BSD convention) or string.h (everybody else).
- * We try the non-BSD convention first; define BSD if the compiler
- * says it can't find string.h.
+ * strings.h (old BSD convention) or string.h (everybody else).
+ * We try the non-BSD convention first; define NEED_BSD_STRINGS
+ * if the compiler says it can't find string.h.
  */
 
-#undef BSD
+#undef NEED_BSD_STRINGS
 
-#ifdef BSD
+#ifdef NEED_BSD_STRINGS
 #include <strings.h>
 #else
 #include <string.h>
 #endif
 
-/* Usually size_t is defined in stdio.h, sys/types.h, and/or string.h.
- * If not, you'll get an error on the "typedef size_t my_size_t;" line below.
- * In that case, you'll have to search through your system library to
- * figure out which include file defines "size_t".  Look for a line that
- * says "typedef something-or-other size_t;" (stddef.h and stdlib.h are
- * good places to look first).  Then, change the line below that says
- * "#include <someincludefile.h>" to instead include the file
- * you found size_t in, and define NEED_SPECIAL_INCLUDE.
+/* On some systems (especially older Unix machines), type size_t is
+ * defined only in the include file <sys/types.h>.  If you get a failure
+ * on the size_t test below, try defining NEED_SYS_TYPES_H.
+ */
+
+#undef NEED_SYS_TYPES_H		/* start by assuming we don't need it */
+#ifdef NEED_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+
+
+/* Usually type size_t is defined in one of the include files we've included
+ * above.  If not, you'll get an error on the "typedef size_t my_size_t;" line.
+ * In that case, first try defining NEED_SYS_TYPES_H just above.
+ * If that doesn't work, you'll have to search through your system library
+ * to figure out which include file defines "size_t".  Look for a line that
+ * says "typedef something-or-other size_t;".  Then, change the line below
+ * that says "#include <someincludefile.h>" to instead include the file
+ * you found size_t in, and define NEED_SPECIAL_INCLUDE.  If you can't find
+ * type size_t anywhere, try replacing "#include <someincludefile.h>" with
+ * "typedef unsigned int size_t;".
  */
 
 #undef NEED_SPECIAL_INCLUDE	/* assume we DON'T need it, for starters */
@@ -102,20 +90,16 @@
 typedef size_t my_size_t;	/* The payoff: do we have size_t now? */
 
 
-#endif /* INCLUDES_ARE_ANSI */
-
-
-
 /* The next question is whether your compiler supports ANSI-style function
- * definitions.  You need to know this in order to choose between using
+ * prototypes.  You need to know this in order to choose between using
  * makefile.ansi and using makefile.unix.
- * The #define line below is set to assume you have ANSI function definitions.
- * If you get an error in this group of lines, undefine HAVE_ANSI_DEFINITIONS.
+ * The #define line below is set to assume you have ANSI function prototypes.
+ * If you get an error in this group of lines, undefine HAVE_PROTOTYPES.
  */
 
-#define HAVE_ANSI_DEFINITIONS
+#define HAVE_PROTOTYPES
 
-#ifdef HAVE_ANSI_DEFINITIONS
+#ifdef HAVE_PROTOTYPES
 int testfunction (int arg1, int * arg2); /* check prototypes */
 
 struct methods_struct {		/* check method-pointer declarations */
@@ -129,7 +113,7 @@
   return arg2[arg1];
 }
 
-int testfunction1 (void)	/* check void arg list */
+int test2function (void)	/* check void arg list */
 {
   return 0;
 }
@@ -167,12 +151,21 @@
 #define HAVE_VOID
 
 #ifdef HAVE_VOID
+/* Caution: a C++ compiler will insist on complete prototypes */
 typedef void * void_ptr;	/* check void * */
-typedef void (*void_func) ();	/* check ptr to function returning void */
+#ifdef HAVE_PROTOTYPES		/* check ptr to function returning void */
+typedef void (*void_func) (int a, int b);
+#else
+typedef void (*void_func) ();
+#endif
 
-void testfunction2 (arg1, arg2)	/* check void function result */
+#ifdef HAVE_PROTOTYPES		/* check void function result */
+void test3function (void_ptr arg1, void_func arg2)
+#else
+void test3function (arg1, arg2)
      void_ptr arg1;
      void_func arg2;
+#endif
 {
   char * locptr = (char *) arg1; /* check casting to and from void * */
   arg1 = (void *) locptr;
@@ -190,215 +183,220 @@
 #ifdef HAVE_CONST
 static const int carray[3] = {1, 2, 3};
 
-int testfunction3 (arg1)
+#ifdef HAVE_PROTOTYPES
+int test4function (const int arg1)
+#else
+int test4function (arg1)
      const int arg1;
+#endif
 {
   return carray[arg1];
 }
 #endif
 
 
+/* If you get an error or warning about this structure definition,
+ * define INCOMPLETE_TYPES_BROKEN.
+ */
+
+#undef INCOMPLETE_TYPES_BROKEN
+
+#ifndef INCOMPLETE_TYPES_BROKEN
+typedef struct undefined_structure * undef_struct_ptr;
+#endif
+
+
+/* If you get an error about duplicate names,
+ * define NEED_SHORT_EXTERNAL_NAMES.
+ */
+
+#undef NEED_SHORT_EXTERNAL_NAMES
+
+#ifndef NEED_SHORT_EXTERNAL_NAMES
+
+int possibly_duplicate_function ()
+{
+  return 0;
+}
+
+int possibly_dupli_function ()
+{
+  return 1;
+}
+
+#endif
+
+
 
 /************************************************************************
  *  OK, that's it.  You should not have to change anything beyond this
  *  point in order to compile and execute this program.  (You might get
  *  some warnings, but you can ignore them.)
  *  When you run the program, it will make a couple more tests that it
- *  can do automatically, and then it will print out a summary of the changes
- *  that you need to make to the makefile and jconfig.h.
+ *  can do automatically, and then it will create jconfig.h and print out
+ *  any additional suggestions it has.
  ************************************************************************
  */
 
 
-static int any_changes = 0;
-
-int new_change ()
-{
-  if (! any_changes) {
-    printf("\nMost of the changes recommended by this program can be made either\n");
-    printf("by editing jconfig.h, or by adding -Dsymbol switches to the CFLAGS\n");
-    printf("line in your Makefile.  (Some PC compilers expect /Dsymbol instead.)\n");
-    printf("The CFLAGS method is simpler, but if your compiler doesn't support -D,\n");
-    printf("then you must change jconfig.h.  Also, it's best to change jconfig.h\n");
-    printf("if you plan to use the JPEG software as a library for other programs.\n");
-    any_changes = 1;
-  }
-  printf("\n");			/* blank line before each problem report */
-  return 0;
-}
-
-
-int test_char_sign (arg)
+#ifdef HAVE_PROTOTYPES
+int is_char_signed (int arg)
+#else
+int is_char_signed (arg)
      int arg;
+#endif
 {
   if (arg == 189) {		/* expected result for unsigned char */
-    new_change();
-    printf("You should add -DCHAR_IS_UNSIGNED to CFLAGS,\n");
-    printf("or else remove the /* */ comment marks from the line\n");
-    printf("/* #define CHAR_IS_UNSIGNED */  in jconfig.h.\n");
-    printf("(Be sure to delete the space before the # character too.)\n");
+    return 0;			/* type char is unsigned */
   }
   else if (arg != -67) {	/* expected result for signed char */
-    new_change();
-    printf("Hmm, it seems 'char' is less than eight bits wide on your machine.\n");
-    printf("I fear the JPEG software will not work at all.\n");
+    printf("Hmm, it seems 'char' is not eight bits wide on your machine.\n");
+    printf("I fear the JPEG software will not work at all.\n\n");
   }
-  return 0;
+  return 1;			/* assume char is signed otherwise */
 }
 
 
-int test_shifting (arg)
+#ifdef HAVE_PROTOTYPES
+int is_shifting_signed (long arg)
+#else
+int is_shifting_signed (arg)
      long arg;
+#endif
 /* See whether right-shift on a long is signed or not. */
 {
   long res = arg >> 4;
 
-  if (res == 0x80817F4L) {	/* expected result for unsigned */
-    new_change();
-    printf("You must add -DRIGHT_SHIFT_IS_UNSIGNED to CFLAGS,\n");
-    printf("or else remove the /* */ comment marks from the line\n");
-    printf("/* #define RIGHT_SHIFT_IS_UNSIGNED */  in jconfig.h.\n");
+  if (res == -0x7F7E80CL) {	/* expected result for signed shift */
+    return 1;			/* right shift is signed */
   }
-  else if (res != -0x7F7E80CL) { /* expected result for signed */
-    new_change();
-    printf("Right shift isn't acting as I expect it to.\n");
-    printf("I fear the JPEG software will not work at all.\n");
+  /* see if unsigned-shift hack will fix it. */
+  /* we can't just test exact value since it depends on width of long... */
+  res |= (~0L) << (32-4);
+  if (res == -0x7F7E80CL) {	/* expected result now? */
+    return 0;			/* right shift is unsigned */
   }
-  return 0;
+  printf("Right shift isn't acting as I expect it to.\n");
+  printf("I fear the JPEG software will not work at all.\n\n");
+  return 0;			/* try it with unsigned anyway */
 }
 
 
+#ifdef HAVE_PROTOTYPES
+int main (int argc, char ** argv)
+#else
 int main (argc, argv)
      int argc;
      char ** argv;
+#endif
 {
   char signed_char_check = (char) (-67);
+  FILE *outfile;
 
-  printf("Results of configuration check for Independent JPEG Group's software:\n");
-  printf("\nIf there's not a specific makefile provided for your compiler,\n");
-#ifdef HAVE_ANSI_DEFINITIONS
-  printf("you should use makefile.ansi as the starting point for your Makefile.\n");
-#else
-  printf("you should use makefile.unix as the starting point for your Makefile.\n");
-#endif
-
-  /* Check whether we have all the ANSI features, */
-  /* and whether this agrees with __STDC__ being predefined. */
-#ifdef __STDC__
-#define HAVE_STDC	/* ANSI compilers won't allow redefining __STDC__ */
-#endif
-
-#ifdef HAVE_ANSI_DEFINITIONS
-#ifdef HAVE_UNSIGNED_CHAR
-#ifdef HAVE_UNSIGNED_SHORT
-#ifdef HAVE_CONST
-#define HAVE_ALL_ANSI_FEATURES
-#endif
-#endif
-#endif
-#endif
-
-#ifdef HAVE_ALL_ANSI_FEATURES
-#ifndef HAVE_STDC
-  new_change();
-  printf("Your compiler doesn't claim to be ANSI-compliant, but it is close enough\n");
-  printf("for me.  Either add -DHAVE_STDC to CFLAGS, or add #define HAVE_STDC at the\n");
-  printf("beginning of jconfig.h.\n");
-#define HAVE_STDC
-#endif
-#else /* !HAVE_ALL_ANSI_FEATURES */
-#ifdef HAVE_STDC
-  new_change();
-  printf("Your compiler claims to be ANSI-compliant, but it is lying!\n");
-  printf("Delete the line  #define HAVE_STDC  near the beginning of jconfig.h.\n");
-#undef HAVE_STDC
-#endif
-#endif /* HAVE_ALL_ANSI_FEATURES */
-
-#ifndef HAVE_STDC
-
-#ifdef HAVE_ANSI_DEFINITIONS
-  new_change();
-  printf("You should add -DPROTO to CFLAGS, or else take out the several\n");
-  printf("#ifdef/#else/#endif lines surrounding #define PROTO in jconfig.h.\n");
-  printf("(Leave only one #define PROTO line.)\n");
-#endif
-
-#ifdef HAVE_UNSIGNED_CHAR
-#ifdef HAVE_UNSIGNED_SHORT
-  new_change();
-  printf("You should add -DHAVE_UNSIGNED_CHAR and -DHAVE_UNSIGNED_SHORT\n");
-  printf("to CFLAGS, or else take out the #ifdef HAVE_STDC/#endif lines\n");
-  printf("surrounding #define HAVE_UNSIGNED_CHAR and #define HAVE_UNSIGNED_SHORT\n");
-  printf("in jconfig.h.\n");
-#else /* only unsigned char */
-  new_change();
-  printf("You should add -DHAVE_UNSIGNED_CHAR to CFLAGS,\n");
-  printf("or else move #define HAVE_UNSIGNED_CHAR outside the\n");
-  printf("#ifdef HAVE_STDC/#endif lines surrounding it in jconfig.h.\n");
-#endif
-#else /* !HAVE_UNSIGNED_CHAR */
-#ifdef HAVE_UNSIGNED_SHORT
-  new_change();
-  printf("You should add -DHAVE_UNSIGNED_SHORT to CFLAGS,\n");
-  printf("or else move #define HAVE_UNSIGNED_SHORT outside the\n");
-  printf("#ifdef HAVE_STDC/#endif lines surrounding it in jconfig.h.\n");
-#endif
-#endif /* HAVE_UNSIGNED_CHAR */
-
-#ifdef HAVE_CONST
-  new_change();
-  printf("You should delete the  #define const  line from jconfig.h.\n");
-#endif
-
-#endif /* HAVE_STDC */
-
-  test_char_sign((int) signed_char_check);
-
-  test_shifting(-0x7F7E80B1L);
-
-#ifndef HAVE_VOID
-  new_change();
-  printf("You should add -Dvoid=char to CFLAGS,\n");
-  printf("or else remove the /* */ comment marks from the line\n");
-  printf("/* #define void char */  in jconfig.h.\n");
-  printf("(Be sure to delete the space before the # character too.)\n");
-#endif
-
-#ifdef INCLUDES_ARE_ANSI
-#ifndef __STDC__
-  new_change();
-  printf("You should add -DINCLUDES_ARE_ANSI to CFLAGS, or else add\n");
-  printf("#define INCLUDES_ARE_ANSI at the beginning of jinclude.h (NOT jconfig.h).\n");
-#endif
-#else /* !INCLUDES_ARE_ANSI */
-#ifdef __STDC__
-  new_change();
-  printf("You should add -DNONANSI_INCLUDES to CFLAGS, or else add\n");
-  printf("#define NONANSI_INCLUDES at the beginning of jinclude.h (NOT jconfig.h).\n");
-#endif
-#ifdef NEED_SPECIAL_INCLUDE
-  new_change();
-  printf("In jinclude.h, change the line reading #include <sys/types.h>\n");
-  printf("to instead include the file you found size_t in.\n");
-#else /* !NEED_SPECIAL_INCLUDE */
-#ifndef HAVE_TYPES_H
-  new_change();
-  printf("In jinclude.h, delete the line reading #include <sys/types.h>.\n");
-#endif
-#endif /* NEED_SPECIAL_INCLUDE */
-#ifdef BSD
-  new_change();
-  printf("You should add -DBSD to CFLAGS, or else add\n");
-  printf("#define BSD at the beginning of jinclude.h (NOT jconfig.h).\n");
-#endif
-#endif /* INCLUDES_ARE_ANSI */
-
-  if (any_changes) {
-    printf("\nI think that's everything...\n");
-  } else {
-    printf("\nI think jconfig.h is OK as distributed.\n");
+  /* Attempt to write jconfig.h */
+  if ((outfile = fopen("jconfig.h", "w")) == NULL) {
+    printf("Failed to write jconfig.h\n");
+    return 1;
   }
 
-  return any_changes;
+  /* Write out all the info */
+  fprintf(outfile, "/* jconfig.h --- generated by ckconfig.c */\n");
+  fprintf(outfile, "/* see jconfig.doc for explanations */\n\n");
+#ifdef HAVE_PROTOTYPES
+  fprintf(outfile, "#define HAVE_PROTOTYPES\n");
+#else
+  fprintf(outfile, "#undef HAVE_PROTOTYPES\n");
+#endif
+#ifdef HAVE_UNSIGNED_CHAR
+  fprintf(outfile, "#define HAVE_UNSIGNED_CHAR\n");
+#else
+  fprintf(outfile, "#undef HAVE_UNSIGNED_CHAR\n");
+#endif
+#ifdef HAVE_UNSIGNED_SHORT
+  fprintf(outfile, "#define HAVE_UNSIGNED_SHORT\n");
+#else
+  fprintf(outfile, "#undef HAVE_UNSIGNED_SHORT\n");
+#endif
+#ifdef HAVE_VOID
+  fprintf(outfile, "/* #define void char */\n");
+#else
+  fprintf(outfile, "#define void char\n");
+#endif
+#ifdef HAVE_CONST
+  fprintf(outfile, "/* #define const */\n");
+#else
+  fprintf(outfile, "#define const\n");
+#endif
+  if (is_char_signed((int) signed_char_check))
+    fprintf(outfile, "#undef CHAR_IS_UNSIGNED\n");
+  else
+    fprintf(outfile, "#define CHAR_IS_UNSIGNED\n");
+#ifdef HAVE_STDDEF_H
+  fprintf(outfile, "#define HAVE_STDDEF_H\n");
+#else
+  fprintf(outfile, "#undef HAVE_STDDEF_H\n");
+#endif
+#ifdef HAVE_STDLIB_H
+  fprintf(outfile, "#define HAVE_STDLIB_H\n");
+#else
+  fprintf(outfile, "#undef HAVE_STDLIB_H\n");
+#endif
+#ifdef NEED_BSD_STRINGS
+  fprintf(outfile, "#define NEED_BSD_STRINGS\n");
+#else
+  fprintf(outfile, "#undef NEED_BSD_STRINGS\n");
+#endif
+#ifdef NEED_SYS_TYPES_H
+  fprintf(outfile, "#define NEED_SYS_TYPES_H\n");
+#else
+  fprintf(outfile, "#undef NEED_SYS_TYPES_H\n");
+#endif
+  fprintf(outfile, "#undef NEED_FAR_POINTERS\n");
+#ifdef NEED_SHORT_EXTERNAL_NAMES
+  fprintf(outfile, "#define NEED_SHORT_EXTERNAL_NAMES\n");
+#else
+  fprintf(outfile, "#undef NEED_SHORT_EXTERNAL_NAMES\n");
+#endif
+#ifdef INCOMPLETE_TYPES_BROKEN
+  fprintf(outfile, "#define INCOMPLETE_TYPES_BROKEN\n");
+#else
+  fprintf(outfile, "#undef INCOMPLETE_TYPES_BROKEN\n");
+#endif
+  fprintf(outfile, "\n#ifdef JPEG_INTERNALS\n\n");
+  if (is_shifting_signed(-0x7F7E80B1L))
+    fprintf(outfile, "#undef RIGHT_SHIFT_IS_UNSIGNED\n");
+  else
+    fprintf(outfile, "#define RIGHT_SHIFT_IS_UNSIGNED\n");
+  fprintf(outfile, "\n#endif /* JPEG_INTERNALS */\n");
+  fprintf(outfile, "\n#ifdef JPEG_CJPEG_DJPEG\n\n");
+  fprintf(outfile, "#define BMP_SUPPORTED		/* BMP image file format */\n");
+  fprintf(outfile, "#define GIF_SUPPORTED		/* GIF image file format */\n");
+  fprintf(outfile, "#define PPM_SUPPORTED		/* PBMPLUS PPM/PGM image file format */\n");
+  fprintf(outfile, "#undef RLE_SUPPORTED		/* Utah RLE image file format */\n");
+  fprintf(outfile, "#define TARGA_SUPPORTED		/* Targa image file format */\n\n");
+  fprintf(outfile, "#undef TWO_FILE_COMMANDLINE	/* You may need this on non-Unix systems */\n");
+  fprintf(outfile, "#undef NEED_SIGNAL_CATCHER	/* Define this if you use jmemname.c */\n");
+  fprintf(outfile, "#undef DONT_USE_B_MODE\n");
+  fprintf(outfile, "/* #define PROGRESS_REPORT */	/* optional */\n");
+  fprintf(outfile, "\n#endif /* JPEG_CJPEG_DJPEG */\n");
+
+  /* Close the jconfig.h file */
+  fclose(outfile);
+
+  /* User report */
+  printf("Configuration check for Independent JPEG Group's software done.\n");
+  printf("\nI have written the jconfig.h file for you.\n\n");
+#ifdef HAVE_PROTOTYPES
+  printf("You should use makefile.ansi as the starting point for your Makefile.\n");
+#else
+  printf("You should use makefile.unix as the starting point for your Makefile.\n");
+#endif
+
+#ifdef NEED_SPECIAL_INCLUDE
+  printf("\nYou'll need to change jconfig.h to include the system include file\n");
+  printf("that you found type size_t in, or add a direct definition of type\n");
+  printf("size_t if that's what you used.  Just add it to the end.\n");
+#endif
+
+  return 0;
 }
diff --git a/coderules.doc b/coderules.doc
new file mode 100644
index 0000000..b28034e
--- /dev/null
+++ b/coderules.doc
@@ -0,0 +1,118 @@
+IJG JPEG LIBRARY:  CODING RULES
+
+Copyright (C) 1991-1994, 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.
+
+
+Since numerous people will be contributing code and bug fixes, it's important
+to establish a common coding style.  The goal of using similar coding styles
+is much more important than the details of just what that style is.
+
+In general we follow the recommendations of "Recommended C Style and Coding
+Standards" revision 6.1 (Cannon et al. as modified by Spencer, Keppel and
+Brader).  This document is available in the IJG FTP archive (see
+jpeg/doc/cstyle.ms.tbl.Z, or cstyle.txt.Z for those without nroff/tbl).
+
+Block comments should be laid out thusly:
+
+/*
+ *  Block comments in this style.
+ */
+
+We indent statements in K&R style, e.g.,
+	if (test) {
+	  then-part;
+	} else {
+	  else-part;
+	}
+with two spaces per indentation level.  (This indentation convention is
+handled automatically by GNU Emacs and many other text editors.)
+
+Multi-word names should be written in lower case with underscores, e.g.,
+multi_word_name (not multiWordName).  Preprocessor symbols and enum constants
+are similar but upper case (MULTI_WORD_NAME).  Names should be unique within
+the first fifteen characters.  (On some older systems, global names must be
+unique within six characters.  We accommodate this without cluttering the
+source code by using macros to substitute shorter names.)
+
+We use function prototypes everywhere; we rely on automatic source code
+transformation to feed prototype-less C compilers.  Transformation is done
+by the simple and portable tool 'ansi2knr.c' (courtesy of Ghostscript).
+ansi2knr is not very bright, so it imposes a format requirement on function
+declarations: the function name MUST BEGIN IN COLUMN 1.  Thus all functions
+should be written in the following style:
+
+LOCAL int *
+function_name (int a, char *b)
+{
+    code...
+}
+
+Note that each function definition is prefixed with GLOBAL, LOCAL, or
+METHODDEF.  These macros expand to "static" or nothing as appropriate.
+They provide a readable indication of the routine's usage and can readily be
+changed for special needs.  (For instance, all routines can be made global for
+use with debuggers or code profilers that require it.)
+
+ansi2knr does not transform method declarations (function pointers in
+structs).  We handle these with a macro JMETHOD, defined as
+	#ifdef HAVE_PROTOTYPES
+	#define JMETHOD(type,methodname,arglist)  type (*methodname) arglist
+	#else
+	#define JMETHOD(type,methodname,arglist)  type (*methodname) ()
+	#endif
+which is used like this:
+	struct function_pointers {
+	  JMETHOD(void, init_entropy_encoder, (int somearg, jparms *jp));
+	  JMETHOD(void, term_entropy_encoder, (void));
+	};
+Note the set of parentheses surrounding the parameter list.
+
+A similar solution is used for external function declarations (see the JPP
+macro).
+
+If the code is to work on non-ANSI compilers, we cannot rely on a prototype
+declaration to coerce actual parameters into the right types.  Therefore, use
+explicit casts on actual parameters whenever the actual parameter type is not
+identical to the formal parameter.  Beware of implicit conversions to "int".
+
+It seems there are some non-ANSI compilers in which the sizeof() operator
+is defined to return int, yet size_t is defined as long.  Needless to say,
+this is brain-damaged.  Always use the SIZEOF() macro in place of sizeof(),
+so that the result is guaranteed to be of type size_t.
+
+
+The JPEG library is intended to be used within larger programs.  Furthermore,
+we want it to be reentrant so that it can be used by applications that process
+multiple images concurrently.  The following rules support these requirements:
+
+1. Avoid direct use of file I/O, "malloc", error report printouts, etc;
+pass these through the common routines provided.
+
+2. Minimize global namespace pollution.  Functions should be declared static
+wherever possible.  (Note that our method-based calling conventions help this
+a lot: in many modules only the initialization function will ever need to be
+called directly, so only that function need be externally visible.)  All
+global function names should begin with "jpeg_", and should have an
+abbreviated name (unique in the first six characters) substituted by macro
+when NEED_SHORT_EXTERNAL_NAMES is set.
+
+3. Don't use global variables; anything that must be used in another module
+should be in the common data structures.
+
+4. Don't use static variables except for read-only constant tables.  Variables
+that should be private to a module can be placed into private structures (see
+the system architecture document, structure.doc).
+
+5. Source file names should begin with "j" for files that are part of the
+library proper; source files that are not part of the library, such as cjpeg.c
+and djpeg.c, do not begin with "j".  Keep source file names to eight
+characters (plus ".c" or ".h", etc) to make life easy for MS-DOSers.  Keep
+compression and decompression code in separate source files --- some
+applications may want only one half of the library.
+
+Note: these rules (particularly #4) are not followed religiously in the
+modules that are used in cjpeg/djpeg but are not part of the JPEG library
+proper.  Those modules are not really intended to be used in other
+applications.
diff --git a/codingrules b/codingrules
deleted file mode 100644
index fd6f700..0000000
--- a/codingrules
+++ /dev/null
@@ -1,99 +0,0 @@
-
-	JPEG SYSTEM CODING RULES		27-SEP-91
-
-Since numerous people will be contributing code and bug fixes, it's important
-to establish a common coding style.  The goal of using similar coding styles
-is much more important than the details of just what that style is.
-
-I suggest we follow the recommendations of "Recommended C Style and Coding
-Standards" revision 6.1 (Cannon et al. as modified by Spencer, Keppel and
-Brader).  I have placed a copy of this document in the jpeg FTP archive (see
-jpeg/doc/cstyle.ms.tbl.Z, or cstyle.txt.Z for those without nroff/tbl).
-
-Unless someone has a real strong objection, let's do block comments thusly:
-
-/*
- *  Block comments in this style.
- */
-
-and indent statements in K&R style, e.g.,
-
-	if (test) {
-	    then-part;
-	} else {
-	    else-part;
-	}
-
-I suggest that multi-word names be written in the style multi_word_name
-rather than multiWordName, but I am open to argument on this.
-
-
-I would like to use function prototypes everywhere, and rely on automatic
-source code transformation to feed non-ANSI C compilers.  The best tool
-I have so far found for this is 'ansi2knr.c', which is part of Ghostscript.
-ansi2knr is not very bright, so it imposes a format requirement on function
-declarations: the function name MUST BEGIN IN COLUMN 1.  Thus all functions
-should be written in the following style:
-
-static int *
-function_name (int a, char *b)
-{
-    code...
-}
-
-ansi2knr won't help with method declarations (function pointers in structs).
-I suggest we use a macro to declare method pointers, something like this:
-
-#ifdef PROTO
-#define METHOD(type,methodname,arglist)  type (*methodname) arglist
-#else
-#define METHOD(type,methodname,arglist)  type (*methodname) ()
-#endif
-
-which is used like this:
-
-struct function_pointers {
-	METHOD(void, init_entropy_encoder, (functptrs fptrs, jparms *jp));
-	METHOD(void, term_entropy_encoder, (void));
-};
-
-Note the set of parentheses surrounding the parameter list.
-
-A similar solution is used for external function declarations (see the PP
-macro in jpegdata.h).
-
-If the code is to work on non-ANSI compilers, you cannot rely on a prototype
-declaration to coerce actual parameters into the right types.  Therefore, use
-explicit casts on actual parameters whenever the actual parameter type is not
-identical to the formal parameter.  Beware of implicit conversions to "int".
-
-It seems there are some non-ANSI compilers in which the sizeof() operator
-is defined to return int, while size_t is defined as long.  Needless to say,
-this is brain-damaged.  Always use the SIZEOF() macro in place of sizeof(),
-so that the result is guaranteed to be of type size_t.
-
-
-We can expect that the JPEG compressor and decompressor will be incorporated
-into larger programs.  Therefore, the following rules are important:
-
-1. Avoid direct use of any file I/O, "malloc", error report printouts, etc;
-pass these through the common routines provided.
-
-2. Assume that the JPEG code may be invoked more than once per program run;
-therefore, do not rely on static initialization of variables, and be careful
-to release all allocated storage at the end of processing.
-
-3. Minimize global namespace pollution.  Functions should be declared static
-wherever possible.  (Note that our method-based calling conventions help this
-a lot: in many modules only the method-selector function will ever need to be
-called directly, so only that function need be externally visible.)  All
-global function names should begin with "j", and should be unique in the first
-six characters for portability reasons.
-Don't use global variables at all; anything that must be used in another
-module should be put into parameters (there'll be some large structs passed
-around for this purpose).
-
-4. Source file names should also begin with "j"; remember to keep them to
-eight characters (plus ".c" or ".h", etc) to make life easy for MS-DOSers.
-Do not put code for both compression and decompression into the same source
-file.
diff --git a/configure b/configure
new file mode 100755
index 0000000..0d62d68
--- /dev/null
+++ b/configure
@@ -0,0 +1,1168 @@
+#!/bin/sh
+# Guess values for system-dependent variables and create Makefiles.
+# Generated automatically using autoconf.
+# Copyright (C) 1991, 1992, 1993 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2, or (at your option)
+# any later version.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+
+# Usage: configure [--srcdir=DIR] [--host=HOST] [--gas] [--nfp]
+#        [--prefix=PREFIX] [--exec-prefix=PREFIX] [--with-PACKAGE[=VALUE]]
+# Ignores all args except --srcdir, --prefix, --exec-prefix, and
+# --with-PACKAGE[=VALUE] unless this script has special code to handle it.
+
+for arg
+do
+  # Handle --exec-prefix with a space before the argument.
+  if test x$next_exec_prefix = xyes; then exec_prefix=$arg; next_exec_prefix=
+  # Handle --host with a space before the argument.
+  elif test x$next_host = xyes; then next_host=
+  # Handle --prefix with a space before the argument.
+  elif test x$next_prefix = xyes; then prefix=$arg; next_prefix=
+  # Handle --srcdir with a space before the argument.
+  elif test x$next_srcdir = xyes; then srcdir=$arg; next_srcdir=
+  else
+    case $arg in
+     # For backward compatibility, recognize -exec-prefix and --exec_prefix.
+     -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* | --exec=* | --exe=* | --ex=* | --e=*)
+	exec_prefix=`echo $arg | sed 's/[-a-z_]*=//'` ;;
+     -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- | --exec | --exe | --ex | --e)
+	next_exec_prefix=yes ;;
+
+     -gas | --gas | --ga | --g) ;;
+
+     -host=* | --host=* | --hos=* | --ho=* | --h=*) ;;
+     -host | --host | --hos | --ho | --h)
+	next_host=yes ;;
+
+     -nfp | --nfp | --nf) ;;
+
+     -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
+	prefix=`echo $arg | sed 's/[-a-z_]*=//'` ;;
+     -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
+	next_prefix=yes ;;
+
+     -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=* | --s=*)
+	srcdir=`echo $arg | sed 's/[-a-z_]*=//'` ;;
+     -srcdir | --srcdir | --srcdi | --srcd | --src | --sr | --s)
+	next_srcdir=yes ;;
+
+     -with-* | --with-*)
+       package=`echo $arg|sed -e 's/-*with-//' -e 's/=.*//'`
+       # Reject names that aren't valid shell variable names.
+       if test -n "`echo $package| sed 's/[-a-zA-Z0-9_]//g'`"; then
+         echo "configure: $package: invalid package name" >&2; exit 1
+       fi
+       package=`echo $package| sed 's/-/_/g'`
+       case "$arg" in
+         *=*) val="`echo $arg|sed 's/[^=]*=//'`" ;;
+         *) val=1 ;;
+       esac
+       eval "with_$package='$val'" ;;
+
+     -v | -verbose | --verbose | --verbos | --verbo | --verb | --ver | --ve | --v)
+       verbose=yes ;;
+
+     *=*)
+       varname=`echo $arg|sed -e 's/=.*//'`
+       # Reject names that aren't valid shell variable names.
+       if test -n "`echo $varname| sed 's/[a-zA-Z0-9_]//g'`"; then
+         echo "configure: $varname: invalid shell variable name" >&2; exit 1
+       fi
+       val="`echo $arg|sed 's/[^=]*=//'`"
+       test -n "$verbose" && echo "	setting shell variable $varname to $val"
+       eval "$varname='$val'"
+       eval "export $varname" ;;
+
+     *) ;;
+    esac
+  fi
+done
+
+trap 'rm -fr conftest* confdefs* core; exit 1' 1 3 15
+trap 'rm -f confdefs*' 0
+
+# NLS nuisances.
+# These must not be set unconditionally because not all systems understand
+# e.g. LANG=C (notably SCO).
+if test "${LC_ALL+set}" = 'set' ; then LC_ALL=C; export LC_ALL; fi
+if test "${LANG+set}"   = 'set' ; then LANG=C;   export LANG;   fi
+
+rm -f conftest* confdefs.h
+# AIX cpp loses on an empty file, so make sure it contains at least a newline.
+echo > confdefs.h
+compile='${CC-cc} $CFLAGS conftest.c -o conftest $LIBS >/dev/null 2>&1'
+
+# A filename unique to this package, relative to the directory that
+# configure is in, which we can look for to find out if srcdir is correct.
+unique_file=jcmaster.c
+
+# Find the source files, if location was not specified.
+if test -z "$srcdir"; then
+  srcdirdefaulted=yes
+  # Try the directory containing this script, then `..'.
+  prog=$0
+  confdir=`echo $prog|sed 's%/[^/][^/]*$%%'`
+  test "X$confdir" = "X$prog" && confdir=.
+  srcdir=$confdir
+  if test ! -r $srcdir/$unique_file; then
+    srcdir=..
+  fi
+fi
+if test ! -r $srcdir/$unique_file; then
+  if test x$srcdirdefaulted = xyes; then
+    echo "configure: Can not find sources in \`${confdir}' or \`..'." 1>&2
+  else
+    echo "configure: Can not find sources in \`${srcdir}'." 1>&2
+  fi
+  exit 1
+fi
+# Preserve a srcdir of `.' to avoid automounter screwups with pwd.
+# But we can't avoid them for `..', to make subdirectories work.
+case $srcdir in
+  .|/*|~*) ;;
+  *) srcdir=`cd $srcdir; pwd` ;; # Make relative path absolute.
+esac
+
+
+# Save the original args to write them into config.status later.
+configure_args="$*"
+
+
+if test -z "$CC"; then
+  # Extract the first word of `gcc', so it can be a program name with args.
+  set dummy gcc; word=$2
+  echo checking for $word
+  IFS="${IFS= 	}"; saveifs="$IFS"; IFS="${IFS}:"
+  for dir in $PATH; do
+    test -z "$dir" && dir=.
+    if test -f $dir/$word; then
+      CC="gcc"
+      break
+    fi
+  done
+  IFS="$saveifs"
+fi
+test -z "$CC" && CC="cc"
+test -n "$CC" && test -n "$verbose" && echo "	setting CC to $CC"
+
+# Find out if we are using GNU C, under whatever name.
+cat > conftest.c <<EOF
+#ifdef __GNUC__
+  yes
+#endif
+EOF
+${CC-cc} -E conftest.c > conftest.out 2>&1
+if egrep yes conftest.out >/dev/null 2>&1; then
+  GCC=1 # For later tests.
+fi
+rm -f conftest*
+
+echo checking how to run the C preprocessor
+if test -z "$CPP"; then
+  # This must be in double quotes, not single quotes, because CPP may get
+  # substituted into the Makefile and ``${CC-cc}'' will simply confuse
+  # make.  It must be expanded now.
+  CPP="${CC-cc} -E"
+  cat > conftest.c <<EOF
+#include "confdefs.h"
+#include <stdio.h>
+Syntax Error
+EOF
+err=`eval "($CPP conftest.c >/dev/null) 2>&1"`
+if test -z "$err"; then
+  :
+else
+  rm -rf conftest*
+  CPP=/lib/cpp
+fi
+rm -f conftest*
+fi
+test ".${verbose}" != "." && echo "	setting CPP to $CPP"
+
+echo checking whether cross-compiling
+# If we cannot run a trivial program, we must be cross compiling.
+cat > conftest.c <<EOF
+#include "confdefs.h"
+main(){exit(0);}
+EOF
+eval $compile
+if test -s conftest && (./conftest; exit) 2>/dev/null; then
+  :
+else
+  cross_compiling=1
+fi
+rm -fr conftest*
+
+echo checking for function prototypes
+cat > conftest.c <<EOF
+#include "confdefs.h"
+
+int testfunction (int arg1, int * arg2); /* check prototypes */
+struct methods_struct {		/* check method-pointer declarations */
+  int (*error_exit) (char *msgtext);
+  int (*trace_message) (char *msgtext);
+  int (*another_method) (void);
+};
+int testfunction (int arg1, int * arg2) /* check definitions */
+{ return arg2[arg1]; }
+int test2function (void)	/* check void arg list */
+{ return 0; }
+
+int main() { exit(0); }
+int t() {   }
+EOF
+if eval $compile; then
+  rm -rf conftest*
+  
+{
+test -n "$verbose" && \
+echo "	defining" HAVE_PROTOTYPES to be empty
+echo "#define" HAVE_PROTOTYPES  >> confdefs.h
+DEFS="$DEFS -DHAVE_PROTOTYPES="
+SEDDEFS="${SEDDEFS}\${SEDdA}HAVE_PROTOTYPES\${SEDdB}HAVE_PROTOTYPES\${SEDdC}\${SEDdD}
+\${SEDuA}HAVE_PROTOTYPES\${SEDuB}HAVE_PROTOTYPES\${SEDuC}\${SEDuD}
+\${SEDeA}HAVE_PROTOTYPES\${SEDeB}HAVE_PROTOTYPES\${SEDeC}\${SEDeD}
+"
+}
+
+
+else
+  rm -rf conftest*
+  echo Your compiler does not seem to know about function prototypes.
+echo Perhaps it needs a special switch to enable ANSI C mode.
+echo If so, we recommend running configure like this:
+echo "   ./configure  CC='cc -switch'"
+echo where -switch is the proper switch.
+
+fi
+rm -f conftest*
+echo checking for stddef.h
+cat > conftest.c <<EOF
+#include "confdefs.h"
+#include <stddef.h>
+EOF
+err=`eval "($CPP conftest.c >/dev/null) 2>&1"`
+if test -z "$err"; then
+  rm -rf conftest*
+  
+{
+test -n "$verbose" && \
+echo "	defining" HAVE_STDDEF_H to be empty
+echo "#define" HAVE_STDDEF_H  >> confdefs.h
+DEFS="$DEFS -DHAVE_STDDEF_H="
+SEDDEFS="${SEDDEFS}\${SEDdA}HAVE_STDDEF_H\${SEDdB}HAVE_STDDEF_H\${SEDdC}\${SEDdD}
+\${SEDuA}HAVE_STDDEF_H\${SEDuB}HAVE_STDDEF_H\${SEDuC}\${SEDuD}
+\${SEDeA}HAVE_STDDEF_H\${SEDeB}HAVE_STDDEF_H\${SEDeC}\${SEDeD}
+"
+}
+
+
+fi
+rm -f conftest*
+
+echo checking for stdlib.h
+cat > conftest.c <<EOF
+#include "confdefs.h"
+#include <stdlib.h>
+EOF
+err=`eval "($CPP conftest.c >/dev/null) 2>&1"`
+if test -z "$err"; then
+  rm -rf conftest*
+  
+{
+test -n "$verbose" && \
+echo "	defining" HAVE_STDLIB_H to be empty
+echo "#define" HAVE_STDLIB_H  >> confdefs.h
+DEFS="$DEFS -DHAVE_STDLIB_H="
+SEDDEFS="${SEDDEFS}\${SEDdA}HAVE_STDLIB_H\${SEDdB}HAVE_STDLIB_H\${SEDdC}\${SEDdD}
+\${SEDuA}HAVE_STDLIB_H\${SEDuB}HAVE_STDLIB_H\${SEDuC}\${SEDuD}
+\${SEDeA}HAVE_STDLIB_H\${SEDeB}HAVE_STDLIB_H\${SEDeC}\${SEDeD}
+"
+}
+
+
+fi
+rm -f conftest*
+
+echo checking for string.h
+cat > conftest.c <<EOF
+#include "confdefs.h"
+#include <string.h>
+EOF
+err=`eval "($CPP conftest.c >/dev/null) 2>&1"`
+if test -z "$err"; then
+  :
+else
+  rm -rf conftest*
+  
+{
+test -n "$verbose" && \
+echo "	defining" NEED_BSD_STRINGS to be empty
+echo "#define" NEED_BSD_STRINGS  >> confdefs.h
+DEFS="$DEFS -DNEED_BSD_STRINGS="
+SEDDEFS="${SEDDEFS}\${SEDdA}NEED_BSD_STRINGS\${SEDdB}NEED_BSD_STRINGS\${SEDdC}\${SEDdD}
+\${SEDuA}NEED_BSD_STRINGS\${SEDuB}NEED_BSD_STRINGS\${SEDuC}\${SEDuD}
+\${SEDeA}NEED_BSD_STRINGS\${SEDeB}NEED_BSD_STRINGS\${SEDeC}\${SEDeD}
+"
+}
+
+fi
+rm -f conftest*
+
+echo checking for size_t
+cat > conftest.c <<EOF
+#include "confdefs.h"
+
+#ifdef HAVE_STDDEF_H
+#include <stddef.h>
+#endif
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
+#endif
+#include <stdio.h>
+#ifdef NEED_BSD_STRINGS
+#include <strings.h>
+#else
+#include <string.h>
+#endif
+typedef size_t my_size_t;
+
+int main() { exit(0); }
+int t() {  my_size_t foovar;  }
+EOF
+if eval $compile; then
+  :
+else
+  rm -rf conftest*
+  echo checking for sys/types.h
+cat > conftest.c <<EOF
+#include "confdefs.h"
+#include <sys/types.h>
+EOF
+err=`eval "($CPP conftest.c >/dev/null) 2>&1"`
+if test -z "$err"; then
+  rm -rf conftest*
+  
+{
+test -n "$verbose" && \
+echo "	defining" NEED_SYS_TYPES_H to be empty
+echo "#define" NEED_SYS_TYPES_H  >> confdefs.h
+DEFS="$DEFS -DNEED_SYS_TYPES_H="
+SEDDEFS="${SEDDEFS}\${SEDdA}NEED_SYS_TYPES_H\${SEDdB}NEED_SYS_TYPES_H\${SEDdC}\${SEDdD}
+\${SEDuA}NEED_SYS_TYPES_H\${SEDuB}NEED_SYS_TYPES_H\${SEDuC}\${SEDuD}
+\${SEDeA}NEED_SYS_TYPES_H\${SEDeB}NEED_SYS_TYPES_H\${SEDeC}\${SEDeD}
+"
+}
+
+
+else
+  rm -rf conftest*
+  echo Type size_t is not defined in any of the usual places.
+echo Try putting '"typedef unsigned int size_t;"' in jconfig.h.
+
+fi
+rm -f conftest*
+
+fi
+rm -f conftest*
+echo checking for unsigned char
+cat > conftest.c <<EOF
+#include "confdefs.h"
+
+int main() { exit(0); }
+int t() {  unsigned char un_char;  }
+EOF
+if eval $compile; then
+  rm -rf conftest*
+  
+{
+test -n "$verbose" && \
+echo "	defining" HAVE_UNSIGNED_CHAR to be empty
+echo "#define" HAVE_UNSIGNED_CHAR  >> confdefs.h
+DEFS="$DEFS -DHAVE_UNSIGNED_CHAR="
+SEDDEFS="${SEDDEFS}\${SEDdA}HAVE_UNSIGNED_CHAR\${SEDdB}HAVE_UNSIGNED_CHAR\${SEDdC}\${SEDdD}
+\${SEDuA}HAVE_UNSIGNED_CHAR\${SEDuB}HAVE_UNSIGNED_CHAR\${SEDuC}\${SEDuD}
+\${SEDeA}HAVE_UNSIGNED_CHAR\${SEDeB}HAVE_UNSIGNED_CHAR\${SEDeC}\${SEDeD}
+"
+}
+
+
+fi
+rm -f conftest*
+echo checking for unsigned short
+cat > conftest.c <<EOF
+#include "confdefs.h"
+
+int main() { exit(0); }
+int t() {  unsigned short un_short;  }
+EOF
+if eval $compile; then
+  rm -rf conftest*
+  
+{
+test -n "$verbose" && \
+echo "	defining" HAVE_UNSIGNED_SHORT to be empty
+echo "#define" HAVE_UNSIGNED_SHORT  >> confdefs.h
+DEFS="$DEFS -DHAVE_UNSIGNED_SHORT="
+SEDDEFS="${SEDDEFS}\${SEDdA}HAVE_UNSIGNED_SHORT\${SEDdB}HAVE_UNSIGNED_SHORT\${SEDdC}\${SEDdD}
+\${SEDuA}HAVE_UNSIGNED_SHORT\${SEDuB}HAVE_UNSIGNED_SHORT\${SEDuC}\${SEDuD}
+\${SEDeA}HAVE_UNSIGNED_SHORT\${SEDeB}HAVE_UNSIGNED_SHORT\${SEDeC}\${SEDeD}
+"
+}
+
+
+fi
+rm -f conftest*
+echo checking for type void
+cat > conftest.c <<EOF
+#include "confdefs.h"
+
+/* Caution: a C++ compiler will insist on valid prototypes */
+typedef void * void_ptr;	/* check void * */
+#ifdef HAVE_PROTOTYPES		/* check ptr to function returning void */
+typedef void (*void_func) (int a, int b);
+#else
+typedef void (*void_func) ();
+#endif
+
+#ifdef HAVE_PROTOTYPES		/* check void function result */
+void test3function (void_ptr arg1, void_func arg2)
+#else
+void test3function (arg1, arg2)
+     void_ptr arg1;
+     void_func arg2;
+#endif
+{
+  char * locptr = (char *) arg1; /* check casting to and from void * */
+  arg1 = (void *) locptr;
+  (*arg2) (1, 2);		/* check call of fcn returning void */
+}
+
+int main() { exit(0); }
+int t() {   }
+EOF
+if eval $compile; then
+  :
+else
+  rm -rf conftest*
+  
+{
+test -n "$verbose" && \
+echo "	defining" void to be char
+echo "#define" void char >> confdefs.h
+DEFS="$DEFS -Dvoid=char"
+SEDDEFS="${SEDDEFS}\${SEDdA}void\${SEDdB}void\${SEDdC}char\${SEDdD}
+\${SEDuA}void\${SEDuB}void\${SEDuC}char\${SEDuD}
+\${SEDeA}void\${SEDeB}void\${SEDeC}char\${SEDeD}
+"
+}
+
+fi
+rm -f conftest*
+prog='/* Ultrix mips cc rejects this.  */
+typedef int charset[2]; const charset x;
+/* SunOS 4.1.1 cc rejects this.  */
+char const *const *ccp;
+char **p;
+/* AIX XL C 1.02.0.0 rejects this.
+   It does not let you subtract one const X* pointer from another in an arm
+   of an if-expression whose if-part is not a constant expression */
+const char *g = "string";
+ccp = &g + (g ? g-g : 0);
+/* HPUX 7.0 cc rejects these. */
+++ccp;
+p = (char**) ccp;
+ccp = (char const *const *) p;
+{ /* SCO 3.2v4 cc rejects this.  */
+  char *t;
+  char const *s = 0 ? (char *) 0 : (char const *) 0;
+
+  *t++ = 0;
+}
+{ /* Someone thinks the Sun supposedly-ANSI compiler will reject this.  */
+  int x[] = {25,17};
+  const int *foo = &x[0];
+  ++foo;
+}
+{ /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */
+  typedef const int *iptr;
+  iptr p = 0;
+  ++p;
+}
+{ /* AIX XL C 1.02.0.0 rejects this saying
+     "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */
+  struct s { int j; const int *ap[3]; };
+  struct s *b; b->j = 5;
+}
+{ /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */
+  const int foo = 10;
+}'
+echo checking for lack of working const
+cat > conftest.c <<EOF
+#include "confdefs.h"
+
+int main() { exit(0); }
+int t() { $prog }
+EOF
+if eval $compile; then
+  :
+else
+  rm -rf conftest*
+  
+{
+test -n "$verbose" && \
+echo "	defining" const to be empty
+echo "#define" const  >> confdefs.h
+DEFS="$DEFS -Dconst="
+SEDDEFS="${SEDDEFS}\${SEDdA}const\${SEDdB}const\${SEDdC}\${SEDdD}
+\${SEDuA}const\${SEDuB}const\${SEDuC}\${SEDuD}
+\${SEDeA}const\${SEDeB}const\${SEDeC}\${SEDeD}
+"
+}
+
+fi
+rm -f conftest*
+
+echo checking for inline
+cat > conftest.c <<EOF
+#include "confdefs.h"
+
+int main() { exit(0); }
+int t() { } inline int foo() { return 0; }
+int bar() { return foo(); }
+EOF
+if eval $compile; then
+  rm -rf conftest*
+  
+{
+test -n "$verbose" && \
+echo "	defining" INLINE to be inline
+echo "#define" INLINE inline >> confdefs.h
+DEFS="$DEFS -DINLINE=inline"
+SEDDEFS="${SEDDEFS}\${SEDdA}INLINE\${SEDdB}INLINE\${SEDdC}inline\${SEDdD}
+\${SEDuA}INLINE\${SEDuB}INLINE\${SEDuC}inline\${SEDuD}
+\${SEDeA}INLINE\${SEDeB}INLINE\${SEDeC}inline\${SEDeD}
+"
+}
+
+
+else
+  rm -rf conftest*
+  cat > conftest.c <<EOF
+#include "confdefs.h"
+
+int main() { exit(0); }
+int t() { } __inline__ int foo() { return 0; }
+int bar() { return foo(); }
+EOF
+if eval $compile; then
+  rm -rf conftest*
+  
+{
+test -n "$verbose" && \
+echo "	defining" INLINE to be __inline__
+echo "#define" INLINE __inline__ >> confdefs.h
+DEFS="$DEFS -DINLINE=__inline__"
+SEDDEFS="${SEDDEFS}\${SEDdA}INLINE\${SEDdB}INLINE\${SEDdC}__inline__\${SEDdD}
+\${SEDuA}INLINE\${SEDuB}INLINE\${SEDuC}__inline__\${SEDuD}
+\${SEDeA}INLINE\${SEDeB}INLINE\${SEDeC}__inline__\${SEDeD}
+"
+}
+
+
+else
+  rm -rf conftest*
+  cat > conftest.c <<EOF
+#include "confdefs.h"
+
+int main() { exit(0); }
+int t() { } __inline int foo() { return 0; }
+int bar() { return foo(); }
+EOF
+if eval $compile; then
+  rm -rf conftest*
+  
+{
+test -n "$verbose" && \
+echo "	defining" INLINE to be __inline
+echo "#define" INLINE __inline >> confdefs.h
+DEFS="$DEFS -DINLINE=__inline"
+SEDDEFS="${SEDDEFS}\${SEDdA}INLINE\${SEDdB}INLINE\${SEDdC}__inline\${SEDdD}
+\${SEDuA}INLINE\${SEDuB}INLINE\${SEDuC}__inline\${SEDuD}
+\${SEDeA}INLINE\${SEDeB}INLINE\${SEDeC}__inline\${SEDeD}
+"
+}
+
+
+else
+  rm -rf conftest*
+  
+{
+test -n "$verbose" && \
+echo "	defining" INLINE to be empty
+echo "#define" INLINE  >> confdefs.h
+DEFS="$DEFS -DINLINE="
+SEDDEFS="${SEDDEFS}\${SEDdA}INLINE\${SEDdB}INLINE\${SEDdC}\${SEDdD}
+\${SEDuA}INLINE\${SEDuB}INLINE\${SEDuC}\${SEDuD}
+\${SEDeA}INLINE\${SEDeB}INLINE\${SEDeC}\${SEDeD}
+"
+}
+
+fi
+rm -f conftest*
+
+fi
+rm -f conftest*
+
+fi
+rm -f conftest*
+echo checking for broken incomplete types
+cat > conftest.c <<EOF
+#include "confdefs.h"
+ typedef struct undefined_structure * undef_struct_ptr; 
+int main() { exit(0); }
+int t() {  }
+EOF
+if eval $compile; then
+  :
+else
+  rm -rf conftest*
+  
+{
+test -n "$verbose" && \
+echo "	defining" INCOMPLETE_TYPES_BROKEN to be empty
+echo "#define" INCOMPLETE_TYPES_BROKEN  >> confdefs.h
+DEFS="$DEFS -DINCOMPLETE_TYPES_BROKEN="
+SEDDEFS="${SEDDEFS}\${SEDdA}INCOMPLETE_TYPES_BROKEN\${SEDdB}INCOMPLETE_TYPES_BROKEN\${SEDdC}\${SEDdD}
+\${SEDuA}INCOMPLETE_TYPES_BROKEN\${SEDuB}INCOMPLETE_TYPES_BROKEN\${SEDuC}\${SEDuD}
+\${SEDeA}INCOMPLETE_TYPES_BROKEN\${SEDeB}INCOMPLETE_TYPES_BROKEN\${SEDeC}\${SEDeD}
+"
+}
+
+fi
+rm -f conftest*
+echo checking for short external names
+cat > conftest.c <<EOF
+#include "confdefs.h"
+
+int possibly_duplicate_function () { return 0; }
+int possibly_dupli_function () { return 1; }
+
+int main() { exit(0); }
+int t() {   }
+EOF
+if eval $compile; then
+  :
+else
+  rm -rf conftest*
+  
+{
+test -n "$verbose" && \
+echo "	defining" NEED_SHORT_EXTERNAL_NAMES to be empty
+echo "#define" NEED_SHORT_EXTERNAL_NAMES  >> confdefs.h
+DEFS="$DEFS -DNEED_SHORT_EXTERNAL_NAMES="
+SEDDEFS="${SEDDEFS}\${SEDdA}NEED_SHORT_EXTERNAL_NAMES\${SEDdB}NEED_SHORT_EXTERNAL_NAMES\${SEDdC}\${SEDdD}
+\${SEDuA}NEED_SHORT_EXTERNAL_NAMES\${SEDuB}NEED_SHORT_EXTERNAL_NAMES\${SEDuC}\${SEDuD}
+\${SEDeA}NEED_SHORT_EXTERNAL_NAMES\${SEDeB}NEED_SHORT_EXTERNAL_NAMES\${SEDeC}\${SEDeD}
+"
+}
+
+fi
+rm -f conftest*
+
+echo checking to see if char is signed
+if test -n "$cross_compiling"
+then
+  echo Assuming that char is signed on target machine.
+echo If it is unsigned, this will be a little bit inefficient.
+
+else
+cat > conftest.c <<EOF
+#include "confdefs.h"
+
+#ifdef HAVE_PROTOTYPES
+int is_char_signed (int arg)
+#else
+int is_char_signed (arg)
+     int arg;
+#endif
+{
+  if (arg == 189) {		/* expected result for unsigned char */
+    return 0;			/* type char is unsigned */
+  }
+  else if (arg != -67) {	/* expected result for signed char */
+    printf("Hmm, it seems 'char' is not eight bits wide on your machine.\n");
+    printf("I fear the JPEG software will not work at all.\n\n");
+  }
+  return 1;			/* assume char is signed otherwise */
+}
+char signed_char_check = (char) (-67);
+main() {
+  exit(is_char_signed((int) signed_char_check));
+}
+EOF
+eval $compile
+if test -s conftest && (./conftest; exit) 2>/dev/null; then
+  
+{
+test -n "$verbose" && \
+echo "	defining" CHAR_IS_UNSIGNED to be empty
+echo "#define" CHAR_IS_UNSIGNED  >> confdefs.h
+DEFS="$DEFS -DCHAR_IS_UNSIGNED="
+SEDDEFS="${SEDDEFS}\${SEDdA}CHAR_IS_UNSIGNED\${SEDdB}CHAR_IS_UNSIGNED\${SEDdC}\${SEDdD}
+\${SEDuA}CHAR_IS_UNSIGNED\${SEDuB}CHAR_IS_UNSIGNED\${SEDuC}\${SEDuD}
+\${SEDeA}CHAR_IS_UNSIGNED\${SEDeB}CHAR_IS_UNSIGNED\${SEDeC}\${SEDeD}
+"
+}
+
+
+fi
+fi
+rm -fr conftest*
+echo checking to see if right shift is signed
+if test -n "$cross_compiling"
+then
+  echo Assuming that right shift is signed on target machine.
+
+else
+cat > conftest.c <<EOF
+#include "confdefs.h"
+
+#ifdef HAVE_PROTOTYPES
+int is_shifting_signed (long arg)
+#else
+int is_shifting_signed (arg)
+     long arg;
+#endif
+/* See whether right-shift on a long is signed or not. */
+{
+  long res = arg >> 4;
+
+  if (res == -0x7F7E80CL) {	/* expected result for signed shift */
+    return 1;			/* right shift is signed */
+  }
+  /* see if unsigned-shift hack will fix it. */
+  /* we can't just test exact value since it depends on width of long... */
+  res |= (~0L) << (32-4);
+  if (res == -0x7F7E80CL) {	/* expected result now? */
+    return 0;			/* right shift is unsigned */
+  }
+  printf("Right shift isn't acting as I expect it to.\n");
+  printf("I fear the JPEG software will not work at all.\n\n");
+  return 0;			/* try it with unsigned anyway */
+}
+main() {
+  exit(is_shifting_signed(-0x7F7E80B1L));
+}
+EOF
+eval $compile
+if test -s conftest && (./conftest; exit) 2>/dev/null; then
+  
+{
+test -n "$verbose" && \
+echo "	defining" RIGHT_SHIFT_IS_UNSIGNED to be empty
+echo "#define" RIGHT_SHIFT_IS_UNSIGNED  >> confdefs.h
+DEFS="$DEFS -DRIGHT_SHIFT_IS_UNSIGNED="
+SEDDEFS="${SEDDEFS}\${SEDdA}RIGHT_SHIFT_IS_UNSIGNED\${SEDdB}RIGHT_SHIFT_IS_UNSIGNED\${SEDdC}\${SEDdD}
+\${SEDuA}RIGHT_SHIFT_IS_UNSIGNED\${SEDuB}RIGHT_SHIFT_IS_UNSIGNED\${SEDuC}\${SEDuD}
+\${SEDeA}RIGHT_SHIFT_IS_UNSIGNED\${SEDeB}RIGHT_SHIFT_IS_UNSIGNED\${SEDeC}\${SEDeD}
+"
+}
+
+
+fi
+fi
+rm -fr conftest*
+echo checking to see if fopen accepts b spec
+if test -n "$cross_compiling"
+then
+  echo Assuming that it does.
+
+else
+cat > conftest.c <<EOF
+#include "confdefs.h"
+
+#include <stdio.h>
+main() {
+  if (fopen("conftestdata", "wb") != NULL)
+    exit(0);
+  exit(1);
+}
+EOF
+eval $compile
+if test -s conftest && (./conftest; exit) 2>/dev/null; then
+  :
+else
+  
+{
+test -n "$verbose" && \
+echo "	defining" DONT_USE_B_MODE to be empty
+echo "#define" DONT_USE_B_MODE  >> confdefs.h
+DEFS="$DEFS -DDONT_USE_B_MODE="
+SEDDEFS="${SEDDEFS}\${SEDdA}DONT_USE_B_MODE\${SEDdB}DONT_USE_B_MODE\${SEDdC}\${SEDdD}
+\${SEDuA}DONT_USE_B_MODE\${SEDuB}DONT_USE_B_MODE\${SEDuC}\${SEDuD}
+\${SEDeA}DONT_USE_B_MODE\${SEDeB}DONT_USE_B_MODE\${SEDeC}\${SEDeD}
+"
+}
+
+fi
+fi
+rm -fr conftest*
+# Make sure to not get the incompatible SysV /etc/install and
+# /usr/sbin/install, which might be in PATH before a BSD-like install,
+# or the SunOS /usr/etc/install directory, or the AIX /bin/install,
+# or the AFS install, which mishandles nonexistent args, or
+# /usr/ucb/install on SVR4, which tries to use the nonexistent group
+# `staff'.  On most BSDish systems install is in /usr/bin, not /usr/ucb
+# anyway.  Sigh.
+if test "z${INSTALL}" = "z" ; then
+  echo checking for install
+  IFS="${IFS= 	}"; saveifs="$IFS"; IFS="${IFS}:"
+  for dir in $PATH; do
+    test -z "$dir" && dir=.
+    case $dir in
+    /etc|/usr/sbin|/usr/etc|/usr/afsws/bin|/usr/ucb) ;;
+    *)
+      if test -f $dir/installbsd; then
+	INSTALL="$dir/installbsd -c" # OSF1
+	INSTALL_PROGRAM='$(INSTALL)'
+	INSTALL_DATA='$(INSTALL) -m 644'
+	break
+      fi
+      if test -f $dir/install; then
+	if grep dspmsg $dir/install >/dev/null 2>&1; then
+	  : # AIX
+	else
+	  INSTALL="$dir/install -c"
+	  INSTALL_PROGRAM='$(INSTALL)'
+	  INSTALL_DATA='$(INSTALL) -m 644'
+	  break
+	fi
+      fi
+      ;;
+    esac
+  done
+  IFS="$saveifs"
+fi
+INSTALL=${INSTALL-cp}
+test -n "$verbose" && echo "	setting INSTALL to $INSTALL"
+INSTALL_PROGRAM=${INSTALL_PROGRAM-'$(INSTALL)'}
+test -n "$verbose" && echo "	setting INSTALL_PROGRAM to $INSTALL_PROGRAM"
+INSTALL_DATA=${INSTALL_DATA-'$(INSTALL)'}
+test -n "$verbose" && echo "	setting INSTALL_DATA to $INSTALL_DATA"
+
+if test -z "$RANLIB"; then
+  # Extract the first word of `ranlib', so it can be a program name with args.
+  set dummy ranlib; word=$2
+  echo checking for $word
+  IFS="${IFS= 	}"; saveifs="$IFS"; IFS="${IFS}:"
+  for dir in $PATH; do
+    test -z "$dir" && dir=.
+    if test -f $dir/$word; then
+      RANLIB="ranlib"
+      break
+    fi
+  done
+  IFS="$saveifs"
+fi
+test -z "$RANLIB" && RANLIB=":"
+test -n "$RANLIB" && test -n "$verbose" && echo "	setting RANLIB to $RANLIB"
+
+# check whether --with-maxmem was given
+withval="$with_maxmem"
+if test -n "$withval"; then
+  DEFAULTMAXMEM=`expr $withval \* 1048576`
+
+{
+test -n "$verbose" && \
+echo "	defining" DEFAULT_MAX_MEM to be ${DEFAULTMAXMEM}
+echo "#define" DEFAULT_MAX_MEM ${DEFAULTMAXMEM} >> confdefs.h
+DEFS="$DEFS -DDEFAULT_MAX_MEM=${DEFAULTMAXMEM}"
+SEDDEFS="${SEDDEFS}\${SEDdA}DEFAULT_MAX_MEM\${SEDdB}DEFAULT_MAX_MEM\${SEDdC}${DEFAULTMAXMEM}\${SEDdD}
+\${SEDuA}DEFAULT_MAX_MEM\${SEDuB}DEFAULT_MAX_MEM\${SEDuC}${DEFAULTMAXMEM}\${SEDuD}
+\${SEDeA}DEFAULT_MAX_MEM\${SEDeB}DEFAULT_MAX_MEM\${SEDeC}${DEFAULTMAXMEM}\${SEDeD}
+"
+}
+
+echo checking for 'tmpfile()'
+cat > conftest.c <<EOF
+#include "confdefs.h"
+#include <stdio.h>
+int main() { exit(0); }
+int t() {  FILE * tfile = tmpfile();  }
+EOF
+if eval $compile; then
+  rm -rf conftest*
+  MEMORYMGR="jmemansi.o"
+
+else
+  rm -rf conftest*
+  MEMORYMGR="jmemname.o"
+
+{
+test -n "$verbose" && \
+echo "	defining" NEED_SIGNAL_CATCHER to be empty
+echo "#define" NEED_SIGNAL_CATCHER  >> confdefs.h
+DEFS="$DEFS -DNEED_SIGNAL_CATCHER="
+SEDDEFS="${SEDDEFS}\${SEDdA}NEED_SIGNAL_CATCHER\${SEDdB}NEED_SIGNAL_CATCHER\${SEDdC}\${SEDdD}
+\${SEDuA}NEED_SIGNAL_CATCHER\${SEDuB}NEED_SIGNAL_CATCHER\${SEDuC}\${SEDuD}
+\${SEDeA}NEED_SIGNAL_CATCHER\${SEDeB}NEED_SIGNAL_CATCHER\${SEDeC}\${SEDeD}
+"
+}
+echo checking for 'mktemp()'
+cat > conftest.c <<EOF
+#include "confdefs.h"
+
+int main() { exit(0); }
+int t() {  char fname[80]; mktemp(fname);  }
+EOF
+if eval $compile; then
+  :
+else
+  rm -rf conftest*
+  
+{
+test -n "$verbose" && \
+echo "	defining" NO_MKTEMP to be empty
+echo "#define" NO_MKTEMP  >> confdefs.h
+DEFS="$DEFS -DNO_MKTEMP="
+SEDDEFS="${SEDDEFS}\${SEDdA}NO_MKTEMP\${SEDdB}NO_MKTEMP\${SEDdC}\${SEDdD}
+\${SEDuA}NO_MKTEMP\${SEDuB}NO_MKTEMP\${SEDuC}\${SEDuD}
+\${SEDeA}NO_MKTEMP\${SEDeB}NO_MKTEMP\${SEDeC}\${SEDeD}
+"
+}
+
+fi
+rm -f conftest*
+
+fi
+rm -f conftest*
+
+else
+  MEMORYMGR="jmemnobs.o"
+fi
+
+# Prepare to massage makefile.auto correctly.
+case "$DEFS" in
+  *HAVE_PROTOTYPES*)
+	ANSI2KNR=""
+	ISANSICOM="# "
+	;;
+  *)
+	ANSI2KNR="ansi2knr"
+	ISANSICOM=""
+	;;
+esac
+case "$DEFS" in
+  *NEED_BSD_STRINGS*)
+	ANSI2KNRFLAGS="-DBSD"
+	;;
+  *)
+	ANSI2KNRFLAGS=""
+	;;
+esac
+# Set default prefixes.
+if test -n "$prefix"; then
+  test -z "$exec_prefix" && exec_prefix='${prefix}'
+  prsub="s%^prefix\\([ 	]*\\)=\\([ 	]*\\).*$%prefix\\1=\\2$prefix%"
+fi
+if test -n "$exec_prefix"; then
+  prsub="$prsub
+s%^exec_prefix\\([ 	]*\\)=\\([ 	]*\\).*$%exec_prefix\\1=\\2$exec_prefix%"
+fi
+# Quote sed substitution magic chars in DEFS.
+cat >conftest.def <<EOF
+$DEFS
+EOF
+escape_ampersand_and_backslash='s%[&\\]%\\&%g'
+DEFS=`sed "$escape_ampersand_and_backslash" <conftest.def`
+rm -f conftest.def
+# Substitute for predefined variables.
+
+trap 'rm -f config.status; exit 1' 1 3 15
+echo creating config.status
+rm -f config.status
+cat > config.status <<EOF
+#!/bin/sh
+# Generated automatically by configure.
+# Run this file to recreate the current configuration.
+# This directory was configured as follows,
+# on host `(hostname || uname -n) 2>/dev/null | sed 1q`:
+#
+# $0 $configure_args
+
+for arg
+do
+  case "\$arg" in
+    -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
+    echo running \${CONFIG_SHELL-/bin/sh} $0 $configure_args
+    exec \${CONFIG_SHELL-/bin/sh} $0 $configure_args ;;
+    *) echo "Usage: config.status --recheck" 2>&1; exit 1 ;;
+  esac
+done
+
+trap 'rm -fr Makefile jconfig.h conftest*; exit 1' 1 3 15
+CC='$CC'
+CPP='$CPP'
+INSTALL='$INSTALL'
+INSTALL_PROGRAM='$INSTALL_PROGRAM'
+INSTALL_DATA='$INSTALL_DATA'
+RANLIB='$RANLIB'
+MEMORYMGR='$MEMORYMGR'
+ANSI2KNR='$ANSI2KNR'
+ISANSICOM='$ISANSICOM'
+ANSI2KNRFLAGS='$ANSI2KNRFLAGS'
+LIBS='$LIBS'
+srcdir='$srcdir'
+prefix='$prefix'
+exec_prefix='$exec_prefix'
+prsub='$prsub'
+extrasub='$extrasub'
+EOF
+cat >> config.status <<\EOF
+
+top_srcdir=$srcdir
+
+CONFIG_FILES=${CONFIG_FILES-"Makefile"}
+for file in .. ${CONFIG_FILES}; do if test "x$file" != x..; then
+  srcdir=$top_srcdir
+  # Remove last slash and all that follows it.  Not all systems have dirname.
+  dir=`echo $file|sed 's%/[^/][^/]*$%%'`
+  if test "$dir" != "$file"; then
+    test "$top_srcdir" != . && srcdir=$top_srcdir/$dir
+    test ! -d $dir && mkdir $dir
+  fi
+  echo creating $file
+  rm -f $file
+  echo "# Generated automatically from `echo $file|sed 's|.*/||'`.auto by configure." > $file
+  sed -e "
+$prsub
+$extrasub
+s%@CC@%$CC%g
+s%@CPP@%$CPP%g
+s%@INSTALL@%$INSTALL%g
+s%@INSTALL_PROGRAM@%$INSTALL_PROGRAM%g
+s%@INSTALL_DATA@%$INSTALL_DATA%g
+s%@RANLIB@%$RANLIB%g
+s%@MEMORYMGR@%$MEMORYMGR%g
+s%@ANSI2KNR@%$ANSI2KNR%g
+s%@ISANSICOM@%$ISANSICOM%g
+s%@ANSI2KNRFLAGS@%$ANSI2KNRFLAGS%g
+s%@LIBS@%$LIBS%g
+s%@srcdir@%$srcdir%g
+s%@DEFS@%-DHAVE_CONFIG_H%" $top_srcdir/makefile.auto >> $file
+fi; done
+
+CONFIG_HEADERS=${CONFIG_HEADERS-"jconfig.h"}
+for file in .. ${CONFIG_HEADERS}; do if test "x$file" != x..; then
+echo creating $file
+
+# These sed commands are put into SEDDEFS when defining a macro.
+# They are broken into pieces to make the sed script easier to manage.
+# They are passed to sed as "A NAME B NAME C VALUE D", where NAME
+# is the cpp macro being defined and VALUE is the value it is being given.
+# Each defining turns into a single global substitution command.
+#
+# SEDd sets the value in "#define NAME VALUE" lines.
+SEDdA='s@^\([ 	]*\)#\([ 	]*define[ 	][ 	]*\)'
+SEDdB='\([ 	][ 	]*\)[^ 	]*@\1#\2'
+SEDdC='\3'
+SEDdD='@g'
+# SEDu turns "#undef NAME" with trailing blanks into "#define NAME VALUE".
+SEDuA='s@^\([ 	]*\)#\([ 	]*\)undef\([ 	][ 	]*\)'
+SEDuB='\([ 	]\)@\1#\2define\3'
+SEDuC=' '
+SEDuD='\4@g'
+# SEDe turns "#undef NAME" without trailing blanks into "#define NAME VALUE".
+SEDeA='s@^\([ 	]*\)#\([ 	]*\)undef\([ 	][ 	]*\)'
+SEDeB='$@\1#\2define\3'
+SEDeC=' '
+SEDeD='@g'
+rm -f conftest.sed
+EOF
+# Turn off quoting long enough to insert the sed commands.
+rm -f conftest.sh
+cat > conftest.sh <<EOF
+$SEDDEFS
+EOF
+
+# Break up $SEDDEFS (now in conftest.sh) because some shells have a limit
+# on the size of here documents.
+
+# Maximum number of lines to put in a single here document.
+maxshlines=9
+
+while :
+do
+  # wc gives bogus results for an empty file on some systems.
+  lines=`grep -c . conftest.sh`
+  if test -z "$lines" || test "$lines" -eq 0; then break; fi
+  rm -f conftest.s1 conftest.s2
+  sed ${maxshlines}q conftest.sh > conftest.s1 # Like head -20.
+  sed 1,${maxshlines}d conftest.sh > conftest.s2 # Like tail +21.
+  # Write a limited-size here document to append to conftest.sed.
+  echo 'cat >> conftest.sed <<CONFEOF' >> config.status
+  cat conftest.s1 >> config.status
+  echo 'CONFEOF' >> config.status
+  rm -f conftest.s1 conftest.sh
+  mv conftest.s2 conftest.sh
+done
+rm -f conftest.sh
+
+# Now back to your regularly scheduled config.status.
+cat >> config.status <<\EOF
+# This sed command replaces #undef's with comments.  This is necessary, for
+# example, in the case of _POSIX_SOURCE, which is predefined and required
+# on some systems where configure will not decide to define it in
+# jconfig.h.
+cat >> conftest.sed <<\CONFEOF
+CONFEOF
+rm -f conftest.h
+# Break up the sed commands because old seds have small limits.
+maxsedlines=20
+cp $top_srcdir/jconfig.auto conftest.h1
+while :
+do
+  lines=`grep -c . conftest.sed`
+  if test -z "$lines" || test "$lines" -eq 0; then break; fi
+  rm -f conftest.s1 conftest.s2 conftest.h2
+  sed ${maxsedlines}q conftest.sed > conftest.s1 # Like head -20.
+  sed 1,${maxsedlines}d conftest.sed > conftest.s2 # Like tail +21.
+  sed -f conftest.s1 < conftest.h1 > conftest.h2
+  rm -f conftest.s1 conftest.h1 conftest.sed
+  mv conftest.h2 conftest.h1
+  mv conftest.s2 conftest.sed
+done
+rm -f conftest.sed conftest.h
+echo "/* $file.  Generated automatically by configure.  */" > conftest.h
+cat conftest.h1 >> conftest.h
+rm -f conftest.h1
+if cmp -s $file conftest.h 2>/dev/null; then
+  # The file exists and we would not be changing it.
+  echo "$file is unchanged"
+  rm -f conftest.h
+else
+  rm -f $file
+  mv conftest.h $file
+fi
+fi; done
+
+
+
+exit 0
+EOF
+chmod +x config.status
+${CONFIG_SHELL-/bin/sh} config.status
+
diff --git a/djpeg.1 b/djpeg.1
index 7f45074..08f80c5 100644
--- a/djpeg.1
+++ b/djpeg.1
@@ -1,43 +1,10 @@
-.TH DJPEG 1 "17 February 1993"
+.TH DJPEG 1 "28 August 1994"
 .SH NAME
 djpeg \- decompress a JPEG file to an image file
 .SH SYNOPSIS
 .B djpeg
 [
-.BI \-colors " N"
-]
-[
-.B \-gif
-]
-[
-.B \-pnm
-]
-[
-.B \-rle
-]
-[
-.B \-targa
-]
-[
-.B \-blocksmooth
-]
-[
-.B \-grayscale
-]
-[
-.BI \-maxmemory " N"
-]
-[
-.B \-nodither
-]
-[
-.B \-onepass
-]
-[
-.B \-verbose
-]
-[
-.B \-debug
+.I options
 ]
 [
 .I filename
@@ -47,9 +14,9 @@
 .LP
 .B djpeg
 decompresses the named JPEG file, or the standard input if no file is named,
-and produces an image file on the standard output.  PBMPLUS (PPM/PGM), GIF,
-Targa, or RLE (Utah Raster Toolkit) output format can be selected.  (RLE is
-supported only if the URT library is available.)
+and produces an image file on the standard output.  PBMPLUS (PPM/PGM), BMP,
+GIF, Targa, or RLE (Utah Raster Toolkit) output format can be selected.
+(RLE is supported only if the URT library is available.)
 .SH OPTIONS
 All switch names may be abbreviated; for example,
 .B \-grayscale
@@ -82,11 +49,47 @@
 .B \-quantize
 is provided only for backwards compatibility.
 .TP
+.B \-fast
+Select recommended processing options for fast, low quality output.  (The
+default options are chosen for highest quality output.)  Currently, this is
+equivalent to \fB\-dct fast \-nosmooth \-onepass \-dither ordered\fR.
+.TP
+.B \-grayscale
+Force gray-scale output even if JPEG file is color.  Useful for viewing on
+monochrome displays; also,
+.B djpeg
+runs noticeably faster in this mode.
+.TP
+.BI \-scale " M/N"
+Scale the output image by a factor M/N.  Currently the scale factor must be
+1/1, 1/2, 1/4, or 1/8.  Scaling is handy if the image is larger than your
+screen; also,
+.B djpeg
+runs much faster when scaling down the output.
+.TP
+.B \-bmp
+Select BMP output format (Windows flavor).  8-bit colormapped format is
+emitted if
+.B \-colors
+or
+.B \-grayscale
+is specified, or if the JPEG file is gray-scale; otherwise, 24-bit full-color
+format is emitted.
+.TP
 .B \-gif
 Select GIF output format.  Since GIF does not support more than 256 colors,
 .B \-colors 256
 is assumed (unless you specify a smaller number of colors).
 .TP
+.B \-os2
+Select BMP output format (OS/2 1.x flavor).  8-bit colormapped format is
+emitted if
+.B \-colors
+or
+.B \-grayscale
+is specified, or if the JPEG file is gray-scale; otherwise, 24-bit full-color
+format is emitted.
+.TP
 .B \-pnm
 Select PBMPLUS (PPM/PGM) output format (this is the default format).
 PGM is emitted if the JPEG file is gray-scale or if
@@ -106,32 +109,48 @@
 .PP
 Switches for advanced users:
 .TP
-.B \-blocksmooth
-Perform cross-block smoothing.  This is slow, quite memory-intensive, and only
-seems to improve the image at very low quality settings (\fB\-quality\fR 10 to
-20 or so).  At normal quality settings it may make the image worse.
+.B \-dct int
+Use integer DCT method (default).
 .TP
-.B \-grayscale
-Force gray-scale output even if JPEG file is color.
-Useful for viewing on monochrome displays.
+.B \-dct fast
+Use fast integer DCT (less accurate).
 .TP
-.BI \-maxmemory " N"
-Set limit for amount of memory to use in processing large images.  Value is
-in thousands of bytes, or millions of bytes if "M" is attached to the
-number.  For example,
-.B \-max 4m
-selects 4000000 bytes.  If more space is needed, temporary files will be used.
+.B \-dct float
+Use floating-point DCT method.
+The floating-point method is the most accurate, but will be the slowest unless
+your machine has very fast floating-point hardware.  Also note that results of
+the floating-point method may vary slightly across machines, while the integer
+methods should give the same results everywhere.  The fast integer method is
+much less accurate than the other two.
 .TP
-.B \-nodither
-Do not use dithering in color quantization.  By default, Floyd-Steinberg
-dithering is applied when quantizing colors, but on some images dithering may
-result in objectionable "graininess".  If that happens, you can turn off
-dithering with
-.BR \-nodither .
-.B \-nodither
-is ignored unless you also say
+.B \-dither fs
+Use Floyd-Steinberg dithering in color quantization.
+.TP
+.B \-dither ordered
+Use ordered dithering in color quantization.
+.TP
+.B \-dither none
+Do not use dithering in color quantization.
+By default, Floyd-Steinberg dithering is applied when quantizing colors; this
+is slow but usually produces the best results.  Ordered dither is a compromise
+between speed and quality; no dithering is fast but usually looks awful.  Note
+that these switches have no effect unless color quantization is being done.
+Ordered dither is only available in
+.B \-onepass
+mode.
+.TP
+.BI \-map " file"
+Quantize to the colors used in the specified image file.  This is useful for
+producing multiple files with identical color maps, or for forcing a
+predefined set of colors to be used.  The
+.I file
+must be a GIF or PPM file. This option overrides
 .B \-colors
-.IR N .
+and
+.BR \-onepass .
+.TP
+.B \-nosmooth
+Use a faster, lower-quality upsampling routine.
 .TP
 .B \-onepass
 Use one-pass instead of two-pass color quantization.  The one-pass method is
@@ -143,6 +162,16 @@
 Also, the one-pass method is always used for gray-scale output (the two-pass
 method is no improvement then).
 .TP
+.BI \-maxmemory " N"
+Set limit for amount of memory to use in processing large images.  Value is
+in thousands of bytes, or millions of bytes if "M" is attached to the
+number.  For example,
+.B \-max 4m
+selects 4000000 bytes.  If more space is needed, temporary files will be used.
+.TP
+.BI \-outfile " name"
+Send output image to the named file, not to standard output.
+.TP
 .B \-verbose
 Enable debug printout.  More
 .BR \-v 's
@@ -160,6 +189,33 @@
 .I foo.jpg
 .B >
 .I foo.gif
+.SH HINTS
+To get a quick preview of an image, use the
+.B \-grayscale
+and/or
+.B \-scale
+switches.
+.B \-grayscale \-scale 1/8
+is the fastest case.
+.PP
+Several options are available that trade off image quality to gain speed.
+.B \-fast
+turns on the recommended settings.
+.PP
+.B \-dct fast
+and/or
+.B \-nosmooth
+gain speed at a small sacrifice in quality.
+When producing a color-quantized image,
+.B \-onepass \-dither ordered
+is fast but much lower quality than the default behavior.
+.B \-dither none
+may give acceptable results in two-pass mode, but is seldom tolerable in
+one-pass mode.
+.PP
+If you are fortunate enough to have very fast floating point hardware,
+.B \-dct float
+may be even faster than \fB\-dct fast\fR.
 .SH ENVIRONMENT
 .TP
 .B JPEGMEM
@@ -172,7 +228,9 @@
 itself is overridden by an explicit
 .BR \-maxmemory .
 .SH SEE ALSO
-.BR cjpeg (1)
+.BR cjpeg (1),
+.BR rdjpgcom (1),
+.BR wrjpgcom (1)
 .br
 .BR ppm (5),
 .BR pgm (5)
diff --git a/djpeg.c b/djpeg.c
new file mode 100644
index 0000000..0df3755
--- /dev/null
+++ b/djpeg.c
@@ -0,0 +1,736 @@
+/*
+ * djpeg.c
+ *
+ * Copyright (C) 1991-1994, 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.
+ *
+ * This file contains a command-line user interface for the JPEG decompressor.
+ * It should work on any system with Unix- or MS-DOS-style command lines.
+ *
+ * Two different command line styles are permitted, depending on the
+ * compile-time switch TWO_FILE_COMMANDLINE:
+ *	djpeg [options]  inputfile outputfile
+ *	djpeg [options]  [inputfile]
+ * In the second style, output is always to standard output, which you'd
+ * normally redirect to a file or pipe to some other program.  Input is
+ * either from a named file or from standard input (typically redirected).
+ * The second style is convenient on Unix but is unhelpful on systems that
+ * don't support pipes.  Also, you MUST use the first style if your system
+ * doesn't do binary I/O to stdin/stdout.
+ * To simplify script writing, the "-outfile" switch is provided.  The syntax
+ *	djpeg [options]  -outfile outputfile  inputfile
+ * works regardless of which command line style is used.
+ */
+
+#include "cdjpeg.h"		/* Common decls for cjpeg/djpeg applications */
+#define JMAKE_MSG_TABLE
+#include "cderror.h"		/* create message string table */
+#include "jversion.h"		/* for version message */
+
+#include <ctype.h>		/* to declare isupper(),tolower(),isprint() */
+#ifdef NEED_SIGNAL_CATCHER
+#include <signal.h>		/* to declare signal() */
+#endif
+#ifdef USE_SETMODE
+#include <fcntl.h>		/* to declare setmode()'s parameter macros */
+/* If you have setmode() but not <io.h>, just delete this line: */
+#include <io.h>			/* to declare setmode() */
+#endif
+
+#ifdef USE_CCOMMAND		/* command-line reader for Macintosh */
+#ifdef __MWERKS__
+#include <SIOUX.h>              /* Metrowerks declares it here */
+#endif
+#ifdef THINK_C
+#include <console.h>		/* Think declares it here */
+#endif
+#endif
+
+#ifdef DONT_USE_B_MODE		/* define mode parameters for fopen() */
+#define READ_BINARY	"r"
+#define WRITE_BINARY	"w"
+#else
+#define READ_BINARY	"rb"
+#define WRITE_BINARY	"wb"
+#endif
+
+#ifndef EXIT_FAILURE		/* define exit() codes if not provided */
+#define EXIT_FAILURE  1
+#endif
+#ifndef EXIT_SUCCESS
+#ifdef VMS
+#define EXIT_SUCCESS  1		/* VMS is very nonstandard */
+#else
+#define EXIT_SUCCESS  0
+#endif
+#endif
+#ifndef EXIT_WARNING
+#ifdef VMS
+#define EXIT_WARNING  1		/* VMS is very nonstandard */
+#else
+#define EXIT_WARNING  2
+#endif
+#endif
+
+
+/*
+ * This list defines the known output image formats
+ * (not all of which need be supported by a given version).
+ * You can change the default output format by defining DEFAULT_FMT;
+ * indeed, you had better do so if you undefine PPM_SUPPORTED.
+ */
+
+typedef enum {
+	FMT_BMP,		/* BMP format (Windows flavor) */
+	FMT_GIF,		/* GIF format */
+	FMT_OS2,		/* BMP format (OS/2 flavor) */
+	FMT_PPM,		/* PPM/PGM (PBMPLUS formats) */
+	FMT_RLE,		/* RLE format */
+	FMT_TARGA,		/* Targa format */
+	FMT_TIFF		/* TIFF format */
+} IMAGE_FORMATS;
+
+#ifndef DEFAULT_FMT		/* so can override from CFLAGS in Makefile */
+#define DEFAULT_FMT	FMT_PPM
+#endif
+
+static IMAGE_FORMATS requested_fmt;
+
+
+/*
+ * Signal catcher to ensure that temporary files are removed before aborting.
+ * NB: for Amiga Manx C this is actually a global routine named _abort();
+ * we put "#define signal_catcher _abort" in jconfig.h.  Talk about bogus...
+ */
+
+#ifdef NEED_SIGNAL_CATCHER
+
+static j_common_ptr sig_cinfo;
+
+GLOBAL void
+signal_catcher (int signum)
+{
+  if (sig_cinfo != NULL) {
+    if (sig_cinfo->err != NULL) /* turn off trace output */
+      sig_cinfo->err->trace_level = 0;
+    jpeg_destroy(sig_cinfo);	/* clean up memory allocation & temp files */
+  }
+  exit(EXIT_FAILURE);
+}
+
+#endif
+
+
+/*
+ * Optional routine to display a percent-done figure on stderr.
+ */
+
+#ifdef PROGRESS_REPORT
+
+METHODDEF void
+progress_monitor (j_common_ptr cinfo)
+{
+  cd_progress_ptr prog = (cd_progress_ptr) cinfo->progress;
+  int total_passes = prog->pub.total_passes + prog->total_extra_passes;
+  int percent_done = (int) (prog->pub.pass_counter*100L/prog->pub.pass_limit);
+
+  if (percent_done != prog->percent_done) {
+    prog->percent_done = percent_done;
+    if (total_passes > 1) {
+      fprintf(stderr, "\rPass %d/%d: %3d%% ",
+	      prog->pub.completed_passes + prog->completed_extra_passes + 1,
+	      total_passes, percent_done);
+    } else {
+      fprintf(stderr, "\r %3d%% ", percent_done);
+    }
+    fflush(stderr);
+  }
+}
+
+#endif
+
+
+/*
+ * Argument-parsing code.
+ * The switch parser is designed to be useful with DOS-style command line
+ * syntax, ie, intermixed switches and file names, where only the switches
+ * to the left of a given file name affect processing of that file.
+ * The main program in this file doesn't actually use this capability...
+ */
+
+
+static const char * progname;	/* program name for error messages */
+static char * outfilename;	/* for -outfile switch */
+
+
+LOCAL void
+usage (void)
+/* complain about bad command line */
+{
+  fprintf(stderr, "usage: %s [switches] ", progname);
+#ifdef TWO_FILE_COMMANDLINE
+  fprintf(stderr, "inputfile outputfile\n");
+#else
+  fprintf(stderr, "[inputfile]\n");
+#endif
+
+  fprintf(stderr, "Switches (names may be abbreviated):\n");
+  fprintf(stderr, "  -colors N      Reduce image to no more than N colors\n");
+  fprintf(stderr, "  -fast          Fast, low-quality processing\n");
+  fprintf(stderr, "  -grayscale     Force grayscale output\n");
+#ifdef IDCT_SCALING_SUPPORTED
+  fprintf(stderr, "  -scale M/N     Scale output image by fraction M/N, eg, 1/8\n");
+#endif
+#ifdef BMP_SUPPORTED
+  fprintf(stderr, "  -bmp           Select BMP output format (Windows style)%s\n",
+	  (DEFAULT_FMT == FMT_BMP ? " (default)" : ""));
+#endif
+#ifdef GIF_SUPPORTED
+  fprintf(stderr, "  -gif           Select GIF output format%s\n",
+	  (DEFAULT_FMT == FMT_GIF ? " (default)" : ""));
+#endif
+#ifdef BMP_SUPPORTED
+  fprintf(stderr, "  -os2           Select BMP output format (OS/2 style)%s\n",
+	  (DEFAULT_FMT == FMT_OS2 ? " (default)" : ""));
+#endif
+#ifdef PPM_SUPPORTED
+  fprintf(stderr, "  -pnm           Select PBMPLUS (PPM/PGM) output format%s\n",
+	  (DEFAULT_FMT == FMT_PPM ? " (default)" : ""));
+#endif
+#ifdef RLE_SUPPORTED
+  fprintf(stderr, "  -rle           Select Utah RLE output format%s\n",
+	  (DEFAULT_FMT == FMT_RLE ? " (default)" : ""));
+#endif
+#ifdef TARGA_SUPPORTED
+  fprintf(stderr, "  -targa         Select Targa output format%s\n",
+	  (DEFAULT_FMT == FMT_TARGA ? " (default)" : ""));
+#endif
+  fprintf(stderr, "Switches for advanced users:\n");
+#ifdef DCT_ISLOW_SUPPORTED
+  fprintf(stderr, "  -dct int       Use integer DCT method%s\n",
+	  (JDCT_DEFAULT == JDCT_ISLOW ? " (default)" : ""));
+#endif
+#ifdef DCT_IFAST_SUPPORTED
+  fprintf(stderr, "  -dct fast      Use fast integer DCT (less accurate)%s\n",
+	  (JDCT_DEFAULT == JDCT_IFAST ? " (default)" : ""));
+#endif
+#ifdef DCT_FLOAT_SUPPORTED
+  fprintf(stderr, "  -dct float     Use floating-point DCT method%s\n",
+	  (JDCT_DEFAULT == JDCT_FLOAT ? " (default)" : ""));
+#endif
+  fprintf(stderr, "  -dither fs     Use F-S dithering (default)\n");
+  fprintf(stderr, "  -dither none   Don't use dithering in quantization\n");
+  fprintf(stderr, "  -dither ordered  Use ordered dither (medium speed, quality)\n");
+#ifdef QUANT_2PASS_SUPPORTED
+  fprintf(stderr, "  -map FILE      Map to colors used in named image file\n");
+#endif
+  fprintf(stderr, "  -nosmooth      Don't use high-quality upsampling\n");
+#ifdef QUANT_1PASS_SUPPORTED
+  fprintf(stderr, "  -onepass       Use 1-pass quantization (fast, low quality)\n");
+#endif
+  fprintf(stderr, "  -maxmemory N   Maximum memory to use (in kbytes)\n");
+  fprintf(stderr, "  -outfile name  Specify name for output file\n");
+  fprintf(stderr, "  -verbose  or  -debug   Emit debug output\n");
+  exit(EXIT_FAILURE);
+}
+
+
+LOCAL boolean
+keymatch (char * arg, const char * keyword, int minchars)
+/* Case-insensitive matching of (possibly abbreviated) keyword switches. */
+/* keyword is the constant keyword (must be lower case already), */
+/* minchars is length of minimum legal abbreviation. */
+{
+  register int ca, ck;
+  register int nmatched = 0;
+
+  while ((ca = *arg++) != '\0') {
+    if ((ck = *keyword++) == '\0')
+      return FALSE;		/* arg longer than keyword, no good */
+    if (isupper(ca))		/* force arg to lcase (assume ck is already) */
+      ca = tolower(ca);
+    if (ca != ck)
+      return FALSE;		/* no good */
+    nmatched++;			/* count matched characters */
+  }
+  /* reached end of argument; fail if it's too short for unique abbrev */
+  if (nmatched < minchars)
+    return FALSE;
+  return TRUE;			/* A-OK */
+}
+
+
+LOCAL int
+parse_switches (j_decompress_ptr cinfo, int argc, char **argv,
+		int last_file_arg_seen, boolean for_real)
+/* Parse optional switches.
+ * Returns argv[] index of first file-name argument (== argc if none).
+ * Any file names with indexes <= last_file_arg_seen are ignored;
+ * they have presumably been processed in a previous iteration.
+ * (Pass 0 for last_file_arg_seen on the first or only iteration.)
+ * for_real is FALSE on the first (dummy) pass; we may skip any expensive
+ * processing.
+ */
+{
+  int argn;
+  char * arg;
+
+  /* Set up default JPEG parameters. */
+  requested_fmt = DEFAULT_FMT;	/* set default output file format */
+  outfilename = NULL;
+  cinfo->err->trace_level = 0;
+
+  /* Scan command line options, adjust parameters */
+
+  for (argn = 1; argn < argc; argn++) {
+    arg = argv[argn];
+    if (*arg != '-') {
+      /* Not a switch, must be a file name argument */
+      if (argn <= last_file_arg_seen) {
+	outfilename = NULL;	/* -outfile applies to just one input file */
+	continue;		/* ignore this name if previously processed */
+      }
+      break;			/* else done parsing switches */
+    }
+    arg++;			/* advance past switch marker character */
+
+    if (keymatch(arg, "bmp", 1)) {
+      /* BMP output format. */
+      requested_fmt = FMT_BMP;
+
+    } else if (keymatch(arg, "colors", 1) || keymatch(arg, "colours", 1) ||
+	       keymatch(arg, "quantize", 1) || keymatch(arg, "quantise", 1)) {
+      /* Do color quantization. */
+      int val;
+
+      if (++argn >= argc)	/* advance to next argument */
+	usage();
+      if (sscanf(argv[argn], "%d", &val) != 1)
+	usage();
+      cinfo->desired_number_of_colors = val;
+      cinfo->quantize_colors = TRUE;
+
+    } else if (keymatch(arg, "dct", 2)) {
+      /* Select IDCT algorithm. */
+      if (++argn >= argc)	/* advance to next argument */
+	usage();
+      if (keymatch(argv[argn], "int", 1)) {
+	cinfo->dct_method = JDCT_ISLOW;
+      } else if (keymatch(argv[argn], "fast", 2)) {
+	cinfo->dct_method = JDCT_IFAST;
+      } else if (keymatch(argv[argn], "float", 2)) {
+	cinfo->dct_method = JDCT_FLOAT;
+      } else
+	usage();
+
+    } else if (keymatch(arg, "dither", 2)) {
+      /* Select dithering algorithm. */
+      if (++argn >= argc)	/* advance to next argument */
+	usage();
+      if (keymatch(argv[argn], "fs", 2)) {
+	cinfo->dither_mode = JDITHER_FS;
+      } else if (keymatch(argv[argn], "none", 2)) {
+	cinfo->dither_mode = JDITHER_NONE;
+      } else if (keymatch(argv[argn], "ordered", 2)) {
+	cinfo->dither_mode = JDITHER_ORDERED;
+      } else
+	usage();
+
+    } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
+      /* Enable debug printouts. */
+      /* On first -d, print version identification */
+      static boolean printed_version = FALSE;
+
+      if (! printed_version) {
+	fprintf(stderr, "Independent JPEG Group's DJPEG, version %s\n%s\n",
+		JVERSION, JCOPYRIGHT);
+	printed_version = TRUE;
+      }
+      cinfo->err->trace_level++;
+
+    } else if (keymatch(arg, "fast", 1)) {
+      /* Select recommended processing options for quick-and-dirty output. */
+      cinfo->two_pass_quantize = FALSE;
+      cinfo->dither_mode = JDITHER_ORDERED;
+      if (! cinfo->quantize_colors) /* don't override an earlier -colors */
+	cinfo->desired_number_of_colors = 216;
+      cinfo->dct_method = JDCT_FASTEST;
+      cinfo->do_fancy_upsampling = FALSE;
+
+    } else if (keymatch(arg, "gif", 1)) {
+      /* GIF output format. */
+      requested_fmt = FMT_GIF;
+
+    } else if (keymatch(arg, "grayscale", 2) || keymatch(arg, "greyscale",2)) {
+      /* Force monochrome output. */
+      cinfo->out_color_space = JCS_GRAYSCALE;
+
+    } else if (keymatch(arg, "map", 3)) {
+      /* Quantize to a color map taken from an input file. */
+      if (++argn >= argc)	/* advance to next argument */
+	usage();
+      if (for_real) {		/* too expensive to do twice! */
+#ifdef QUANT_2PASS_SUPPORTED	/* otherwise can't quantize to supplied map */
+	FILE * mapfile;
+
+	if ((mapfile = fopen(argv[argn], READ_BINARY)) == NULL) {
+	  fprintf(stderr, "%s: can't open %s\n", progname, argv[argn]);
+	  exit(EXIT_FAILURE);
+	}
+	read_color_map(cinfo, mapfile);
+	fclose(mapfile);
+	cinfo->quantize_colors = TRUE;
+#else
+	ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+      }
+
+    } else if (keymatch(arg, "maxmemory", 3)) {
+      /* Maximum memory in Kb (or Mb with 'm'). */
+      long lval;
+      char ch = 'x';
+
+      if (++argn >= argc)	/* advance to next argument */
+	usage();
+      if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
+	usage();
+      if (ch == 'm' || ch == 'M')
+	lval *= 1000L;
+      cinfo->mem->max_memory_to_use = lval * 1000L;
+
+    } else if (keymatch(arg, "nosmooth", 3)) {
+      /* Suppress fancy upsampling */
+      cinfo->do_fancy_upsampling = FALSE;
+
+    } else if (keymatch(arg, "onepass", 3)) {
+      /* Use fast one-pass quantization. */
+      cinfo->two_pass_quantize = FALSE;
+
+    } else if (keymatch(arg, "os2", 3)) {
+      /* BMP output format (OS/2 flavor). */
+      requested_fmt = FMT_OS2;
+
+    } else if (keymatch(arg, "outfile", 4)) {
+      /* Set output file name. */
+      if (++argn >= argc)	/* advance to next argument */
+	usage();
+      outfilename = argv[argn];	/* save it away for later use */
+
+    } else if (keymatch(arg, "pnm", 1) || keymatch(arg, "ppm", 1)) {
+      /* PPM/PGM output format. */
+      requested_fmt = FMT_PPM;
+
+    } else if (keymatch(arg, "rle", 1)) {
+      /* RLE output format. */
+      requested_fmt = FMT_RLE;
+
+    } else if (keymatch(arg, "scale", 1)) {
+      /* Scale the output image by a fraction M/N. */
+      if (++argn >= argc)	/* advance to next argument */
+	usage();
+      if (sscanf(argv[argn], "%d/%d",
+		 &cinfo->scale_num, &cinfo->scale_denom) != 2)
+	usage();
+
+    } else if (keymatch(arg, "targa", 1)) {
+      /* Targa output format. */
+      requested_fmt = FMT_TARGA;
+
+    } else {
+      usage();			/* bogus switch */
+    }
+  }
+
+  return argn;			/* return index of next arg (file name) */
+}
+
+
+/*
+ * Marker processor for COM markers.
+ * This replaces the library's built-in processor, which just skips the marker.
+ * We want to print out the marker as text, if possible.
+ * Note this code relies on a non-suspending data source.
+ */
+
+LOCAL unsigned int
+jpeg_getc (j_decompress_ptr cinfo)
+/* Read next byte */
+{
+  struct jpeg_source_mgr * datasrc = cinfo->src;
+
+  if (datasrc->bytes_in_buffer == 0) {
+    if (! (*datasrc->fill_input_buffer) (cinfo))
+      ERREXIT(cinfo, JERR_CANT_SUSPEND);
+  }
+  datasrc->bytes_in_buffer--;
+  return GETJOCTET(*datasrc->next_input_byte++);
+}
+
+
+METHODDEF boolean
+COM_handler (j_decompress_ptr cinfo)
+{
+  boolean traceit = (cinfo->err->trace_level >= 1);
+  INT32 length;
+  unsigned int ch;
+  unsigned int lastch = 0;
+
+  length = jpeg_getc(cinfo) << 8;
+  length += jpeg_getc(cinfo);
+  length -= 2;			/* discount the length word itself */
+
+  if (traceit)
+    fprintf(stderr, "Comment, length %ld:\n", (long) length);
+
+  while (--length >= 0) {
+    ch = jpeg_getc(cinfo);
+    if (traceit) {
+      /* Emit the character in a readable form.
+       * Nonprintables are converted to \nnn form,
+       * while \ is converted to \\.
+       * Newlines in CR, CR/LF, or LF form will be printed as one newline.
+       */
+      if (ch == '\r') {
+	fprintf(stderr, "\n");
+      } else if (ch == '\n') {
+	if (lastch != '\r')
+	  fprintf(stderr, "\n");
+      } else if (ch == '\\') {
+	fprintf(stderr, "\\\\");
+      } else if (isprint(ch)) {
+	putc(ch, stderr);
+      } else {
+	fprintf(stderr, "\\%03o", ch);
+      }
+      lastch = ch;
+    }
+  }
+
+  if (traceit)
+    fprintf(stderr, "\n");
+
+  return TRUE;
+}
+
+
+/*
+ * The main program.
+ */
+
+GLOBAL int
+main (int argc, char **argv)
+{
+  struct jpeg_decompress_struct cinfo;
+  struct jpeg_error_mgr jerr;
+#ifdef PROGRESS_REPORT
+  struct cdjpeg_progress_mgr progress;
+#endif
+  int file_index;
+  djpeg_dest_ptr dest_mgr = NULL;
+  FILE * input_file;
+  FILE * output_file;
+  JDIMENSION num_scanlines;
+
+  /* On Mac, fetch a command line. */
+#ifdef USE_CCOMMAND
+  argc = ccommand(&argv);
+#endif
+
+  progname = argv[0];
+  if (progname == NULL || progname[0] == 0)
+    progname = "djpeg";		/* in case C library doesn't provide it */
+
+  /* Initialize the JPEG decompression object with default error handling. */
+  cinfo.err = jpeg_std_error(&jerr);
+  jpeg_create_decompress(&cinfo);
+  /* Add some application-specific error messages (from cderror.h) */
+  jerr.addon_message_table = addon_message_table;
+  jerr.first_addon_message = JMSG_FIRSTADDONCODE;
+  jerr.last_addon_message = JMSG_LASTADDONCODE;
+  /* Insert custom COM marker processor. */
+  jpeg_set_marker_processor(&cinfo, JPEG_COM, COM_handler);
+
+  /* Now safe to enable signal catcher. */
+#ifdef NEED_SIGNAL_CATCHER
+  sig_cinfo = (j_common_ptr) &cinfo;
+  signal(SIGINT, signal_catcher);
+#ifdef SIGTERM			/* not all systems have SIGTERM */
+  signal(SIGTERM, signal_catcher);
+#endif
+#endif
+
+  /* Scan command line to find file names. */
+  /* It is convenient to use just one switch-parsing routine, but the switch
+   * values read here are ignored; we will rescan the switches after opening
+   * the input file.
+   * (Exception: tracing level set here controls verbosity for COM markers
+   * found during jpeg_read_header...)
+   */
+
+  file_index = parse_switches(&cinfo, argc, argv, 0, FALSE);
+
+#ifdef TWO_FILE_COMMANDLINE
+  /* Must have either -outfile switch or explicit output file name */
+  if (outfilename == NULL) {
+    if (file_index != argc-2) {
+      fprintf(stderr, "%s: must name one input and one output file\n",
+	      progname);
+      usage();
+    }
+    outfilename = argv[file_index+1];
+  } else {
+    if (file_index != argc-1) {
+      fprintf(stderr, "%s: must name one input and one output file\n",
+	      progname);
+      usage();
+    }
+  }
+#else
+  /* Unix style: expect zero or one file name */
+  if (file_index < argc-1) {
+    fprintf(stderr, "%s: only one input file\n", progname);
+    usage();
+  }
+#endif /* TWO_FILE_COMMANDLINE */
+
+  /* Open the input file. */
+  if (file_index < argc) {
+    if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
+      fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
+      exit(EXIT_FAILURE);
+    }
+  } else {
+    /* default input file is stdin */
+#ifdef USE_SETMODE		/* need to hack file mode? */
+    setmode(fileno(stdin), O_BINARY);
+#endif
+#ifdef USE_FDOPEN		/* need to re-open in binary mode? */
+    if ((input_file = fdopen(fileno(stdin), READ_BINARY)) == NULL) {
+      fprintf(stderr, "%s: can't open stdin\n", progname);
+      exit(EXIT_FAILURE);
+    }
+#else
+    input_file = stdin;
+#endif
+  }
+
+  /* Open the output file. */
+  if (outfilename != NULL) {
+    if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
+      fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
+      exit(EXIT_FAILURE);
+    }
+  } else {
+    /* default output file is stdout */
+#ifdef USE_SETMODE		/* need to hack file mode? */
+    setmode(fileno(stdout), O_BINARY);
+#endif
+#ifdef USE_FDOPEN		/* need to re-open in binary mode? */
+    if ((output_file = fdopen(fileno(stdout), WRITE_BINARY)) == NULL) {
+      fprintf(stderr, "%s: can't open stdout\n", progname);
+      exit(EXIT_FAILURE);
+    }
+#else
+    output_file = stdout;
+#endif
+  }
+
+#ifdef PROGRESS_REPORT
+  /* Enable progress display, unless trace output is on */
+  if (jerr.trace_level == 0) {
+    progress.pub.progress_monitor = progress_monitor;
+    progress.completed_extra_passes = 0;
+    progress.total_extra_passes = 0;
+    progress.percent_done = -1;
+    cinfo.progress = &progress.pub;
+  }
+#endif
+
+  /* Specify data source for decompression */
+  jpeg_stdio_src(&cinfo, input_file);
+
+  /* Read file header, set default decompression parameters */
+  (void) jpeg_read_header(&cinfo, TRUE);
+
+  /* Adjust default decompression parameters by re-parsing the options */
+  file_index = parse_switches(&cinfo, argc, argv, 0, TRUE);
+
+  /* Initialize the output module now to let it override any crucial
+   * option settings (for instance, GIF wants to force color quantization).
+   */
+  switch (requested_fmt) {
+#ifdef BMP_SUPPORTED
+  case FMT_BMP:
+    dest_mgr = jinit_write_bmp(&cinfo, FALSE);
+    break;
+  case FMT_OS2:
+    dest_mgr = jinit_write_bmp(&cinfo, TRUE);
+    break;
+#endif
+#ifdef GIF_SUPPORTED
+  case FMT_GIF:
+    dest_mgr = jinit_write_gif(&cinfo);
+    break;
+#endif
+#ifdef PPM_SUPPORTED
+  case FMT_PPM:
+    dest_mgr = jinit_write_ppm(&cinfo);
+    break;
+#endif
+#ifdef RLE_SUPPORTED
+  case FMT_RLE:
+    dest_mgr = jinit_write_rle(&cinfo);
+    break;
+#endif
+#ifdef TARGA_SUPPORTED
+  case FMT_TARGA:
+    dest_mgr = jinit_write_targa(&cinfo);
+    break;
+#endif
+  default:
+    ERREXIT(&cinfo, JERR_UNSUPPORTED_FORMAT);
+    break;
+  }
+  dest_mgr->output_file = output_file;
+
+  /* Start decompressor */
+  jpeg_start_decompress(&cinfo);
+
+  /* Write output file header */
+  (*dest_mgr->start_output) (&cinfo, dest_mgr);
+
+  /* Process data */
+  while (cinfo.output_scanline < cinfo.output_height) {
+    num_scanlines = jpeg_read_scanlines(&cinfo, dest_mgr->buffer,
+					dest_mgr->buffer_height);
+    (*dest_mgr->put_pixel_rows) (&cinfo, dest_mgr, num_scanlines);
+  }
+
+#ifdef PROGRESS_REPORT
+  /* Hack: count final pass as done in case finish_output does an extra pass.
+   * The library won't have updated completed_passes.
+   */
+  progress.pub.completed_passes = progress.pub.total_passes;
+#endif
+
+  /* Finish decompression and release memory.
+   * I must do it in this order because output module has allocated memory
+   * of lifespan JPOOL_IMAGE; it needs to finish before releasing memory.
+   */
+  (*dest_mgr->finish_output) (&cinfo, dest_mgr);
+  jpeg_finish_decompress(&cinfo);
+  jpeg_destroy_decompress(&cinfo);
+
+#ifdef PROGRESS_REPORT
+  /* Clear away progress display */
+  if (jerr.trace_level == 0) {
+    fprintf(stderr, "\r                \r");
+    fflush(stderr);
+  }
+#endif
+
+  /* All done. */
+  exit(jerr.num_warnings ? EXIT_WARNING : EXIT_SUCCESS);
+  return 0;			/* suppress no-return-value warnings */
+}
diff --git a/example.c b/example.c
index 666dd6f..cb8c64a 100644
--- a/example.c
+++ b/example.c
@@ -1,31 +1,29 @@
 /*
  * example.c
  *
- * This file is not actually part of the JPEG software.  Rather, it provides
- * a skeleton that may be useful for constructing applications that use the
- * JPEG software as subroutines.  This code will NOT do anything useful as is.
+ * This file illustrates how to use the IJG code as a subroutine library
+ * to read or write JPEG image files.  You should look at this code in
+ * conjunction with the documentation file libjpeg.doc.
  *
- * This file illustrates how to use the JPEG code as a subroutine library
- * to read or write JPEG image files.  We assume here that you are not
- * merely interested in converting the image to yet another image file format
- * (if you are, you should be adding another I/O module to cjpeg/djpeg, not
- * constructing a new application).  Instead, we show how to pass the
- * decompressed image data into or out of routines that you provide.  For
- * example, a viewer program might use the JPEG decompressor together with
- * routines that write the decompressed image directly to a display.
+ * This code will not do anything useful as-is, but it may be helpful as a
+ * skeleton for constructing routines that call the JPEG library.  
  *
  * We present these routines in the same coding style used in the JPEG code
  * (ANSI function definitions, etc); but you are of course free to code your
  * routines in a different style if you prefer.
  */
 
+#include <stdio.h>
+
 /*
- * Include file for declaring JPEG data structures.
- * This file also includes some system headers like <stdio.h>;
- * if you prefer, you can include "jconfig.h" and "jpegdata.h" instead.
+ * Include file for users of JPEG library.
+ * You will need to have included system headers that define at least
+ * the typedefs FILE and size_t before you can include jpeglib.h.
+ * (stdio.h is sufficient on ANSI-conforming systems.)
+ * You may also wish to include "jerror.h".
  */
 
-#include "jinclude.h"
+#include "jpeglib.h"
 
 /*
  * <setjmp.h> is used for the optional error recovery mechanism shown in
@@ -45,587 +43,375 @@
 
 
 /*
- * To supply the image data for compression, you must define three routines
- * input_init, get_input_row, and input_term.  These routines will be called
- * from the JPEG compressor via function pointer values that you store in the
- * cinfo data structure; hence they need not be globally visible and the exact
- * names don't matter.  (In fact, the "METHODDEF" macro expands to "static" if
- * you use the unmodified JPEG include files.)
+ * IMAGE DATA FORMATS:
  *
- * The input file reading modules (jrdppm.c, jrdgif.c, jrdtarga.c, etc) may be
- * useful examples of what these routines should actually do, although each of
- * them is encrusted with a lot of specialized code for its own file format.
+ * The standard input image format is a rectangular array of pixels, with
+ * each pixel having the same number of "component" values (color channels).
+ * Each pixel row is an array of JSAMPLEs (which typically are unsigned chars).
+ * If you are working with color data, then the color values for each pixel
+ * must be adjacent in the row; for example, R,G,B,R,G,B,R,G,B,... for 24-bit
+ * RGB color.
+ *
+ * For this example, we'll assume that this data structure matches the way
+ * our application has stored the image in memory, so we can just pass a
+ * pointer to our image buffer.  In particular, let's say that the image is
+ * RGB color and is described by:
  */
 
-
-METHODDEF void
-input_init (compress_info_ptr cinfo)
-/* Initialize for input; return image size and component data. */
-{
-  /* This routine must return five pieces of information about the incoming
-   * image, and must do any setup needed for the get_input_row routine.
-   * The image information is returned in fields of the cinfo struct.
-   * (If you don't care about modularity, you could initialize these fields
-   * in the main JPEG calling routine, and make this routine be a no-op.)
-   * We show some example values here.
-   */
-  cinfo->image_width = 640;		/* width in pixels */
-  cinfo->image_height = 480;		/* height in pixels */
-  /* JPEG views an image as being a rectangular array of pixels, with each
-   * pixel having the same number of "component" values (color channels).
-   * You must specify how many components there are and the colorspace
-   * interpretation of the components.  Most applications will use RGB data or
-   * grayscale data.  If you want to use something else, you'll need to study
-   * and perhaps modify jcdeflts.c, jccolor.c, and jdcolor.c.
-   */
-  cinfo->input_components = 3;		/* or 1 for grayscale */
-  cinfo->in_color_space = CS_RGB;	/* or CS_GRAYSCALE for grayscale */
-  cinfo->data_precision = 8;		/* bits per pixel component value */
-  /* In the current JPEG software, data_precision must be set equal to
-   * BITS_IN_JSAMPLE, which is 8 unless you twiddle jconfig.h.  Future
-   * versions might allow you to say either 8 or 12 if compiled with
-   * 12-bit JSAMPLEs, or up to 16 in lossless mode.  In any case,
-   * it is up to you to scale incoming pixel values to the range
-   *   0 .. (1<<data_precision)-1.
-   * If your image data format is fixed at a byte per component,
-   * then saying "8" is probably the best long-term solution.
-   */
-}
+extern JSAMPLE * image_buffer;	/* Points to large array of R,G,B-order data */
+extern int image_height;	/* Number of rows in image */
+extern int image_width;		/* Number of columns in image */
 
 
 /*
- * This function is called repeatedly and must supply the next row of pixels
- * on each call.  The rows MUST be returned in top-to-bottom order if you want
- * your JPEG files to be compatible with everyone else's.  (If you cannot
- * readily read your data in that order, you'll need an intermediate array to
- * hold the image.  See jrdtarga.c or jrdrle.c for examples of handling
- * bottom-to-top source data using the JPEG code's portable mechanisms.)
- * The data is to be returned into a 2-D array of JSAMPLEs, indexed as
- *		JSAMPLE pixel_row[component][column]
- * where component runs from 0 to cinfo->input_components-1, and column runs
- * from 0 to cinfo->image_width-1 (column 0 is left edge of image).  Note that
- * this is actually an array of pointers to arrays rather than a true 2D array,
- * since C does not support variable-size multidimensional arrays.
- * JSAMPLE is typically typedef'd as "unsigned char".
- */
-
-
-METHODDEF void
-get_input_row (compress_info_ptr cinfo, JSAMPARRAY pixel_row)
-/* Read next row of pixels into pixel_row[][] */
-{
-  /* This example shows how you might read RGB data (3 components)
-   * from an input file in which the data is stored 3 bytes per pixel
-   * in left-to-right, top-to-bottom order.
-   */
-  register FILE * infile = cinfo->input_file;
-  register JSAMPROW ptr0, ptr1, ptr2;
-  register long col;
-  
-  ptr0 = pixel_row[0];
-  ptr1 = pixel_row[1];
-  ptr2 = pixel_row[2];
-  for (col = 0; col < cinfo->image_width; col++) {
-    *ptr0++ = (JSAMPLE) getc(infile); /* red */
-    *ptr1++ = (JSAMPLE) getc(infile); /* green */
-    *ptr2++ = (JSAMPLE) getc(infile); /* blue */
-  }
-}
-
-
-METHODDEF void
-input_term (compress_info_ptr cinfo)
-/* Finish up at the end of the input */
-{
-  /* This termination routine will very often have no work to do, */
-  /* but you must provide it anyway. */
-  /* Note that the JPEG code will only call it during successful exit; */
-  /* if you want it called during error exit, you gotta do that yourself. */
-}
-
-
-/*
- * That's it for the routines that deal with reading the input image data.
- * Now we have overall control and parameter selection routines.
- */
-
-
-/*
- * This routine must determine what output JPEG file format is to be written,
- * and make any other compression parameter changes that are desirable.
- * This routine gets control after the input file header has been read
- * (i.e., right after input_init has been called).  You could combine its
- * functions into input_init, or even into the main control routine, but
- * if you have several different input_init routines, it's a definite win
- * to keep this separate.  You MUST supply this routine even if it's a no-op.
- */
-
-METHODDEF void
-c_ui_method_selection (compress_info_ptr cinfo)
-{
-  /* If the input is gray scale, generate a monochrome JPEG file. */
-  if (cinfo->in_color_space == CS_GRAYSCALE)
-    j_monochrome_default(cinfo);
-  /* For now, always select JFIF output format. */
-  jselwjfif(cinfo);
-}
-
-
-/*
- * OK, here is the main function that actually causes everything to happen.
- * We assume here that the target filename is supplied by the caller of this
- * routine, and that all JPEG compression parameters can be default values.
+ * Sample routine for JPEG compression.  We assume that the target file name
+ * and a compression quality factor are passed in.
  */
 
 GLOBAL void
-write_JPEG_file (char * filename)
+write_JPEG_file (char * filename, int quality)
 {
-  /* These three structs contain JPEG parameters and working data.
-   * They must survive for the duration of parameter setup and one
-   * call to jpeg_compress; typically, making them local data in the
-   * calling routine is the best strategy.
+  /* This struct contains the JPEG compression parameters and pointers to
+   * working space (which is allocated as needed by the JPEG library).
+   * It is possible to have several such structures, representing multiple
+   * compression/decompression processes, in existence at once.  We refer
+   * to any one struct (and its associated working data) as a "JPEG object".
    */
-  struct Compress_info_struct cinfo;
-  struct Compress_methods_struct c_methods;
-  struct External_methods_struct e_methods;
+  struct jpeg_compress_struct cinfo;
+  /* This struct represents a JPEG error handler.  It is declared separately
+   * because applications often want to supply a specialized error handler
+   * (see the second half of this file for an example).  But here we just
+   * take the easy way out and use the standard error handler, which will
+   * print a message on stderr and call exit() if compression fails.
+   */
+  struct jpeg_error_mgr jerr;
+  /* More stuff */
+  FILE * outfile;		/* target file */
+  JSAMPROW row_pointer[1];	/* pointer to JSAMPLE row[s] */
+  int row_stride;		/* physical row width in image buffer */
 
-  /* Initialize the system-dependent method pointers. */
-  cinfo.methods = &c_methods;	/* links to method structs */
-  cinfo.emethods = &e_methods;
-  /* Here we use the default JPEG error handler, which will just print
-   * an error message on stderr and call exit().  See the second half of
-   * this file for an example of more graceful error recovery.
-   */
-  jselerror(&e_methods);	/* select std error/trace message routines */
-  /* Here we use the standard memory manager provided with the JPEG code.
-   * In some cases you might want to replace the memory manager, or at
-   * least the system-dependent part of it, with your own code.
-   */
-  jselmemmgr(&e_methods);	/* select std memory allocation routines */
-  /* If the compressor requires full-image buffers (for entropy-coding
-   * optimization or a noninterleaved JPEG file), it will create temporary
-   * files for anything that doesn't fit within the maximum-memory setting.
-   * (Note that temp files are NOT needed if you use the default parameters.)
-   * You can change the default maximum-memory setting by changing
-   * e_methods.max_memory_to_use after jselmemmgr returns.
-   * On some systems you may also need to set up a signal handler to
-   * ensure that temporary files are deleted if the program is interrupted.
-   * (This is most important if you are on MS-DOS and use the jmemdos.c
-   * memory manager back end; it will try to grab extended memory for
-   * temp files, and that space will NOT be freed automatically.)
-   * See jcmain.c or jdmain.c for an example signal handler.
-   */
+  /* Step 1: allocate and initialize JPEG compression object */
 
-  /* Here, set up pointers to your own routines for input data handling
-   * and post-init parameter selection.
+  /* We have to set up the error handler first, in case the initialization
+   * step fails.  (Unlikely, but it could happen if you are out of memory.)
+   * This routine fills in the contents of struct jerr, and returns jerr's
+   * address which we place into the link field in cinfo.
    */
-  c_methods.input_init = input_init;
-  c_methods.get_input_row = get_input_row;
-  c_methods.input_term = input_term;
-  c_methods.c_ui_method_selection = c_ui_method_selection;
+  cinfo.err = jpeg_std_error(&jerr);
+  /* Now we can initialize the JPEG compression object. */
+  jpeg_create_compress(&cinfo);
 
-  /* Set up default JPEG parameters in the cinfo data structure. */
-  j_c_defaults(&cinfo, 75, FALSE);
-  /* Note: 75 is the recommended default quality level; you may instead pass
-   * a user-specified quality level.  Be aware that values below 25 will cause
-   * non-baseline JPEG files to be created (and a warning message to that
-   * effect to be emitted on stderr).  This won't bother our decoder, but some
-   * commercial JPEG implementations may choke on non-baseline JPEG files.
-   * If you want to force baseline compatibility, pass TRUE instead of FALSE.
-   * (If non-baseline files are fine, but you could do without that warning
-   * message, set e_methods.trace_level to -1.)
-   */
+  /* Step 2: specify data destination (eg, a file) */
+  /* Note: steps 2 and 3 can be done in either order. */
 
-  /* At this point you can modify the default parameters set by j_c_defaults
-   * as needed.  For a minimal implementation, you shouldn't need to change
-   * anything.  See jcmain.c for some examples of what you might change.
-   */
-
-  /* Select the input and output files.
-   * Note that cinfo.input_file is only used if your input reading routines
-   * use it; otherwise, you can just make it NULL.
+  /* Here we use the library-supplied code to send compressed data to a
+   * stdio stream.  You can also write your own code to do something else.
    * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
    * requires it in order to write binary files.
    */
-
-  cinfo.input_file = NULL;	/* if no actual input file involved */
-
-  if ((cinfo.output_file = fopen(filename, "wb")) == NULL) {
+  if ((outfile = fopen(filename, "wb")) == NULL) {
     fprintf(stderr, "can't open %s\n", filename);
     exit(1);
   }
+  jpeg_stdio_dest(&cinfo, outfile);
 
-  /* Here we go! */
-  jpeg_compress(&cinfo);
+  /* Step 3: set parameters for compression */
 
-  /* That's it, son.  Nothin' else to do, except close files. */
-  /* Here we assume only the output file need be closed. */
-  fclose(cinfo.output_file);
-
-  /* Note: if you want to compress more than one image, we recommend you
-   * repeat this whole routine.  You MUST repeat the j_c_defaults()/alter
-   * parameters/jpeg_compress() sequence, as some data structures allocated
-   * in j_c_defaults are freed upon exit from jpeg_compress.
+  /* First we supply a description of the input image.
+   * Four fields of the cinfo struct must be filled in:
    */
+  cinfo.image_width = image_width; 	/* image width and height, in pixels */
+  cinfo.image_height = image_height;
+  cinfo.input_components = 3;		/* # of color components per pixel */
+  cinfo.in_color_space = JCS_RGB; 	/* colorspace of input image */
+  /* Now use the library's routine to set default compression parameters.
+   * (You must set at least cinfo.in_color_space before calling this,
+   * since the defaults depend on the source color space.)
+   */
+  jpeg_set_defaults(&cinfo);
+  /* Now you can set any non-default parameters you wish to.
+   * Here we just illustrate the use of quality (quantization table) scaling:
+   */
+  jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
+
+  /* Step 4: Start compressor */
+
+  /* TRUE ensures that we will write a complete interchange-JPEG file.
+   * Pass TRUE unless you are very sure of what you're doing.
+   */
+  jpeg_start_compress(&cinfo, TRUE);
+
+  /* Step 5: while (scan lines remain to be written) */
+  /*           jpeg_write_scanlines(...); */
+
+  /* Here we use the library's state variable cinfo.next_scanline as the
+   * loop counter, so that we don't have to keep track ourselves.
+   * To keep things simple, we pass one scanline per call; you can pass
+   * more if you wish, though.
+   */
+  row_stride = image_width * 3;	/* JSAMPLEs per row in image_buffer */
+
+  while (cinfo.next_scanline < cinfo.image_height) {
+    row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
+    (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
+  }
+
+  /* Step 6: Finish compression */
+
+  jpeg_finish_compress(&cinfo);
+  /* After finish_compress, we can close the output file. */
+  fclose(outfile);
+
+  /* Step 7: release JPEG compression object */
+
+  /* This is an important step since it will release a good deal of memory. */
+  jpeg_destroy_compress(&cinfo);
+
+  /* And we're done! */
 }
 
 
+/*
+ * SOME FINE POINTS:
+ *
+ * In the above loop, we ignored the return value of jpeg_write_scanlines,
+ * which is the number of scanlines actually written.  We could get away
+ * with this because we were only relying on the value of cinfo.next_scanline,
+ * which will be incremented correctly.  If you maintain additional loop
+ * variables then you should be careful to increment them properly.
+ * Actually, for output to a stdio stream you needn't worry, because
+ * then jpeg_write_scanlines will write all the lines passed (or else exit
+ * with a fatal error).  Partial writes can only occur if you use a data
+ * destination module that can demand suspension of the compressor.
+ * (If you don't know what that's for, you don't need it.)
+ *
+ * If the compressor requires full-image buffers (for entropy-coding
+ * optimization or a noninterleaved JPEG file), it will create temporary
+ * files for anything that doesn't fit within the maximum-memory setting.
+ * (Note that temp files are NOT needed if you use the default parameters.)
+ * On some systems you may need to set up a signal handler to ensure that
+ * temporary files are deleted if the program is interrupted.  See libjpeg.doc.
+ *
+ * Scanlines MUST be supplied in top-to-bottom order if you want your JPEG
+ * files to be compatible with everyone else's.  If you cannot readily read
+ * your data in that order, you'll need an intermediate array to hold the
+ * image.  See rdtarga.c or rdbmp.c for examples of handling bottom-to-top
+ * source data using the JPEG code's internal virtual-array mechanisms.
+ */
+
+
 
 /******************** JPEG DECOMPRESSION SAMPLE INTERFACE *******************/
 
 /* This half of the example shows how to read data from the JPEG decompressor.
- * It's a little more refined than the above in that we show how to do your
- * own error recovery.  If you don't care about that, you don't need these
- * next two routines.
- */
-
-
-/*
- * These routines replace the default trace/error routines included with the
- * JPEG code.  The example trace_message routine shown here is actually the
- * same as the standard one, but you could modify it if you don't want messages
- * sent to stderr.  The example error_exit routine is set up to return
- * control to read_JPEG_file() rather than calling exit().  You can use the
- * same routines for both compression and decompression error recovery.
- */
-
-/* These static variables are needed by the error routines. */
-static jmp_buf setjmp_buffer;	/* for return to caller */
-static external_methods_ptr emethods; /* needed for access to message_parm */
-
-
-/* This routine is used for any and all trace, debug, or error printouts
- * from the JPEG code.  The parameter is a printf format string; up to 8
- * integer data values for the format string have been stored in the
- * message_parm[] field of the external_methods struct.
- */
-
-METHODDEF void
-trace_message (const char *msgtext)
-{
-  fprintf(stderr, msgtext,
-	  emethods->message_parm[0], emethods->message_parm[1],
-	  emethods->message_parm[2], emethods->message_parm[3],
-	  emethods->message_parm[4], emethods->message_parm[5],
-	  emethods->message_parm[6], emethods->message_parm[7]);
-  fprintf(stderr, "\n");	/* there is no \n in the format string! */
-}
-
-/*
- * The error_exit() routine should not return to its caller.  The default
- * routine calls exit(), but here we assume that we want to return to
- * read_JPEG_file, which has set up a setjmp context for the purpose.
- * You should make sure that the free_all method is called, either within
- * error_exit or after the return to the outer-level routine.
- */
-
-METHODDEF void
-error_exit (const char *msgtext)
-{
-  trace_message(msgtext);	/* report the error message */
-  (*emethods->free_all) ();	/* clean up memory allocation & temp files */
-  longjmp(setjmp_buffer, 1);	/* return control to outer routine */
-}
-
-
-
-/*
- * To accept the image data from decompression, you must define four routines
- * output_init, put_color_map, put_pixel_rows, and output_term.
+ * It's a bit more refined than the above, in that we show:
+ *   (a) how to modify the JPEG library's standard error-reporting behavior;
+ *   (b) how to allocate workspace using the library's memory manager.
  *
- * You must understand the distinction between full color output mode
- * (N independent color components) and colormapped output mode (a single
- * output component representing an index into a color map).  You should use
- * colormapped mode to write to a colormapped display screen or output file.
- * Colormapped mode is also useful for reducing grayscale output to a small
- * number of gray levels: when using the 1-pass quantizer on grayscale data,
- * the colormap entries will be evenly spaced from 0 to MAX_JSAMPLE, so you
- * can regard the indexes as directly representing gray levels at reduced
- * precision.  In any other case, you should not depend on the colormap
- * entries having any particular order.
- * To get colormapped output, set cinfo->quantize_colors to TRUE and set
- * cinfo->desired_number_of_colors to the maximum number of entries in the
- * colormap.  This can be done either in your main routine or in
- * d_ui_method_selection.  For grayscale quantization, also set
- * cinfo->two_pass_quantize to FALSE to ensure the 1-pass quantizer is used
- * (presently this is the default, but it may not be so in the future).
- *
- * The output file writing modules (jwrppm.c, jwrgif.c, jwrtarga.c, etc) may be
- * useful examples of what these routines should actually do, although each of
- * them is encrusted with a lot of specialized code for its own file format.
- */
-
-
-METHODDEF void
-output_init (decompress_info_ptr cinfo)
-/* This routine should do any setup required */
-{
-  /* This routine can initialize for output based on the data passed in cinfo.
-   * Useful fields include:
-   *	image_width, image_height	Pretty obvious, I hope.
-   *	data_precision			bits per pixel value; typically 8.
-   *	out_color_space			output colorspace previously requested
-   *	color_out_comps			number of color components in same
-   *	final_out_comps			number of components actually output
-   * final_out_comps is 1 if quantize_colors is true, else it is equal to
-   * color_out_comps.
-   *
-   * If you have requested color quantization, the colormap is NOT yet set.
-   * You may wish to defer output initialization until put_color_map is called.
-   */
-}
-
-
-/*
- * This routine is called if and only if you have set cinfo->quantize_colors
- * to TRUE.  It is given the selected colormap and can complete any required
- * initialization.  This call will occur after output_init and before any
- * calls to put_pixel_rows.  Note that the colormap pointer is also placed
- * in a cinfo field, whence it can be used by put_pixel_rows or output_term.
- * num_colors will be less than or equal to desired_number_of_colors.
- *
- * The colormap data is supplied as a 2-D array of JSAMPLEs, indexed as
- *		JSAMPLE colormap[component][indexvalue]
- * where component runs from 0 to cinfo->color_out_comps-1, and indexvalue
- * runs from 0 to num_colors-1.  Note that this is actually an array of
- * pointers to arrays rather than a true 2D array, since C does not support
- * variable-size multidimensional arrays.
- * JSAMPLE is typically typedef'd as "unsigned char".  If you want your code
- * to be as portable as the JPEG code proper, you should always access JSAMPLE
- * values with the GETJSAMPLE() macro, which will do the right thing if the
- * machine has only signed chars.
- */
-
-METHODDEF void
-put_color_map (decompress_info_ptr cinfo, int num_colors, JSAMPARRAY colormap)
-/* Write the color map */
-{
-  /* You need not provide this routine if you always set cinfo->quantize_colors
-   * FALSE; but a safer practice is to provide it and have it just print an
-   * error message, like this:
-   */
-  fprintf(stderr, "put_color_map called: there's a bug here somewhere!\n");
-}
-
-
-/*
- * This function is called repeatedly, with a few more rows of pixels supplied
- * on each call.  With the current JPEG code, some multiple of 8 rows will be
- * passed on each call except the last, but it is extremely bad form to depend
- * on this.  You CAN assume num_rows > 0.
- * The data is supplied in top-to-bottom row order (the standard order within
- * a JPEG file).  If you cannot readily use the data in that order, you'll
- * need an intermediate array to hold the image.  See jwrrle.c for an example
- * of outputting data in bottom-to-top order.
- *
- * The data is supplied as a 3-D array of JSAMPLEs, indexed as
- *		JSAMPLE pixel_data[component][row][column]
- * where component runs from 0 to cinfo->final_out_comps-1, row runs from 0 to
- * num_rows-1, and column runs from 0 to cinfo->image_width-1 (column 0 is
- * left edge of image).  Note that this is actually an array of pointers to
- * pointers to arrays rather than a true 3D array, since C does not support
- * variable-size multidimensional arrays.
- * JSAMPLE is typically typedef'd as "unsigned char".  If you want your code
- * to be as portable as the JPEG code proper, you should always access JSAMPLE
- * values with the GETJSAMPLE() macro, which will do the right thing if the
- * machine has only signed chars.
- *
- * If quantize_colors is true, then there is only one component, and its values
- * are indexes into the previously supplied colormap.  Otherwise the values
- * are actual data in your selected output colorspace.
- */
-
-
-METHODDEF void
-put_pixel_rows (decompress_info_ptr cinfo, int num_rows, JSAMPIMAGE pixel_data)
-/* Write some rows of output data */
-{
-  /* This example shows how you might write full-color RGB data (3 components)
-   * to an output file in which the data is stored 3 bytes per pixel.
-   */
-  register FILE * outfile = cinfo->output_file;
-  register JSAMPROW ptr0, ptr1, ptr2;
-  register long col;
-  register int row;
-  
-  for (row = 0; row < num_rows; row++) {
-    ptr0 = pixel_data[0][row];
-    ptr1 = pixel_data[1][row];
-    ptr2 = pixel_data[2][row];
-    for (col = 0; col < cinfo->image_width; col++) {
-      putc(GETJSAMPLE(*ptr0), outfile);	/* red */
-      ptr0++;
-      putc(GETJSAMPLE(*ptr1), outfile);	/* green */
-      ptr1++;
-      putc(GETJSAMPLE(*ptr2), outfile);	/* blue */
-      ptr2++;
-    }
-  }
-}
-
-
-METHODDEF void
-output_term (decompress_info_ptr cinfo)
-/* Finish up at the end of the output */
-{
-  /* This termination routine may not need to do anything. */
-  /* Note that the JPEG code will only call it during successful exit; */
-  /* if you want it called during error exit, you gotta do that yourself. */
-}
-
-
-/*
- * That's it for the routines that deal with writing the output image.
- * Now we have overall control and parameter selection routines.
+ * Just to make this example a little different from the first one, we'll
+ * assume that we do not intend to put the whole image into an in-memory
+ * buffer, but to send it line-by-line someplace else.  We need a one-
+ * scanline-high JSAMPLE array as a work buffer, and we will let the JPEG
+ * memory manager allocate it for us.  This approach is actually quite useful
+ * because we don't need to remember to deallocate the buffer separately: it
+ * will go away automatically when the JPEG object is cleaned up.
  */
 
 
 /*
- * This routine gets control after the JPEG file header has been read;
- * at this point the image size and colorspace are known.
- * The routine must determine what output routines are to be used, and make
- * any decompression parameter changes that are desirable.  For example,
- * if it is found that the JPEG file is grayscale, you might want to do
- * things differently than if it is color.  You can also delay setting
- * quantize_colors and associated options until this point. 
+ * ERROR HANDLING:
  *
- * j_d_defaults initializes out_color_space to CS_RGB.  If you want grayscale
- * output you should set out_color_space to CS_GRAYSCALE.  Note that you can
- * force grayscale output from a color JPEG file (though not vice versa).
+ * The JPEG library's standard error handler (jerror.c) is divided into
+ * several "methods" which you can override individually.  This lets you
+ * adjust the behavior without duplicating a lot of code, which you might
+ * have to update with each future release.
+ *
+ * Our example here shows how to override the "error_exit" method so that
+ * control is returned to the library's caller when a fatal error occurs,
+ * rather than calling exit() as the standard error_exit method does.
+ *
+ * We use C's setjmp/longjmp facility to return control.  This means that the
+ * routine which calls the JPEG library must first execute a setjmp() call to
+ * establish the return point.  We want the replacement error_exit to do a
+ * longjmp().  But we need to make the setjmp buffer accessible to the
+ * error_exit routine.  To do this, we make a private extension of the
+ * standard JPEG error handler object.  (If we were using C++, we'd say we
+ * were making a subclass of the regular error handler.)
+ *
+ * Here's the extended error handler struct:
+ */
+
+struct my_error_mgr {
+  struct jpeg_error_mgr pub;	/* "public" fields */
+
+  jmp_buf setjmp_buffer;	/* for return to caller */
+};
+
+typedef struct my_error_mgr * my_error_ptr;
+
+/*
+ * Here's the routine that will replace the standard error_exit method:
  */
 
 METHODDEF void
-d_ui_method_selection (decompress_info_ptr cinfo)
+my_error_exit (j_common_ptr cinfo)
 {
-  /* if grayscale input, force grayscale output; */
-  /* else leave the output colorspace as set by main routine. */
-  if (cinfo->jpeg_color_space == CS_GRAYSCALE)
-    cinfo->out_color_space = CS_GRAYSCALE;
+  /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
+  my_error_ptr myerr = (my_error_ptr) cinfo->err;
 
-  /* select output routines */
-  cinfo->methods->output_init = output_init;
-  cinfo->methods->put_color_map = put_color_map;
-  cinfo->methods->put_pixel_rows = put_pixel_rows;
-  cinfo->methods->output_term = output_term;
+  /* Always display the message. */
+  /* We could postpone this until after returning, if we chose. */
+  (*cinfo->err->output_message) (cinfo);
+
+  /* Return control to the setjmp point */
+  longjmp(myerr->setjmp_buffer, 1);
 }
 
 
 /*
- * OK, here is the main function that actually causes everything to happen.
- * We assume here that the JPEG filename is supplied by the caller of this
- * routine, and that all decompression parameters can be default values.
- * The routine returns 1 if successful, 0 if not.
+ * Sample routine for JPEG decompression.  We assume that the source file name
+ * is passed in.  We want to return 1 on success, 0 on error.
  */
 
+
 GLOBAL int
 read_JPEG_file (char * filename)
 {
-  /* These three structs contain JPEG parameters and working data.
-   * They must survive for the duration of parameter setup and one
-   * call to jpeg_decompress; typically, making them local data in the
-   * calling routine is the best strategy.
+  /* This struct contains the JPEG decompression parameters and pointers to
+   * working space (which is allocated as needed by the JPEG library).
    */
-  struct Decompress_info_struct cinfo;
-  struct Decompress_methods_struct dc_methods;
-  struct External_methods_struct e_methods;
+  struct jpeg_decompress_struct cinfo;
+  /* We use our private extension JPEG error handler. */
+  struct my_error_mgr jerr;
+  /* More stuff */
+  FILE * infile;		/* source file */
+  JSAMPARRAY buffer;		/* Output row buffer */
+  int row_stride;		/* physical row width in output buffer */
 
-  /* Select the input and output files.
-   * In this example we want to open the input file before doing anything else,
+  /* In this example we want to open the input file before doing anything else,
    * so that the setjmp() error recovery below can assume the file is open.
-   * Note that cinfo.output_file is only used if your output handling routines
-   * use it; otherwise, you can just make it NULL.
    * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
    * requires it in order to read binary files.
    */
 
-  if ((cinfo.input_file = fopen(filename, "rb")) == NULL) {
+  if ((infile = fopen(filename, "rb")) == NULL) {
     fprintf(stderr, "can't open %s\n", filename);
     return 0;
   }
 
-  cinfo.output_file = NULL;	/* if no actual output file involved */
+  /* Step 1: allocate and initialize JPEG decompression object */
 
-  /* Initialize the system-dependent method pointers. */
-  cinfo.methods = &dc_methods;	/* links to method structs */
-  cinfo.emethods = &e_methods;
-  /* Here we supply our own error handler; compare to use of standard error
-   * handler in the previous write_JPEG_file example.
-   */
-  emethods = &e_methods;	/* save struct addr for possible access */
-  e_methods.error_exit = error_exit; /* supply error-exit routine */
-  e_methods.trace_message = trace_message; /* supply trace-message routine */
-  e_methods.trace_level = 0;	/* default = no tracing */
-  e_methods.num_warnings = 0;	/* no warnings emitted yet */
-  e_methods.first_warning_level = 0; /* display first corrupt-data warning */
-  e_methods.more_warning_level = 3; /* but suppress additional ones */
-
-  /* prepare setjmp context for possible exit from error_exit */
-  if (setjmp(setjmp_buffer)) {
+  /* We set up the normal JPEG error routines, then override error_exit. */
+  cinfo.err = jpeg_std_error(&jerr.pub);
+  jerr.pub.error_exit = my_error_exit;
+  /* Establish the setjmp return context for my_error_exit to use. */
+  if (setjmp(jerr.setjmp_buffer)) {
     /* If we get here, the JPEG code has signaled an error.
-     * Memory allocation has already been cleaned up (see free_all call in
-     * error_exit), but we need to close the input file before returning.
-     * You might also need to close an output file, etc.
+     * We need to clean up the JPEG object, close the input file, and return.
      */
-    fclose(cinfo.input_file);
+    jpeg_destroy_decompress(&cinfo);
+    fclose(infile);
     return 0;
   }
+  /* Now we can initialize the JPEG decompression object. */
+  jpeg_create_decompress(&cinfo);
 
-  /* Here we use the standard memory manager provided with the JPEG code.
-   * In some cases you might want to replace the memory manager, or at
-   * least the system-dependent part of it, with your own code.
-   */
-  jselmemmgr(&e_methods);	/* select std memory allocation routines */
-  /* If the decompressor requires full-image buffers (for two-pass color
-   * quantization or a noninterleaved JPEG file), it will create temporary
-   * files for anything that doesn't fit within the maximum-memory setting.
-   * You can change the default maximum-memory setting by changing
-   * e_methods.max_memory_to_use after jselmemmgr returns.
-   * On some systems you may also need to set up a signal handler to
-   * ensure that temporary files are deleted if the program is interrupted.
-   * (This is most important if you are on MS-DOS and use the jmemdos.c
-   * memory manager back end; it will try to grab extended memory for
-   * temp files, and that space will NOT be freed automatically.)
-   * See jcmain.c or jdmain.c for an example signal handler.
+  /* Step 2: specify data source (eg, a file) */
+
+  jpeg_stdio_src(&cinfo, infile);
+
+  /* Step 3: read file parameters with jpeg_read_header() */
+
+  (void) jpeg_read_header(&cinfo, TRUE);
+  /* We can ignore the return value from jpeg_read_header since
+   *   (a) suspension is not possible with the stdio data source, and
+   *   (b) we passed TRUE to reject a tables-only JPEG file as an error.
+   * See libjpeg.doc for more info.
    */
 
-  /* Here, set up the pointer to your own routine for post-header-reading
-   * parameter selection.  You could also initialize the pointers to the
-   * output data handling routines here, if they are not dependent on the
-   * image type.
-   */
-  dc_methods.d_ui_method_selection = d_ui_method_selection;
+  /* Step 4: set parameters for decompression */
 
-  /* Set up default decompression parameters. */
-  j_d_defaults(&cinfo, TRUE);
-  /* TRUE indicates that an input buffer should be allocated.
-   * In unusual cases you may want to allocate the input buffer yourself;
-   * see jddeflts.c for commentary.
+  /* In this example, we don't need to change any of the defaults set by
+   * jpeg_read_header(), so we do nothing here.
    */
 
-  /* At this point you can modify the default parameters set by j_d_defaults
-   * as needed; for example, you can request color quantization or force
-   * grayscale output.  See jdmain.c for examples of what you might change.
+  /* Step 5: Start decompressor */
+
+  jpeg_start_decompress(&cinfo);
+
+  /* We may need to do some setup of our own at this point before reading
+   * the data.  After jpeg_start_decompress() we have the correct scaled
+   * output image dimensions available, as well as the output colormap
+   * if we asked for color quantization.
+   * In this example, we need to make an output work buffer of the right size.
+   */ 
+  /* JSAMPLEs per row in output buffer */
+  row_stride = cinfo.output_width * cinfo.output_components;
+  /* Make a one-row-high sample array that will go away when done with image */
+  buffer = (*cinfo.mem->alloc_sarray)
+		((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
+
+  /* Step 6: while (scan lines remain to be read) */
+  /*           jpeg_read_scanlines(...); */
+
+  /* Here we use the library's state variable cinfo.output_scanline as the
+   * loop counter, so that we don't have to keep track ourselves.
+   */
+  while (cinfo.output_scanline < cinfo.output_height) {
+    (void) jpeg_read_scanlines(&cinfo, buffer, 1);
+    /* Assume put_scanline_someplace wants a pointer and sample count. */
+    put_scanline_someplace(buffer[0], row_stride);
+  }
+
+  /* Step 7: Finish decompression */
+
+  (void) jpeg_finish_decompress(&cinfo);
+  /* We can ignore the return value since suspension is not possible
+   * with the stdio data source.
    */
 
-  /* Set up to read a JFIF or baseline-JPEG file. */
-  /* This is the only JPEG file format currently supported. */
-  jselrjfif(&cinfo);
+  /* Step 8: Release JPEG decompression object */
 
-  /* Here we go! */
-  jpeg_decompress(&cinfo);
+  /* This is an important step since it will release a good deal of memory. */
+  jpeg_destroy_decompress(&cinfo);
 
-  /* That's it, son.  Nothin' else to do, except close files. */
-  /* Here we assume only the input file need be closed. */
-  fclose(cinfo.input_file);
-
-  /* You might want to test e_methods.num_warnings to see if bad data was
-   * detected.  In this example, we just blindly forge ahead.
+  /* After finish_decompress, we can close the input file.
+   * Here we postpone it until after no more JPEG errors are possible,
+   * so as to simplify the setjmp error logic above.  (Actually, I don't
+   * think that jpeg_destroy can do an error exit, but why assume anything...)
    */
-  return 1;			/* indicate success */
+  fclose(infile);
 
-  /* Note: if you want to decompress more than one image, we recommend you
-   * repeat this whole routine.  You MUST repeat the j_d_defaults()/alter
-   * parameters/jpeg_decompress() sequence, as some data structures allocated
-   * in j_d_defaults are freed upon exit from jpeg_decompress.
+  /* At this point you may want to check to see whether any corrupt-data
+   * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
    */
+
+  /* And we're done! */
+  return 1;
 }
+
+
+/*
+ * SOME FINE POINTS:
+ *
+ * In the above code, we ignored the return value of jpeg_read_scanlines,
+ * which is the number of scanlines actually read.  We could get away with
+ * this because we asked for only one line at a time and we weren't using
+ * a suspending data source.  See libjpeg.doc for more info.
+ *
+ * We cheated a bit by calling alloc_sarray() after jpeg_start_decompress();
+ * we should have done it beforehand to ensure that the space would be
+ * counted against the JPEG max_memory setting.  In some systems the above
+ * code would risk an out-of-memory error.  However, in general we don't
+ * know the output image dimensions before jpeg_start_decompress(), unless we
+ * call jpeg_calc_output_dimensions().  See libjpeg.doc for more about this.
+ *
+ * Scanlines are returned in the same order as they appear in the JPEG file,
+ * which is standardly top-to-bottom.  If you must emit data bottom-to-top,
+ * you can use one of the virtual arrays provided by the JPEG memory manager
+ * to invert the data.  See wrbmp.c for an example.
+ *
+ * As with compression, some operating modes may require temporary files.
+ * On some systems you may need to set up a signal handler to ensure that
+ * temporary files are deleted if the program is interrupted.  See libjpeg.doc.
+ */
diff --git a/filelist.doc b/filelist.doc
new file mode 100644
index 0000000..0965b74
--- /dev/null
+++ b/filelist.doc
@@ -0,0 +1,185 @@
+IJG JPEG LIBRARY:  FILE LIST
+
+Copyright (C) 1994, 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.
+
+
+Here is a road map to the files in the IJG JPEG distribution.  The
+distribution includes the JPEG library proper, plus two application
+programs ("cjpeg" and "djpeg") which use the library to convert JPEG
+files to and from some other popular image formats.  There are also
+two stand-alone applications, "rdjpgcom" and "wrjpgcom".
+
+
+THE JPEG LIBRARY
+================
+
+Include files:
+
+jpeglib.h	JPEG library's exported data and function declarations.
+jconfig.h	Configuration declarations.  Note: this file is not present
+		in the distribution; it is generated during installation.
+jmorecfg.h	Additional configuration declarations; need not be changed
+		for a standard installation.
+jerror.h	Declares JPEG library's error and trace message codes.
+jinclude.h	Central include file used by library's .c files.
+jpegint.h	JPEG library's internal data structures.
+jdct.h		Private declarations for forward & reverse DCT subsystems.
+jmemsys.h	Private declarations for memory management subsystem.
+jversion.h	Version information.
+
+Applications using the library should include jpeglib.h (which in turn
+includes jconfig.h and jmorecfg.h).  Optionally, jerror.h may be included
+if the application needs to reference individual JPEG error codes.  The
+other include files are intended for internal use and would not normally
+be included by an application program.  (cjpeg/djpeg do use jinclude.h,
+since its function is to improve portability of the whole IJG distribution.
+Most other applications will directly include the system include files they
+want, and hence won't need jinclude.h.)
+
+
+C source code files:
+
+These files contain most of the functions intended to be called directly by
+an application program:
+
+jcapi.c		Application program interface routines for compression.
+jdapi.c		Application program interface routines for decompression.
+jcomapi.c	Application program interface routines common to compression
+		and decompression.
+jcparam.c	Compression parameter setting helper routines.
+
+Compression side of the library:
+
+jcmaster.c	Master control: determines which other modules to use.
+jcmainct.c	Main buffer controller (preprocessor => JPEG compressor).
+jcprepct.c	Preprocessor buffer controller.
+jccoefct.c	Buffer controller for DCT coefficient buffer.
+jccolor.c	Color space conversion.
+jcsample.c	Downsampling.
+jcdctmgr.c	DCT manager (DCT implementation selection & control).
+jfdctint.c	Forward DCT using slow-but-accurate integer method.
+jfdctfst.c	Forward DCT using faster, less accurate integer method.
+jfdctflt.c	Forward DCT using floating-point arithmetic.
+jchuff.c	Huffman entropy coding.
+jcmarker.c	JPEG marker writing.
+jdatadst.c	Data destination manager for stdio output.
+
+Decompression side of the library:
+
+jdmaster.c	Master control: determines which other modules to use.
+jdmainct.c	Main buffer controller (JPEG decompressor => postprocessor).
+jdcoefct.c	Buffer controller for DCT coefficient buffer.
+jdpostct.c	Postprocessor buffer controller.
+jdmarker.c	JPEG marker reading.
+jdhuff.c	Huffman entropy decoding.
+jddctmgr.c	IDCT manager (IDCT implementation selection & control).
+jidctint.c	Inverse DCT using slow-but-accurate integer method.
+jidctfst.c	Inverse DCT using faster, less accurate integer method.
+jidctflt.c	Inverse DCT using floating-point arithmetic.
+jidctred.c	Inverse DCTs with reduced-size outputs.
+jdsample.c	Upsampling.
+jdcolor.c	Color space conversion.
+jdmerge.c	Merged upsampling/color conversion (faster, lower quality).
+jquant1.c	One-pass color quantization using a fixed-spacing colormap.
+jquant2.c	Two-pass color quantization using a custom-generated colormap.
+		Also handles one-pass quantization to an externally given map.
+jdatasrc.c	Data source manager for stdio input.
+
+Support files for both compression and decompression:
+
+jerror.c	Standard error handling routines (application replaceable).
+jmemmgr.c	System-independent (more or less) memory management code.
+jutils.c	Miscellaneous utility routines.
+
+jmemmgr.c relies on a system-dependent memory management module.  The IJG
+distribution includes the following implementations of the system-dependent
+module:
+
+jmemnobs.c	"No backing store": assumes adequate virtual memory exists.
+jmemansi.c	Makes temporary files with ANSI-standard routine tmpfile().
+jmemname.c	Makes temporary files with program-generated file names.
+jmemdos.c	Custom implementation for MS-DOS: knows about extended and
+		expanded memory as well as temporary files.
+
+Exactly one of the system-dependent modules should be configured into an
+installed JPEG library (see install.doc for hints about which one to use).
+On unusual systems you may find it worthwhile to make a special
+system-dependent memory manager.
+
+
+Non-C source code files:
+
+jmemdosa.asm	80x86 assembly code support for jmemdos.c; used only in
+		MS-DOS-specific configurations of the JPEG library.
+
+
+CJPEG/DJPEG
+===========
+
+Include files:
+
+cdjpeg.h	Declarations shared by cjpeg/djpeg modules.
+cderror.h	Additional error and trace message codes for cjpeg/djpeg.
+
+C source code files:
+
+cjpeg.c		Main program for cjpeg.
+djpeg.c		Main program for djpeg.
+rdcolmap.c	Code to read a colormap file for djpeg's "-map" option.
+
+Image file reader modules for cjpeg:
+
+rdbmp.c		BMP file input.
+rdgif.c		GIF file input.
+rdppm.c		PPM/PGM file input.
+rdrle.c		Utah RLE file input.
+rdtarga.c	Targa file input.
+
+Image file writer modules for djpeg:
+
+wrbmp.c		BMP file output.
+wrgif.c		GIF file output.
+wrppm.c		PPM/PGM file output.
+wrrle.c		Utah RLE file output.
+wrtarga.c	Targa file output.
+
+
+RDJPGCOM/WRJPGCOM
+=================
+
+C source code files:
+
+rdjpgcom.c	Stand-alone rdjpgcom application.
+wrjpgcom.c	Stand-alone wrjpgcom application.
+
+These programs do not depend on the IJG library.  They do use
+jconfig.h and jinclude.h, simply to improve portability.
+
+
+ADDITIONAL FILES
+================
+
+Documentation (see README for a guide to the documentation files):
+
+README		Master documentation file.
+*.doc		Other documentation files.
+*.1		Documentation in Unix man page format.
+change.log	Version-to-version change highlights.
+example.c	Sample code for calling JPEG library.
+
+Configuration/installation files and programs (see install.doc for more info):
+
+configure	Unix shell script to perform automatic configuration.
+ckconfig.c	Program to generate jconfig.h on non-Unix systems.
+jconfig.doc	Template for making jconfig.h by hand.
+makefile.*	Sample makefiles for particular systems.
+jconfig.*	Sample jconfig.h for particular systems.
+ansi2knr.c	De-ANSIfier for pre-ANSI C compilers (courtesy of
+		L. Peter Deutsch and Aladdin Enterprises).
+
+Test files (see install.doc for test procedure):
+
+test*.*		Source and comparison files for confidence test.
+		These are binary image files, NOT text files.
diff --git a/install.doc b/install.doc
new file mode 100644
index 0000000..289ce24
--- /dev/null
+++ b/install.doc
@@ -0,0 +1,745 @@
+INSTALLATION INSTRUCTIONS for the Independent JPEG Group's JPEG software
+
+Copyright (C) 1991-1994, 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.
+
+
+This file explains how to configure and install the IJG software.  We have
+tried to make this software extremely portable and flexible, so that it can be
+adapted to almost any environment.  The downside of this decision is that the
+installation process is complicated.  We have provided shortcuts to simplify
+the task on common systems.  But in any case, you will need at least a little
+familiarity with C programming and program build procedures for your system.
+
+If you are only using this software as part of a larger program, the larger
+program's installation procedure may take care of configuring the IJG code.
+For example, Ghostscript's installation script will configure the IJG code.
+You don't need to read this file if you just want to compile Ghostscript.
+
+If you are on a Unix machine, you may not need to read this file at all.
+Try doing
+	./configure
+	make
+	make test
+If that doesn't complain, do
+	make install
+(better do "make -n install" first to see if the makefile will put the files
+where you want them).  Read further if you run into snags or want to customize
+the code for your system.
+
+
+TABLE OF CONTENTS
+-----------------
+
+Before you start
+Configuring the software:
+	using the automatic "configure" script
+	using one of the supplied jconfig and makefile files
+	by hand
+Building the software
+Testing the software
+Installing the software
+Optional stuff
+Optimization
+Hints for specific systems
+
+
+BEFORE YOU START
+================
+
+Before installing the software you must unpack the distributed source code.
+Since you are reading this file, you have probably already succeeded in this
+task.  However, there is a potential for error if you needed to convert the
+files to the local standard text file format (for example, if you are on
+MS-DOS you may have converted LF end-of-line to CR/LF).  You must apply
+such conversion to all the files EXCEPT those whose names begin with "test".
+The test files contain binary data; if you change them in any way then the
+self-test will give bad results.
+
+Please check the last section of this file to see if there are hints for the
+specific machine or compiler you are using.
+
+
+CONFIGURING THE SOFTWARE
+========================
+
+To configure the IJG code for your system, you need to create two files:
+  * jconfig.h: contains values for system-dependent #define symbols.
+  * Makefile: controls the compilation process.
+(On a non-Unix machine, you may create "project files" or some other
+substitute for a Makefile.  jconfig.h is needed in any environment.)
+
+We provide three different ways to generate these files:
+  * On a Unix system, you can just run the "configure" script.
+  * We provide sample jconfig files and makefiles for popular machines;
+    if your machine matches one of the samples, just copy the right sample
+    files to jconfig.h and Makefile.
+  * If all else fails, read the instructions below and make your own files.
+
+
+Configuring the software using the automatic "configure" script
+---------------------------------------------------------------
+
+If you are on a Unix machine, you can just type
+	./configure
+and let the configure script construct appropriate configuration files.
+If you're using "csh" on an old version of System V, you might need to type
+	sh configure
+instead to prevent csh from trying to execute configure itself.
+Expect configure to run for a few minutes, particularly on slower machines;
+it works by compiling a series of test programs.
+
+Configure was created with GNU Autoconf and it follows the usual conventions
+for GNU configure scripts.  It makes a few assumptions that you may want to
+override.  You can do this by providing optional switches to configure:
+
+* Configure will use gcc (GNU C compiler) if it's available, otherwise cc.
+To force a particular compiler to be selected, use the CC option, for example
+	./configure CC='cc'
+The same method can be used to include any unusual compiler switches.
+For example, on HP-UX you probably want to say
+	./configure CC='cc -Aa'
+to get HP's compiler to run in ANSI mode.
+
+* Configure will set up the makefile so that "make install" will install files
+into /usr/local/bin, /usr/local/man, etc.  You can specify an installation
+prefix other than "/usr/local" by giving configure the option "--prefix=PATH".
+
+* If you don't have a lot of swap space, you may need to enable the IJG
+software's internal virtual memory mechanism.  To do this, give the option
+"--with-maxmem=N" where N is the default maxmemory limit in megabytes.
+This is discussed in more detail under "Selecting a memory manager", below.
+You probably don't need to worry about this on reasonably-sized Unix machines,
+unless you plan to process very large images.
+
+Configure has some other features that are useful if you are cross-compiling
+or working in a network of multiple machine types; but if you need those
+features, you probably already know how to use them.
+
+
+Configuring the software using one of the supplied jconfig and makefile files
+-----------------------------------------------------------------------------
+
+If you have one of these systems, you can just use the provided configuration
+files:
+
+Makefile	jconfig file	System and/or compiler
+
+makefile.manx	jconfig.manx	Amiga, Manx Aztec C
+makefile.sas	jconfig.sas	Amiga, SAS C
+mak*jpeg.st	jconfig.st	Atari ST/STE/TT, Pure C or Turbo C
+makefile.bcc	jconfig.bcc	MS-DOS, Borland C (Turbo C)
+makefile.dj	jconfig.dj	MS-DOS, DJGPP (Delorie's port of GNU C)
+makefile.mc6	jconfig.mc6	MS-DOS, Microsoft C version 6.x and up
+makefile.mms	jconfig.vms	Digital VMS, with MMS software
+makefile.vms	jconfig.vms	Digital VMS, without MMS software
+
+Copy the proper jconfig file to jconfig.h and the makefile to Makefile
+(or whatever your system uses as the standard makefile name).  For the
+Atari, we provide three project files; see the Atari hints below.
+
+
+Configuring the software by hand
+--------------------------------
+
+First, generate a jconfig.h file.  If you are moderately familiar with C,
+the comments in jconfig.doc should be enough information to do this; just
+copy jconfig.doc to jconfig.h and edit it appropriately.  Otherwise, you may
+prefer to use the ckconfig.c program.  You will need to compile and execute
+ckconfig.c by hand --- we hope you know at least enough to do that.
+ckconfig.c may not compile the first try (in fact, the whole idea is for it
+to fail if anything is going to).  If you get compile errors, fix them by
+editing ckconfig.c according to the directions given in ckconfig.c.  Once
+you get it to run, it will write a suitable jconfig.h file, and will also
+print out some advice about which makefile to use.
+
+You may also want to look at the canned jconfig files, if there is one for a
+system similar to yours.
+
+Second, select a makefile and copy it to Makefile (or whatever your system
+uses as the standard makefile name).  The most generic makefiles we provide
+are
+	makefile.ansi:	if your C compiler supports function prototypes
+	makefile.unix:	if not.
+(You have function prototypes if ckconfig.c put "#define HAVE_PROTOTYPES"
+in jconfig.h.)  You may want to start from one of the other makefiles if
+there is one for a system similar to yours.
+
+Look over the selected Makefile and adjust options as needed.  In particular
+you may want to change the CC and CFLAGS definitions.  For instance, if you
+are using GCC, set CC=gcc.  If you had to use any compiler switches to get
+ckconfig.c to work, make sure the same switches are in CFLAGS.
+
+If you are on a system that doesn't use makefiles, you'll need to set up
+project files (or whatever you do use) to compile all the source files and
+link them into executable files cjpeg, djpeg, rdjpgcom, and wrjpgcom.  See
+the file lists in any of the makefiles to find out which files go into each
+program.  Note that the provided makefiles all make a "library" file libjpeg
+first, but you don't have to do that if you don't want to; the file lists
+identify which source files are actually needed for compression,
+decompression, or both.  As a last resort, you can make a batch script that
+just compiles everything and links it all together; makefile.vms is an
+example of this (it's for VMS systems that have no make-like utility).
+
+Here are comments about some specific configuration decisions you'll
+need to make:
+
+Command line style
+------------------
+
+cjpeg and djpeg can use a Unix-like command line style which supports
+redirection and piping, like this:
+	cjpeg inputfile >outputfile
+	cjpeg <inputfile >outputfile
+	source program | cjpeg >outputfile
+The simpler "two file" command line style is just
+	cjpeg inputfile outputfile
+You may prefer the two-file style, particularly if you don't have pipes.
+
+You MUST use two-file style on any system that doesn't cope well with binary
+data fed through stdin/stdout; this is true for some MS-DOS compilers, for
+example.  If you're not on a Unix system, it's safest to assume you need
+two-file style.  (But if your compiler provides either the Posix-standard
+fdopen() library routine or a Microsoft-compatible setmode() routine, you
+can safely use the Unix command line style, by defining USE_FDOPEN or
+USE_SETMODE respectively.)
+
+To use the two-file style, make jconfig.h say "#define TWO_FILE_COMMANDLINE".
+
+Selecting a memory manager
+--------------------------
+
+The IJG code is capable of working on images that are too big to fit in main
+memory; data is swapped out to temporary files as necessary.  However, the
+code to do this is rather system-dependent.  We provide four different
+memory managers:
+
+* jmemansi.c	This version uses the ANSI-standard library routine tmpfile(),
+		which not all non-ANSI systems have.  On some systems
+		tmpfile() may put the temporary file in a non-optimal
+		location; if you don't like what it does, use jmemname.c.
+
+* jmemname.c	This version creates named temporary files.  For anything
+		except a Unix machine, you'll need to configure the
+		select_file_name() routine appropriately; see the comments
+		near the head of jmemname.c.  If you use this version, define
+		NEED_SIGNAL_CATCHER in jconfig.h to make sure the temp files
+		are removed if the program is aborted.
+
+* jmemnobs.c	(That stands for No Backing Store :-).)  This will compile on
+		almost any system, but it assumes you have enough main memory
+		or virtual memory to hold the biggest images you work with.
+
+* jmemdos.c	This should be used with most 16-bit MS-DOS compilers.
+		See the system-specific notes about MS-DOS for more info.
+		IMPORTANT: if you use this, define USE_MSDOS_MEMMGR in
+		jconfig.h, and include the assembly file jmemdosa.asm in the
+		programs.  The supplied makefiles and jconfig files for
+		MS-DOS compilers already do both.
+
+To use a particular memory manager, change the SYSDEPMEM variable in your
+makefile to equal the corresponding object file name (for example, jmemansi.o
+or jmemansi.obj for jmemansi.c).
+
+If you have plenty of (real or virtual) main memory, just use jmemnobs.c.
+"Plenty" means about ten bytes for every pixel in the largest images
+you plan to process, so a lot of systems don't meet this criterion.
+If yours doesn't, try jmemansi.c first.  If that doesn't compile, you'll have
+to use jmemname.c; be sure to adjust select_file_name() for local conditions.
+You may also need to change unlink() to remove() in close_backing_store().
+
+Except with jmemnobs.c, you need to adjust the DEFAULT_MAX_MEM setting to a
+reasonable value for your system (either by adding a #define for
+DEFAULT_MAX_MEM to jconfig.h, or by adding a -D switch to the Makefile).
+This value limits the amount of data space the program will attempt to
+allocate.  Code and static data space isn't counted, so the actual memory
+needs for cjpeg or djpeg are typically 100 to 150Kb more than the max-memory
+setting.  Larger max-memory settings reduce the amount of I/O needed to
+process a large image, but too large a value can result in "insufficient
+memory" failures.  On most Unix machines (and other systems with virtual
+memory), just set DEFAULT_MAX_MEM to several million and forget it.  At the
+other end of the spectrum, for MS-DOS machines you probably can't go much
+above 300K to 400K.  (On MS-DOS the value refers to conventional memory only.
+Extended/expanded memory is handled separately by jmemdos.c.)
+
+
+BUILDING THE SOFTWARE
+=====================
+
+Now you should be able to compile the software.  Just say "make" (or
+whatever's necessary to start the compilation).  Have a cup of coffee.
+
+Here are some things that could go wrong:
+
+If your compiler complains about undefined structures, you should be able to
+shut it up by putting "#define INCOMPLETE_TYPES_BROKEN" in jconfig.h.
+
+If you have trouble with missing system include files or inclusion of the
+wrong ones, read jinclude.h.  This shouldn't happen if you used configure
+or ckconfig.c to set up jconfig.h.
+
+There are a fair number of routines that do not use all of their parameters;
+some compilers will issue warnings about this, which you can ignore.  There
+are also a few configuration checks that may give "unreachable code" warnings.
+Any other warning deserves investigation.
+
+If you don't have a getenv() library routine, define NO_GETENV.
+
+Also see the system-specific hints, below.
+
+
+TESTING THE SOFTWARE
+====================
+
+As a quick test of functionality we've included a small sample image in
+several forms:
+	testorig.jpg	Starting point for the djpeg tests.
+	testimg.ppm	The output of djpeg testorig.jpg
+	testimg.gif	The output of djpeg -gif testorig.jpg
+	testimg.jpg	The output of cjpeg testimg.ppm
+(The two .jpg files aren't identical since JPEG is lossy.)  If you can
+generate duplicates of the testimg.* files then you probably have working
+programs.
+
+With most of the makefiles, "make test" will perform the necessary
+comparisons.
+
+If you're using a makefile that doesn't provide the test option, run djpeg
+and cjpeg by hand to generate testout.ppm, testout.gif, and testout.jpg,
+then compare these to testimg.* with whatever binary file comparison tool
+you have.  The files should be bit-for-bit identical.
+
+If the programs complain "MAX_ALLOC_CHUNK is wrong, please fix", then you
+need to reduce MAX_ALLOC_CHUNK to a value that fits in type size_t.
+Try adding "#define MAX_ALLOC_CHUNK 65520L" to jconfig.h.  A less likely
+configuration error is "ALIGN_TYPE is wrong, please fix": defining ALIGN_TYPE
+as long should take care of that one.
+
+If the cjpeg test run fails with "Missing Huffman code table entry", it's a
+good bet that you needed to define RIGHT_SHIFT_IS_UNSIGNED.  Go back to the
+configuration step and run ckconfig.c.  (This is a good plan for any other
+test failure, too.)
+
+If you are using Unix (one-file) command line style on a non-Unix system,
+it's a good idea to check that binary I/O through stdin/stdout actually
+works.  You should get the same results from "djpeg <testorig.jpg >out.ppm"
+as from "djpeg -outfile out.ppm testorig.jpg".  Note that the makefiles all
+use the latter style and therefore do not exercise stdin/stdout!  If this
+check fails, try recompiling cjpeg.c and djpeg.c with USE_SETMODE or
+USE_FDOPEN.  If it still doesn't work, better use two-file style.
+(rdjpgcom.c and wrjpgcom.c will also need to be recompiled.)
+
+If you chose a memory manager other than jmemnobs.c, you should test that
+temporary-file usage works.  Try "djpeg -gif -max 0 testorig.jpg" and make
+sure its output matches testimg.gif.  If you have any really large images
+handy, try compressing them with -optimize and/or decompressing with -gif to
+make sure your DEFAULT_MAX_MEM setting is not too large.
+
+NOTE: this is far from an exhaustive test of the JPEG software; some modules,
+such as 1-pass color quantization, are not exercised at all.  It's just a
+quick test to give you some confidence that you haven't missed something
+major.
+
+
+INSTALLING THE SOFTWARE
+=======================
+
+Once you're done with the above steps, you can install the software by
+copying the executable files (cjpeg, djpeg, rdjpgcom, and wrjpgcom) to
+wherever you normally install programs.  On Unix systems, you'll also want
+to put the man pages (cjpeg.1, djpeg.1, rdjpgcom.1, wrjpgcom.1) in the
+man-page directory.  The canned makefiles don't support this step since
+there's such a wide variety of installation procedures on different systems.
+
+If you generated a Makefile with the "configure" script, you can just say
+	make install
+to install the programs and their man pages into the standard places.
+(You'll probably need to be root to do this.)  We recommend first saying
+	make -n install
+to see where configure thought the files should go.  You may need to edit
+the Makefile, particularly if your system's conventions for man page
+filenames don't match what configure expects.
+
+If you want to install the library file libjpeg.a and the include files j*.h
+(for use in compiling other programs besides cjpeg/djpeg), then say
+	make install-lib
+
+
+OPTIONAL STUFF
+==============
+
+Progress monitor:
+
+If you like, you can #define PROGRESS_REPORT (in jconfig.h) to enable display
+of percent-done progress reports.  The routines provided in cjpeg.c/djpeg.c
+merely print percentages to stderr, but you can customize them to do
+something fancier.
+
+Utah RLE file format support:
+
+We distribute the software with support for RLE image files (Utah Raster
+Toolkit format) disabled, because the RLE support won't compile without the
+Utah library.  If you have URT version 3.1 or later, you can enable RLE
+support as follows:
+	1.  #define RLE_SUPPORTED in jconfig.h.
+	2.  Add a -I option to CFLAGS in the Makefile for the directory
+	    containing the URT .h files (typically the "include"
+	    subdirectory of the URT distribution).
+	3.  Add -L... -lrle to LDLIBS in the Makefile, where ... specifies
+	    the directory containing the URT "librle.a" file (typically the
+	    "lib" subdirectory of the URT distribution).
+
+Removing code:
+
+If you need to make a smaller version of the JPEG software, some optional
+functions can be removed at compile time.  See the xxx_SUPPORTED #defines in
+jconfig.h and jmorecfg.h.  If at all possible, we recommend that you leave in
+decoder support for all valid JPEG files, to ensure that you can read anyone's
+output.  Taking out support for image file formats that you don't use is the
+most painless way to make the programs smaller.  Another possibility is to
+remove some of the DCT methods: in particular, the "IFAST" method may not be
+enough faster than the others to be worth keeping on your machine.  (If you
+do remove ISLOW or IFAST, be sure to redefine JDCT_DEFAULT or JDCT_FASTEST
+to a supported method, by adding a #define in jconfig.h.)
+
+
+OPTIMIZATION
+============
+
+Unless you own a Cray, you'll probably be interested in making the JPEG
+software go as fast as possible.  This section covers some machine-dependent
+optimizations you may want to try.  We suggest that before trying any of
+this, you first get the basic installation to pass the self-test step.
+Repeat the self-test after any optimization to make sure that you haven't
+broken anything.
+
+The integer DCT routines perform a lot of multiplications.  These
+multiplications must yield 32-bit results, but none of their input values
+are more than 16 bits wide.  On many machines, notably the 680x0 and 80x86
+CPUs, a 16x16=>32 bit multiply instruction is faster than a full 32x32=>32
+bit multiply.  Unfortunately there is no portable way to specify such a
+multiplication in C, but some compilers can generate one when you use the
+right combination of casts.  See the MULTIPLYxxx macro definitions in
+jdct.h.  If your compiler makes "int" be 32 bits and "short" be 16 bits,
+defining SHORTxSHORT_32 is fairly likely to work.  When experimenting with
+alternate definitions, be sure to test not only whether the code still works
+(use the self-test), but also whether it is actually faster --- on some
+compilers, alternate definitions may compute the right answer, yet be slower
+than the default.  Timing cjpeg on a large PPM input file is the best way to
+check this, as the DCT will be the largest fraction of the runtime in that
+mode.  (Note: some of the distributed compiler-specific jconfig files
+already contain #define switches to select appropriate MULTIPLYxxx
+definitions.)
+
+If your machine has sufficiently fast floating point hardware, you may find
+that the float DCT method is faster than the integer DCT methods, even
+after tweaking the integer multiply macros.  In that case you may want to
+make the float DCT be the default method.  (The only objection to this is
+that float DCT results may vary slightly across machines.)  To do that, add
+"#define JDCT_DEFAULT JDCT_FLOAT" to jconfig.h.  Even if you don't change
+the default, you should redefine JDCT_FASTEST, which is the method selected
+by djpeg's -fast switch.  Don't forget to update the documentation files
+(usage.doc and/or cjpeg.1, djpeg.1) to agree with what you've done.
+
+If access to "short" arrays is slow on your machine, it may be a win to
+define type JCOEF as int rather than short.  This will cost a good deal of
+memory though, particularly in some multi-pass modes, so don't do it unless
+you have memory to burn and short is REALLY slow.
+
+If your compiler can compile function calls in-line, make sure the INLINE
+macro in jmorecfg.h is defined as the keyword that marks a function
+inline-able.  Some compilers have a switch that tells the compiler to inline
+any function it thinks is profitable (e.g., -finline-functions for gcc).
+Enabling such a switch is likely to make the compiled code bigger but faster.
+
+In general, it's worth trying the maximum optimization level of your compiler,
+and experimenting with any optional optimizations such as loop unrolling.
+(Unfortunately, far too many compilers have optimizer bugs ... be prepared to
+back off if the code fails self-test.)  If you do any experimentation along
+these lines, please report the optimal settings to jpeg-info@uunet.uu.net so
+we can mention them in future releases.  Be sure to specify your machine and
+compiler version.
+
+
+HINTS FOR SPECIFIC SYSTEMS
+==========================
+
+We welcome reports on changes needed for systems not mentioned here.  Submit
+'em to jpeg-info@uunet.uu.net.  Also, if configure or ckconfig.c is wrong
+about how to configure the JPEG software for your system, please let us know.
+
+
+Acorn RISC OS:
+
+(Thanks to Simon Middleton for these hints on compiling with Desktop C.)
+After renaming the files according to Acorn conventions, take a copy of
+makefile.ansi, change all occurrences of 'libjpeg.a' to 'libjpeg.o' and
+change these definitions as indicated:
+
+CFLAGS= -throwback -IC: -Wn
+LDLIBS=C:o.Stubs
+SYSDEPMEM=jmemansi.o
+LN=Link
+AR=LibFile -c -o
+
+Also add a new line '.c.o:; $(cc) $< $(cflags) -c -o $@'.  Remove the
+lines '$(RM) libjpeg.o' and '$(AR2) libjpeg.o' and the 'jconfig.h'
+dependency section.
+
+Copy jconfig.doc to jconfig.h.  Edit jconfig.h to define TWO_FILE_COMMANDLINE
+and CHAR_IS_UNSIGNED.
+
+Run the makefile using !AMU not !Make.  If you want to use the 'clean' and
+'test' makefile entries then you will have to fiddle with the syntax a bit
+and rename the test files.
+
+
+Amiga:
+
+SAS C 6.50 reportedly is too buggy to compile the IJG code properly.
+A patch to update to 6.51 is available from SAS or AmiNet FTP sites.
+
+
+Atari ST/STE/TT:
+ 
+Copy the project files makcjpeg.st, makdjpeg.st, and makljpeg.st to cjpeg.prj,
+djpeg.prj, and libjpeg.prj respectively.  The project files should work as-is
+with Pure C.  For Turbo C, change library filenames "PC..." to "TC..." in
+cjpeg.prj and djpeg.prj.  Note that libjpeg.prj selects jmemansi.c as the
+recommended memory manager.  You'll probably want to adjust the
+DEFAULT_MAX_MEM setting --- you want it to be a couple hundred K less than
+your normal free memory.  Put "#define DEFAULT_MAX_MEM nnnn" into jconfig.h
+to do this.
+
+To use the 68881/68882 coprocessor for the floating point DCT, add the
+compiler option "-8" to the project files and replace PCFLTLIB.LIB with
+PC881LIB.LIB in cjpeg.prj and djpeg.prj.  Or if you don't have a
+coprocessor, you may prefer to remove the float DCT code by undefining
+DCT_FLOAT_SUPPORTED in jmorecfg.h (since without a coprocessor, the float
+code will be too slow to be useful).  In that case, you can delete
+PCFLTLIB.LIB from the project files.
+
+Note that you must make libjpeg.lib before making cjpeg.ttp or djpeg.ttp.
+You'll have to perform the self-test by hand.
+
+We haven't bothered to include project files for rdjpgcom and wrjpgcom.
+Those source files should just be compiled by themselves; they don't
+depend on the JPEG library.
+
+There is a bug in some older versions of the Turbo C library which causes the
+space used by temporary files created with "tmpfile()" not to be freed after
+an abnormal program exit.  If you check your disk afterwards, you will find
+cluster chains that are allocated but not used by a file.  This should not
+happen in cjpeg or djpeg, since we enable a signal catcher to explicitly close
+temp files before exiting.  But if you use the JPEG library with your own
+code, be sure to supply a signal catcher, or else use a different
+system-dependent memory manager.
+
+
+Cray:
+
+Should you be so fortunate as to be running JPEG on a Cray YMP, there is a
+compiler bug in old versions of Cray's Standard C (prior to 3.1).  If you
+still have an old compiler, you'll need to insert a line reading
+"#pragma novector" just before the loop	
+    for (i = 1; i <= (int) htbl->bits[l]; i++)
+      huffsize[p++] = (char) l;
+in fix_huff_tbl (in V5beta1, line 204 of jchuff.c and line 176 of jdhuff.c).
+[This bug may or may not still occur with the current IJG code, but it's
+probably a dead issue anyway...]
+
+
+HP-UX:
+
+If you have HP-UX 7.05 or later with the "software development" C compiler,
+you should run the compiler in ANSI mode.  If using the configure script,
+say
+	./configure CC='cc -Aa'
+(or -Ae if you prefer).  If configuring by hand, use makefile.ansi and add
+"-Aa" to the CFLAGS line in the makefile.
+
+If you have a pre-7.05 system, or if you are using the non-ANSI C compiler
+delivered with a minimum HP-UX system, then you must use makefile.unix
+(and do NOT add -Aa); or just run configure without the CC option.
+
+On HP 9000 series 800 machines, the HP C compiler is buggy in revisions prior
+to A.08.07.  If you get complaints about "not a typedef name", you'll have to
+use makefile.unix, or run configure without the CC option.
+
+
+Macintosh, MPW:
+
+We don't directly support MPW in the current release, but Larry Rosenstein
+ported an earlier version of the IJG code without very much trouble.  There's
+useful notes and conversion scripts in his kit for porting PBMPLUS to MPW.
+You can obtain the kit by FTP to ftp.apple.com, files /pub/lsr/pbmplus-port*.
+
+
+Macintosh, Metrowerks CodeWarrior:
+
+Metrowerks release DR2 has problems with the IJG code; don't use it.  Release
+DR3.5 or later should be OK.
+
+The command-line-style interface can be used by defining USE_CCOMMAND and
+TWO_FILE_COMMANDLINE (see next entry for more details).
+
+On 680x0 Macs, Metrowerks defines type "double" as a 10-byte IEEE extended
+float.  jmemmgr.c won't like this: it wants sizeof(ALIGN_TYPE) to be a power
+of 2.  Add "#define ALIGN_TYPE long" to jconfig.h to eliminate the complaint.
+
+
+Macintosh, Think C:
+
+The supplied user-interface files (cjpeg.c and djpeg.c) are set up to provide
+a Unix-style command line interface.  You can use this interface on the Mac
+by means of Think's ccommand() library routine.  However, a much better
+Mac-style user interface has been prepared by Jim Brunner.  You can obtain
+the additional source code needed for that user interface by FTP to
+sumex-aim.stanford.edu, file /info-mac/dev/src/jpeg-convert-c.hqx.  Jim's
+documentation also includes more detailed build instructions for Think C.
+(Jim is working on updating this code to work with v5 of the IJG library,
+but it wasn't ready as of v5 release time.  Should be out before too long.)
+
+If you want to build the minimal command line version, proceed as follows.
+You'll have to prepare project files for the programs; we don't include any
+in the distribution since they are not text files.  Use the file lists in
+any of the supplied makefiles as a guide.  Also add the ANSI and Unix C
+libraries in a separate segment.  You may need to divide the JPEG files into
+more than one segment; we recommend dividing compression and decompression
+modules.  Define USE_CCOMMAND in jconfig.h so that the ccommand() routine is
+called.  You must also define TWO_FILE_COMMANDLINE because stdin/stdout
+don't handle binary data correctly.
+
+On 680x0 Macs, Think C defines type "double" as a 12-byte IEEE extended float.
+jmemmgr.c won't like this: it wants sizeof(ALIGN_TYPE) to be a power of 2.
+Add "#define ALIGN_TYPE long" to jconfig.h to eliminate the complaint.
+
+
+MIPS R3000:
+
+MIPS's cc version 1.31 has a rather nasty optimization bug.  Don't use -O
+if you have that compiler version.  (Use "cc -V" to check the version.)
+Note that the R3000 chip is found in workstations from DEC and others.
+
+
+MS-DOS, generic comments for 16-bit compilers:
+
+The IJG code is designed to be compiled in 80x86 "small" or "medium" memory
+models (i.e., data pointers are 16 bits unless explicitly declared "far";
+code pointers can be either size).  You may be able to use small model to
+compile cjpeg or djpeg by itself, but you will probably have to use medium
+model for any larger application.  This won't make much difference in
+performance.  You *will* take a noticeable performance hit if you use a
+large-data memory model, and you should avoid "huge" model if at all
+possible.  Be sure that NEED_FAR_POINTERS is defined in jconfig.h if you use
+a small-data memory model; be sure it is NOT defined if you use a large-data
+model.  (The supplied makefiles and jconfig files for Borland and Microsoft C
+compile in medium model and define NEED_FAR_POINTERS.)
+
+The DOS-specific memory manager, jmemdos.c, should be used if possible.
+It needs some assembly-code routines which are in jmemdosa.asm; make sure
+your makefile assembles that file and includes it in the library.  If you
+don't have a suitable assembler, you can get pre-assembled object files for
+jmemdosa by FTP from ftp.uu.net: graphics/jpeg/jdosaobj.zip.
+
+When using jmemdos.c, jconfig.h must define USE_MSDOS_MEMMGR and must set
+MAX_ALLOC_CHUNK to less than 64K (65520L is a typical value).  If your
+C library's far-heap malloc() can't allocate blocks that large, reduce
+MAX_ALLOC_CHUNK to whatever it can handle.
+
+If you can't use jmemdos.c for some reason --- for example, because you
+don't have an assembler to assemble jmemdosa.asm --- you'll have to fall
+back to jmemansi.c or jmemname.c.  You'll probably still need to set
+MAX_ALLOC_CHUNK in jconfig.h, because most DOS C libraries won't malloc()
+more than 64K at a time.  IMPORTANT: if you use jmemansi.c or jmemname.c,
+you will have to compile in a large-data memory model in order to get the
+right stdio library.  Too bad.
+
+wrjpgcom needs to be compiled in large model, because it malloc()s a 64KB
+work area to hold the comment text.  If your C library's malloc can't
+handle that, reduce MAX_COM_LENGTH as necessary in wrjpgcom.c.
+
+Most MS-DOS compilers treat stdin/stdout as text files, so you must use
+two-file command line style.  But if your compiler has either fdopen() or
+setmode(), you can use one-file style if you like.  To do this, define
+USE_SETMODE or USE_FDOPEN so that stdin/stdout will be set to binary mode.
+(USE_SETMODE seems to work with more DOS compilers than USE_FDOPEN.)  You
+should test that I/O through stdin/stdout produces the same results as I/O
+to explicitly named files... the "make test" procedures in the supplied
+makefiles do NOT use stdin/stdout.
+
+
+MS-DOS, generic comments for 32-bit compilers:
+
+None of the above comments about memory models apply if you are using a
+32-bit flat-memory-space environment, such as DJGPP or Watcom C.  (And you
+should use one if you have it, as performance will be much better than
+8086-compatible code!)  For flat-memory-space compilers, do NOT define
+NEED_FAR_POINTERS, and do NOT use jmemdos.c.  Use jmemnobs.c if the
+environment supplies adequate virtual memory, otherwise use jmemansi.c or
+jmemname.c.
+
+You'll still need to be careful about binary I/O through stdin/stdout.
+See the last paragraph of the previous section.
+
+
+MS-DOS, Borland C:
+
+If you want one-file command line style, just undefine TWO_FILE_COMMANDLINE.
+jconfig.bcc includes #define USE_SETMODE.  (fdopen does not work correctly.)
+
+Be sure to convert all the source files to DOS text format (CR/LF newlines).
+Although Borland C will often work OK with unmodified Unix (LF newlines)
+source files, sometimes it will give bogus compile errors.
+"Illegal character '#'" is the most common such error.
+
+
+MS-DOS, DJGPP:
+
+Use a recent version of DJGPP (1.11 or better).  If you prefer two-file
+command line style, change the supplied jconfig.dj to define
+TWO_FILE_COMMANDLINE.  makefile.dj is set up to generate only COFF files
+(cjpeg, djpeg, etc) when you say make.  After testing, say "make exe" to
+make executables with stub.exe, or "make standalone" if you want executables
+that include go32.  You will probably need to tweak the makefile's pointer to
+go32.exe to do "make standalone".
+
+
+MS-DOS, Microsoft C:
+
+If you want one-file command line style, just undefine TWO_FILE_COMMANDLINE.
+jconfig.mc6 includes #define USE_SETMODE.  (fdopen does not work correctly.)
+
+Old versions of MS C fail with an "out of macro expansion space" error
+because they can't cope with the macro TRACEMS8 (defined in jerror.h).
+If this happens to you, the easiest solution is to change TRACEMS8 to
+expand to nothing.  You'll lose the ability to dump out JPEG coefficient
+tables with djpeg -debug -debug, but at least you can compile.
+
+Original MS C 6.0 is very buggy; it compiles incorrect code unless you turn
+off optimization entirely (remove -O from CFLAGS).  6.00A is better, but it
+still generates bad code if you enable loop optimizations (-Ol or -Ox).
+
+MS C 8.0 reportedly fails to compile jquant1.c if optimization is turned off
+(yes, off).
+
+
+SGI:
+
+Set "AR2= ar -ts" rather than "AR2= ranlib" in the Makefile.  If you are
+using configure, you should say
+	./configure RANLIB='ar -ts'
+
+
+VMS:
+
+On an Alpha/VMS system with MMS, be sure to use the "/Marco=Alpha=1"
+qualifier with MMS when building the JPEG package.
+
+VAX/VMS v5.5-1 may have problems with the test step of the build procedure
+reporting differences when it compares the original and test GIF and JPG
+images.  If the error points to the last block of the files, it is most
+likely bogus and may be safely ignored.  It seems to be because the files
+are Stream_LF and Backup/Compare has difficulty with the (presumably) null
+padded files.  This problem was not observed on VAX/VMS v6.1 or AXP/VMS v6.1.
diff --git a/jbsmooth.c b/jbsmooth.c
deleted file mode 100644
index 223143e..0000000
--- a/jbsmooth.c
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * jbsmooth.c
- *
- * Copyright (C) 1991, 1992, 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.
- *
- * This file contains cross-block smoothing routines.
- * These routines are invoked via the smooth_coefficients method.
- */
-
-#include "jinclude.h"
-
-#ifdef BLOCK_SMOOTHING_SUPPORTED
-
-
-/*
- * Cross-block coefficient smoothing.
- */
-
-METHODDEF void
-smooth_coefficients (decompress_info_ptr cinfo,
-		     jpeg_component_info *compptr,
-		     JBLOCKROW above,
-		     JBLOCKROW currow,
-		     JBLOCKROW below,
-		     JBLOCKROW output)
-{
-  QUANT_TBL_PTR Qptr = cinfo->quant_tbl_ptrs[compptr->quant_tbl_no];
-  long blocks_in_row = compptr->downsampled_width / DCTSIZE;
-  long col;
-
-  /* First, copy the block row as-is.
-   * This takes care of the first & last blocks in the row, the top/bottom
-   * special cases, and the higher-order coefficients in each block.
-   */
-  jcopy_block_row(currow, output, blocks_in_row);
-
-  /* Now apply the smoothing calculation, but not to any blocks on the
-   * edges of the image.
-   */
-
-  if (above != NULL && below != NULL) {
-    for (col = 1; col < blocks_in_row-1; col++) {
-
-      /* See section K.8 of the JPEG standard.
-       *
-       * As I understand it, this produces approximations
-       * for the low frequency AC components, based on the
-       * DC values of the block and its eight neighboring blocks.
-       * (Thus it can't be used for blocks on the image edges.)
-       */
-
-      /* The layout of these variables corresponds to text and figure in K.8 */
-      
-      JCOEF DC1, DC2, DC3;
-      JCOEF DC4, DC5, DC6;
-      JCOEF DC7, DC8, DC9;
-      
-      long       AC01, AC02;
-      long AC10, AC11;
-      long AC20;
-      
-      DC1 = above [col-1][0];
-      DC2 = above [col  ][0];
-      DC3 = above [col+1][0];
-      DC4 = currow[col-1][0];
-      DC5 = currow[col  ][0];
-      DC6 = currow[col+1][0];
-      DC7 = below [col-1][0];
-      DC8 = below [col  ][0];
-      DC9 = below [col+1][0];
-      
-#define DIVIDE_256(x)	x = ( (x) < 0 ? -((128-(x))/256) : ((x)+128)/256 )
-      
-      AC01 = (36 * (DC4 - DC6));
-      DIVIDE_256(AC01);
-      AC10 = (36 * (DC2 - DC8));
-      DIVIDE_256(AC10);
-      AC20 = (9 * (DC2 + DC8 - 2*DC5));
-      DIVIDE_256(AC20);
-      AC11 = (5 * ((DC1 - DC3) - (DC7 - DC9)));
-      DIVIDE_256(AC11);
-      AC02 = (9 * (DC4 + DC6 - 2*DC5));
-      DIVIDE_256(AC02);
-      
-      /* I think that this checks to see if the quantisation
-       * on the transmitting side would have produced this
-       * answer. If so, then we use our (hopefully better)
-       * estimate.
-       */
-
-#define ABS(x)	((x) < 0 ? -(x) : (x))
-
-#define COND_ASSIGN(_ac,_n,_z)   if ((ABS(output[col][_n] - (_ac))<<1) <= Qptr[_z]) output[col][_n] = (JCOEF) (_ac)
-
-      COND_ASSIGN(AC01,  1, 1);
-      COND_ASSIGN(AC02,  2, 5);
-      COND_ASSIGN(AC10,  8, 2);
-      COND_ASSIGN(AC11,  9, 4);
-      COND_ASSIGN(AC20, 16, 3);
-    }
-  }
-}
-
-
-/*
- * The method selection routine for cross-block smoothing.
- */
-
-GLOBAL void
-jselbsmooth (decompress_info_ptr cinfo)
-{
-  /* just one implementation for now */
-  cinfo->methods->smooth_coefficients = smooth_coefficients;
-}
-
-#endif /* BLOCK_SMOOTHING_SUPPORTED */
diff --git a/jcapi.c b/jcapi.c
new file mode 100644
index 0000000..d9ba37b
--- /dev/null
+++ b/jcapi.c
@@ -0,0 +1,369 @@
+/*
+ * jcapi.c
+ *
+ * Copyright (C) 1994, 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.
+ *
+ * This file contains application interface code for the compression half of
+ * the JPEG library.  Most of the routines intended to be called directly by
+ * an application are in this file.  But also see jcparam.c for
+ * parameter-setup helper routines, and jcomapi.c for routines shared by
+ * compression and decompression.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/*
+ * Initialization of a JPEG compression object.
+ * The error manager must already be set up (in case memory manager fails).
+ */
+
+GLOBAL void
+jpeg_create_compress (j_compress_ptr cinfo)
+{
+  int i;
+
+  /* For debugging purposes, zero the whole master structure.
+   * But error manager pointer is already there, so save and restore it.
+   */
+  {
+    struct jpeg_error_mgr * err = cinfo->err;
+    MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
+    cinfo->err = err;
+  }
+  cinfo->is_decompressor = FALSE;
+
+  /* Initialize a memory manager instance for this object */
+  jinit_memory_mgr((j_common_ptr) cinfo);
+
+  /* Zero out pointers to permanent structures. */
+  cinfo->progress = NULL;
+  cinfo->dest = NULL;
+
+  cinfo->comp_info = NULL;
+
+  for (i = 0; i < NUM_QUANT_TBLS; i++)
+    cinfo->quant_tbl_ptrs[i] = NULL;
+
+  for (i = 0; i < NUM_HUFF_TBLS; i++) {
+    cinfo->dc_huff_tbl_ptrs[i] = NULL;
+    cinfo->ac_huff_tbl_ptrs[i] = NULL;
+  }
+
+  cinfo->input_gamma = 1.0;	/* in case application forgets */
+
+  /* OK, I'm ready */
+  cinfo->global_state = CSTATE_START;
+}
+
+
+/*
+ * Destruction of a JPEG compression object
+ */
+
+GLOBAL void
+jpeg_destroy_compress (j_compress_ptr cinfo)
+{
+  jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
+}
+
+
+/*
+ * Forcibly suppress or un-suppress all quantization and Huffman tables.
+ * Marks all currently defined tables as already written (if suppress)
+ * or not written (if !suppress).  This will control whether they get emitted
+ * by a subsequent jpeg_start_compress call.
+ *
+ * This routine is exported for use by applications that want to produce
+ * abbreviated JPEG datastreams.  It logically belongs in jcparam.c, but
+ * since it is called by jpeg_start_compress, we put it here --- otherwise
+ * jcparam.o would be linked whether the application used it or not.
+ */
+
+GLOBAL void
+jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
+{
+  int i;
+  JQUANT_TBL * qtbl;
+  JHUFF_TBL * htbl;
+
+  for (i = 0; i < NUM_QUANT_TBLS; i++) {
+    if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
+      qtbl->sent_table = suppress;
+  }
+
+  for (i = 0; i < NUM_HUFF_TBLS; i++) {
+    if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
+      htbl->sent_table = suppress;
+    if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
+      htbl->sent_table = suppress;
+  }
+}
+
+
+/*
+ * Compression initialization.
+ * Before calling this, all parameters and a data destination must be set up.
+ *
+ * We require a write_all_tables parameter as a failsafe check when writing
+ * multiple datastreams from the same compression object.  Since prior runs
+ * will have left all the tables marked sent_table=TRUE, a subsequent run
+ * would emit an abbreviated stream (no tables) by default.  This may be what
+ * is wanted, but for safety's sake it should not be the default behavior:
+ * programmers should have to make a deliberate choice to emit abbreviated
+ * images.  Therefore the documentation and examples should encourage people
+ * to pass write_all_tables=TRUE; then it will take active thought to do the
+ * wrong thing.
+ */
+
+GLOBAL void
+jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
+{
+  if (cinfo->global_state != CSTATE_START)
+    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+  if (write_all_tables)
+    jpeg_suppress_tables(cinfo, FALSE);	/* mark all tables to be written */
+
+  /* (Re)initialize error mgr and destination modules */
+  (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
+  (*cinfo->dest->init_destination) (cinfo);
+  /* Perform master selection of active modules */
+  jinit_master_compress(cinfo);
+  /* Set up for the first pass */
+  (*cinfo->master->prepare_for_pass) (cinfo);
+  /* Ready for application to drive first pass through jpeg_write_scanlines
+   * or jpeg_write_raw_data.
+   */
+  cinfo->next_scanline = 0;
+  cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
+}
+
+
+/*
+ * Write some scanlines of data to the JPEG compressor.
+ *
+ * The return value will be the number of lines actually written.
+ * This should be less than the supplied num_lines only in case that
+ * the data destination module has requested suspension of the compressor,
+ * or if more than image_height scanlines are passed in.
+ *
+ * Note: we warn about excess calls to jpeg_write_scanlines() since
+ * this likely signals an application programmer error.  However,
+ * excess scanlines passed in the last valid call are *silently* ignored,
+ * so that the application need not adjust num_lines for end-of-image
+ * when using a multiple-scanline buffer.
+ */
+
+GLOBAL JDIMENSION
+jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
+		      JDIMENSION num_lines)
+{
+  JDIMENSION row_ctr, rows_left;
+
+  if (cinfo->global_state != CSTATE_SCANNING)
+    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+  if (cinfo->next_scanline >= cinfo->image_height)
+    WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
+
+  /* Call progress monitor hook if present */
+  if (cinfo->progress != NULL) {
+    cinfo->progress->pass_counter = (long) cinfo->next_scanline;
+    cinfo->progress->pass_limit = (long) cinfo->image_height;
+    (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+  }
+
+  /* Give master control module another chance if this is first call to
+   * jpeg_write_scanlines.  This lets output of the frame/scan headers be
+   * delayed so that application can write COM, etc, markers between
+   * jpeg_start_compress and jpeg_write_scanlines.
+   */
+  if (cinfo->master->call_pass_startup)
+    (*cinfo->master->pass_startup) (cinfo);
+
+  /* Ignore any extra scanlines at bottom of image. */
+  rows_left = cinfo->image_height - cinfo->next_scanline;
+  if (num_lines > rows_left)
+    num_lines = rows_left;
+
+  row_ctr = 0;
+  (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
+  cinfo->next_scanline += row_ctr;
+  return row_ctr;
+}
+
+
+/*
+ * Alternate entry point to write raw data.
+ * Processes exactly one iMCU row per call.
+ */
+
+GLOBAL JDIMENSION
+jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
+		     JDIMENSION num_lines)
+{
+  JDIMENSION mcu_ctr, lines_per_MCU_row;
+
+  if (cinfo->global_state != CSTATE_RAW_OK)
+    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+  if (cinfo->next_scanline >= cinfo->image_height) {
+    WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
+    return 0;
+  }
+
+  /* Call progress monitor hook if present */
+  if (cinfo->progress != NULL) {
+    cinfo->progress->pass_counter = (long) cinfo->next_scanline;
+    cinfo->progress->pass_limit = (long) cinfo->image_height;
+    (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+  }
+
+  /* Give master control module another chance if this is first call to
+   * jpeg_write_raw_data.  This lets output of the frame/scan headers be
+   * delayed so that application can write COM, etc, markers between
+   * jpeg_start_compress and jpeg_write_raw_data.
+   */
+  if (cinfo->master->call_pass_startup)
+    (*cinfo->master->pass_startup) (cinfo);
+
+  /* Verify that at least one iMCU row has been passed. */
+  lines_per_MCU_row = cinfo->max_v_samp_factor * DCTSIZE;
+  if (num_lines < lines_per_MCU_row)
+    ERREXIT(cinfo, JERR_BUFFER_SIZE);
+
+  /* Directly compress the row. */
+  mcu_ctr = 0;
+  (*cinfo->coef->compress_data) (cinfo, data, &mcu_ctr);
+  /* If compressor did not consume the whole row, then we must need to
+   * suspend processing; this is not currently supported.
+   */
+  if (mcu_ctr != cinfo->MCUs_per_row)
+    ERREXIT(cinfo, JERR_CANT_SUSPEND);
+
+  /* OK, we processed one iMCU row. */
+  cinfo->next_scanline += lines_per_MCU_row;
+  return lines_per_MCU_row;
+}
+
+
+/*
+ * Finish JPEG compression.
+ *
+ * If a multipass operating mode was selected, this may do a great deal of
+ * work including most of the actual output.
+ */
+
+GLOBAL void
+jpeg_finish_compress (j_compress_ptr cinfo)
+{
+  JDIMENSION iMCU_row, mcu_ctr;
+
+  if (cinfo->global_state != CSTATE_SCANNING && 
+      cinfo->global_state != CSTATE_RAW_OK)
+    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+  if (cinfo->next_scanline < cinfo->image_height)
+    ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
+  /* Terminate first pass */
+  (*cinfo->master->finish_pass) (cinfo);
+  /* Perform any remaining passes */
+  while (! cinfo->master->is_last_pass) {
+    (*cinfo->master->prepare_for_pass) (cinfo);
+    for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
+      if (cinfo->progress != NULL) {
+	cinfo->progress->pass_counter = (long) iMCU_row;
+	cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
+	(*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
+      }
+      /* We bypass the main controller and invoke coef controller directly;
+       * all work is being done from the coefficient buffer.
+       */
+      mcu_ctr = 0;
+      (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL, &mcu_ctr);
+      if (mcu_ctr != cinfo->MCUs_per_row)
+	ERREXIT(cinfo, JERR_CANT_SUSPEND);
+    }
+    (*cinfo->master->finish_pass) (cinfo);
+  }
+  /* Write EOI, do final cleanup */
+  (*cinfo->marker->write_file_trailer) (cinfo);
+  (*cinfo->dest->term_destination) (cinfo);
+  /* We can use jpeg_abort to release memory and reset global_state */
+  jpeg_abort((j_common_ptr) cinfo);
+}
+
+
+/*
+ * Write a special marker.
+ * This is only recommended for writing COM or APPn markers.
+ * Must be called after jpeg_start_compress() and before
+ * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
+ */
+
+GLOBAL void
+jpeg_write_marker (j_compress_ptr cinfo, int marker,
+		   const JOCTET *dataptr, unsigned int datalen)
+{
+  if (cinfo->next_scanline != 0 ||
+      (cinfo->global_state != CSTATE_SCANNING &&
+       cinfo->global_state != CSTATE_RAW_OK))
+    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+  (*cinfo->marker->write_any_marker) (cinfo, marker, dataptr, datalen);
+}
+
+
+/*
+ * Alternate compression function: just write an abbreviated table file.
+ * Before calling this, all parameters and a data destination must be set up.
+ *
+ * To produce a pair of files containing abbreviated tables and abbreviated
+ * image data, one would proceed as follows:
+ *
+ *		initialize JPEG object
+ *		set JPEG parameters
+ *		set destination to table file
+ *		jpeg_write_tables(cinfo);
+ *		set destination to image file
+ *		jpeg_start_compress(cinfo, FALSE);
+ *		write data...
+ *		jpeg_finish_compress(cinfo);
+ *
+ * jpeg_write_tables has the side effect of marking all tables written
+ * (same as jpeg_suppress_tables(..., TRUE)).  Thus a subsequent start_compress
+ * will not re-emit the tables unless it is passed write_all_tables=TRUE.
+ */
+
+GLOBAL void
+jpeg_write_tables (j_compress_ptr cinfo)
+{
+  if (cinfo->global_state != CSTATE_START)
+    ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
+
+  /* (Re)initialize error mgr and destination modules */
+  (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
+  (*cinfo->dest->init_destination) (cinfo);
+  /* Initialize the marker writer ... bit of a crock to do it here. */
+  jinit_marker_writer(cinfo);
+  /* Write them tables! */
+  (*cinfo->marker->write_tables_only) (cinfo);
+  /* And clean up. */
+  (*cinfo->dest->term_destination) (cinfo);
+  /* We can use jpeg_abort to release memory ... is this necessary? */
+  jpeg_abort((j_common_ptr) cinfo);
+}
+
+
+/*
+ * Abort processing of a JPEG compression operation,
+ * but don't destroy the object itself.
+ */
+
+GLOBAL void
+jpeg_abort_compress (j_compress_ptr cinfo)
+{
+  jpeg_abort((j_common_ptr) cinfo); /* use common routine */
+}
diff --git a/jcarith.c b/jcarith.c
deleted file mode 100644
index 108a9fb..0000000
--- a/jcarith.c
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * jcarith.c
- *
- * Copyright (C) 1991, 1992, 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.
- *
- * This file contains arithmetic entropy encoding routines.
- * These routines are invoked via the methods entropy_encode,
- * entropy_encode_init/term, and entropy_optimize.
- */
-
-#include "jinclude.h"
-
-#ifdef C_ARITH_CODING_SUPPORTED
-
-
-/*
- * The arithmetic coding option of the JPEG standard specifies Q-coding,
- * which is covered by patents held by IBM (and possibly AT&T and Mitsubishi).
- * At this time it does not appear to be legal for the Independent JPEG
- * Group to distribute software that implements arithmetic coding.
- * We have therefore removed arithmetic coding support from the
- * distributed source code.
- *
- * We're not happy about it either.
- */
-
-
-/*
- * The method selection routine for arithmetic entropy encoding.
- */
-
-GLOBAL void
-jselcarithmetic (compress_info_ptr cinfo)
-{
-  if (cinfo->arith_code) {
-    ERREXIT(cinfo->emethods, "Sorry, there are legal restrictions on arithmetic coding");
-  }
-}
-
-#endif /* C_ARITH_CODING_SUPPORTED */
diff --git a/jccoefct.c b/jccoefct.c
new file mode 100644
index 0000000..2ca1f37
--- /dev/null
+++ b/jccoefct.c
@@ -0,0 +1,414 @@
+/*
+ * jccoefct.c
+ *
+ * Copyright (C) 1994, 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.
+ *
+ * This file contains the coefficient buffer controller for compression.
+ * This controller is the top level of the JPEG compressor proper.
+ * The coefficient buffer lies between forward-DCT and entropy encoding steps.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* We use a full-image coefficient buffer when doing Huffman optimization,
+ * and also for writing multiple-scan JPEG files.  In all cases, the DCT
+ * step is run during the first pass, and subsequent passes need only read
+ * the buffered coefficients.
+ */
+#ifdef ENTROPY_OPT_SUPPORTED
+#define FULL_COEF_BUFFER_SUPPORTED
+#else
+#ifdef C_MULTISCAN_FILES_SUPPORTED
+#define FULL_COEF_BUFFER_SUPPORTED
+#endif
+#endif
+
+
+/* Private buffer controller object */
+
+typedef struct {
+  struct jpeg_c_coef_controller pub; /* public fields */
+
+  JDIMENSION MCU_row_num;	/* keep track of MCU row # within image */
+
+  /* For single-pass compression, it's sufficient to buffer just one MCU
+   * (although this may prove a bit slow in practice).  We allocate a
+   * workspace of MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
+   * MCU constructed and sent.  (On 80x86, the workspace is FAR even though
+   * it's not really very big; this is to keep the module interfaces unchanged
+   * when a large coefficient buffer is necessary.)
+   * In multi-pass modes, this array points to the current MCU's blocks
+   * within the virtual arrays.
+   */
+  JBLOCKROW MCU_buffer[MAX_BLOCKS_IN_MCU];
+
+  /* In multi-pass modes, we need a virtual block array for each component. */
+  jvirt_barray_ptr whole_image[MAX_COMPONENTS];
+} my_coef_controller;
+
+typedef my_coef_controller * my_coef_ptr;
+
+
+/* Forward declarations */
+METHODDEF void compress_data
+    JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION *in_mcu_ctr));
+#ifdef FULL_COEF_BUFFER_SUPPORTED
+METHODDEF void compress_first_pass
+    JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION *in_mcu_ctr));
+METHODDEF void compress_output
+    JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf, JDIMENSION *in_mcu_ctr));
+#endif
+
+
+/*
+ * Initialize for a processing pass.
+ */
+
+METHODDEF void
+start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
+{
+  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+
+  coef->MCU_row_num = 0;
+
+  switch (pass_mode) {
+  case JBUF_PASS_THRU:
+    if (coef->whole_image[0] != NULL)
+      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+    coef->pub.compress_data = compress_data;
+    break;
+#ifdef FULL_COEF_BUFFER_SUPPORTED
+  case JBUF_SAVE_AND_PASS:
+    if (coef->whole_image[0] == NULL)
+      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+    coef->pub.compress_data = compress_first_pass;
+    break;
+  case JBUF_CRANK_DEST:
+    if (coef->whole_image[0] == NULL)
+      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+    coef->pub.compress_data = compress_output;
+    break;
+#endif
+  default:
+    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+    break;
+  }
+}
+
+
+/*
+ * Process some data in the single-pass case.
+ * Up to one MCU row is processed (less if suspension is forced).
+ *
+ * NB: input_buf contains a plane for each component in image.
+ * For single pass, this is the same as the components in the scan.
+ */
+
+METHODDEF void
+compress_data (j_compress_ptr cinfo,
+	       JSAMPIMAGE input_buf, JDIMENSION *in_mcu_ctr)
+{
+  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+  JDIMENSION MCU_col_num;	/* index of current MCU within row */
+  JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
+  JDIMENSION last_MCU_row = cinfo->MCU_rows_in_scan - 1;
+  int blkn, bi, ci, yindex, blockcnt;
+  JDIMENSION ypos, xpos;
+  jpeg_component_info *compptr;
+
+  /* Loop to write as much as one whole MCU row */
+
+  for (MCU_col_num = *in_mcu_ctr; MCU_col_num <= last_MCU_col; MCU_col_num++) {
+    /* Determine where data comes from in input_buf and do the DCT thing.
+     * Each call on forward_DCT processes a horizontal row of DCT blocks
+     * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
+     * sequentially.  Dummy blocks at the right or bottom edge are filled in
+     * specially.  The data in them does not matter for image reconstruction,
+     * so we fill them with values that will encode to the smallest amount of
+     * data, viz: all zeroes in the AC entries, DC entries equal to previous
+     * block's DC value.  (Thanks to Thomas Kinsman for this idea.)
+     */
+    blkn = 0;
+    for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+      compptr = cinfo->cur_comp_info[ci];
+      blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
+					      : compptr->last_col_width;
+      xpos = MCU_col_num * compptr->MCU_sample_width;
+      ypos = 0;
+      for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
+	if (coef->MCU_row_num < last_MCU_row ||
+	    yindex < compptr->last_row_height) {
+	  (*cinfo->fdct->forward_DCT) (cinfo, compptr,
+				       input_buf[ci], coef->MCU_buffer[blkn],
+				       ypos, xpos, (JDIMENSION) blockcnt);
+	  if (blockcnt < compptr->MCU_width) {
+	    /* Create some dummy blocks at the right edge of the image. */
+	    jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
+		      (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
+	    for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
+	      coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
+	    }
+	  }
+	} else {
+	  /* Create a whole row of dummy blocks at the bottom of the image. */
+	  jzero_far((void FAR *) coef->MCU_buffer[blkn],
+		    compptr->MCU_width * SIZEOF(JBLOCK));
+	  for (bi = 0; bi < compptr->MCU_width; bi++) {
+	    coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
+	  }
+	}
+	blkn += compptr->MCU_width;
+	ypos += DCTSIZE;
+      }
+    }
+    /* Try to write the MCU.  In event of a suspension failure, we will
+     * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
+     */
+    if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer))
+      break;			/* suspension forced; exit loop */
+  }
+  if (MCU_col_num > last_MCU_col)
+    coef->MCU_row_num++;	/* advance if we finished the row */
+  *in_mcu_ctr = MCU_col_num;
+}
+
+
+#ifdef FULL_COEF_BUFFER_SUPPORTED
+
+/*
+ * Process some data in the first pass of a multi-pass case.
+ * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
+ * per call, ie, v_samp_factor block rows for each component in the image.
+ * This amount of data is read from the source buffer, DCT'd and quantized,
+ * and saved into the virtual arrays.  We also generate suitable dummy blocks
+ * as needed at the right and lower edges.  (The dummy blocks are constructed
+ * in the virtual arrays, which have been padded appropriately.)  This makes
+ * it possible for subsequent passes not to worry about real vs. dummy blocks.
+ *
+ * We must also emit the data to the entropy encoder.  This is conveniently
+ * done by calling compress_output() after we've loaded the current strip
+ * of the virtual arrays.
+ *
+ * NB: input_buf contains a plane for each component in image.  All
+ * components are DCT'd and loaded into the virtual arrays in this pass.
+ * However, it may be that only a subset of the components are emitted to
+ * the entropy encoder during this first pass; be careful about looking
+ * at the scan-dependent variables (MCU dimensions, etc).
+ */
+
+METHODDEF void
+compress_first_pass (j_compress_ptr cinfo,
+		     JSAMPIMAGE input_buf, JDIMENSION *in_mcu_ctr)
+{
+  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+  JDIMENSION last_MCU_row = cinfo->total_iMCU_rows - 1;
+  JDIMENSION blocks_across, MCUs_across, MCUindex;
+  int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
+  JCOEF lastDC;
+  jpeg_component_info *compptr;
+  JBLOCKARRAY buffer;
+  JBLOCKROW thisblockrow, lastblockrow;
+
+  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+       ci++, compptr++) {
+    /* Align the virtual buffer for this component. */
+    buffer = (*cinfo->mem->access_virt_barray)
+      ((j_common_ptr) cinfo, coef->whole_image[ci],
+       coef->MCU_row_num * compptr->v_samp_factor, TRUE);
+    /* Count non-dummy DCT block rows in this iMCU row. */
+    if (coef->MCU_row_num < last_MCU_row)
+      block_rows = compptr->v_samp_factor;
+    else {
+      block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
+      if (block_rows == 0) block_rows = compptr->v_samp_factor;
+    }
+    blocks_across = compptr->width_in_blocks;
+    h_samp_factor = compptr->h_samp_factor;
+    /* Count number of dummy blocks to be added at the right margin. */
+    ndummy = (int) (blocks_across % h_samp_factor);
+    if (ndummy > 0)
+      ndummy = h_samp_factor - ndummy;
+    /* Perform DCT for all non-dummy blocks in this iMCU row.  Each call
+     * on forward_DCT processes a complete horizontal row of DCT blocks.
+     */
+    for (block_row = 0; block_row < block_rows; block_row++) {
+      thisblockrow = buffer[block_row];
+      (*cinfo->fdct->forward_DCT) (cinfo, compptr,
+				   input_buf[ci], thisblockrow,
+				   (JDIMENSION) (block_row * DCTSIZE),
+				   (JDIMENSION) 0, blocks_across);
+      if (ndummy > 0) {
+	/* Create dummy blocks at the right edge of the image. */
+	thisblockrow += blocks_across; /* => first dummy block */
+	jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
+	lastDC = thisblockrow[-1][0];
+	for (bi = 0; bi < ndummy; bi++) {
+	  thisblockrow[bi][0] = lastDC;
+	}
+      }
+    }
+    /* If at end of image, create dummy block rows as needed.
+     * The tricky part here is that within each MCU, we want the DC values
+     * of the dummy blocks to match the last real block's DC value.
+     * This squeezes a few more bytes out of the resulting file...
+     */
+    if (coef->MCU_row_num == last_MCU_row) {
+      blocks_across += ndummy;	/* include lower right corner */
+      MCUs_across = blocks_across / h_samp_factor;
+      for (block_row = block_rows; block_row < compptr->v_samp_factor;
+	   block_row++) {
+	thisblockrow = buffer[block_row];
+	lastblockrow = buffer[block_row-1];
+	jzero_far((void FAR *) thisblockrow,
+		  (size_t) (blocks_across * SIZEOF(JBLOCK)));
+	for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
+	  lastDC = lastblockrow[h_samp_factor-1][0];
+	  for (bi = 0; bi < h_samp_factor; bi++) {
+	    thisblockrow[bi][0] = lastDC;
+	  }
+	  thisblockrow += h_samp_factor; /* advance to next MCU in row */
+	  lastblockrow += h_samp_factor;
+	}
+      }
+    }
+  }
+  /* NB: compress_output will increment MCU_row_num */
+
+  /* Emit data to the entropy encoder, sharing code with subsequent passes */
+  compress_output(cinfo, input_buf, in_mcu_ctr);
+}
+
+
+/*
+ * Process some data in subsequent passes of a multi-pass case.
+ * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
+ * per call, ie, v_samp_factor block rows for each component in the scan.
+ * The data is obtained from the virtual arrays and fed to the entropy coder.
+ *
+ * Note that output suspension is not supported during multi-pass operation,
+ * so the complete MCU row will always be emitted to the entropy encoder
+ * before returning.
+ *
+ * NB: input_buf is ignored; it is likely to be a NULL pointer.
+ */
+
+METHODDEF void
+compress_output (j_compress_ptr cinfo,
+		 JSAMPIMAGE input_buf, JDIMENSION *in_mcu_ctr)
+{
+  my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
+  JDIMENSION MCU_col_num;	/* index of current MCU within row */
+  int blkn, ci, xindex, yindex, yoffset, num_MCU_rows;
+  JDIMENSION remaining_rows, start_col;
+  JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
+  JBLOCKROW buffer_ptr;
+  jpeg_component_info *compptr;
+
+  /* Align the virtual buffers for the components used in this scan.
+   * NB: during first pass, this is safe only because the buffers will
+   * already be aligned properly, so jmemmgr.c won't need to do any I/O.
+   */
+  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+    compptr = cinfo->cur_comp_info[ci];
+    buffer[ci] = (*cinfo->mem->access_virt_barray)
+      ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
+       coef->MCU_row_num * compptr->v_samp_factor, FALSE);
+  }
+
+  /* In an interleaved scan, we process exactly one MCU row.
+   * In a noninterleaved scan, we need to process v_samp_factor MCU rows,
+   * each of which contains a single block row.
+   */
+  if (cinfo->comps_in_scan == 1) {
+    compptr = cinfo->cur_comp_info[0];
+    num_MCU_rows = compptr->v_samp_factor;
+    /* but watch out for the bottom of the image */
+    remaining_rows = cinfo->MCU_rows_in_scan -
+		     coef->MCU_row_num * compptr->v_samp_factor;
+    if (remaining_rows < (JDIMENSION) num_MCU_rows)
+      num_MCU_rows = (int) remaining_rows;
+  } else {
+    num_MCU_rows = 1;
+  }
+
+  /* Loop to process one whole iMCU row */
+  for (yoffset = 0; yoffset < num_MCU_rows; yoffset++) {
+    for (MCU_col_num = 0; MCU_col_num < cinfo->MCUs_per_row; MCU_col_num++) {
+      /* Construct list of pointers to DCT blocks belonging to this MCU */
+      blkn = 0;			/* index of current DCT block within MCU */
+      for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+	compptr = cinfo->cur_comp_info[ci];
+	start_col = MCU_col_num * compptr->MCU_width;
+	for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
+	  buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
+	  for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
+	    coef->MCU_buffer[blkn++] = buffer_ptr++;
+	  }
+	}
+      }
+      /* Try to write the MCU. */
+      if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
+	ERREXIT(cinfo, JERR_CANT_SUSPEND); /* not supported */
+      }
+    }
+  }
+
+  coef->MCU_row_num++;		/* advance to next iMCU row */
+  *in_mcu_ctr = cinfo->MCUs_per_row;
+}
+
+#endif /* FULL_COEF_BUFFER_SUPPORTED */
+
+
+/*
+ * Initialize coefficient buffer controller.
+ */
+
+GLOBAL void
+jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
+{
+  my_coef_ptr coef;
+  int ci, i;
+  jpeg_component_info *compptr;
+  JBLOCKROW buffer;
+
+  coef = (my_coef_ptr)
+    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+				SIZEOF(my_coef_controller));
+  cinfo->coef = (struct jpeg_c_coef_controller *) coef;
+  coef->pub.start_pass = start_pass_coef;
+
+  /* Create the coefficient buffer. */
+  if (need_full_buffer) {
+#ifdef FULL_COEF_BUFFER_SUPPORTED
+    /* Allocate a full-image virtual array for each component, */
+    /* padded to a multiple of samp_factor DCT blocks in each direction. */
+    /* Note memmgr implicitly pads the vertical direction. */
+    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+	 ci++, compptr++) {
+      coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
+	((j_common_ptr) cinfo, JPOOL_IMAGE,
+	 (JDIMENSION) jround_up((long) compptr->width_in_blocks,
+				(long) compptr->h_samp_factor),
+	 compptr->height_in_blocks,
+	 (JDIMENSION) compptr->v_samp_factor);
+    }
+#else
+    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+#endif
+  } else {
+    /* We only need a single-MCU buffer. */
+    buffer = (JBLOCKROW)
+      (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+				  MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
+    for (i = 0; i < MAX_BLOCKS_IN_MCU; i++) {
+      coef->MCU_buffer[i] = buffer + i;
+    }
+    coef->whole_image[0] = NULL; /* flag for no virtual arrays */
+  }
+}
diff --git a/jccolor.c b/jccolor.c
index 0da5e1b..4ab3d7e 100644
--- a/jccolor.c
+++ b/jccolor.c
@@ -1,19 +1,28 @@
 /*
  * jccolor.c
  *
- * Copyright (C) 1991, 1992, Thomas G. Lane.
+ * Copyright (C) 1991-1994, 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.
  *
  * This file contains input colorspace conversion routines.
- * These routines are invoked via the methods get_sample_rows
- * and colorin_init/term.
  */
 
+#define JPEG_INTERNALS
 #include "jinclude.h"
+#include "jpeglib.h"
 
 
-static JSAMPARRAY pixel_row;	/* Workspace for a pixel row in input format */
+/* Private subobject */
+
+typedef struct {
+  struct jpeg_color_converter pub; /* public fields */
+
+  /* Private state for RGB->YCC conversion */
+  INT32 * rgb_ycc_tab;		/* => table for RGB to YCbCr conversion */
+} my_color_converter;
+
+typedef my_color_converter * my_cconvert_ptr;
 
 
 /**************** RGB -> YCbCr conversion: most common case **************/
@@ -41,11 +50,7 @@
  * in the tables to save adding them separately in the inner loop.
  */
 
-#ifdef SIXTEEN_BIT_SAMPLES
-#define SCALEBITS	14	/* avoid overflow */
-#else
-#define SCALEBITS	16	/* speedier right-shift on some machines */
-#endif
+#define SCALEBITS	16	/* speediest right-shift on some machines */
 #define ONE_HALF	((INT32) 1 << (SCALEBITS-1))
 #define FIX(x)		((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
 
@@ -55,7 +60,6 @@
  * machines (more than can hold all eight addresses, anyway).
  */
 
-static INT32 * rgb_ycc_tab;	/* => table for RGB to YCbCr conversion */
 #define R_Y_OFF		0			/* offset to R => Y section */
 #define G_Y_OFF		(1*(MAXJSAMPLE+1))	/* offset to G => Y section */
 #define B_Y_OFF		(2*(MAXJSAMPLE+1))	/* etc. */
@@ -69,21 +73,20 @@
 
 
 /*
- * Initialize for colorspace conversion.
+ * Initialize for RGB->YCC colorspace conversion.
  */
 
 METHODDEF void
-rgb_ycc_init (compress_info_ptr cinfo)
+rgb_ycc_start (j_compress_ptr cinfo)
 {
+  my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+  INT32 * rgb_ycc_tab;
   INT32 i;
 
-  /* Allocate a workspace for the result of get_input_row. */
-  pixel_row = (*cinfo->emethods->alloc_small_sarray)
-		(cinfo->image_width, (long) cinfo->input_components);
-
   /* Allocate and fill in the conversion tables. */
-  rgb_ycc_tab = (INT32 *) (*cinfo->emethods->alloc_small)
-				(TABLE_SIZE * SIZEOF(INT32));
+  cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
+    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+				(TABLE_SIZE * SIZEOF(INT32)));
 
   for (i = 0; i <= MAXJSAMPLE; i++) {
     rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
@@ -102,40 +105,41 @@
 
 
 /*
- * Fetch some rows of pixels from get_input_row and convert to the
- * JPEG colorspace.
+ * Convert some rows of samples to the JPEG colorspace.
+ *
+ * Note that we change from the application's interleaved-pixel format
+ * to our internal noninterleaved, one-plane-per-component format.
+ * The input buffer is therefore three times as wide as the output buffer.
+ *
+ * A starting row offset is provided only for the output buffer.  The caller
+ * can easily adjust the passed input_buf value to accommodate any row
+ * offset required on that side.
  */
 
 METHODDEF void
-get_rgb_ycc_rows (compress_info_ptr cinfo,
-		  int rows_to_read, JSAMPIMAGE image_data)
+rgb_ycc_convert (j_compress_ptr cinfo,
+		 JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+		 JDIMENSION output_row, int num_rows)
 {
-#ifdef SIXTEEN_BIT_SAMPLES
-  register UINT16 r, g, b;
-#else
+  my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
   register int r, g, b;
-#endif
-  register INT32 * ctab = rgb_ycc_tab;
-  register JSAMPROW inptr0, inptr1, inptr2;
+  register INT32 * ctab = cconvert->rgb_ycc_tab;
+  register JSAMPROW inptr;
   register JSAMPROW outptr0, outptr1, outptr2;
-  register long col;
-  long width = cinfo->image_width;
-  int row;
+  register JDIMENSION col;
+  JDIMENSION num_cols = cinfo->image_width;
 
-  for (row = 0; row < rows_to_read; row++) {
-    /* Read one row from the source file */
-    (*cinfo->methods->get_input_row) (cinfo, pixel_row);
-    /* Convert colorspace */
-    inptr0 = pixel_row[0];
-    inptr1 = pixel_row[1];
-    inptr2 = pixel_row[2];
-    outptr0 = image_data[0][row];
-    outptr1 = image_data[1][row];
-    outptr2 = image_data[2][row];
-    for (col = 0; col < width; col++) {
-      r = GETJSAMPLE(inptr0[col]);
-      g = GETJSAMPLE(inptr1[col]);
-      b = GETJSAMPLE(inptr2[col]);
+  while (--num_rows >= 0) {
+    inptr = *input_buf++;
+    outptr0 = output_buf[0][output_row];
+    outptr1 = output_buf[1][output_row];
+    outptr2 = output_buf[2][output_row];
+    output_row++;
+    for (col = 0; col < num_cols; col++) {
+      r = GETJSAMPLE(inptr[RGB_RED]);
+      g = GETJSAMPLE(inptr[RGB_GREEN]);
+      b = GETJSAMPLE(inptr[RGB_BLUE]);
+      inptr += RGB_PIXELSIZE;
       /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
        * must be too; we do not need an explicit range-limiting operation.
        * Hence the value being shifted is never negative, and we don't
@@ -162,46 +166,34 @@
 
 
 /*
- * Fetch some rows of pixels from get_input_row and convert to the
- * JPEG colorspace.
+ * Convert some rows of samples to the JPEG colorspace.
  * This version handles RGB->grayscale conversion, which is the same
  * as the RGB->Y portion of RGB->YCbCr.
- * We assume rgb_ycc_init has been called (we only use the Y tables).
+ * We assume rgb_ycc_start has been called (we only use the Y tables).
  */
 
 METHODDEF void
-get_rgb_gray_rows (compress_info_ptr cinfo,
-		   int rows_to_read, JSAMPIMAGE image_data)
+rgb_gray_convert (j_compress_ptr cinfo,
+		  JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+		  JDIMENSION output_row, int num_rows)
 {
-#ifdef SIXTEEN_BIT_SAMPLES
-  register UINT16 r, g, b;
-#else
+  my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
   register int r, g, b;
-#endif
-  register INT32 * ctab = rgb_ycc_tab;
-  register JSAMPROW inptr0, inptr1, inptr2;
+  register INT32 * ctab = cconvert->rgb_ycc_tab;
+  register JSAMPROW inptr;
   register JSAMPROW outptr;
-  register long col;
-  long width = cinfo->image_width;
-  int row;
+  register JDIMENSION col;
+  JDIMENSION num_cols = cinfo->image_width;
 
-  for (row = 0; row < rows_to_read; row++) {
-    /* Read one row from the source file */
-    (*cinfo->methods->get_input_row) (cinfo, pixel_row);
-    /* Convert colorspace */
-    inptr0 = pixel_row[0];
-    inptr1 = pixel_row[1];
-    inptr2 = pixel_row[2];
-    outptr = image_data[0][row];
-    for (col = 0; col < width; col++) {
-      r = GETJSAMPLE(inptr0[col]);
-      g = GETJSAMPLE(inptr1[col]);
-      b = GETJSAMPLE(inptr2[col]);
-      /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
-       * must be too; we do not need an explicit range-limiting operation.
-       * Hence the value being shifted is never negative, and we don't
-       * need the general RIGHT_SHIFT macro.
-       */
+  while (--num_rows >= 0) {
+    inptr = *input_buf++;
+    outptr = output_buf[0][output_row];
+    output_row++;
+    for (col = 0; col < num_cols; col++) {
+      r = GETJSAMPLE(inptr[RGB_RED]);
+      g = GETJSAMPLE(inptr[RGB_GREEN]);
+      b = GETJSAMPLE(inptr[RGB_BLUE]);
+      inptr += RGB_PIXELSIZE;
       /* Y */
       outptr[col] = (JSAMPLE)
 		((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
@@ -212,150 +204,246 @@
 
 
 /*
- * Initialize for colorspace conversion.
+ * Convert some rows of samples to the JPEG colorspace.
+ * This version handles Adobe-style CMYK->YCCK conversion,
+ * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
+ * conversion as above, while passing K (black) unchanged.
+ * We assume rgb_ycc_start has been called.
  */
 
 METHODDEF void
-colorin_init (compress_info_ptr cinfo)
+cmyk_ycck_convert (j_compress_ptr cinfo,
+		   JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+		   JDIMENSION output_row, int num_rows)
 {
-  /* Allocate a workspace for the result of get_input_row. */
-  pixel_row = (*cinfo->emethods->alloc_small_sarray)
-		(cinfo->image_width, (long) cinfo->input_components);
-}
+  my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
+  register int r, g, b;
+  register INT32 * ctab = cconvert->rgb_ycc_tab;
+  register JSAMPROW inptr;
+  register JSAMPROW outptr0, outptr1, outptr2, outptr3;
+  register JDIMENSION col;
+  JDIMENSION num_cols = cinfo->image_width;
 
-
-/*
- * Fetch some rows of pixels from get_input_row and convert to the
- * JPEG colorspace.
- * This version handles grayscale output with no conversion.
- * The source can be either plain grayscale or YCbCr (since Y == gray).
- */
-
-METHODDEF void
-get_grayscale_rows (compress_info_ptr cinfo,
-		    int rows_to_read, JSAMPIMAGE image_data)
-{
-  int row;
-
-  for (row = 0; row < rows_to_read; row++) {
-    /* Read one row from the source file */
-    (*cinfo->methods->get_input_row) (cinfo, pixel_row);
-    /* Convert colorspace (gamma mapping needed here) */
-    jcopy_sample_rows(pixel_row, 0, image_data[0], row,
-		      1, cinfo->image_width);
-  }
-}
-
-
-/*
- * Fetch some rows of pixels from get_input_row and convert to the
- * JPEG colorspace.
- * This version handles multi-component colorspaces without conversion.
- */
-
-METHODDEF void
-get_noconvert_rows (compress_info_ptr cinfo,
-		    int rows_to_read, JSAMPIMAGE image_data)
-{
-  int row, ci;
-
-  for (row = 0; row < rows_to_read; row++) {
-    /* Read one row from the source file */
-    (*cinfo->methods->get_input_row) (cinfo, pixel_row);
-    /* Convert colorspace (gamma mapping needed here) */
-    for (ci = 0; ci < cinfo->input_components; ci++) {
-      jcopy_sample_rows(pixel_row, ci, image_data[ci], row,
-			1, cinfo->image_width);
+  while (--num_rows >= 0) {
+    inptr = *input_buf++;
+    outptr0 = output_buf[0][output_row];
+    outptr1 = output_buf[1][output_row];
+    outptr2 = output_buf[2][output_row];
+    outptr3 = output_buf[3][output_row];
+    output_row++;
+    for (col = 0; col < num_cols; col++) {
+      r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
+      g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
+      b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
+      /* K passes through as-is */
+      outptr3[col] = inptr[3];	/* don't need GETJSAMPLE here */
+      inptr += 4;
+      /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
+       * must be too; we do not need an explicit range-limiting operation.
+       * Hence the value being shifted is never negative, and we don't
+       * need the general RIGHT_SHIFT macro.
+       */
+      /* Y */
+      outptr0[col] = (JSAMPLE)
+		((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
+		 >> SCALEBITS);
+      /* Cb */
+      outptr1[col] = (JSAMPLE)
+		((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
+		 >> SCALEBITS);
+      /* Cr */
+      outptr2[col] = (JSAMPLE)
+		((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
+		 >> SCALEBITS);
     }
   }
 }
 
 
 /*
- * Finish up at the end of the file.
+ * Convert some rows of samples to the JPEG colorspace.
+ * This version handles grayscale output with no conversion.
+ * The source can be either plain grayscale or YCbCr (since Y == gray).
  */
 
 METHODDEF void
-colorin_term (compress_info_ptr cinfo)
+grayscale_convert (j_compress_ptr cinfo,
+		   JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+		   JDIMENSION output_row, int num_rows)
 {
-  /* no work (we let free_all release the workspace) */
+  register JSAMPROW inptr;
+  register JSAMPROW outptr;
+  register JDIMENSION col;
+  JDIMENSION num_cols = cinfo->image_width;
+  int instride = cinfo->input_components;
+
+  while (--num_rows >= 0) {
+    inptr = *input_buf++;
+    outptr = output_buf[0][output_row];
+    output_row++;
+    for (col = 0; col < num_cols; col++) {
+      outptr[col] = inptr[0];	/* don't need GETJSAMPLE() here */
+      inptr += instride;
+    }
+  }
 }
 
 
 /*
- * The method selection routine for input colorspace conversion.
+ * Convert some rows of samples to the JPEG colorspace.
+ * This version handles multi-component colorspaces without conversion.
+ * We assume input_components == num_components.
+ */
+
+METHODDEF void
+null_convert (j_compress_ptr cinfo,
+	      JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
+	      JDIMENSION output_row, int num_rows)
+{
+  register JSAMPROW inptr;
+  register JSAMPROW outptr;
+  register JDIMENSION col;
+  register int ci;
+  int nc = cinfo->num_components;
+  JDIMENSION num_cols = cinfo->image_width;
+
+  while (--num_rows >= 0) {
+    /* It seems fastest to make a separate pass for each component. */
+    for (ci = 0; ci < nc; ci++) {
+      inptr = *input_buf;
+      outptr = output_buf[ci][output_row];
+      for (col = 0; col < num_cols; col++) {
+	outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
+	inptr += nc;
+      }
+    }
+    input_buf++;
+    output_row++;
+  }
+}
+
+
+/*
+ * Empty method for start_pass.
+ */
+
+METHODDEF void
+null_method (j_compress_ptr cinfo)
+{
+  /* no work needed */
+}
+
+
+/*
+ * Module initialization routine for input colorspace conversion.
  */
 
 GLOBAL void
-jselccolor (compress_info_ptr cinfo)
+jinit_color_converter (j_compress_ptr cinfo)
 {
+  my_cconvert_ptr cconvert;
+
+  cconvert = (my_cconvert_ptr)
+    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+				SIZEOF(my_color_converter));
+  cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
+  /* set start_pass to null method until we find out differently */
+  cconvert->pub.start_pass = null_method;
+
   /* Make sure input_components agrees with in_color_space */
   switch (cinfo->in_color_space) {
-  case CS_GRAYSCALE:
+  case JCS_GRAYSCALE:
     if (cinfo->input_components != 1)
-      ERREXIT(cinfo->emethods, "Bogus input colorspace");
+      ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
     break;
 
-  case CS_RGB:
-  case CS_YCbCr:
-  case CS_YIQ:
+  case JCS_RGB:
+#if RGB_PIXELSIZE != 3
+    if (cinfo->input_components != RGB_PIXELSIZE)
+      ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
+    break;
+#endif /* else share code with YCbCr */
+
+  case JCS_YCbCr:
     if (cinfo->input_components != 3)
-      ERREXIT(cinfo->emethods, "Bogus input colorspace");
+      ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
     break;
 
-  case CS_CMYK:
+  case JCS_CMYK:
+  case JCS_YCCK:
     if (cinfo->input_components != 4)
-      ERREXIT(cinfo->emethods, "Bogus input colorspace");
+      ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
     break;
 
-  default:
-    ERREXIT(cinfo->emethods, "Unsupported input colorspace");
+  default:			/* JCS_UNKNOWN can be anything */
+    if (cinfo->input_components < 1)
+      ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
     break;
   }
 
-  /* Standard init/term methods (may override below) */
-  cinfo->methods->colorin_init = colorin_init;
-  cinfo->methods->colorin_term = colorin_term;
-
   /* Check num_components, set conversion method based on requested space */
   switch (cinfo->jpeg_color_space) {
-  case CS_GRAYSCALE:
+  case JCS_GRAYSCALE:
     if (cinfo->num_components != 1)
-      ERREXIT(cinfo->emethods, "Bogus JPEG colorspace");
-    if (cinfo->in_color_space == CS_GRAYSCALE)
-      cinfo->methods->get_sample_rows = get_grayscale_rows;
-    else if (cinfo->in_color_space == CS_RGB) {
-      cinfo->methods->colorin_init = rgb_ycc_init;
-      cinfo->methods->get_sample_rows = get_rgb_gray_rows;
-    } else if (cinfo->in_color_space == CS_YCbCr)
-      cinfo->methods->get_sample_rows = get_grayscale_rows;
+      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+    if (cinfo->in_color_space == JCS_GRAYSCALE)
+      cconvert->pub.color_convert = grayscale_convert;
+    else if (cinfo->in_color_space == JCS_RGB) {
+      cconvert->pub.start_pass = rgb_ycc_start;
+      cconvert->pub.color_convert = rgb_gray_convert;
+    } else if (cinfo->in_color_space == JCS_YCbCr)
+      cconvert->pub.color_convert = grayscale_convert;
     else
-      ERREXIT(cinfo->emethods, "Unsupported color conversion request");
+      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
     break;
 
-  case CS_YCbCr:
+  case JCS_RGB:
     if (cinfo->num_components != 3)
-      ERREXIT(cinfo->emethods, "Bogus JPEG colorspace");
-    if (cinfo->in_color_space == CS_RGB) {
-      cinfo->methods->colorin_init = rgb_ycc_init;
-      cinfo->methods->get_sample_rows = get_rgb_ycc_rows;
-    } else if (cinfo->in_color_space == CS_YCbCr)
-      cinfo->methods->get_sample_rows = get_noconvert_rows;
+      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+    if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
+      cconvert->pub.color_convert = null_convert;
     else
-      ERREXIT(cinfo->emethods, "Unsupported color conversion request");
+      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
     break;
 
-  case CS_CMYK:
+  case JCS_YCbCr:
+    if (cinfo->num_components != 3)
+      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+    if (cinfo->in_color_space == JCS_RGB) {
+      cconvert->pub.start_pass = rgb_ycc_start;
+      cconvert->pub.color_convert = rgb_ycc_convert;
+    } else if (cinfo->in_color_space == JCS_YCbCr)
+      cconvert->pub.color_convert = null_convert;
+    else
+      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+    break;
+
+  case JCS_CMYK:
     if (cinfo->num_components != 4)
-      ERREXIT(cinfo->emethods, "Bogus JPEG colorspace");
-    if (cinfo->in_color_space == CS_CMYK)
-      cinfo->methods->get_sample_rows = get_noconvert_rows;
+      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+    if (cinfo->in_color_space == JCS_CMYK)
+      cconvert->pub.color_convert = null_convert;
     else
-      ERREXIT(cinfo->emethods, "Unsupported color conversion request");
+      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
     break;
 
-  default:
-    ERREXIT(cinfo->emethods, "Unsupported JPEG colorspace");
+  case JCS_YCCK:
+    if (cinfo->num_components != 4)
+      ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
+    if (cinfo->in_color_space == JCS_CMYK) {
+      cconvert->pub.start_pass = rgb_ycc_start;
+      cconvert->pub.color_convert = cmyk_ycck_convert;
+    } else if (cinfo->in_color_space == JCS_YCCK)
+      cconvert->pub.color_convert = null_convert;
+    else
+      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+    break;
+
+  default:			/* allow null conversion of JCS_UNKNOWN */
+    if (cinfo->jpeg_color_space != cinfo->in_color_space ||
+	cinfo->num_components != cinfo->input_components)
+      ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
+    cconvert->pub.color_convert = null_convert;
     break;
   }
 }
diff --git a/jcdctmgr.c b/jcdctmgr.c
new file mode 100644
index 0000000..459c3d3
--- /dev/null
+++ b/jcdctmgr.c
@@ -0,0 +1,398 @@
+/*
+ * jcdctmgr.c
+ *
+ * Copyright (C) 1994, 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.
+ *
+ * This file contains the forward-DCT management logic.
+ * This code selects a particular DCT implementation to be used,
+ * and it performs related housekeeping chores including coefficient
+ * quantization.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+#include "jdct.h"		/* Private declarations for DCT subsystem */
+
+
+/* Private subobject for this module */
+
+typedef struct {
+  struct jpeg_forward_dct pub;	/* public fields */
+
+  /* Pointer to the DCT routine actually in use */
+  forward_DCT_method_ptr do_dct;
+
+  /* The actual post-DCT divisors --- not identical to the quant table
+   * entries, because of scaling (especially for an unnormalized DCT).
+   * Each table is given in zigzag order.
+   */
+  DCTELEM * divisors[NUM_QUANT_TBLS];
+
+#ifdef DCT_FLOAT_SUPPORTED
+  /* Same as above for the floating-point case. */
+  float_DCT_method_ptr do_float_dct;
+  FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
+#endif
+} my_fdct_controller;
+
+typedef my_fdct_controller * my_fdct_ptr;
+
+
+/* ZAG[i] is the natural-order position of the i'th element of zigzag order. */
+
+static const int ZAG[DCTSIZE2] = {
+  0,  1,  8, 16,  9,  2,  3, 10,
+ 17, 24, 32, 25, 18, 11,  4,  5,
+ 12, 19, 26, 33, 40, 48, 41, 34,
+ 27, 20, 13,  6,  7, 14, 21, 28,
+ 35, 42, 49, 56, 57, 50, 43, 36,
+ 29, 22, 15, 23, 30, 37, 44, 51,
+ 58, 59, 52, 45, 38, 31, 39, 46,
+ 53, 60, 61, 54, 47, 55, 62, 63
+};
+
+
+/*
+ * Initialize for a processing pass.
+ * Verify that all referenced Q-tables are present, and set up
+ * the divisor table for each one.
+ * In the current implementation, DCT of all components is done during
+ * the first pass, even if only some components will be output in the
+ * first scan.  Hence all components should be examined here.
+ */
+
+METHODDEF void
+start_pass_fdctmgr (j_compress_ptr cinfo)
+{
+  my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
+  int ci, qtblno, i;
+  jpeg_component_info *compptr;
+  JQUANT_TBL * qtbl;
+  DCTELEM * dtbl;
+
+  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+       ci++, compptr++) {
+    qtblno = compptr->quant_tbl_no;
+    /* Make sure specified quantization table is present */
+    if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
+	cinfo->quant_tbl_ptrs[qtblno] == NULL)
+      ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
+    qtbl = cinfo->quant_tbl_ptrs[qtblno];
+    /* Compute divisors for this quant table */
+    /* We may do this more than once for same table, but it's not a big deal */
+    switch (cinfo->dct_method) {
+#ifdef DCT_ISLOW_SUPPORTED
+    case JDCT_ISLOW:
+      /* For LL&M IDCT method, divisors are equal to raw quantization
+       * coefficients multiplied by 8 (to counteract scaling).
+       */
+      if (fdct->divisors[qtblno] == NULL) {
+	fdct->divisors[qtblno] = (DCTELEM *)
+	  (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+				      DCTSIZE2 * SIZEOF(DCTELEM));
+      }
+      dtbl = fdct->divisors[qtblno];
+      for (i = 0; i < DCTSIZE2; i++) {
+	dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
+      }
+      break;
+#endif
+#ifdef DCT_IFAST_SUPPORTED
+    case JDCT_IFAST:
+      {
+	/* For AA&N IDCT method, divisors are equal to quantization
+	 * coefficients scaled by scalefactor[row]*scalefactor[col], where
+	 *   scalefactor[0] = 1
+	 *   scalefactor[k] = cos(k*PI/16) * sqrt(2)    for k=1..7
+	 * We apply a further scale factor of 8.
+	 */
+#define CONST_BITS 14
+	static const INT16 aanscales[DCTSIZE2] = {
+	  /* precomputed values scaled up by 14 bits: in natural order */
+	  16384, 22725, 21407, 19266, 16384, 12873,  8867,  4520,
+	  22725, 31521, 29692, 26722, 22725, 17855, 12299,  6270,
+	  21407, 29692, 27969, 25172, 21407, 16819, 11585,  5906,
+	  19266, 26722, 25172, 22654, 19266, 15137, 10426,  5315,
+	  16384, 22725, 21407, 19266, 16384, 12873,  8867,  4520,
+	  12873, 17855, 16819, 15137, 12873, 10114,  6967,  3552,
+	   8867, 12299, 11585, 10426,  8867,  6967,  4799,  2446,
+	   4520,  6270,  5906,  5315,  4520,  3552,  2446,  1247
+	};
+	SHIFT_TEMPS
+
+	if (fdct->divisors[qtblno] == NULL) {
+	  fdct->divisors[qtblno] = (DCTELEM *)
+	    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+					DCTSIZE2 * SIZEOF(DCTELEM));
+	}
+	dtbl = fdct->divisors[qtblno];
+	for (i = 0; i < DCTSIZE2; i++) {
+	  dtbl[i] = (DCTELEM)
+	    DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
+				  (INT32) aanscales[ZAG[i]]),
+		    CONST_BITS-3);
+	}
+      }
+      break;
+#endif
+#ifdef DCT_FLOAT_SUPPORTED
+    case JDCT_FLOAT:
+      {
+	/* For float AA&N IDCT method, divisors are equal to quantization
+	 * coefficients scaled by scalefactor[row]*scalefactor[col], where
+	 *   scalefactor[0] = 1
+	 *   scalefactor[k] = cos(k*PI/16) * sqrt(2)    for k=1..7
+	 * We apply a further scale factor of 8.
+	 * What's actually stored is 1/divisor so that the inner loop can
+	 * use a multiplication rather than a division.
+	 */
+	FAST_FLOAT * fdtbl;
+	int row, col;
+	static const double aanscalefactor[DCTSIZE] = {
+	  1.0, 1.387039845, 1.306562965, 1.175875602,
+	  1.0, 0.785694958, 0.541196100, 0.275899379
+	};
+
+	if (fdct->float_divisors[qtblno] == NULL) {
+	  fdct->float_divisors[qtblno] = (FAST_FLOAT *)
+	    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+					DCTSIZE2 * SIZEOF(FAST_FLOAT));
+	}
+	fdtbl = fdct->float_divisors[qtblno];
+	for (i = 0; i < DCTSIZE2; i++) {
+	  row = ZAG[i] >> 3;
+	  col = ZAG[i] & 7;
+	  fdtbl[i] = (FAST_FLOAT)
+	    (1.0 / (((double) qtbl->quantval[i] *
+		     aanscalefactor[row] * aanscalefactor[col] * 8.0)));
+	}
+      }
+      break;
+#endif
+    default:
+      ERREXIT(cinfo, JERR_NOT_COMPILED);
+      break;
+    }
+  }
+}
+
+
+/*
+ * Perform forward DCT on one or more blocks of a component.
+ *
+ * The input samples are taken from the sample_data[] array starting at
+ * position start_row/start_col, and moving to the right for any additional
+ * blocks. The quantized, zigzagged coefficients are returned in coef_blocks[].
+ */
+
+METHODDEF void
+forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
+	     JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
+	     JDIMENSION start_row, JDIMENSION start_col,
+	     JDIMENSION num_blocks)
+/* This version is used for integer DCT implementations. */
+{
+  /* This routine is heavily used, so it's worth coding it tightly. */
+  my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
+  forward_DCT_method_ptr do_dct = fdct->do_dct;
+  DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
+  DCTELEM workspace[DCTSIZE2];	/* work area for FDCT subroutine */
+  JDIMENSION bi;
+
+  sample_data += start_row;	/* fold in the vertical offset once */
+
+  for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
+    /* Load data into workspace, applying unsigned->signed conversion */
+    { register DCTELEM *workspaceptr;
+      register JSAMPROW elemptr;
+      register int elemr;
+
+      workspaceptr = workspace;
+      for (elemr = 0; elemr < DCTSIZE; elemr++) {
+	elemptr = sample_data[elemr] + start_col;
+#if DCTSIZE == 8		/* unroll the inner loop */
+	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+#else
+	{ register int elemc;
+	  for (elemc = DCTSIZE; elemc > 0; elemc--) {
+	    *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+	  }
+	}
+#endif
+      }
+    }
+
+    /* Perform the DCT */
+    (*do_dct) (workspace);
+
+    /* Quantize/descale the coefficients, and store into coef_blocks[] */
+    { register DCTELEM temp, qval;
+      register int i;
+      register JCOEFPTR output_ptr = coef_blocks[bi];
+
+      for (i = 0; i < DCTSIZE2; i++) {
+	qval = divisors[i];
+	temp = workspace[ZAG[i]];
+	/* Divide the coefficient value by qval, ensuring proper rounding.
+	 * Since C does not specify the direction of rounding for negative
+	 * quotients, we have to force the dividend positive for portability.
+	 *
+	 * In most files, at least half of the output values will be zero
+	 * (at default quantization settings, more like three-quarters...)
+	 * so we should ensure that this case is fast.  On many machines,
+	 * a comparison is enough cheaper than a divide to make a special test
+	 * a win.  Since both inputs will be nonnegative, we need only test
+	 * for a < b to discover whether a/b is 0.
+	 * If your machine's division is fast enough, define FAST_DIVIDE.
+	 */
+#ifdef FAST_DIVIDE
+#define DIVIDE_BY(a,b)	a /= b
+#else
+#define DIVIDE_BY(a,b)	if (a >= b) a /= b; else a = 0
+#endif
+	if (temp < 0) {
+	  temp = -temp;
+	  temp += qval>>1;	/* for rounding */
+	  DIVIDE_BY(temp, qval);
+	  temp = -temp;
+	} else {
+	  temp += qval>>1;	/* for rounding */
+	  DIVIDE_BY(temp, qval);
+	}
+	output_ptr[i] = (JCOEF) temp;
+      }
+    }
+  }
+}
+
+
+#ifdef DCT_FLOAT_SUPPORTED
+
+METHODDEF void
+forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
+		   JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
+		   JDIMENSION start_row, JDIMENSION start_col,
+		   JDIMENSION num_blocks)
+/* This version is used for floating-point DCT implementations. */
+{
+  /* This routine is heavily used, so it's worth coding it tightly. */
+  my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
+  float_DCT_method_ptr do_dct = fdct->do_float_dct;
+  FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
+  FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
+  JDIMENSION bi;
+
+  sample_data += start_row;	/* fold in the vertical offset once */
+
+  for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
+    /* Load data into workspace, applying unsigned->signed conversion */
+    { register FAST_FLOAT *workspaceptr;
+      register JSAMPROW elemptr;
+      register int elemr;
+
+      workspaceptr = workspace;
+      for (elemr = 0; elemr < DCTSIZE; elemr++) {
+	elemptr = sample_data[elemr] + start_col;
+#if DCTSIZE == 8		/* unroll the inner loop */
+	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+	*workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+#else
+	{ register int elemc;
+	  for (elemc = DCTSIZE; elemc > 0; elemc--) {
+	    *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
+	  }
+	}
+#endif
+      }
+    }
+
+    /* Perform the DCT */
+    (*do_dct) (workspace);
+
+    /* Quantize/descale the coefficients, and store into coef_blocks[] */
+    { register FAST_FLOAT temp;
+      register int i;
+      register JCOEFPTR output_ptr = coef_blocks[bi];
+
+      for (i = 0; i < DCTSIZE2; i++) {
+	/* Apply the quantization and scaling factor */
+	temp = workspace[ZAG[i]] * divisors[i];
+	/* Round to nearest integer.
+	 * Since C does not specify the direction of rounding for negative
+	 * quotients, we have to force the dividend positive for portability.
+	 * The maximum coefficient size is +-16K (for 12-bit data), so this
+	 * code should work for either 16-bit or 32-bit ints.
+	 */
+	output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
+      }
+    }
+  }
+}
+
+#endif /* DCT_FLOAT_SUPPORTED */
+
+
+/*
+ * Initialize FDCT manager.
+ */
+
+GLOBAL void
+jinit_forward_dct (j_compress_ptr cinfo)
+{
+  my_fdct_ptr fdct;
+  int i;
+
+  fdct = (my_fdct_ptr)
+    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+				SIZEOF(my_fdct_controller));
+  cinfo->fdct = (struct jpeg_forward_dct *) fdct;
+  fdct->pub.start_pass = start_pass_fdctmgr;
+
+  switch (cinfo->dct_method) {
+#ifdef DCT_ISLOW_SUPPORTED
+  case JDCT_ISLOW:
+    fdct->pub.forward_DCT = forward_DCT;
+    fdct->do_dct = jpeg_fdct_islow;
+    break;
+#endif
+#ifdef DCT_IFAST_SUPPORTED
+  case JDCT_IFAST:
+    fdct->pub.forward_DCT = forward_DCT;
+    fdct->do_dct = jpeg_fdct_ifast;
+    break;
+#endif
+#ifdef DCT_FLOAT_SUPPORTED
+  case JDCT_FLOAT:
+    fdct->pub.forward_DCT = forward_DCT_float;
+    fdct->do_float_dct = jpeg_fdct_float;
+    break;
+#endif
+  default:
+    ERREXIT(cinfo, JERR_NOT_COMPILED);
+    break;
+  }
+
+  /* Mark divisor tables unallocated */
+  for (i = 0; i < NUM_QUANT_TBLS; i++) {
+    fdct->divisors[i] = NULL;
+#ifdef DCT_FLOAT_SUPPORTED
+    fdct->float_divisors[i] = NULL;
+#endif
+  }
+}
diff --git a/jcdeflts.c b/jcdeflts.c
deleted file mode 100644
index eddba20..0000000
--- a/jcdeflts.c
+++ /dev/null
@@ -1,391 +0,0 @@
-/*
- * jcdeflts.c
- *
- * Copyright (C) 1991, 1992, 1993, 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.
- *
- * This file contains optional default-setting code for the JPEG compressor.
- * User interfaces do not have to use this file, but those that don't use it
- * must know a lot more about the innards of the JPEG code.
- */
-
-#include "jinclude.h"
-
-
-/* Default do-nothing progress monitoring routine.
- * This can be overridden by a user interface that wishes to
- * provide progress monitoring; just set methods->progress_monitor
- * after j_c_defaults is done.  The routine will be called periodically
- * during the compression process.
- *
- * During any one pass, loopcounter increases from 0 up to (not including)
- * looplimit; the step size is not necessarily 1.  Both the step size and
- * the limit may differ between passes.  The expected total number of passes
- * is in cinfo->total_passes, and the number of passes already completed is
- * in cinfo->completed_passes.  Thus the fraction of work completed may be
- * estimated as
- *		completed_passes + (loopcounter/looplimit)
- *		------------------------------------------
- *				total_passes
- * ignoring the fact that the passes may not be equal amounts of work.
- */
-
-METHODDEF void
-progress_monitor (compress_info_ptr cinfo, long loopcounter, long looplimit)
-{
-  /* do nothing */
-}
-
-
-/*
- * Huffman table setup routines
- */
-
-LOCAL void
-add_huff_table (compress_info_ptr cinfo,
-		HUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
-/* Define a Huffman table */
-{
-  if (*htblptr == NULL)
-    *htblptr = (HUFF_TBL *) (*cinfo->emethods->alloc_small) (SIZEOF(HUFF_TBL));
-  
-  MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
-  MEMCOPY((*htblptr)->huffval, val, SIZEOF((*htblptr)->huffval));
-
-  /* Initialize sent_table FALSE so table will be written to JPEG file.
-   * In an application where we are writing non-interchange JPEG files,
-   * it might be desirable to save space by leaving default Huffman tables
-   * out of the file.  To do that, just initialize sent_table = TRUE...
-   */
-
-  (*htblptr)->sent_table = FALSE;
-}
-
-
-LOCAL void
-std_huff_tables (compress_info_ptr cinfo)
-/* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
-/* IMPORTANT: these are only valid for 8-bit data precision! */
-{
-  static const UINT8 dc_luminance_bits[17] =
-    { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
-  static const UINT8 dc_luminance_val[] =
-    { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
-  
-  static const UINT8 dc_chrominance_bits[17] =
-    { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
-  static const UINT8 dc_chrominance_val[] =
-    { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
-  
-  static const UINT8 ac_luminance_bits[17] =
-    { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
-  static const UINT8 ac_luminance_val[] =
-    { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
-      0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
-      0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
-      0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
-      0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
-      0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
-      0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
-      0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
-      0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
-      0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
-      0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
-      0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
-      0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
-      0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
-      0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
-      0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
-      0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
-      0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
-      0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
-      0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
-      0xf9, 0xfa };
-  
-  static const UINT8 ac_chrominance_bits[17] =
-    { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
-  static const UINT8 ac_chrominance_val[] =
-    { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
-      0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
-      0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
-      0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
-      0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
-      0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
-      0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
-      0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
-      0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
-      0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
-      0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
-      0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
-      0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
-      0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
-      0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
-      0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
-      0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
-      0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
-      0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
-      0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
-      0xf9, 0xfa };
-  
-  add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
-		 dc_luminance_bits, dc_luminance_val);
-  add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
-		 ac_luminance_bits, ac_luminance_val);
-  add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
-		 dc_chrominance_bits, dc_chrominance_val);
-  add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
-		 ac_chrominance_bits, ac_chrominance_val);
-}
-
-
-/*
- * Quantization table setup routines
- */
-
-GLOBAL void
-j_add_quant_table (compress_info_ptr cinfo, int which_tbl,
-		   const QUANT_VAL *basic_table, int scale_factor,
-		   boolean force_baseline)
-/* Define a quantization table equal to the basic_table times
- * a scale factor (given as a percentage).
- * If force_baseline is TRUE, the computed quantization table entries
- * are limited to 1..255 for JPEG baseline compatibility.
- */
-{
-  QUANT_TBL_PTR * qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
-  int i;
-  long temp;
-
-  if (*qtblptr == NULL)
-    *qtblptr = (QUANT_TBL_PTR) (*cinfo->emethods->alloc_small) (SIZEOF(QUANT_TBL));
-
-  for (i = 0; i < DCTSIZE2; i++) {
-    temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
-    /* limit the values to the valid range */
-    if (temp <= 0L) temp = 1L;
-#ifdef EIGHT_BIT_SAMPLES
-    if (temp > 32767L) temp = 32767L; /* QUANT_VALs are 'short' */
-#else
-    if (temp > 65535L) temp = 65535L; /* QUANT_VALs are 'UINT16' */
-#endif
-    if (force_baseline && temp > 255L)
-      temp = 255L;		/* limit to baseline range if requested */
-    (*qtblptr)[i] = (QUANT_VAL) temp;
-  }
-}
-
-
-GLOBAL int
-j_quality_scaling (int quality)
-/* Convert a user-specified quality rating to a percentage scaling factor
- * for an underlying quantization table, using our recommended scaling curve.
- * The input 'quality' factor should be 0 (terrible) to 100 (very good).
- */
-{
-  /* Safety limit on quality factor.  Convert 0 to 1 to avoid zero divide. */
-  if (quality <= 0) quality = 1;
-  if (quality > 100) quality = 100;
-
-  /* The basic table is used as-is (scaling 100) for a quality of 50.
-   * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
-   * note that at Q=100 the scaling is 0, which will cause j_add_quant_table
-   * to make all the table entries 1 (hence, no quantization loss).
-   * Qualities 1..50 are converted to scaling percentage 5000/Q.
-   */
-  if (quality < 50)
-    quality = 5000 / quality;
-  else
-    quality = 200 - quality*2;
-
-  return quality;
-}
-
-
-GLOBAL void
-j_set_quality (compress_info_ptr cinfo, int quality, boolean force_baseline)
-/* Set or change the 'quality' (quantization) setting, using default tables.
- * This is the standard quality-adjusting entry point for typical user
- * interfaces; only those who want detailed control over quantization tables
- * would use the preceding two routines directly.
- */
-{
-  /* This is the sample quantization table given in the JPEG spec section K.1,
-   * but expressed in zigzag order (as are all of our quant. tables).
-   * The spec says that the values given produce "good" quality, and
-   * when divided by 2, "very good" quality.  (These two settings are
-   * selected by quality=50 and quality=75 respectively.)
-   */
-  static const QUANT_VAL std_luminance_quant_tbl[DCTSIZE2] = {
-    16,  11,  12,  14,  12,  10,  16,  14,
-    13,  14,  18,  17,  16,  19,  24,  40,
-    26,  24,  22,  22,  24,  49,  35,  37,
-    29,  40,  58,  51,  61,  60,  57,  51,
-    56,  55,  64,  72,  92,  78,  64,  68,
-    87,  69,  55,  56,  80, 109,  81,  87,
-    95,  98, 103, 104, 103,  62,  77, 113,
-    121, 112, 100, 120,  92, 101, 103,  99
-    };
-  static const QUANT_VAL std_chrominance_quant_tbl[DCTSIZE2] = {
-    17,  18,  18,  24,  21,  24,  47,  26,
-    26,  47,  99,  66,  56,  66,  99,  99,
-    99,  99,  99,  99,  99,  99,  99,  99,
-    99,  99,  99,  99,  99,  99,  99,  99,
-    99,  99,  99,  99,  99,  99,  99,  99,
-    99,  99,  99,  99,  99,  99,  99,  99,
-    99,  99,  99,  99,  99,  99,  99,  99,
-    99,  99,  99,  99,  99,  99,  99,  99
-    };
-
-  /* Convert user 0-100 rating to percentage scaling */
-  quality = j_quality_scaling(quality);
-
-  /* Set up two quantization tables using the specified quality scaling */
-  j_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
-		    quality, force_baseline);
-  j_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
-		    quality, force_baseline);
-}
-
-
-
-/* Default parameter setup for compression.
- *
- * User interfaces that don't choose to use this routine must do their
- * own setup of all these parameters.  Alternately, you can call this
- * to establish defaults and then alter parameters selectively.  This
- * is the recommended approach since, if we add any new parameters,
- * your code will still work (they'll be set to reasonable defaults).
- *
- * See above for the meaning of the 'quality' and 'force_baseline' parameters.
- * Typically, the application's default quality setting will be passed to this
- * routine.  A later call on j_set_quality() can be used to change to a
- * user-specified quality setting.
- *
- * This routine sets up for a color image; to output a grayscale image,
- * do this first and call j_monochrome_default() afterwards.
- * (The latter can be called within c_ui_method_selection, so the
- * choice can depend on the input file header.)
- * Note that if you want a JPEG colorspace other than GRAYSCALE or YCbCr,
- * you should also change the component ID codes, and you should NOT emit
- * a JFIF header (set write_JFIF_header = FALSE).
- *
- * CAUTION: if you want to compress multiple images per run, it's necessary
- * to call j_c_defaults before *each* call to jpeg_compress, since subsidiary
- * structures like the Huffman tables are automatically freed during cleanup.
- */
-
-GLOBAL void
-j_c_defaults (compress_info_ptr cinfo, int quality, boolean force_baseline)
-/* NB: the external methods must already be set up. */
-{
-  short i;
-  jpeg_component_info * compptr;
-
-  /* Initialize pointers as needed to mark stuff unallocated. */
-  cinfo->comp_info = NULL;
-  for (i = 0; i < NUM_QUANT_TBLS; i++)
-    cinfo->quant_tbl_ptrs[i] = NULL;
-  for (i = 0; i < NUM_HUFF_TBLS; i++) {
-    cinfo->dc_huff_tbl_ptrs[i] = NULL;
-    cinfo->ac_huff_tbl_ptrs[i] = NULL;
-  }
-
-  cinfo->data_precision = BITS_IN_JSAMPLE; /* default; can be overridden by input_init */
-  cinfo->density_unit = 0;	/* Pixel size is unknown by default */
-  cinfo->X_density = 1;		/* Pixel aspect ratio is square by default */
-  cinfo->Y_density = 1;
-
-  cinfo->input_gamma = 1.0;	/* no gamma correction by default */
-
-  cinfo->write_JFIF_header = TRUE; /* write a JFIF marker */
-  cinfo->comment_text = NULL;	/* but no COM block */
-
-  /* Prepare three color components; first is luminance which is also usable */
-  /* for grayscale.  The others are assumed to be UV or similar chrominance. */
-  cinfo->jpeg_color_space = CS_YCbCr;
-  cinfo->num_components = 3;
-  cinfo->comp_info = (jpeg_component_info *)
-    (*cinfo->emethods->alloc_small) (4 * SIZEOF(jpeg_component_info));
-  /* Note: we allocate a 4-entry comp_info array so that user interface can
-   * easily change over to CMYK color space if desired.
-   */
-
-  compptr = &cinfo->comp_info[0];
-  compptr->component_index = 0;
-  compptr->component_id = 1;	/* JFIF specifies IDs 1,2,3 */
-  compptr->h_samp_factor = 2;	/* default to 2x2 subsamples of chrominance */
-  compptr->v_samp_factor = 2;
-  compptr->quant_tbl_no = 0;	/* use tables 0 for luminance */
-  compptr->dc_tbl_no = 0;
-  compptr->ac_tbl_no = 0;
-
-  compptr = &cinfo->comp_info[1];
-  compptr->component_index = 1;
-  compptr->component_id = 2;
-  compptr->h_samp_factor = 1;
-  compptr->v_samp_factor = 1;
-  compptr->quant_tbl_no = 1;	/* use tables 1 for chrominance */
-  compptr->dc_tbl_no = 1;
-  compptr->ac_tbl_no = 1;
-
-  compptr = &cinfo->comp_info[2];
-  compptr->component_index = 2;
-  compptr->component_id = 3;
-  compptr->h_samp_factor = 1;
-  compptr->v_samp_factor = 1;
-  compptr->quant_tbl_no = 1;	/* use tables 1 for chrominance */
-  compptr->dc_tbl_no = 1;
-  compptr->ac_tbl_no = 1;
-
-  /* Set up two quantization tables using the specified quality scaling */
-  j_set_quality(cinfo, quality, force_baseline);
-
-  /* Set up two Huffman tables in case user interface wants Huffman coding */
-  std_huff_tables(cinfo);
-
-  /* Initialize default arithmetic coding conditioning */
-  for (i = 0; i < NUM_ARITH_TBLS; i++) {
-    cinfo->arith_dc_L[i] = 0;
-    cinfo->arith_dc_U[i] = 1;
-    cinfo->arith_ac_K[i] = 5;
-  }
-
-  /* Use Huffman coding, not arithmetic coding, by default */
-  cinfo->arith_code = FALSE;
-
-  /* Color images are interleaved by default */
-  cinfo->interleave = TRUE;
-
-  /* By default, don't do extra passes to optimize entropy coding */
-  cinfo->optimize_coding = FALSE;
-
-  /* By default, use the simpler non-cosited sampling alignment */
-  cinfo->CCIR601_sampling = FALSE;
-
-  /* No input smoothing */
-  cinfo->smoothing_factor = 0;
-
-  /* No restart markers */
-  cinfo->restart_interval = 0;
-  cinfo->restart_in_rows = 0;
-
-  /* Install default do-nothing progress monitoring method. */
-  cinfo->methods->progress_monitor = progress_monitor;
-}
-
-
-
-GLOBAL void
-j_monochrome_default (compress_info_ptr cinfo)
-/* Change the j_c_defaults() values to emit a monochrome JPEG file. */
-{
-  jpeg_component_info * compptr;
-
-  cinfo->jpeg_color_space = CS_GRAYSCALE;
-  cinfo->num_components = 1;
-  /* Set single component to 1x1 subsampling */
-  compptr = &cinfo->comp_info[0];
-  compptr->h_samp_factor = 1;
-  compptr->v_samp_factor = 1;
-}
diff --git a/jcexpand.c b/jcexpand.c
deleted file mode 100644
index 6b42b71..0000000
--- a/jcexpand.c
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * jcexpand.c
- *
- * Copyright (C) 1991, 1992, 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.
- *
- * This file contains image edge-expansion routines.
- * These routines are invoked via the edge_expand method.
- */
-
-#include "jinclude.h"
-
-
-/*
- * Expand an image so that it is a multiple of the MCU dimensions.
- * This is to be accomplished by duplicating the rightmost column
- * and/or bottommost row of pixels.  The image has not yet been
- * downsampled, so all components have the same dimensions.
- */
-
-METHODDEF void
-edge_expand (compress_info_ptr cinfo,
-	     long input_cols, int input_rows,
-	     long output_cols, int output_rows,
-	     JSAMPIMAGE image_data)
-{
-  /* Expand horizontally */
-  if (input_cols < output_cols) {
-    register JSAMPROW ptr;
-    register JSAMPLE pixval;
-    register long count;
-    register int row;
-    short ci;
-    long numcols = output_cols - input_cols;
-
-    for (ci = 0; ci < cinfo->num_components; ci++) {
-      for (row = 0; row < input_rows; row++) {
-	ptr = image_data[ci][row] + (input_cols-1);
-	pixval = GETJSAMPLE(*ptr++);
-	for (count = numcols; count > 0; count--)
-	  *ptr++ = pixval;
-      }
-    }
-  }
-
-  /* Expand vertically */
-  /* This happens only once at the bottom of the image, */
-  /* so it needn't be super-efficient */
-  if (input_rows < output_rows) {
-    register int row;
-    short ci;
-    JSAMPARRAY this_component;
-
-    for (ci = 0; ci < cinfo->num_components; ci++) {
-      this_component = image_data[ci];
-      for (row = input_rows; row < output_rows; row++) {
-	jcopy_sample_rows(this_component, input_rows-1, this_component, row,
-			  1, output_cols);
-      }
-    }
-  }
-}
-
-
-/*
- * The method selection routine for edge expansion.
- */
-
-GLOBAL void
-jselexpand (compress_info_ptr cinfo)
-{
-  /* just one implementation for now */
-  cinfo->methods->edge_expand = edge_expand;
-}
diff --git a/jchuff.c b/jchuff.c
index 9eb558a..9ddefc5 100644
--- a/jchuff.c
+++ b/jchuff.c
@@ -1,38 +1,200 @@
 /*
  * jchuff.c
  *
- * Copyright (C) 1991, 1992, 1993, Thomas G. Lane.
+ * Copyright (C) 1991-1994, 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.
  *
  * This file contains Huffman entropy encoding routines.
- * These routines are invoked via the methods entropy_encode,
- * entropy_encode_init/term, and entropy_optimize.
+ *
+ * Much of the complexity here has to do with supporting output suspension.
+ * If the data destination module demands suspension, we want to be able to
+ * back up to the start of the current MCU.  To do this, we copy state
+ * variables into local working storage, and update them back to the
+ * permanent JPEG objects only upon successful completion of an MCU.
  */
 
+#define JPEG_INTERNALS
 #include "jinclude.h"
+#include "jpeglib.h"
 
 
-/* Static variables to avoid passing 'round extra parameters */
+/* Derived data constructed for each Huffman table */
 
-static compress_info_ptr cinfo;
+typedef struct {
+  unsigned int ehufco[256];	/* code for each symbol */
+  char ehufsi[256];		/* length of code for each symbol */
+  /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
+} C_DERIVED_TBL;
 
-static INT32 huff_put_buffer;	/* current bit-accumulation buffer */
-static int huff_put_bits;	/* # of bits now in it */
+/* Expanded entropy encoder object for Huffman encoding.
+ *
+ * The savable_state subrecord contains fields that change within an MCU,
+ * but must not be updated permanently until we complete the MCU.
+ */
 
-static char * output_buffer;	/* output buffer */
-static int bytes_in_buffer;
+typedef struct {
+  INT32 put_buffer;		/* current bit-accumulation buffer */
+  int put_bits;			/* # of bits now in it */
+  int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
+} savable_state;
 
+/* This macro is to work around compilers with missing or broken
+ * structure assignment.  You'll need to fix this code if you have
+ * such a compiler and you change MAX_COMPS_IN_SCAN.
+ */
+
+#ifndef NO_STRUCT_ASSIGN
+#define ASSIGN_STATE(dest,src)  ((dest) = (src))
+#else
+#if MAX_COMPS_IN_SCAN == 4
+#define ASSIGN_STATE(dest,src)  \
+	((dest).put_buffer = (src).put_buffer, \
+	 (dest).put_bits = (src).put_bits, \
+	 (dest).last_dc_val[0] = (src).last_dc_val[0], \
+	 (dest).last_dc_val[1] = (src).last_dc_val[1], \
+	 (dest).last_dc_val[2] = (src).last_dc_val[2], \
+	 (dest).last_dc_val[3] = (src).last_dc_val[3])
+#endif
+#endif
+
+
+typedef struct {
+  struct jpeg_entropy_encoder pub; /* public fields */
+
+  savable_state saved;		/* Bit buffer & DC state at start of MCU */
+
+  /* These fields are NOT loaded into local working state. */
+  unsigned int restarts_to_go;	/* MCUs left in this restart interval */
+  int next_restart_num;		/* next restart number to write (0-7) */
+
+  /* Pointers to derived tables (these workspaces have image lifespan) */
+  C_DERIVED_TBL * dc_derived_tbls[NUM_HUFF_TBLS];
+  C_DERIVED_TBL * ac_derived_tbls[NUM_HUFF_TBLS];
+
+#ifdef ENTROPY_OPT_SUPPORTED	/* Statistics tables for optimization */
+  long * dc_count_ptrs[NUM_HUFF_TBLS];
+  long * ac_count_ptrs[NUM_HUFF_TBLS];
+#endif
+} huff_entropy_encoder;
+
+typedef huff_entropy_encoder * huff_entropy_ptr;
+
+/* Working state while writing an MCU.
+ * This struct contains all the fields that are needed by subroutines.
+ */
+
+typedef struct {
+  JOCTET * next_output_byte;	/* => next byte to write in buffer */
+  size_t free_in_buffer;	/* # of byte spaces remaining in buffer */
+  savable_state cur;		/* Current bit buffer & DC state */
+  j_compress_ptr cinfo;		/* dump_buffer needs access to this */
+} working_state;
+
+
+/* Forward declarations */
+METHODDEF boolean encode_mcu_huff JPP((j_compress_ptr cinfo,
+				       JBLOCKROW *MCU_data));
+METHODDEF void finish_pass_huff JPP((j_compress_ptr cinfo));
+#ifdef ENTROPY_OPT_SUPPORTED
+METHODDEF boolean encode_mcu_gather JPP((j_compress_ptr cinfo,
+					 JBLOCKROW *MCU_data));
+METHODDEF void finish_pass_gather JPP((j_compress_ptr cinfo));
+#endif
+LOCAL void fix_huff_tbl JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl,
+			     C_DERIVED_TBL ** pdtbl));
+
+
+/*
+ * Initialize for a Huffman-compressed scan.
+ * If gather_statistics is TRUE, we do not output anything during the scan,
+ * just count the Huffman symbols used and generate Huffman code tables.
+ */
+
+METHODDEF void
+start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
+{
+  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+  int ci, dctbl, actbl;
+  jpeg_component_info * compptr;
+
+  if (gather_statistics) {
+#ifdef ENTROPY_OPT_SUPPORTED
+    entropy->pub.encode_mcu = encode_mcu_gather;
+    entropy->pub.finish_pass = finish_pass_gather;
+#else
+    ERREXIT(cinfo, JERR_NOT_COMPILED);
+#endif
+  } else {
+    entropy->pub.encode_mcu = encode_mcu_huff;
+    entropy->pub.finish_pass = finish_pass_huff;
+  }
+
+  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+    compptr = cinfo->cur_comp_info[ci];
+    dctbl = compptr->dc_tbl_no;
+    actbl = compptr->ac_tbl_no;
+    /* Make sure requested tables are present */
+    /* (In gather mode, tables need not be allocated yet) */
+    if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS ||
+	(cinfo->dc_huff_tbl_ptrs[dctbl] == NULL && !gather_statistics))
+      ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
+    if (actbl < 0 || actbl >= NUM_HUFF_TBLS ||
+	(cinfo->ac_huff_tbl_ptrs[actbl] == NULL && !gather_statistics))
+      ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
+    if (gather_statistics) {
+#ifdef ENTROPY_OPT_SUPPORTED
+      /* Allocate and zero the statistics tables */
+      /* Note that gen_huff_coding expects 257 entries in each table! */
+      if (entropy->dc_count_ptrs[dctbl] == NULL)
+	entropy->dc_count_ptrs[dctbl] = (long *)
+	  (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+				      257 * SIZEOF(long));
+      MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
+      if (entropy->ac_count_ptrs[actbl] == NULL)
+	entropy->ac_count_ptrs[actbl] = (long *)
+	  (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+				      257 * SIZEOF(long));
+      MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
+#endif
+    } else {
+      /* Compute derived values for Huffman tables */
+      /* We may do this more than once for a table, but it's not expensive */
+      fix_huff_tbl(cinfo, cinfo->dc_huff_tbl_ptrs[dctbl],
+		   & entropy->dc_derived_tbls[dctbl]);
+      fix_huff_tbl(cinfo, cinfo->ac_huff_tbl_ptrs[actbl],
+		   & entropy->ac_derived_tbls[actbl]);
+    }
+    /* Initialize DC predictions to 0 */
+    entropy->saved.last_dc_val[ci] = 0;
+  }
+
+  /* Initialize bit buffer to empty */
+  entropy->saved.put_buffer = 0;
+  entropy->saved.put_bits = 0;
+
+  /* Initialize restart stuff */
+  entropy->restarts_to_go = cinfo->restart_interval;
+  entropy->next_restart_num = 0;
+}
 
 
 LOCAL void
-fix_huff_tbl (HUFF_TBL * htbl)
-/* Compute derived values for a Huffman table */
+fix_huff_tbl (j_compress_ptr cinfo, JHUFF_TBL * htbl, C_DERIVED_TBL ** pdtbl)
+/* Compute the derived values for a Huffman table */
 {
+  C_DERIVED_TBL *dtbl;
   int p, i, l, lastp, si;
   char huffsize[257];
-  UINT16 huffcode[257];
-  UINT16 code;
+  unsigned int huffcode[257];
+  unsigned int code;
+
+  /* Allocate a workspace if we haven't already done so. */
+  if (*pdtbl == NULL)
+    *pdtbl = (C_DERIVED_TBL *)
+      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+				  SIZEOF(C_DERIVED_TBL));
+  dtbl = *pdtbl;
   
   /* Figure C.1: make table of Huffman code length for each symbol */
   /* Note that this is in code-length order. */
@@ -66,92 +228,103 @@
   /* Set any codeless symbols to have code length 0;
    * this allows emit_bits to detect any attempt to emit such symbols.
    */
-  MEMZERO(htbl->priv.enc.ehufsi, SIZEOF(htbl->priv.enc.ehufsi));
+  MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
 
   for (p = 0; p < lastp; p++) {
-    htbl->priv.enc.ehufco[htbl->huffval[p]] = huffcode[p];
-    htbl->priv.enc.ehufsi[htbl->huffval[p]] = huffsize[p];
+    dtbl->ehufco[htbl->huffval[p]] = huffcode[p];
+    dtbl->ehufsi[htbl->huffval[p]] = huffsize[p];
   }
 }
 
 
 /* Outputting bytes to the file */
 
-LOCAL void
-flush_bytes (void)
+/* Emit a byte, taking 'action' if must suspend. */
+#define emit_byte(state,val,action)  \
+	{ *(state)->next_output_byte++ = (JOCTET) (val);  \
+	  if (--(state)->free_in_buffer == 0)  \
+	    if (! dump_buffer(state))  \
+	      { action; } }
+
+
+LOCAL boolean
+dump_buffer (working_state * state)
+/* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
 {
-  if (bytes_in_buffer)
-    (*cinfo->methods->entropy_output) (cinfo, output_buffer, bytes_in_buffer);
-  bytes_in_buffer = 0;
+  struct jpeg_destination_mgr * dest = state->cinfo->dest;
+
+  if (! (*dest->empty_output_buffer) (state->cinfo))
+    return FALSE;
+  /* After a successful buffer dump, must reset buffer pointers */
+  state->next_output_byte = dest->next_output_byte;
+  state->free_in_buffer = dest->free_in_buffer;
+  return TRUE;
 }
 
 
-#define emit_byte(val)  \
-  MAKESTMT( if (bytes_in_buffer >= JPEG_BUF_SIZE) \
-	      flush_bytes(); \
-	    output_buffer[bytes_in_buffer++] = (char) (val); )
-
-
-
 /* Outputting bits to the file */
 
-/* Only the right 24 bits of huff_put_buffer are used; the valid bits are
+/* Only the right 24 bits of put_buffer are used; the valid bits are
  * left-justified in this part.  At most 16 bits can be passed to emit_bits
- * in one call, and we never retain more than 7 bits in huff_put_buffer
+ * in one call, and we never retain more than 7 bits in put_buffer
  * between calls, so 24 bits are sufficient.
  */
 
 INLINE
-LOCAL void
-emit_bits (UINT16 code, int size)
+LOCAL boolean
+emit_bits (working_state * state, unsigned int code, int size)
+/* Emit some bits; return TRUE if successful, FALSE if must suspend */
 {
   /* This routine is heavily used, so it's worth coding tightly. */
-  register INT32 put_buffer = code;
-  register int put_bits = huff_put_bits;
+  register INT32 put_buffer = (INT32) code;
+  register int put_bits = state->cur.put_bits;
 
   /* if size is 0, caller used an invalid Huffman table entry */
   if (size == 0)
-    ERREXIT(cinfo->emethods, "Missing Huffman code table entry");
+    ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
 
-  put_buffer &= (((INT32) 1) << size) - 1; /* Mask off any excess bits in code */
+  put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
   
   put_bits += size;		/* new number of bits in buffer */
   
   put_buffer <<= 24 - put_bits; /* align incoming bits */
 
-  put_buffer |= huff_put_buffer; /* and merge with old buffer contents */
+  put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
   
   while (put_bits >= 8) {
     int c = (int) ((put_buffer >> 16) & 0xFF);
     
-    emit_byte(c);
+    emit_byte(state, c, return FALSE);
     if (c == 0xFF) {		/* need to stuff a zero byte? */
-      emit_byte(0);
+      emit_byte(state, 0, return FALSE);
     }
     put_buffer <<= 8;
     put_bits -= 8;
   }
 
-  huff_put_buffer = put_buffer;	/* Update global variables */
-  huff_put_bits = put_bits;
+  state->cur.put_buffer = put_buffer; /* update state variables */
+  state->cur.put_bits = put_bits;
+
+  return TRUE;
 }
 
 
-LOCAL void
-flush_bits (void)
+LOCAL boolean
+flush_bits (working_state * state)
 {
-  emit_bits((UINT16) 0x7F, 7);	/* fill any partial byte with ones */
-  huff_put_buffer = 0;		/* and reset bit-buffer to empty */
-  huff_put_bits = 0;
+  if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
+    return FALSE;
+  state->cur.put_buffer = 0;	/* and reset bit-buffer to empty */
+  state->cur.put_bits = 0;
+  return TRUE;
 }
 
 
-
 /* Encode a single block's worth of coefficients */
-/* Note that the DC coefficient has already been converted to a difference */
 
-LOCAL void
-encode_one_block (JBLOCK block, HUFF_TBL *dctbl, HUFF_TBL *actbl)
+LOCAL boolean
+encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
+		  C_DERIVED_TBL *dctbl, C_DERIVED_TBL *actbl)
 {
   register int temp, temp2;
   register int nbits;
@@ -159,7 +332,7 @@
   
   /* Encode the DC coefficient difference per section F.1.2.1 */
   
-  temp = temp2 = block[0];
+  temp = temp2 = block[0] - last_dc_val;
 
   if (temp < 0) {
     temp = -temp;		/* temp is abs value of input */
@@ -176,13 +349,15 @@
   }
   
   /* Emit the Huffman-coded symbol for the number of bits */
-  emit_bits(dctbl->priv.enc.ehufco[nbits], dctbl->priv.enc.ehufsi[nbits]);
+  if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
+    return FALSE;
 
   /* Emit that number of bits of the value, if positive, */
   /* or the complement of its magnitude, if negative. */
   if (nbits)			/* emit_bits rejects calls with size 0 */
-    emit_bits((UINT16) temp2, nbits);
-  
+    if (! emit_bits(state, (unsigned int) temp2, nbits))
+      return FALSE;
+
   /* Encode the AC coefficients per section F.1.2.2 */
   
   r = 0;			/* r = run length of zeros */
@@ -193,7 +368,8 @@
     } else {
       /* if run length > 15, must emit special run-length-16 codes (0xF0) */
       while (r > 15) {
-	emit_bits(actbl->priv.enc.ehufco[0xF0], actbl->priv.enc.ehufsi[0xF0]);
+	if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
+	  return FALSE;
 	r -= 16;
       }
 
@@ -206,16 +382,18 @@
       
       /* Find the number of bits needed for the magnitude of the coefficient */
       nbits = 1;		/* there must be at least one 1 bit */
-      while (temp >>= 1)
+      while ((temp >>= 1))
 	nbits++;
       
       /* Emit Huffman symbol for run length / number of bits */
       i = (r << 4) + nbits;
-      emit_bits(actbl->priv.enc.ehufco[i], actbl->priv.enc.ehufsi[i]);
-      
+      if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
+	return FALSE;
+
       /* Emit that number of bits of the value, if positive, */
       /* or the complement of its magnitude, if negative. */
-      emit_bits((UINT16) temp2, nbits);
+      if (! emit_bits(state, (unsigned int) temp2, nbits))
+	return FALSE;
       
       r = 0;
     }
@@ -223,51 +401,10 @@
 
   /* If the last coef(s) were zero, emit an end-of-block code */
   if (r > 0)
-    emit_bits(actbl->priv.enc.ehufco[0], actbl->priv.enc.ehufsi[0]);
-}
+    if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
+      return FALSE;
 
-
-
-/*
- * Initialize for a Huffman-compressed scan.
- * This is invoked after writing the SOS marker.
- * The pipeline controller must establish the entropy_output method pointer
- * before calling this routine.
- */
-
-METHODDEF void
-huff_init (compress_info_ptr xinfo)
-{
-  short ci;
-  jpeg_component_info * compptr;
-
-  /* Initialize static variables */
-  cinfo = xinfo;
-  huff_put_buffer = 0;
-  huff_put_bits = 0;
-
-  /* Initialize the output buffer */
-  output_buffer = (char *) (*cinfo->emethods->alloc_small)
-				((size_t) JPEG_BUF_SIZE);
-  bytes_in_buffer = 0;
-
-  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
-    compptr = cinfo->cur_comp_info[ci];
-    /* Make sure requested tables are present */
-    if (cinfo->dc_huff_tbl_ptrs[compptr->dc_tbl_no] == NULL ||
-	cinfo->ac_huff_tbl_ptrs[compptr->ac_tbl_no] == NULL)
-      ERREXIT(cinfo->emethods, "Use of undefined Huffman table");
-    /* Compute derived values for Huffman tables */
-    /* We may do this more than once for same table, but it's not a big deal */
-    fix_huff_tbl(cinfo->dc_huff_tbl_ptrs[compptr->dc_tbl_no]);
-    fix_huff_tbl(cinfo->ac_huff_tbl_ptrs[compptr->ac_tbl_no]);
-    /* Initialize DC predictions to 0 */
-    cinfo->last_dc_val[ci] = 0;
-  }
-
-  /* Initialize restart stuff */
-  cinfo->restarts_to_go = cinfo->restart_interval;
-  cinfo->next_restart_num = 0;
+  return TRUE;
 }
 
 
@@ -275,24 +412,24 @@
  * Emit a restart marker & resynchronize predictions.
  */
 
-LOCAL void
-emit_restart (compress_info_ptr cinfo)
+LOCAL boolean
+emit_restart (working_state * state, int restart_num)
 {
-  short ci;
+  int ci;
 
-  flush_bits();
+  if (! flush_bits(state))
+    return FALSE;
 
-  emit_byte(0xFF);
-  emit_byte(RST0 + cinfo->next_restart_num);
+  emit_byte(state, 0xFF, return FALSE);
+  emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
 
   /* Re-initialize DC predictions to 0 */
-  for (ci = 0; ci < cinfo->comps_in_scan; ci++)
-    cinfo->last_dc_val[ci] = 0;
+  for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
+    state->cur.last_dc_val[ci] = 0;
 
-  /* Update restart state */
-  cinfo->restarts_to_go = cinfo->restart_interval;
-  cinfo->next_restart_num++;
-  cinfo->next_restart_num &= 7;
+  /* The restart counter is not updated until we successfully write the MCU. */
+
+  return TRUE;
 }
 
 
@@ -300,31 +437,56 @@
  * Encode and output one MCU's worth of Huffman-compressed coefficients.
  */
 
-METHODDEF void
-huff_encode (compress_info_ptr cinfo, JBLOCK *MCU_data)
+METHODDEF boolean
+encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
 {
-  short blkn, ci;
+  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+  working_state state;
+  int blkn, ci;
   jpeg_component_info * compptr;
-  JCOEF temp;
 
-  /* Account for restart interval, emit restart marker if needed */
+  /* Load up working state */
+  state.next_output_byte = cinfo->dest->next_output_byte;
+  state.free_in_buffer = cinfo->dest->free_in_buffer;
+  ASSIGN_STATE(state.cur, entropy->saved);
+  state.cinfo = cinfo;
+
+  /* Emit restart marker if needed */
   if (cinfo->restart_interval) {
-    if (cinfo->restarts_to_go == 0)
-      emit_restart(cinfo);
-    cinfo->restarts_to_go--;
+    if (entropy->restarts_to_go == 0)
+      if (! emit_restart(&state, entropy->next_restart_num))
+	return FALSE;
   }
 
+  /* Encode the MCU data blocks */
   for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
     ci = cinfo->MCU_membership[blkn];
     compptr = cinfo->cur_comp_info[ci];
-    /* Convert DC value to difference, update last_dc_val */
-    temp = MCU_data[blkn][0];
-    MCU_data[blkn][0] -= cinfo->last_dc_val[ci];
-    cinfo->last_dc_val[ci] = temp;
-    encode_one_block(MCU_data[blkn],
-		     cinfo->dc_huff_tbl_ptrs[compptr->dc_tbl_no],
-		     cinfo->ac_huff_tbl_ptrs[compptr->ac_tbl_no]);
+    if (! encode_one_block(&state,
+			   MCU_data[blkn][0], state.cur.last_dc_val[ci],
+			   entropy->dc_derived_tbls[compptr->dc_tbl_no],
+			   entropy->ac_derived_tbls[compptr->ac_tbl_no]))
+      return FALSE;
+    /* Update last_dc_val */
+    state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
   }
+
+  /* Completed MCU, so update state */
+  cinfo->dest->next_output_byte = state.next_output_byte;
+  cinfo->dest->free_in_buffer = state.free_in_buffer;
+  ASSIGN_STATE(entropy->saved, state.cur);
+
+  /* Update restart-interval state too */
+  if (cinfo->restart_interval) {
+    if (entropy->restarts_to_go == 0) {
+      entropy->restarts_to_go = cinfo->restart_interval;
+      entropy->next_restart_num++;
+      entropy->next_restart_num &= 7;
+    }
+    entropy->restarts_to_go--;
+  }
+
+  return TRUE;
 }
 
 
@@ -333,18 +495,28 @@
  */
 
 METHODDEF void
-huff_term (compress_info_ptr cinfo)
+finish_pass_huff (j_compress_ptr cinfo)
 {
+  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+  working_state state;
+
+  /* Load up working state ... flush_bits needs it */
+  state.next_output_byte = cinfo->dest->next_output_byte;
+  state.free_in_buffer = cinfo->dest->free_in_buffer;
+  ASSIGN_STATE(state.cur, entropy->saved);
+  state.cinfo = cinfo;
+
   /* Flush out the last data */
-  flush_bits();
-  flush_bytes();
-  /* Release the I/O buffer */
-  (*cinfo->emethods->free_small) ((void *) output_buffer);
+  if (! flush_bits(&state))
+    ERREXIT(cinfo, JERR_CANT_SUSPEND);
+
+  /* Update state */
+  cinfo->dest->next_output_byte = state.next_output_byte;
+  cinfo->dest->free_in_buffer = state.free_in_buffer;
+  ASSIGN_STATE(entropy->saved, state.cur);
 }
 
 
-
-
 /*
  * Huffman coding optimization.
  *
@@ -353,24 +525,127 @@
  * count the number of uses of each symbol that is to be Huffman-coded.
  * (This process must agree with the code above.)  Then we build an
  * optimal Huffman coding tree for the observed counts.
+ *
+ * The JPEG standard requires Huffman codes to be no more than 16 bits long.
+ * If some symbols have a very small but nonzero probability, the Huffman tree
+ * must be adjusted to meet the code length restriction.  We currently use
+ * the adjustment method suggested in the JPEG spec.  This method is *not*
+ * optimal; it may not choose the best possible limited-length code.  But
+ * since the symbols involved are infrequently used, it's not clear that
+ * going to extra trouble is worthwhile.
  */
 
 #ifdef ENTROPY_OPT_SUPPORTED
 
 
-/* These are static so htest_one_block can find 'em */
-static long * dc_count_ptrs[NUM_HUFF_TBLS];
-static long * ac_count_ptrs[NUM_HUFF_TBLS];
-
+/* Process a single block's worth of coefficients */
 
 LOCAL void
-gen_huff_coding (compress_info_ptr cinfo, HUFF_TBL *htbl, long freq[])
-/* Generate the optimal coding for the given counts */
+htest_one_block (JCOEFPTR block, int last_dc_val,
+		 long dc_counts[], long ac_counts[])
+{
+  register int temp;
+  register int nbits;
+  register int k, r;
+  
+  /* Encode the DC coefficient difference per section F.1.2.1 */
+  
+  temp = block[0] - last_dc_val;
+  if (temp < 0)
+    temp = -temp;
+  
+  /* Find the number of bits needed for the magnitude of the coefficient */
+  nbits = 0;
+  while (temp) {
+    nbits++;
+    temp >>= 1;
+  }
+
+  /* Count the Huffman symbol for the number of bits */
+  dc_counts[nbits]++;
+  
+  /* Encode the AC coefficients per section F.1.2.2 */
+  
+  r = 0;			/* r = run length of zeros */
+  
+  for (k = 1; k < DCTSIZE2; k++) {
+    if ((temp = block[k]) == 0) {
+      r++;
+    } else {
+      /* if run length > 15, must emit special run-length-16 codes (0xF0) */
+      while (r > 15) {
+	ac_counts[0xF0]++;
+	r -= 16;
+      }
+      
+      /* Find the number of bits needed for the magnitude of the coefficient */
+      if (temp < 0)
+	temp = -temp;
+      
+      /* Find the number of bits needed for the magnitude of the coefficient */
+      nbits = 1;		/* there must be at least one 1 bit */
+      while ((temp >>= 1))
+	nbits++;
+      
+      /* Count Huffman symbol for run length / number of bits */
+      ac_counts[(r << 4) + nbits]++;
+      
+      r = 0;
+    }
+  }
+
+  /* If the last coef(s) were zero, emit an end-of-block code */
+  if (r > 0)
+    ac_counts[0]++;
+}
+
+
+/*
+ * Trial-encode one MCU's worth of Huffman-compressed coefficients.
+ * No data is actually output, so no suspension return is possible.
+ */
+
+METHODDEF boolean
+encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
+{
+  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+  int blkn, ci;
+  jpeg_component_info * compptr;
+
+  /* Take care of restart intervals if needed */
+  if (cinfo->restart_interval) {
+    if (entropy->restarts_to_go == 0) {
+      /* Re-initialize DC predictions to 0 */
+      for (ci = 0; ci < cinfo->comps_in_scan; ci++)
+	entropy->saved.last_dc_val[ci] = 0;
+      /* Update restart state */
+      entropy->restarts_to_go = cinfo->restart_interval;
+    }
+    entropy->restarts_to_go--;
+  }
+
+  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
+    ci = cinfo->MCU_membership[blkn];
+    compptr = cinfo->cur_comp_info[ci];
+    htest_one_block(MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
+		    entropy->dc_count_ptrs[compptr->dc_tbl_no],
+		    entropy->ac_count_ptrs[compptr->ac_tbl_no]);
+    entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
+  }
+
+  return TRUE;
+}
+
+
+/* Generate the optimal coding for the given counts, initialize htbl */
+
+LOCAL void
+gen_huff_coding (j_compress_ptr cinfo, JHUFF_TBL *htbl, long freq[])
 {
 #define MAX_CLEN 32		/* assumed maximum initial code length */
   UINT8 bits[MAX_CLEN+1];	/* bits[k] = # of symbols with code length k */
-  short codesize[257];		/* codesize[k] = code length of symbol k */
-  short others[257];		/* next symbol in current branch of tree */
+  int codesize[257];		/* codesize[k] = code length of symbol k */
+  int others[257];		/* next symbol in current branch of tree */
   int c1, c2;
   int p, i, j;
   long v;
@@ -383,7 +658,7 @@
     others[i] = -1;		/* init links to empty */
   
   freq[256] = 1;		/* make sure there is a nonzero count */
-  /* including the pseudo-symbol 256 in the Huffman procedure guarantees
+  /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
    * that no real symbol is given code-value of all ones, because 256
    * will be placed in the largest codeword category.
    */
@@ -444,7 +719,7 @@
       /* The JPEG standard seems to think that this can't happen, */
       /* but I'm paranoid... */
       if (codesize[i] > MAX_CLEN)
-	ERREXIT(cinfo->emethods, "Huffman code size table overflow");
+	ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
 
       bits[codesize[i]]++;
     }
@@ -495,176 +770,49 @@
       }
     }
   }
+
+  /* Set sent_table FALSE so updated table will be written to JPEG file. */
+  htbl->sent_table = FALSE;
 }
 
 
-/* Process a single block's worth of coefficients */
-/* Note that the DC coefficient has already been converted to a difference */
-
-LOCAL void
-htest_one_block (JBLOCK block, JCOEF block0,
-		 long dc_counts[], long ac_counts[])
-{
-  register INT32 temp;
-  register int nbits;
-  register int k, r;
-  
-  /* Encode the DC coefficient difference per section F.1.2.1 */
-  
-  /* Find the number of bits needed for the magnitude of the coefficient */
-  temp = block0;
-  if (temp < 0) temp = -temp;
-  
-  for (nbits = 0; temp; nbits++)
-    temp >>= 1;
-  
-  /* Count the Huffman symbol for the number of bits */
-  dc_counts[nbits]++;
-  
-  /* Encode the AC coefficients per section F.1.2.2 */
-  
-  r = 0;			/* r = run length of zeros */
-  
-  for (k = 1; k < DCTSIZE2; k++) {
-    if ((temp = block[k]) == 0) {
-      r++;
-    } else {
-      /* if run length > 15, must emit special run-length-16 codes (0xF0) */
-      while (r > 15) {
-	ac_counts[0xF0]++;
-	r -= 16;
-      }
-      
-      /* Find the number of bits needed for the magnitude of the coefficient */
-      if (temp < 0) temp = -temp;
-      
-      for (nbits = 0; temp; nbits++)
-	temp >>= 1;
-      
-      /* Count Huffman symbol for run length / number of bits */
-      ac_counts[(r << 4) + nbits]++;
-      
-      r = 0;
-    }
-  }
-
-  /* If the last coef(s) were zero, emit an end-of-block code */
-  if (r > 0)
-    ac_counts[0]++;
-}
-
-
-
 /*
- * Trial-encode one MCU's worth of Huffman-compressed coefficients.
- */
-
-LOCAL void
-htest_encode (compress_info_ptr cinfo, JBLOCK *MCU_data)
-{
-  short blkn, ci;
-  jpeg_component_info * compptr;
-
-  /* Take care of restart intervals if needed */
-  if (cinfo->restart_interval) {
-    if (cinfo->restarts_to_go == 0) {
-      /* Re-initialize DC predictions to 0 */
-      for (ci = 0; ci < cinfo->comps_in_scan; ci++)
-	cinfo->last_dc_val[ci] = 0;
-      /* Update restart state */
-      cinfo->restarts_to_go = cinfo->restart_interval;
-    }
-    cinfo->restarts_to_go--;
-  }
-
-  for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
-    ci = cinfo->MCU_membership[blkn];
-    compptr = cinfo->cur_comp_info[ci];
-    /* NB: unlike the real entropy encoder, we may not change the input data */
-    htest_one_block(MCU_data[blkn],
-		    (JCOEF) (MCU_data[blkn][0] - cinfo->last_dc_val[ci]),
-		    dc_count_ptrs[compptr->dc_tbl_no],
-		    ac_count_ptrs[compptr->ac_tbl_no]);
-    cinfo->last_dc_val[ci] = MCU_data[blkn][0];
-  }
-}
-
-
-
-/*
- * Find the best coding parameters for a Huffman-coded scan.
- * When called, the scan data has already been converted to a sequence of
- * MCU groups of quantized coefficients, which are stored in a "big" array.
- * The source_method knows how to iterate through that array.
- * On return, the MCU data is unmodified, but the Huffman tables referenced
- * by the scan components may have been altered.
+ * Finish up a statistics-gathering pass and create the new Huffman tables.
  */
 
 METHODDEF void
-huff_optimize (compress_info_ptr cinfo, MCU_output_caller_ptr source_method)
-/* Optimize Huffman-coding parameters (Huffman symbol table) */
+finish_pass_gather (j_compress_ptr cinfo)
 {
-  int i, tbl;
-  HUFF_TBL **htblptr;
+  huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
+  int ci, dctbl, actbl;
+  jpeg_component_info * compptr;
+  JHUFF_TBL **htblptr;
+  boolean did_dc[NUM_HUFF_TBLS];
+  boolean did_ac[NUM_HUFF_TBLS];
 
-  /* Allocate and zero the count tables */
-  /* Note that gen_huff_coding expects 257 entries in each table! */
+  /* It's important not to apply gen_huff_coding more than once per table,
+   * because it clobbers the input frequency counts!
+   */
+  MEMZERO(did_dc, SIZEOF(did_dc));
+  MEMZERO(did_ac, SIZEOF(did_ac));
 
-  for (i = 0; i < NUM_HUFF_TBLS; i++) {
-    dc_count_ptrs[i] = NULL;
-    ac_count_ptrs[i] = NULL;
-  }
-
-  for (i = 0; i < cinfo->comps_in_scan; i++) {
-    /* Create DC table */
-    tbl = cinfo->cur_comp_info[i]->dc_tbl_no;
-    if (dc_count_ptrs[tbl] == NULL) {
-      dc_count_ptrs[tbl] = (long *) (*cinfo->emethods->alloc_small)
-					(257 * SIZEOF(long));
-      MEMZERO(dc_count_ptrs[tbl], 257 * SIZEOF(long));
-    }
-    /* Create AC table */
-    tbl = cinfo->cur_comp_info[i]->ac_tbl_no;
-    if (ac_count_ptrs[tbl] == NULL) {
-      ac_count_ptrs[tbl] = (long *) (*cinfo->emethods->alloc_small)
-					(257 * SIZEOF(long));
-      MEMZERO(ac_count_ptrs[tbl], 257 * SIZEOF(long));
-    }
-  }
-
-  /* Initialize DC predictions to 0 */
-  for (i = 0; i < cinfo->comps_in_scan; i++) {
-    cinfo->last_dc_val[i] = 0;
-  }
-  /* Initialize restart stuff */
-  cinfo->restarts_to_go = cinfo->restart_interval;
-
-  /* Scan the MCU data, count symbol uses */
-  (*source_method) (cinfo, htest_encode);
-
-  /* Now generate optimal Huffman tables */
-  for (tbl = 0; tbl < NUM_HUFF_TBLS; tbl++) {
-    if (dc_count_ptrs[tbl] != NULL) {
-      htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
+  for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
+    compptr = cinfo->cur_comp_info[ci];
+    dctbl = compptr->dc_tbl_no;
+    actbl = compptr->ac_tbl_no;
+    if (! did_dc[dctbl]) {
+      htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
       if (*htblptr == NULL)
-	*htblptr = (HUFF_TBL *) (*cinfo->emethods->alloc_small) (SIZEOF(HUFF_TBL));
-      /* Set sent_table FALSE so updated table will be written to JPEG file. */
-      (*htblptr)->sent_table = FALSE;
-      /* Compute the optimal Huffman encoding */
-      gen_huff_coding(cinfo, *htblptr, dc_count_ptrs[tbl]);
-      /* Release the count table */
-      (*cinfo->emethods->free_small) ((void *) dc_count_ptrs[tbl]);
+	*htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
+      gen_huff_coding(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
+      did_dc[dctbl] = TRUE;
     }
-    if (ac_count_ptrs[tbl] != NULL) {
-      htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
+    if (! did_ac[actbl]) {
+      htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
       if (*htblptr == NULL)
-	*htblptr = (HUFF_TBL *) (*cinfo->emethods->alloc_small) (SIZEOF(HUFF_TBL));
-      /* Set sent_table FALSE so updated table will be written to JPEG file. */
-      (*htblptr)->sent_table = FALSE;
-      /* Compute the optimal Huffman encoding */
-      gen_huff_coding(cinfo, *htblptr, ac_count_ptrs[tbl]);
-      /* Release the count table */
-      (*cinfo->emethods->free_small) ((void *) ac_count_ptrs[tbl]);
+	*htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
+      gen_huff_coding(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
+      did_ac[actbl] = TRUE;
     }
   }
 }
@@ -674,27 +822,26 @@
 
 
 /*
- * The method selection routine for Huffman entropy encoding.
+ * Module initialization routine for Huffman entropy encoding.
  */
 
 GLOBAL void
-jselchuffman (compress_info_ptr cinfo)
+jinit_huff_encoder (j_compress_ptr cinfo)
 {
-  if (! cinfo->arith_code) {
-    cinfo->methods->entropy_encode_init = huff_init;
-    cinfo->methods->entropy_encode = huff_encode;
-    cinfo->methods->entropy_encode_term = huff_term;
+  huff_entropy_ptr entropy;
+  int i;
+
+  entropy = (huff_entropy_ptr)
+    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+				SIZEOF(huff_entropy_encoder));
+  cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
+  entropy->pub.start_pass = start_pass_huff;
+
+  /* Mark tables unallocated */
+  for (i = 0; i < NUM_HUFF_TBLS; i++) {
+    entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
 #ifdef ENTROPY_OPT_SUPPORTED
-    cinfo->methods->entropy_optimize = huff_optimize;
-    /* The standard Huffman tables are only valid for 8-bit data precision.
-     * If the precision is higher, force optimization on so that usable
-     * tables will be computed.  This test can be removed if default tables
-     * are supplied that are valid for the desired precision.
-     */
-    if (cinfo->data_precision > 8)
-      cinfo->optimize_coding = TRUE;
-    if (cinfo->optimize_coding)
-      cinfo->total_passes++;	/* one pass needed for entropy optimization */
+    entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
 #endif
   }
 }
diff --git a/jcmain.c b/jcmain.c
deleted file mode 100644
index 03d24fc..0000000
--- a/jcmain.c
+++ /dev/null
@@ -1,733 +0,0 @@
-/*
- * jcmain.c
- *
- * Copyright (C) 1991, 1992, 1993, 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.
- *
- * This file contains a command-line user interface for the JPEG compressor.
- * It should work on any system with Unix- or MS-DOS-style command lines.
- *
- * Two different command line styles are permitted, depending on the
- * compile-time switch TWO_FILE_COMMANDLINE:
- *	cjpeg [options]  inputfile outputfile
- *	cjpeg [options]  [inputfile]
- * In the second style, output is always to standard output, which you'd
- * normally redirect to a file or pipe to some other program.  Input is
- * either from a named file or from standard input (typically redirected).
- * The second style is convenient on Unix but is unhelpful on systems that
- * don't support pipes.  Also, you MUST use the first style if your system
- * doesn't do binary I/O to stdin/stdout.
- * To simplify script writing, the "-outfile" switch is provided.  The syntax
- *	cjpeg [options]  -outfile outputfile  inputfile
- * works regardless of which command line style is used.
- */
-
-#include "jinclude.h"
-#ifdef INCLUDES_ARE_ANSI
-#include <stdlib.h>		/* to declare exit() */
-#endif
-#include <ctype.h>		/* to declare isupper(), tolower() */
-#ifdef NEED_SIGNAL_CATCHER
-#include <signal.h>		/* to declare signal() */
-#endif
-#ifdef USE_SETMODE
-#include <fcntl.h>		/* to declare setmode() */
-#endif
-
-#ifdef THINK_C
-#include <console.h>		/* command-line reader for Macintosh */
-#endif
-
-#ifdef DONT_USE_B_MODE		/* define mode parameters for fopen() */
-#define READ_BINARY	"r"
-#define WRITE_BINARY	"w"
-#else
-#define READ_BINARY	"rb"
-#define WRITE_BINARY	"wb"
-#endif
-
-#ifndef EXIT_FAILURE		/* define exit() codes if not provided */
-#define EXIT_FAILURE  1
-#endif
-#ifndef EXIT_SUCCESS
-#ifdef VMS
-#define EXIT_SUCCESS  1		/* VMS is very nonstandard */
-#else
-#define EXIT_SUCCESS  0
-#endif
-#endif
-
-
-#include "jversion.h"		/* for version message */
-
-
-/*
- * This routine determines what format the input file is,
- * and selects the appropriate input-reading module.
- *
- * To determine which family of input formats the file belongs to,
- * we may look only at the first byte of the file, since C does not
- * guarantee that more than one character can be pushed back with ungetc.
- * Looking at additional bytes would require one of these approaches:
- *     1) assume we can fseek() the input file (fails for piped input);
- *     2) assume we can push back more than one character (works in
- *        some C implementations, but unportable);
- *     3) provide our own buffering as is done in djpeg (breaks input readers
- *        that want to use stdio directly, such as the RLE library);
- * or  4) don't put back the data, and modify the input_init methods to assume
- *        they start reading after the start of file (also breaks RLE library).
- * #1 is attractive for MS-DOS but is untenable on Unix.
- *
- * The most portable solution for file types that can't be identified by their
- * first byte is to make the user tell us what they are.  This is also the
- * only approach for "raw" file types that contain only arbitrary values.
- * We presently apply this method for Targa files.  Most of the time Targa
- * files start with 0x00, so we recognize that case.  Potentially, however,
- * a Targa file could start with any byte value (byte 0 is the length of the
- * seldom-used ID field), so we provide a switch to force Targa input mode.
- */
-
-static boolean is_targa;	/* records user -targa switch */
-
-
-LOCAL void
-select_file_type (compress_info_ptr cinfo)
-{
-  int c;
-
-  if (is_targa) {
-#ifdef TARGA_SUPPORTED
-    jselrtarga(cinfo);
-#else
-    ERREXIT(cinfo->emethods, "Targa support was not compiled");
-#endif
-    return;
-  }
-
-  if ((c = getc(cinfo->input_file)) == EOF)
-    ERREXIT(cinfo->emethods, "Empty input file");
-
-  switch (c) {
-#ifdef GIF_SUPPORTED
-  case 'G':
-    jselrgif(cinfo);
-    break;
-#endif
-#ifdef PPM_SUPPORTED
-  case 'P':
-    jselrppm(cinfo);
-    break;
-#endif
-#ifdef RLE_SUPPORTED
-  case 'R':
-    jselrrle(cinfo);
-    break;
-#endif
-#ifdef TARGA_SUPPORTED
-  case 0x00:
-    jselrtarga(cinfo);
-    break;
-#endif
-  default:
-#ifdef TARGA_SUPPORTED
-    ERREXIT(cinfo->emethods, "Unrecognized input file format --- perhaps you need -targa");
-#else
-    ERREXIT(cinfo->emethods, "Unrecognized input file format");
-#endif
-    break;
-  }
-
-  if (ungetc(c, cinfo->input_file) == EOF)
-    ERREXIT(cinfo->emethods, "ungetc failed");
-}
-
-
-/*
- * This routine gets control after the input file header has been read.
- * It must determine what output JPEG file format is to be written,
- * and make any other compression parameter changes that are desirable.
- */
-
-METHODDEF void
-c_ui_method_selection (compress_info_ptr cinfo)
-{
-  /* If the input is gray scale, generate a monochrome JPEG file. */
-  if (cinfo->in_color_space == CS_GRAYSCALE)
-    j_monochrome_default(cinfo);
-  /* For now, always select JFIF output format. */
-#ifdef JFIF_SUPPORTED
-  jselwjfif(cinfo);
-#else
-  You shoulda defined JFIF_SUPPORTED.   /* deliberate syntax error */
-#endif
-}
-
-
-/*
- * Signal catcher to ensure that temporary files are removed before aborting.
- * NB: for Amiga Manx C this is actually a global routine named _abort();
- * see -Dsignal_catcher=_abort in CFLAGS.  Talk about bogus...
- */
-
-#ifdef NEED_SIGNAL_CATCHER
-
-static external_methods_ptr emethods; /* for access to free_all */
-
-GLOBAL void
-signal_catcher (int signum)
-{
-  if (emethods != NULL) {
-    emethods->trace_level = 0;	/* turn off trace output */
-    (*emethods->free_all) ();	/* clean up memory allocation & temp files */
-  }
-  exit(EXIT_FAILURE);
-}
-
-#endif
-
-
-/*
- * Optional routine to display a percent-done figure on stderr.
- * See jcdeflts.c for explanation of the information used.
- */
-
-#ifdef PROGRESS_REPORT
-
-METHODDEF void
-progress_monitor (compress_info_ptr cinfo, long loopcounter, long looplimit)
-{
-  if (cinfo->total_passes > 1) {
-    fprintf(stderr, "\rPass %d/%d: %3d%% ",
-	    cinfo->completed_passes+1, cinfo->total_passes,
-	    (int) (loopcounter*100L/looplimit));
-  } else {
-    fprintf(stderr, "\r %3d%% ",
-	    (int) (loopcounter*100L/looplimit));
-  }
-  fflush(stderr);
-}
-
-#endif
-
-
-/*
- * Argument-parsing code.
- * The switch parser is designed to be useful with DOS-style command line
- * syntax, ie, intermixed switches and file names, where only the switches
- * to the left of a given file name affect processing of that file.
- * The main program in this file doesn't actually use this capability...
- */
-
-
-static char * progname;		/* program name for error messages */
-static char * outfilename;	/* for -outfile switch */
-
-
-LOCAL void
-usage (void)
-/* complain about bad command line */
-{
-  fprintf(stderr, "usage: %s [switches] ", progname);
-#ifdef TWO_FILE_COMMANDLINE
-  fprintf(stderr, "inputfile outputfile\n");
-#else
-  fprintf(stderr, "[inputfile]\n");
-#endif
-
-  fprintf(stderr, "Switches (names may be abbreviated):\n");
-  fprintf(stderr, "  -quality N     Compression quality (0..100; 5-95 is useful range)\n");
-  fprintf(stderr, "  -grayscale     Create monochrome JPEG file\n");
-#ifdef ENTROPY_OPT_SUPPORTED
-  fprintf(stderr, "  -optimize      Optimize Huffman table (smaller file, but slow compression)\n");
-#endif
-#ifdef TARGA_SUPPORTED
-  fprintf(stderr, "  -targa         Input file is Targa format (usually not needed)\n");
-#endif
-  fprintf(stderr, "Switches for advanced users:\n");
-  fprintf(stderr, "  -restart N     Set restart interval in rows, or in blocks with B\n");
-#ifdef INPUT_SMOOTHING_SUPPORTED
-  fprintf(stderr, "  -smooth N      Smooth dithered input (N=1..100 is strength)\n");
-#endif
-  fprintf(stderr, "  -maxmemory N   Maximum memory to use (in kbytes)\n");
-  fprintf(stderr, "  -verbose  or  -debug   Emit debug output\n");
-  fprintf(stderr, "Switches for wizards:\n");
-#ifdef C_ARITH_CODING_SUPPORTED
-  fprintf(stderr, "  -arithmetic    Use arithmetic coding\n");
-#endif
-#ifdef C_MULTISCAN_FILES_SUPPORTED
-  fprintf(stderr, "  -nointerleave  Create noninterleaved JPEG file\n");
-#endif
-  fprintf(stderr, "  -qtables file  Use quantization tables given in file\n");
-  fprintf(stderr, "  -sample HxV[,...]  Set JPEG sampling factors\n");
-  exit(EXIT_FAILURE);
-}
-
-
-LOCAL boolean
-keymatch (char * arg, const char * keyword, int minchars)
-/* Case-insensitive matching of (possibly abbreviated) keyword switches. */
-/* keyword is the constant keyword (must be lower case already), */
-/* minchars is length of minimum legal abbreviation. */
-{
-  register int ca, ck;
-  register int nmatched = 0;
-
-  while ((ca = *arg++) != '\0') {
-    if ((ck = *keyword++) == '\0')
-      return FALSE;		/* arg longer than keyword, no good */
-    if (isupper(ca))		/* force arg to lcase (assume ck is already) */
-      ca = tolower(ca);
-    if (ca != ck)
-      return FALSE;		/* no good */
-    nmatched++;			/* count matched characters */
-  }
-  /* reached end of argument; fail if it's too short for unique abbrev */
-  if (nmatched < minchars)
-    return FALSE;
-  return TRUE;			/* A-OK */
-}
-
-
-LOCAL int
-qt_getc (FILE * file)
-/* Read next char, skipping over any comments (# to end of line) */
-/* A comment/newline sequence is returned as a newline */
-{
-  register int ch;
-  
-  ch = getc(file);
-  if (ch == '#') {
-    do {
-      ch = getc(file);
-    } while (ch != '\n' && ch != EOF);
-  }
-  return ch;
-}
-
-
-LOCAL long
-read_qt_integer (FILE * file)
-/* Read an unsigned decimal integer from a quantization-table file */
-/* Swallows one trailing character after the integer */
-{
-  register int ch;
-  register long val;
-  
-  /* Skip any leading whitespace, detect EOF */
-  do {
-    ch = qt_getc(file);
-    if (ch == EOF)
-      return EOF;
-  } while (isspace(ch));
-  
-  if (! isdigit(ch)) {
-    fprintf(stderr, "%s: bogus data in quantization file\n", progname);
-    exit(EXIT_FAILURE);
-  }
-
-  val = ch - '0';
-  while (ch = qt_getc(file), isdigit(ch)) {
-    val *= 10;
-    val += ch - '0';
-  }
-  return val;
-}
-
-
-LOCAL void
-read_quant_tables (compress_info_ptr cinfo, char * filename, int scale_factor)
-/* Read a set of quantization tables from the specified file.
- * The file is plain ASCII text: decimal numbers with whitespace between.
- * Comments preceded by '#' may be included in the file.
- * There may be one to NUM_QUANT_TBLS tables in the file, each of 64 values.
- * The tables are implicitly numbered 0,1,etc.
- */
-{
-  /* ZIG[i] is the zigzag-order position of the i'th element of a DCT block */
-  /* read in natural order (left to right, top to bottom). */
-  static const short ZIG[DCTSIZE2] = {
-     0,  1,  5,  6, 14, 15, 27, 28,
-     2,  4,  7, 13, 16, 26, 29, 42,
-     3,  8, 12, 17, 25, 30, 41, 43,
-     9, 11, 18, 24, 31, 40, 44, 53,
-    10, 19, 23, 32, 39, 45, 52, 54,
-    20, 22, 33, 38, 46, 51, 55, 60,
-    21, 34, 37, 47, 50, 56, 59, 61,
-    35, 36, 48, 49, 57, 58, 62, 63
-    };
-  FILE * fp;
-  int tblno, i;
-  long val;
-  QUANT_TBL table;
-
-  if ((fp = fopen(filename, "r")) == NULL) {
-    fprintf(stderr, "%s: can't open %s\n", progname, filename);
-    exit(EXIT_FAILURE);
-  }
-  tblno = 0;
-
-  while ((val = read_qt_integer(fp)) != EOF) { /* read 1st element of table */
-    if (tblno >= NUM_QUANT_TBLS) {
-      fprintf(stderr, "%s: too many tables in file %s\n", progname, filename);
-      exit(EXIT_FAILURE);
-    }
-    table[0] = (QUANT_VAL) val;
-    for (i = 1; i < DCTSIZE2; i++) {
-      if ((val = read_qt_integer(fp)) == EOF) {
-	fprintf(stderr, "%s: incomplete table in file %s\n", progname, filename);
-	exit(EXIT_FAILURE);
-      }
-      table[ZIG[i]] = (QUANT_VAL) val;
-    }
-    j_add_quant_table(cinfo, tblno, table, scale_factor, FALSE);
-    tblno++;
-  }
-
-  fclose(fp);
-}
-
-
-LOCAL void
-set_sample_factors (compress_info_ptr cinfo, char *arg)
-/* Process a sample-factors parameter string, of the form */
-/*     HxV[,HxV,...]    */
-{
-#define MAX_COMPONENTS 4	/* # of comp_info slots made by jcdeflts.c */
-  int ci, val1, val2;
-  char ch1, ch2;
-
-  for (ci = 0; ci < MAX_COMPONENTS; ci++) {
-    if (*arg) {
-      ch2 = ',';		/* if not set by sscanf, will be ',' */
-      if (sscanf(arg, "%d%c%d%c", &val1, &ch1, &val2, &ch2) < 3)
-	usage();
-      if ((ch1 != 'x' && ch1 != 'X') || ch2 != ',')
-	usage();		/* syntax check */
-      if (val1 <= 0 || val1 > 4 || val2 <= 0 || val2 > 4) {
-	fprintf(stderr, "JPEG sampling factors must be 1..4\n");
-	exit(EXIT_FAILURE);
-      }
-      cinfo->comp_info[ci].h_samp_factor = val1;
-      cinfo->comp_info[ci].v_samp_factor = val2;
-      while (*arg && *arg++ != ',') /* advance to next segment of arg string */
-	;
-    } else {
-      /* reached end of parameter, set remaining components to 1x1 sampling */
-      cinfo->comp_info[ci].h_samp_factor = 1;
-      cinfo->comp_info[ci].v_samp_factor = 1;
-    }
-  }
-}
-
-
-LOCAL int
-parse_switches (compress_info_ptr cinfo, int last_file_arg_seen,
-		int argc, char **argv)
-/* Initialize cinfo with default switch settings, then parse option switches.
- * Returns argv[] index of first file-name argument (== argc if none).
- * Any file names with indexes <= last_file_arg_seen are ignored;
- * they have presumably been processed in a previous iteration.
- * (Pass 0 for last_file_arg_seen on the first or only iteration.)
- */
-{
-  int argn;
-  char * arg;
-  char * qtablefile = NULL;	/* saves -qtables filename if any */
-  int q_scale_factor = 100;	/* default to no scaling for -qtables */
-
-  /* (Re-)initialize the system-dependent error and memory managers. */
-  jselerror(cinfo->emethods);	/* error/trace message routines */
-  jselmemmgr(cinfo->emethods);	/* memory allocation routines */
-  cinfo->methods->c_ui_method_selection = c_ui_method_selection;
-
-  /* Now OK to enable signal catcher. */
-#ifdef NEED_SIGNAL_CATCHER
-  emethods = cinfo->emethods;
-#endif
-
-  /* Set up default JPEG parameters. */
-  /* Note that default -quality level here need not, and does not,
-   * match the default scaling for an explicit -qtables argument.
-   */
-  j_c_defaults(cinfo, 75, FALSE); /* default quality level = 75 */
-  is_targa = FALSE;
-  outfilename = NULL;
-
-  /* Scan command line options, adjust parameters */
-
-  for (argn = 1; argn < argc; argn++) {
-    arg = argv[argn];
-    if (*arg != '-') {
-      /* Not a switch, must be a file name argument */
-      if (argn <= last_file_arg_seen) {
-	outfilename = NULL;	/* -outfile applies to just one input file */
-	continue;		/* ignore this name if previously processed */
-      }
-      break;			/* else done parsing switches */
-    }
-    arg++;			/* advance past switch marker character */
-
-    if (keymatch(arg, "arithmetic", 1)) {
-      /* Use arithmetic coding. */
-#ifdef C_ARITH_CODING_SUPPORTED
-      cinfo->arith_code = TRUE;
-#else
-      fprintf(stderr, "%s: sorry, arithmetic coding not supported\n",
-	      progname);
-      exit(EXIT_FAILURE);
-#endif
-
-    } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
-      /* Enable debug printouts. */
-      /* On first -d, print version identification */
-      if (last_file_arg_seen == 0 && cinfo->emethods->trace_level == 0)
-	fprintf(stderr, "Independent JPEG Group's CJPEG, version %s\n%s\n",
-		JVERSION, JCOPYRIGHT);
-      cinfo->emethods->trace_level++;
-
-    } else if (keymatch(arg, "grayscale", 2) || keymatch(arg, "greyscale",2)) {
-      /* Force a monochrome JPEG file to be generated. */
-      j_monochrome_default(cinfo);
-
-    } else if (keymatch(arg, "maxmemory", 1)) {
-      /* Maximum memory in Kb (or Mb with 'm'). */
-      long lval;
-      char ch = 'x';
-
-      if (++argn >= argc)	/* advance to next argument */
-	usage();
-      if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
-	usage();
-      if (ch == 'm' || ch == 'M')
-	lval *= 1000L;
-      cinfo->emethods->max_memory_to_use = lval * 1000L;
-
-    } else if (keymatch(arg, "nointerleave", 3)) {
-      /* Create noninterleaved file. */
-#ifdef C_MULTISCAN_FILES_SUPPORTED
-      cinfo->interleave = FALSE;
-#else
-      fprintf(stderr, "%s: sorry, multiple-scan support was not compiled\n",
-	      progname);
-      exit(EXIT_FAILURE);
-#endif
-
-    } else if (keymatch(arg, "optimize", 1) || keymatch(arg, "optimise", 1)) {
-      /* Enable entropy parm optimization. */
-#ifdef ENTROPY_OPT_SUPPORTED
-      cinfo->optimize_coding = TRUE;
-#else
-      fprintf(stderr, "%s: sorry, entropy optimization was not compiled\n",
-	      progname);
-      exit(EXIT_FAILURE);
-#endif
-
-    } else if (keymatch(arg, "outfile", 3)) {
-      /* Set output file name. */
-      if (++argn >= argc)	/* advance to next argument */
-	usage();
-      outfilename = argv[argn];	/* save it away for later use */
-
-    } else if (keymatch(arg, "quality", 1)) {
-      /* Quality factor (quantization table scaling factor). */
-      int val;
-
-      if (++argn >= argc)	/* advance to next argument */
-	usage();
-      if (sscanf(argv[argn], "%d", &val) != 1)
-	usage();
-      /* Set quantization tables (will be overridden if -qtables also given).
-       * Note: we make force_baseline FALSE.
-       * This means non-baseline JPEG files can be created with low Q values.
-       * To ensure only baseline files are generated, pass TRUE instead.
-       */
-      j_set_quality(cinfo, val, FALSE);
-      /* Change scale factor in case -qtables is present. */
-      q_scale_factor = j_quality_scaling(val);
-
-    } else if (keymatch(arg, "qtables", 2)) {
-      /* Quantization tables fetched from file. */
-      if (++argn >= argc)	/* advance to next argument */
-	usage();
-      qtablefile = argv[argn];
-      /* we postpone actually reading the file in case -quality comes later */
-
-    } else if (keymatch(arg, "restart", 1)) {
-      /* Restart interval in MCU rows (or in MCUs with 'b'). */
-      long lval;
-      char ch = 'x';
-
-      if (++argn >= argc)	/* advance to next argument */
-	usage();
-      if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
-	usage();
-      if (lval < 0 || lval > 65535L)
-	usage();
-      if (ch == 'b' || ch == 'B')
-	cinfo->restart_interval = (UINT16) lval;
-      else
-	cinfo->restart_in_rows = (int) lval;
-
-    } else if (keymatch(arg, "sample", 2)) {
-      /* Set sampling factors. */
-      if (++argn >= argc)	/* advance to next argument */
-	usage();
-      set_sample_factors(cinfo, argv[argn]);
-
-    } else if (keymatch(arg, "smooth", 2)) {
-      /* Set input smoothing factor. */
-      int val;
-
-      if (++argn >= argc)	/* advance to next argument */
-	usage();
-      if (sscanf(argv[argn], "%d", &val) != 1)
-	usage();
-      if (val < 0 || val > 100)
-	usage();
-      cinfo->smoothing_factor = val;
-
-    } else if (keymatch(arg, "targa", 1)) {
-      /* Input file is Targa format. */
-      is_targa = TRUE;
-
-    } else {
-      usage();			/* bogus switch */
-    }
-  }
-
-  /* Post-switch-scanning cleanup */
-
-  if (qtablefile != NULL)	/* process -qtables if it was present */
-    read_quant_tables(cinfo, qtablefile, q_scale_factor);
-
-  return argn;			/* return index of next arg (file name) */
-}
-
-
-/*
- * The main program.
- */
-
-GLOBAL int
-main (int argc, char **argv)
-{
-  struct Compress_info_struct cinfo;
-  struct Compress_methods_struct c_methods;
-  struct External_methods_struct e_methods;
-  int file_index;
-
-  /* On Mac, fetch a command line. */
-#ifdef THINK_C
-  argc = ccommand(&argv);
-#endif
-
-  progname = argv[0];
-
-  /* Set up links to method structures. */
-  cinfo.methods = &c_methods;
-  cinfo.emethods = &e_methods;
-
-  /* Install, but don't yet enable signal catcher. */
-#ifdef NEED_SIGNAL_CATCHER
-  emethods = NULL;
-  signal(SIGINT, signal_catcher);
-#ifdef SIGTERM			/* not all systems have SIGTERM */
-  signal(SIGTERM, signal_catcher);
-#endif
-#endif
-
-  /* Scan command line: set up compression parameters, find file names. */
-
-  file_index = parse_switches(&cinfo, 0, argc, argv);
-
-#ifdef TWO_FILE_COMMANDLINE
-  /* Must have either -outfile switch or explicit output file name */
-  if (outfilename == NULL) {
-    if (file_index != argc-2) {
-      fprintf(stderr, "%s: must name one input and one output file\n",
-	      progname);
-      usage();
-    }
-    outfilename = argv[file_index+1];
-  } else {
-    if (file_index != argc-1) {
-      fprintf(stderr, "%s: must name one input and one output file\n",
-	      progname);
-      usage();
-    }
-  }
-#else
-  /* Unix style: expect zero or one file name */
-  if (file_index < argc-1) {
-    fprintf(stderr, "%s: only one input file\n", progname);
-    usage();
-  }
-#endif /* TWO_FILE_COMMANDLINE */
-
-  /* Open the input file. */
-  if (file_index < argc) {
-    if ((cinfo.input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
-      fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
-      exit(EXIT_FAILURE);
-    }
-  } else {
-    /* default input file is stdin */
-#ifdef USE_SETMODE		/* need to hack file mode? */
-    setmode(fileno(stdin), O_BINARY);
-#endif
-#ifdef USE_FDOPEN		/* need to re-open in binary mode? */
-    if ((cinfo.input_file = fdopen(fileno(stdin), READ_BINARY)) == NULL) {
-      fprintf(stderr, "%s: can't open stdin\n", progname);
-      exit(EXIT_FAILURE);
-    }
-#else
-    cinfo.input_file = stdin;
-#endif
-  }
-
-  /* Open the output file. */
-  if (outfilename != NULL) {
-    if ((cinfo.output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
-      fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
-      exit(EXIT_FAILURE);
-    }
-  } else {
-    /* default output file is stdout */
-#ifdef USE_SETMODE		/* need to hack file mode? */
-    setmode(fileno(stdout), O_BINARY);
-#endif
-#ifdef USE_FDOPEN		/* need to re-open in binary mode? */
-    if ((cinfo.output_file = fdopen(fileno(stdout), WRITE_BINARY)) == NULL) {
-      fprintf(stderr, "%s: can't open stdout\n", progname);
-      exit(EXIT_FAILURE);
-    }
-#else
-    cinfo.output_file = stdout;
-#endif
-  }
-
-  /* Figure out the input file format, and set up to read it. */
-  select_file_type(&cinfo);
-
-#ifdef PROGRESS_REPORT
-  /* Start up progress display, unless trace output is on */
-  if (e_methods.trace_level == 0)
-    c_methods.progress_monitor = progress_monitor;
-#endif
-
-  /* Do it to it! */
-  jpeg_compress(&cinfo);
-
-#ifdef PROGRESS_REPORT
-  /* Clear away progress display */
-  if (e_methods.trace_level == 0) {
-    fprintf(stderr, "\r                \r");
-    fflush(stderr);
-  }
-#endif
-
-  /* All done. */
-  exit(EXIT_SUCCESS);
-  return 0;			/* suppress no-return-value warnings */
-}
diff --git a/jcmainct.c b/jcmainct.c
new file mode 100644
index 0000000..5359268
--- /dev/null
+++ b/jcmainct.c
@@ -0,0 +1,298 @@
+/*
+ * jcmainct.c
+ *
+ * Copyright (C) 1994, 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.
+ *
+ * This file contains the main buffer controller for compression.
+ * The main buffer lies between the pre-processor and the JPEG
+ * compressor proper; it holds downsampled data in the JPEG colorspace.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+/* Note: currently, there is no operating mode in which a full-image buffer
+ * is needed at this step.  If there were, that mode could not be used with
+ * "raw data" input, since this module is bypassed in that case.  However,
+ * we've left the code here for possible use in special applications.
+ */
+#undef FULL_MAIN_BUFFER_SUPPORTED
+
+
+/* Private buffer controller object */
+
+typedef struct {
+  struct jpeg_c_main_controller pub; /* public fields */
+
+  JDIMENSION cur_mcu_row;	/* number of current iMCU row */
+  JDIMENSION rowgroup_ctr;	/* counts row groups received in iMCU row */
+  JDIMENSION mcu_ctr;		/* counts MCUs output from current row */
+  boolean suspended;		/* remember if we suspended output */
+  J_BUF_MODE pass_mode;		/* current operating mode */
+
+  /* If using just a strip buffer, this points to the entire set of buffers
+   * (we allocate one for each component).  In the full-image case, this
+   * points to the currently accessible strips of the virtual arrays.
+   */
+  JSAMPARRAY buffer[MAX_COMPONENTS];
+
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+  /* If using full-image storage, this array holds pointers to virtual-array
+   * control blocks for each component.  Unused if not full-image storage.
+   */
+  jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
+#endif
+} my_main_controller;
+
+typedef my_main_controller * my_main_ptr;
+
+
+/* Forward declarations */
+METHODDEF void process_data_simple_main
+	JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
+	     JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+METHODDEF void process_data_buffer_main
+	JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
+	     JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
+#endif
+
+
+/*
+ * Initialize for a processing pass.
+ */
+
+METHODDEF void
+start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
+{
+  my_main_ptr main = (my_main_ptr) cinfo->main;
+
+  /* Do nothing in raw-data mode. */
+  if (cinfo->raw_data_in)
+    return;
+
+  main->cur_mcu_row = 0;	/* initialize counters */
+  main->rowgroup_ctr = 0;
+  main->mcu_ctr = 0;
+  main->suspended = FALSE;
+  main->pass_mode = pass_mode;	/* save mode for use by process_data */
+
+  switch (pass_mode) {
+  case JBUF_PASS_THRU:
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+    if (main->whole_image[0] != NULL)
+      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+#endif
+    main->pub.process_data = process_data_simple_main;
+    break;
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+  case JBUF_SAVE_SOURCE:
+  case JBUF_CRANK_DEST:
+  case JBUF_SAVE_AND_PASS:
+    if (main->whole_image[0] == NULL)
+      ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+    main->pub.process_data = process_data_buffer_main;
+    break;
+#endif
+  default:
+    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+    break;
+  }
+}
+
+
+/*
+ * Process some data.
+ * This routine handles the simple pass-through mode,
+ * where we have only a strip buffer.
+ */
+
+METHODDEF void
+process_data_simple_main (j_compress_ptr cinfo,
+			  JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+			  JDIMENSION in_rows_avail)
+{
+  my_main_ptr main = (my_main_ptr) cinfo->main;
+
+  while (main->cur_mcu_row < cinfo->total_iMCU_rows) {
+    /* Read input data if we haven't filled the main buffer yet */
+    if (main->rowgroup_ctr < DCTSIZE)
+      (*cinfo->prep->pre_process_data) (cinfo,
+					input_buf, in_row_ctr, in_rows_avail,
+					main->buffer, &main->rowgroup_ctr,
+					(JDIMENSION) DCTSIZE);
+
+    /* If we don't have a full iMCU row buffered, return to application for
+     * more data.  Note that preprocessor will always pad to fill the iMCU row
+     * at the bottom of the image.
+     */
+    if (main->rowgroup_ctr != DCTSIZE)
+      return;
+
+    /* Send the completed row to the compressor */
+    (*cinfo->coef->compress_data) (cinfo, main->buffer, &main->mcu_ctr);
+
+    /* If compressor did not consume the whole row, then we must need to
+     * suspend processing and return to the application.  In this situation
+     * we pretend we didn't yet consume the last input row; otherwise, if
+     * it happened to be the last row of the image, the application would
+     * think we were done.
+     */
+    if (main->mcu_ctr < cinfo->MCUs_per_row) {
+      if (! main->suspended) {
+	(*in_row_ctr)--;
+	main->suspended = TRUE;
+      }
+      return;
+    }
+    /* We did finish the row.  Undo our little suspension hack if a previous
+     * call suspended; then mark the main buffer empty.
+     */
+    if (main->suspended) {
+      (*in_row_ctr)++;
+      main->suspended = FALSE;
+    }
+    main->mcu_ctr = 0;
+    main->rowgroup_ctr = 0;
+    main->cur_mcu_row++;
+  }
+}
+
+
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+
+/*
+ * Process some data.
+ * This routine handles all of the modes that use a full-size buffer.
+ */
+
+METHODDEF void
+process_data_buffer_main (j_compress_ptr cinfo,
+			  JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
+			  JDIMENSION in_rows_avail)
+{
+  my_main_ptr main = (my_main_ptr) cinfo->main;
+  int ci;
+  jpeg_component_info *compptr;
+  boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
+
+  while (main->cur_mcu_row < cinfo->total_iMCU_rows) {
+    /* Realign the virtual buffers if at the start of an iMCU row. */
+    if (main->rowgroup_ctr == 0) {
+      for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+	   ci++, compptr++) {
+	main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
+	  ((j_common_ptr) cinfo, main->whole_image[ci],
+	   main->cur_mcu_row * (compptr->v_samp_factor * DCTSIZE), writing);
+      }
+      /* In a read pass, pretend we just read some source data. */
+      if (! writing) {
+	*in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
+	main->rowgroup_ctr = DCTSIZE;
+      }
+    }
+
+    /* If a write pass, read input data until the current iMCU row is full. */
+    /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
+    if (writing) {
+      (*cinfo->prep->pre_process_data) (cinfo,
+					input_buf, in_row_ctr, in_rows_avail,
+					main->buffer, &main->rowgroup_ctr,
+					(JDIMENSION) DCTSIZE);
+      /* Return to application if we need more data to fill the iMCU row. */
+      if (main->rowgroup_ctr < DCTSIZE)
+	return;
+    }
+
+    /* Emit data, unless this is a sink-only pass. */
+    if (main->pass_mode != JBUF_SAVE_SOURCE) {
+      (*cinfo->coef->compress_data) (cinfo, main->buffer, &main->mcu_ctr);
+      /* If compressor did not consume the whole row, then we must need to
+       * suspend processing and return to the application.  In this situation
+       * we pretend we didn't yet consume the last input row; otherwise, if
+       * it happened to be the last row of the image, the application would
+       * think we were done.
+       */
+      if (main->mcu_ctr < cinfo->MCUs_per_row) {
+	if (! main->suspended) {
+	  (*in_row_ctr)--;
+	  main->suspended = TRUE;
+	}
+	return;
+      }
+      /* We did finish the row.  Undo our little suspension hack if a previous
+       * call suspended; then mark the main buffer empty.
+       */
+      if (main->suspended) {
+	(*in_row_ctr)++;
+	main->suspended = FALSE;
+      }
+    }
+
+    /* If get here, we are done with this iMCU row.  Mark buffer empty. */
+    main->mcu_ctr = 0;
+    main->rowgroup_ctr = 0;
+    main->cur_mcu_row++;
+  }
+}
+
+#endif /* FULL_MAIN_BUFFER_SUPPORTED */
+
+
+/*
+ * Initialize main buffer controller.
+ */
+
+GLOBAL void
+jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
+{
+  my_main_ptr main;
+  int ci;
+  jpeg_component_info *compptr;
+
+  main = (my_main_ptr)
+    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+				SIZEOF(my_main_controller));
+  cinfo->main = (struct jpeg_c_main_controller *) main;
+  main->pub.start_pass = start_pass_main;
+
+  /* We don't need to create a buffer in raw-data mode. */
+  if (cinfo->raw_data_in)
+    return;
+
+  /* Create the buffer.  It holds downsampled data, so each component
+   * may be of a different size.
+   */
+  if (need_full_buffer) {
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+    /* Allocate a full-image virtual array for each component */
+    /* Note we implicitly pad the bottom to a multiple of the iMCU height */
+    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+	 ci++, compptr++) {
+      main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
+	((j_common_ptr) cinfo, JPOOL_IMAGE,
+	 compptr->width_in_blocks * DCTSIZE,
+	 compptr->height_in_blocks * DCTSIZE,
+	 (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
+    }
+#else
+    ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
+#endif
+  } else {
+#ifdef FULL_MAIN_BUFFER_SUPPORTED
+    main->whole_image[0] = NULL; /* flag for no virtual arrays */
+#endif
+    /* Allocate a strip buffer for each component */
+    for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+	 ci++, compptr++) {
+      main->buffer[ci] = (*cinfo->mem->alloc_sarray)
+	((j_common_ptr) cinfo, JPOOL_IMAGE,
+	 compptr->width_in_blocks * DCTSIZE,
+	 (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
+    }
+  }
+}
diff --git a/jcmarker.c b/jcmarker.c
new file mode 100644
index 0000000..5454658
--- /dev/null
+++ b/jcmarker.c
@@ -0,0 +1,605 @@
+/*
+ * jcmarker.c
+ *
+ * Copyright (C) 1991-1994, 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.
+ *
+ * This file contains routines to write JPEG datastream markers.
+ */
+
+#define JPEG_INTERNALS
+#include "jinclude.h"
+#include "jpeglib.h"
+
+
+typedef enum {			/* JPEG marker codes */
+  M_SOF0  = 0xc0,
+  M_SOF1  = 0xc1,
+  M_SOF2  = 0xc2,
+  M_SOF3  = 0xc3,
+  
+  M_SOF5  = 0xc5,
+  M_SOF6  = 0xc6,
+  M_SOF7  = 0xc7,
+  
+  M_JPG   = 0xc8,
+  M_SOF9  = 0xc9,
+  M_SOF10 = 0xca,
+  M_SOF11 = 0xcb,
+  
+  M_SOF13 = 0xcd,
+  M_SOF14 = 0xce,
+  M_SOF15 = 0xcf,
+  
+  M_DHT   = 0xc4,
+  
+  M_DAC   = 0xcc,
+  
+  M_RST0  = 0xd0,
+  M_RST1  = 0xd1,
+  M_RST2  = 0xd2,
+  M_RST3  = 0xd3,
+  M_RST4  = 0xd4,
+  M_RST5  = 0xd5,
+  M_RST6  = 0xd6,
+  M_RST7  = 0xd7,
+  
+  M_SOI   = 0xd8,
+  M_EOI   = 0xd9,
+  M_SOS   = 0xda,
+  M_DQT   = 0xdb,
+  M_DNL   = 0xdc,
+  M_DRI   = 0xdd,
+  M_DHP   = 0xde,
+  M_EXP   = 0xdf,
+  
+  M_APP0  = 0xe0,
+  M_APP1  = 0xe1,
+  M_APP2  = 0xe2,
+  M_APP3  = 0xe3,
+  M_APP4  = 0xe4,
+  M_APP5  = 0xe5,
+  M_APP6  = 0xe6,
+  M_APP7  = 0xe7,
+  M_APP8  = 0xe8,
+  M_APP9  = 0xe9,
+  M_APP10 = 0xea,
+  M_APP11 = 0xeb,
+  M_APP12 = 0xec,
+  M_APP13 = 0xed,
+  M_APP14 = 0xee,
+  M_APP15 = 0xef,
+  
+  M_JPG0  = 0xf0,
+  M_JPG13 = 0xfd,
+  M_COM   = 0xfe,
+  
+  M_TEM   = 0x01,
+  
+  M_ERROR = 0x100
+} JPEG_MARKER;
+
+
+/*
+ * Basic output routines.
+ *
+ * Note that we do not support suspension while writing a marker.
+ * Therefore, an application using suspension must ensure that there is
+ * enough buffer space for the initial markers (typ. 600-700 bytes) before
+ * calling jpeg_start_compress, and enough space to write the trailing EOI
+ * (a few bytes) before calling jpeg_finish_compress.  Multipass compression
+ * modes are not supported at all with suspension, so those two are the only
+ * points where markers will be written.
+ */
+
+LOCAL void
+emit_byte (j_compress_ptr cinfo, int val)
+/* Emit a byte */
+{
+  struct jpeg_destination_mgr * dest = cinfo->dest;
+
+  *(dest->next_output_byte)++ = (JOCTET) val;
+  if (--dest->free_in_buffer == 0) {
+    if (! (*dest->empty_output_buffer) (cinfo))
+      ERREXIT(cinfo, JERR_CANT_SUSPEND);
+  }
+}
+
+
+LOCAL void
+emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
+/* Emit a marker code */
+{
+  emit_byte(cinfo, 0xFF);
+  emit_byte(cinfo, (int) mark);
+}
+
+
+LOCAL void
+emit_2bytes (j_compress_ptr cinfo, int value)
+/* Emit a 2-byte integer; these are always MSB first in JPEG files */
+{
+  emit_byte(cinfo, (value >> 8) & 0xFF);
+  emit_byte(cinfo, value & 0xFF);
+}
+
+
+/*
+ * Routines to write specific marker types.
+ */
+
+LOCAL int
+emit_dqt (j_compress_ptr cinfo, int index)
+/* Emit a DQT marker */
+/* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
+{
+  JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
+  int prec;
+  int i;
+
+  if (qtbl == NULL)
+    ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
+
+  prec = 0;
+  for (i = 0; i < DCTSIZE2; i++) {
+    if (qtbl->quantval[i] > 255)
+      prec = 1;
+  }
+
+  if (! qtbl->sent_table) {
+    emit_marker(cinfo, M_DQT);
+
+    emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
+
+    emit_byte(cinfo, index + (prec<<4));
+
+    for (i = 0; i < DCTSIZE2; i++) {
+      if (prec)
+	emit_byte(cinfo, qtbl->quantval[i] >> 8);
+      emit_byte(cinfo, qtbl->quantval[i] & 0xFF);
+    }
+
+    qtbl->sent_table = TRUE;
+  }
+
+  return prec;
+}
+
+
+LOCAL void
+emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
+/* Emit a DHT marker */
+{
+  JHUFF_TBL * htbl;
+  int length, i;
+  
+  if (is_ac) {
+    htbl = cinfo->ac_huff_tbl_ptrs[index];
+    index += 0x10;		/* output index has AC bit set */
+  } else {
+    htbl = cinfo->dc_huff_tbl_ptrs[index];
+  }
+
+  if (htbl == NULL)
+    ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
+  
+  if (! htbl->sent_table) {
+    emit_marker(cinfo, M_DHT);
+    
+    length = 0;
+    for (i = 1; i <= 16; i++)
+      length += htbl->bits[i];
+    
+    emit_2bytes(cinfo, length + 2 + 1 + 16);
+    emit_byte(cinfo, index);
+    
+    for (i = 1; i <= 16; i++)
+      emit_byte(cinfo, htbl->bits[i]);
+    
+    for (i = 0; i < length; i++)
+      emit_byte(cinfo, htbl->huffval[i]);
+    
+    htbl->sent_table = TRUE;
+  }
+}
+
+
+LOCAL void
+emit_dac (j_compress_ptr cinfo)
+/* Emit a DAC marker */
+/* Since the useful info is so small, we want to emit all the tables in */
+/* one DAC marker.  Therefore this routine does its own scan of the table. */
+{
+#ifdef C_ARITH_CODING_SUPPORTED
+  char dc_in_use[NUM_ARITH_TBLS];
+  char ac_in_use[NUM_ARITH_TBLS];
+  int length, i;
+  jpeg_component_info *compptr;
+  
+  for (i = 0; i < NUM_ARITH_TBLS; i++)
+    dc_in_use[i] = ac_in_use[i] = 0;
+  
+  for (i = 0; i < cinfo->comps_in_scan; i++) {
+    compptr = cinfo->cur_comp_info[i];
+    dc_in_use[compptr->dc_tbl_no] = 1;
+    ac_in_use[compptr->ac_tbl_no] = 1;
+  }
+  
+  length = 0;
+  for (i = 0; i < NUM_ARITH_TBLS; i++)
+    length += dc_in_use[i] + ac_in_use[i];
+  
+  emit_marker(cinfo, M_DAC);
+  
+  emit_2bytes(cinfo, length*2 + 2);
+  
+  for (i = 0; i < NUM_ARITH_TBLS; i++) {
+    if (dc_in_use[i]) {
+      emit_byte(cinfo, i);
+      emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
+    }
+    if (ac_in_use[i]) {
+      emit_byte(cinfo, i + 0x10);
+      emit_byte(cinfo, cinfo->arith_ac_K[i]);
+    }
+  }
+#endif /* C_ARITH_CODING_SUPPORTED */
+}
+
+
+LOCAL void
+emit_dri (j_compress_ptr cinfo)
+/* Emit a DRI marker */
+{
+  emit_marker(cinfo, M_DRI);
+  
+  emit_2bytes(cinfo, 4);	/* fixed length */
+
+  emit_2bytes(cinfo, (int) cinfo->restart_interval);
+}
+
+
+LOCAL void
+emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
+/* Emit a SOF marker */
+{
+  int ci;
+  jpeg_component_info *compptr;
+  
+  emit_marker(cinfo, code);
+  
+  emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
+
+  /* Make sure image isn't bigger than SOF field can handle */
+  if ((long) cinfo->image_height > 65535L ||
+      (long) cinfo->image_width > 65535L)
+    ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
+
+  emit_byte(cinfo, cinfo->data_precision);
+  emit_2bytes(cinfo, (int) cinfo->image_height);
+  emit_2bytes(cinfo, (int) cinfo->image_width);
+
+  emit_byte(cinfo, cinfo->num_components);
+
+  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+       ci++, compptr++) {
+    emit_byte(cinfo, compptr->component_id);
+    emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
+    emit_byte(cinfo, compptr->quant_tbl_no);
+  }
+}
+
+
+LOCAL void
+emit_sos (j_compress_ptr cinfo)
+/* Emit a SOS marker */
+{
+  int i;
+  jpeg_component_info *compptr;
+  
+  emit_marker(cinfo, M_SOS);
+  
+  emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
+  
+  emit_byte(cinfo, cinfo->comps_in_scan);
+  
+  for (i = 0; i < cinfo->comps_in_scan; i++) {
+    compptr = cinfo->cur_comp_info[i];
+    emit_byte(cinfo, compptr->component_id);
+    emit_byte(cinfo, (compptr->dc_tbl_no << 4) + compptr->ac_tbl_no);
+  }
+
+  emit_byte(cinfo, 0);		/* Spectral selection start */
+  emit_byte(cinfo, DCTSIZE2-1);	/* Spectral selection end */
+  emit_byte(cinfo, 0);		/* Successive approximation */
+}
+
+
+LOCAL void
+emit_jfif_app0 (j_compress_ptr cinfo)
+/* Emit a JFIF-compliant APP0 marker */
+{
+  /*
+   * Length of APP0 block	(2 bytes)
+   * Block ID			(4 bytes - ASCII "JFIF")
+   * Zero byte			(1 byte to terminate the ID string)
+   * Version Major, Minor	(2 bytes - 0x01, 0x01)
+   * Units			(1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
+   * Xdpu			(2 bytes - dots per unit horizontal)
+   * Ydpu			(2 bytes - dots per unit vertical)
+   * Thumbnail X size		(1 byte)
+   * Thumbnail Y size		(1 byte)
+   */
+  
+  emit_marker(cinfo, M_APP0);
+  
+  emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
+
+  emit_byte(cinfo, 0x4A);	/* Identifier: ASCII "JFIF" */
+  emit_byte(cinfo, 0x46);
+  emit_byte(cinfo, 0x49);
+  emit_byte(cinfo, 0x46);
+  emit_byte(cinfo, 0);
+  /* We currently emit version code 1.01 since we use no 1.02 features.
+   * This may avoid complaints from some older decoders.
+   */
+  emit_byte(cinfo, 1);		/* Major version */
+  emit_byte(cinfo, 1);		/* Minor version */
+  emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
+  emit_2bytes(cinfo, (int) cinfo->X_density);
+  emit_2bytes(cinfo, (int) cinfo->Y_density);
+  emit_byte(cinfo, 0);		/* No thumbnail image */
+  emit_byte(cinfo, 0);
+}
+
+
+LOCAL void
+emit_adobe_app14 (j_compress_ptr cinfo)
+/* Emit an Adobe APP14 marker */
+{
+  /*
+   * Length of APP14 block	(2 bytes)
+   * Block ID			(5 bytes - ASCII "Adobe")
+   * Version Number		(2 bytes - currently 100)
+   * Flags0			(2 bytes - currently 0)
+   * Flags1			(2 bytes - currently 0)
+   * Color transform		(1 byte)
+   *
+   * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
+   * now in circulation seem to use Version = 100, so that's what we write.
+   *
+   * We write the color transform byte as 1 if the JPEG color space is
+   * YCbCr, 2 if it's YCCK, 0 otherwise.  Adobe's definition has to do with
+   * whether the encoder performed a transformation, which is pretty useless.
+   */
+  
+  emit_marker(cinfo, M_APP14);
+  
+  emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
+
+  emit_byte(cinfo, 0x41);	/* Identifier: ASCII "Adobe" */
+  emit_byte(cinfo, 0x64);
+  emit_byte(cinfo, 0x6F);
+  emit_byte(cinfo, 0x62);
+  emit_byte(cinfo, 0x65);
+  emit_2bytes(cinfo, 100);	/* Version */
+  emit_2bytes(cinfo, 0);	/* Flags0 */
+  emit_2bytes(cinfo, 0);	/* Flags1 */
+  switch (cinfo->jpeg_color_space) {
+  case JCS_YCbCr:
+    emit_byte(cinfo, 1);	/* Color transform = 1 */
+    break;
+  case JCS_YCCK:
+    emit_byte(cinfo, 2);	/* Color transform = 2 */
+    break;
+  default:
+    emit_byte(cinfo, 0);	/* Color transform = 0 */
+    break;
+  }
+}
+
+
+/*
+ * This routine is exported for possible use by applications.
+ * The intended use is to emit COM or APPn markers after calling
+ * jpeg_start_compress() and before the first jpeg_write_scanlines() call
+ * (hence, after write_file_header but before write_frame_header).
+ * Other uses are not guaranteed to produce desirable results.
+ */
+
+METHODDEF void
+write_any_marker (j_compress_ptr cinfo, int marker,
+		  const JOCTET *dataptr, unsigned int datalen)
+/* Emit an arbitrary marker with parameters */
+{
+  if (datalen <= (unsigned int) 65533) { /* safety check */
+    emit_marker(cinfo, (JPEG_MARKER) marker);
+  
+    emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
+
+    while (datalen--) {
+      emit_byte(cinfo, *dataptr);
+      dataptr++;
+    }
+  }
+}
+
+
+/*
+ * Write datastream header.
+ * This consists of an SOI and optional APPn markers.
+ * We recommend use of the JFIF marker, but not the Adobe marker,
+ * when using YCbCr or grayscale data.  The JFIF marker should NOT
+ * be used for any other JPEG colorspace.  The Adobe marker is helpful
+ * to distinguish RGB, CMYK, and YCCK colorspaces.
+ * Note that an application can write additional header markers after
+ * jpeg_start_decompress returns.
+ */
+
+METHODDEF void
+write_file_header (j_compress_ptr cinfo)
+{
+  emit_marker(cinfo, M_SOI);	/* first the SOI */
+
+  if (cinfo->write_JFIF_header)	/* next an optional JFIF APP0 */
+    emit_jfif_app0(cinfo);
+  if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
+    emit_adobe_app14(cinfo);
+}
+
+
+/*
+ * Write frame header.
+ * This consists of DQT and SOFn markers.
+ * Note that we do not emit the SOF until we have emitted the DQT(s).
+ * This avoids compatibility problems with incorrect implementations that
+ * try to error-check the quant table numbers as soon as they see the SOF.
+ */
+
+METHODDEF void
+write_frame_header (j_compress_ptr cinfo)
+{
+  int ci, prec;
+  boolean is_baseline;
+  jpeg_component_info *compptr;
+  
+  /* Emit DQT for each quantization table.
+   * Note that emit_dqt() suppresses any duplicate tables.
+   */
+  prec = 0;
+  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+       ci++, compptr++) {
+    prec += emit_dqt(cinfo, compptr->quant_tbl_no);
+  }
+  /* now prec is nonzero iff there are any 16-bit quant tables. */
+
+  /* Check for a non-baseline specification.
+   * Note we assume that Huffman table numbers won't be changed later.
+   */
+  is_baseline = TRUE;
+  if (cinfo->arith_code || (cinfo->data_precision != 8))
+    is_baseline = FALSE;
+  for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
+       ci++, compptr++) {
+    if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
+      is_baseline = FALSE;
+  }
+  if (prec && is_baseline) {
+    is_baseline = FALSE;
+    /* If it's baseline except for quantizer size, warn the user */
+    TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
+  }
+
+  /* Emit the proper SOF marker */
+  if (cinfo->arith_code)
+    emit_sof(cinfo, M_SOF9);	/* SOF code for arithmetic coding */
+  else if (is_baseline)
+    emit_sof(cinfo, M_SOF0);	/* SOF code for baseline implementation */
+  else
+    emit_sof(cinfo, M_SOF1);	/* SOF code for non-baseline Huffman file */
+}
+
+
+/*
+ * Write scan header.
+ * This consists of DHT or DAC markers, optional DRI, and SOS.
+ * Compressed data will be written following the SOS.
+ */
+
+METHODDEF void
+write_scan_header (j_compress_ptr cinfo)
+{
+  int i;
+  jpeg_component_info *compptr;
+
+  if (cinfo->arith_code) {
+    /* Emit arith conditioning info.  We may have some duplication
+     * if the file has multiple scans, but it's so small it's hardly
+     * worth worrying about.
+     */
+    emit_dac(cinfo);
+  } else {
+    /* Emit Huffman tables.
+     * Note that emit_dht() suppresses any duplicate tables.
+     */
+    for (i = 0; i < cinfo->comps_in_scan; i++) {
+      compptr = cinfo->cur_comp_info[i];
+      emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
+      emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
+    }
+  }
+
+  /* Emit DRI if required --- note that DRI value could change for each scan.
+   * If it doesn't, a tiny amount of space is wasted in multiple-scan files.
+   * We assume DRI will never be nonzero for one scan and zero for a later one.
+   */
+  if (cinfo->restart_interval)
+    emit_dri(cinfo);
+
+  emit_sos(cinfo);
+}
+
+
+/*
+ * Write datastream trailer.
+ */
+
+METHODDEF void
+write_file_trailer (j_compress_ptr cinfo)
+{
+  emit_marker(cinfo, M_EOI);
+}
+
+
+/*
+ * Write an abbreviated table-specification datastream.
+ * This consists of SOI, DQT and DHT tables, and EOI.
+ * Any table that is defined and not marked sent_table = TRUE will be
+ * emitted.  Note that all tables will be marked sent_table = TRUE at exit.
+ */
+
+METHODDEF void
+write_tables_only (j_compress_ptr cinfo)
+{
+  int i;
+
+  emit_marker(cinfo, M_SOI);
+
+  for (i = 0; i < NUM_QUANT_TBLS; i++) {
+    if (cinfo->quant_tbl_ptrs[i] != NULL)
+      (void) emit_dqt(cinfo, i);
+  }
+
+  if (! cinfo->arith_code) {
+    for (i = 0; i < NUM_HUFF_TBLS; i++) {
+      if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
+	emit_dht(cinfo, i, FALSE);
+      if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
+	emit_dht(cinfo, i, TRUE);
+    }
+  }
+
+  emit_marker(cinfo, M_EOI);
+}
+
+
+/*
+ * Initialize the marker writer module.
+ */
+
+GLOBAL void
+jinit_marker_writer (j_compress_ptr cinfo)
+{
+  /* Create the subobject */
+  cinfo->marker = (struct jpeg_marker_writer *)
+    (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
+				SIZEOF(struct jpeg_marker_writer));
+  /* Initialize method pointers */
+  cinfo->marker->write_any_marker = write_any_marker;
+  cinfo->marker->write_file_header = write_file_header;
+  cinfo->marker->write_frame_header = write_frame_header;
+  cinfo->marker->write_scan_header = write_scan_header;
+  cinfo->marker->write_file_trailer = write_file_trailer;
+  cinfo->marker->write_tables_only = write_tables_only;
+}
diff --git a/jcmaster.c b/jcmaster.c
index b192aae..d9b5c03 100644
--- a/jcmaster.c
+++ b/jcmaster.c
@@ -1,133 +1,387 @@
 /*
  * jcmaster.c
  *
- * Copyright (C) 1991, 1992, Thomas G. Lane.
+ * Copyright (C) 1991-1994, 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.
  *
- * This file contains the main control for the JPEG compressor.
- * The system-dependent (user interface) code should call jpeg_compress()
- * after doing appropriate setup of the compress_info_struct parameter.
+ * This file contains master control logic for the JPEG compressor.
+ * These routines are concerned with selecting the modules to be executed
+ * and with determining the number of passes and the work to be done in each
+ * pass.
  */
 
+#define JPEG_INTERNALS
 #include "jinclude.h"
+#include "jpeglib.h"
 
 
-METHODDEF void
-c_per_scan_method_selection (compress_info_ptr cinfo)
-/* Central point for per-scan method selection */
-{
-  /* Edge expansion */
-  jselexpand(cinfo);
-  /* Downsampling of pixels */
-  jseldownsample(cinfo);
-  /* MCU extraction */
-  jselcmcu(cinfo);
-}
+/* Private state */
 
+typedef struct {
+  struct jpeg_comp_master pub;	/* public fields */
+
+  int pass_number;		/* eventually need more complex state... */
+} my_comp_master;
+
+typedef my_comp_master *