The Independent JPEG Group's JPEG software v2
diff --git a/CHANGELOG b/CHANGELOG
new file mode 100644
index 0000000..7146f38
--- /dev/null
+++ b/CHANGELOG
@@ -0,0 +1,37 @@
+CHANGELOG for Independent JPEG Group's JPEG software
+
+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 9a2a1bb..524f329 100644
--- a/README
+++ b/README
@@ -1,27 +1,27 @@
 The Independent JPEG Group's JPEG software
 ==========================================
 
-README for release of  7-Oct-91
-===============================
+README for release 2 of 13-Dec-91
+=================================
 
-This distribution contains the first public release of the Independent JPEG
+This distribution contains the second 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.
 
-This software is still undergoing revision.  Updated versions may be obtained
-by anonymous FTP to uunet.uu.net; look under directory /graphics/jpeg.  This
-particular version will be archived as jpegsrc.v1.tar.Z.  If you don't have
-access to Internet FTP, UUNET's archives are also available via UUCP; contact
-postmaster@uunet.uu.net for information on retrieving files that way.
+For installation instructions, see file SETUP; for usage instructions, see
+file USAGE (or the cjpeg.1 and djpeg.1 manual pages).
 
-Please report any problems with this software to jpeg-info@uunet.uu.net.
+This software is still undergoing revision.  Updated versions may be obtained
+by FTP or UUCP to uunet.uu.net and other archive sites; see ARCHIVE LOCATIONS
+below for details.
 
 If you intend to become a serious user of this software, please contact
-jpeg-info@uunet to be added to our electronic mailing list.  Then you'll be
-notified of updates and have a chance to participate in discussions, etc.
+jpeg-info@uunet.uu.net to be added to our electronic mailing list.  Then
+you'll be notified of updates and have a chance to participate in discussions,
+etc.
 
-This software is the work of Tom Lane, Philip Gladstone, Luis Ortiz, and other
-members of the independent JPEG group.
+This software is the work of Tom Lane, Philip Gladstone, Luis Ortiz,
+Lee Crocker, and other members of the Independent JPEG Group.
 
 
 DISCLAIMER
@@ -32,20 +32,23 @@
 an accurate implementation of the JPEG standard.  (See LEGAL ISSUES for even
 more disclaimers.)
 
+Please report any problems with this software to jpeg-info@uunet.uu.net.
+
 
 WHAT'S HERE
 ===========
 
 This distribution contains software to implement JPEG image compression and
-decompression.  JPEG is a standardized compression method for full-color and
-gray-scale images.  JPEG is intended for "real-world" scenes; cartoons and
-other non-realistic images are not its strong suit.  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 images of real-world scenes, very good compression levels can be
-obtained with hardly any visible change, and amazingly high compression levels
-can be obtained if you can tolerate a low-quality image.  For more details,
-see the references, or just experiment with various compression settings.
+decompression.  JPEG (pronounced "jay-peg") is a standardized compression
+method for full-color and gray-scale images.  JPEG is intended for
+"real-world" scenes; cartoons and other non-realistic images are not its
+strong suit.  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 images of real-world scenes,
+very good compression levels can be obtained with no visible change, and
+amazingly high compression levels can be obtained if you can tolerate a
+low-quality image.  For more details, see the references, or just experiment
+with various compression settings.
 
 The software implements JPEG baseline and extended-sequential compression
 processes.  Provision is made for supporting all variants of these processes,
@@ -67,9 +70,9 @@
 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 SETUP), compile and go.
+  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 as time goes on.
+  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
@@ -77,7 +80,7 @@
   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 appropriate user interfaces, for example.)
+  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
@@ -90,181 +93,85 @@
 products; no royalty is required.
 
 
-SETUP
-=====
+ARCHIVE LOCATIONS
+=================
 
-The installation process is not very automatic; you will need at least some
-familiarity with C programming and program build procedures for your system.
-(Volunteers to work on improving this situation are welcome.  Also, we will
-probably start distributing pre-built binaries for popular systems at some
-point.)
+The "official" archive site for this software is uunet.uu.net (Internet
+address 137.39.1.2 or 192.48.96.2).  The most recent released version can
+always be found there in directory graphics/jpeg.  This particular version
+will be archived as jpegsrc.v2.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.
 
-First, select a makefile and copy it to "Makefile".  "makefile.unix"
-is appropriate for most Unix and Unix-like systems.  Special makefiles are
-included for various PC compilers.  If you don't see a makefile for your
-system, we recommend starting from makefile.unix.
+Various other Internet sites maintain copies of the UUNET file, which may or
+may not be up-to-date.  In Europe, try nic.funet.fi (128.214.6.100; look in
+directory pub/graphics/programs/jpeg).
 
-Look over the Makefile and adjust options as needed.  In particular, you'll
-need to change the CC= and CFLAGS= definitions if you don't have gcc
-(makefile.unix only).  If you have a function-prototype-less compiler, be sure
-to uncomment the .c.o rule and say "make ansi2knr".  This will cause the
-source files to be preprocessed to change our ANSI-style function definitions
-to old-style definitions.  (Thanks to Peter Deutsch of Aladdin Enterprises for
-ansi2knr.)
+You can also obtain this software from CompuServe, in the GRAPHSUPPORT forum
+(GO PICS), library 10; this version will be file jpsrc2.zip.
 
-Also look over jconfig.h and adjust #defines as necessary.  If you have an
-ANSI-compliant C compiler (gcc for instance), no changes should be necessary
-except perhaps for RIGHT_SHIFT_IS_UNSIGNED and TWO_FILE_COMMANDLINE.  For
-older compilers other mods may be needed, depending on what ANSI features are
-supported.  If you prefer, you can usually leave jconfig.h unmodified and add
--D switches to the Makefile's CFLAGS= definition.
-
-Then say "make".
-
-If you have trouble with missing system include files or inclusion of the
-wrong ones, you can fix it in jinclude.h.  In particular, if you are using
-gcc on a machine with non-ANSI system include files, you are likely to find
-that jinclude.h tries to include the wrong files (because gcc defines
-__STDC__).  There's no good automatic solution to this, so you'll just have
-to hand-edit jinclude.h.
-
-As a quick test of functionality we've included three sample files:
-	testorig.jpg	same as blkint.jpg from JPEG validation floppy.
-	testimg.ppm	output of djpeg testorig.jpg
-	testimg.jpg	output of cjpeg testimg.ppm
-The two .jpg files aren't identical due to different parameter choices (and
-wouldn't be anyway, since JPEG is lossy).  However, if you can generate
-duplicates of testimg.ppm and testimg.jpg then you probably have a working
-port.  "make test" will perform the necessary comparisons (by generating
-testout.ppm and testout.jpg and comparing these to testimg.*).  NOTE: this
-is far from an exhaustive test of the JPEG software; some modules, such as
-color quantization and GIF I/O, are not exercised at all.  It's just a quick
-test to give you some confidence that you haven't missed something major.
-
-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.  (Not a lot is actually removed right now, but as more optional
-stuff gets added, this mechanism will start to make a difference.)
-
-If you want to incorporate the JPEG code as subroutines in a larger program,
-we recommend that you make libjpeg.a.  Then use the .h files and libjpeg.a as
-your interface to the JPEG functions.  Your surrounding program will have to
-provide functionality similar to what's in jcmain.c or jdmain.c, and you may
-want to replace jerror.c and possibly other modules depending on your needs.
-See the "architecture" file for more info.  If it seems to you that the system
-structure doesn't accommodate what you want to do, please contact the authors.
-
-Special notes for Macintosh Think C users: If you have version 5.0 you should
-be able to just turn on __STDC__ through the compiler switch that enables
-that.  With version 4.0 you must manually edit jconfig.h to define PROTO,
-HAVE_UNSIGNED_CHAR, HAVE_UNSIGNED_SHORT, and const.  (It seems to be safe to
-just define __STDC__ to take care of the first three.)  When setting up
-project files, use the COBJECTS and DOBJECTS lists in makefile.unix as a guide
-to which files need to be included, and 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 are not reasonably handy at configuring and installing portable C
+programs, you may have some difficulty installing this package.  You may
+prefer to obtain a pre-built executable version.  A collection of pre-built
+executables for various machines is currently available for anonymous FTP at
+procyon.cis.ksu.edu (129.130.10.80 --- this number is due to change soon);
+look under /pub/JPEG.  The administrators of this system ask that FTP traffic
+be limited to non-prime hours.  For more information on this archive, please
+contact Steve Davis (strat@cis.ksu.edu).  This collection is not maintained by
+the Independent JPEG Group, and programs in it may not be the latest version.
 
 
-USAGE
-=====
+SUPPORTING SOFTWARE
+===================
 
-The user interface is pretty minimal at this point.  We haven't bothered to
-generate manual-page files since the switches badly need redesign.  At the
-moment, things work like this:
+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.
 
-There are two programs, cjpeg to compress an image file into JPEG format,
-and djpeg to decompress.
+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.
+There will soon be a new release of xv that 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.  Caveat user.)
 
-On Unix systems, you say:
-	cjpeg [switches] [imagefile] >jpegfile
-	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 PC, Macintosh, and Amiga systems, you say:
-	cjpeg [switches] imagefile jpegfile
-	djpeg [switches] jpegfile  imagefile
-i.e., both 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 in jconfig.h or in the Makefile.  You MUST use this style
-on any system that doesn't cope well with binary data fed through
-stdin/stdout.
+SOFTWARE THAT'S NO HELP AT ALL
+==============================
 
-Currently supported image file formats include raw-format PPM, raw-format PGM
-(for monochrome images), and GIF.  cjpeg recognizes the input image format
-automatically, but you have to tell djpeg which format to generate.
+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).
 
-The only JPEG file format currently supported is a raw JPEG data stream.
-Unless modified, the programs use the JFIF conventions for variables left
-unspecified by the JPEG standard.  (In particular, cjpeg generates a JFIF APP0
-marker.)  Support for the JPEG-in-TIFF format will probably be added at some
-future date.
+Unfortunately, most 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.  Many 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 command line switches for cjpeg are:
+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
+standard, for use in "high end" applications that need to record a lot of
+additional data about an image.  We intend to support JPEG-in-TIFF in the
+future.  We hope that these two formats will be sufficient and that other,
+incompatible JPEG file formats will not proliferate.
 
-	-I		Generate noninterleaved JPEG file (not yet supported).
-
-	-Q quality	Scale quantization tables to adjust quality.
-			Quality is 0 (worst) to 100 (best); default is 75.
-			(See below for more info.)
-
-	-a		Use arithmetic coding rather than Huffman coding.
-			(Not currently supported, see LEGAL ISSUES.)
-
-	-o		Perform optimization of entropy encoding parameters.
-			Without this, default Huffman or arithmetic
-			parameters are used.  -o makes the JPEG file a tad
-			smaller, but compression uses much more memory.
-			Image quality is unaffected by -o.
-
-	-d		Enable debug printout.  More -d's give more printout.
-
-Typically you'd use -Q settings of 50 or 75 or so.  -Q 100 will generate a
-quantization table of all 1's, meaning no quantization loss; then any
-differences between input and output images are due to subsampling or to
-roundoff error in the DCT or colorspace-conversion steps.  -Q values below 50
-may be useful for making real small, low-quality images.  Try -Q 2 (or so) for
-some amusing Cubist effects.  (Note that -Q values below about 25 generate
-2-byte quantization tables, which are not decodable by pure baseline JPEG
-decoders.  cjpeg emits a warning message when you give such a -Q value.)
-
-The command line switches for djpeg are:
-
-	-G		Select GIF output format (implies -q, with default
-			of 256 colors).
-
-	-b		Perform cross-block smoothing.  This is quite
-			memory-intensive and only seems to improve the image
-			at very low quality settings (-Q 10 to 20 or so).
-
-	-g		Force gray-scale output even if input is color.
-
-	-q N		Quantize to N colors.
-
-	-D		Use Floyd-Steinberg dithering in color quantization.
-
-	-2		Use two-pass color quantization (not yet supported).
-
-	-d		Enable debug printout.  More -d's give more printout.
-
-Color quantization currently uses a rather shoddy algorithm (although it's not
-so horrible when dithered).  Because of this, the GIF output mode is not
-recommended in the current release, except for gray-scale output.  You can get
-better results by applying ppmquant to the unquantized (PPM) output of djpeg,
-then converting to GIF with ppmtogif.  We expect to provide a considerably
-better quantization algorithm in a future release.
-
-Note that djpeg *can* read noninterleaved JPEG files even though cjpeg can't
-yet generate them.  For most applications this is a nonissue, since hardly
-anybody seems to be using noninterleaved format.
-
-On a non-virtual-memory machine, you may run out of memory if you use -I or -o
-in cjpeg, or -q ... -2 in djpeg, or try to read an interlaced GIF file.  This
-will be addressed eventually by replacing jvirtmem.c with something that uses
-temporary files for large images (see TO DO).
+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 JPEG-in-TIFF!
 
 
 REFERENCES
@@ -276,13 +183,25 @@
 	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.)  We highly recommend reading that
-article before looking at any of the JPEG software.
+article before trying to understand the innards of any JPEG software.
 
 For more detail about the JPEG standard you pretty much have to go to the
-draft standard, which is not nearly as intelligible as Wallace's article.
-The current version is ISO/IEC Committee Draft CD 10918-1 dated 1991-03-15.
-The standard is not presently available electronically; you must order a paper
-copy through ISO.
+draft standard (which is not nearly as intelligible as Wallace's article).
+The standard is not now available electronically; you must order a paper copy
+through ISO.  In the US, copies may be ordered from ANSI Sales at (212)
+642-4900.  The standard is divided into two parts: Part 1 is the actual
+specification, and Part 2 covers compliance testing methods.  The current
+"committee draft" version of Part 1 is titled "Digital Compression and Coding
+of Continuous-tone Still Images, Part 1: Requirements and guidelines" and has
+document number ISO/IEC CD 10918-1.  (The alternate number SC2 N2215 should
+also be mentioned when ordering.)  This draft is expected to be superseded by
+the Draft International Standard version around the end of November 1991.
+Ordering info will be the same as above, but replace "CD" with "DIS" in the
+document number (alternate number not yet known).  The committee draft of
+Part 2 is expected to be available around the end of December 1991.  It will
+be titled "Digital Compression and Coding of Continuous-tone Still Images,
+Part 2: Compliance testing" and will have document number ISO/IEC CD 10918-2
+(alternate number not yet known).
 
 The JPEG standard does not specify all details of an interchangeable file
 format.  For the omitted details we follow the "JFIF" conventions, revision
@@ -292,28 +211,14 @@
 	399A West Trimble Road
 	San Jose, CA  95131
 	(408) 944-6300
-Requests can also be e-mailed to info@c3.pla.ca.us (this address good after
-10/10/91).  The same source can supply copies of the draft JPEG-in-TIFF specs.
+Requests can also be e-mailed to info@c3.pla.ca.us.  The same source can
+supply copies of the draft JPEG-in-TIFF specs.
 
 If you want to understand this implementation, start by reading the
 "architecture" documentation file.  Please read "codingrules" if you want to
 contribute any code.
 
 
-SUPPORTING SOFTWARE
-===================
-
-You will probably want Jef Poskanzer's PBMPLUS image software; this 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).
-
-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.
-
-
 LEGAL ISSUES
 ============
 
@@ -360,14 +265,21 @@
 
 
 It appears that the arithmetic coding option of the JPEG spec is covered by
-patents held by IBM, and possibly also patents of 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
+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
-people will choose to use it.  If you do obtain such a license, contact
-jpeg-info@uunet.uu.net for a copy of our arithmetic coding modules.)  So far
-as we are aware, there are no patent restrictions on the remaining code.
+people will choose to use it.  If you do obtain the necessary licenses,
+contact jpeg-info@uunet.uu.net for a copy of our arithmetic coding modules.)
+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."
 
 
 TO DO
diff --git a/SETUP b/SETUP
new file mode 100644
index 0000000..31f445c
--- /dev/null
+++ b/SETUP
@@ -0,0 +1,235 @@
+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
+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 under MS-DOS.
+	makefile.tc:   for Borland's Turbo C under MS-DOS.
+	makefile.pwc:  for Mix Software's Power C under MS-DOS.
+	makefile.manx: for Manx Aztec C on Amigas.
+	makefile.sas:  for SAS C on Amigas.
+
+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 config.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 config.c by hand; the makefiles
+don't provide any support for this.  config.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 config.c according to the directions
+given in config.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 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 (makcjpeg.lst and
+makdjpeg.lst are handy summaries).
+
+
+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.)
+
+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 config.c to figure out what to change.  (See description
+of config.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.
+
+
+STEP 3: 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 config.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).
+
+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 4: TEST
+============
+
+As a quick test of functionality we've included three small sample files:
+	testorig.jpg	A reduced section of the well-known Lenna picture.
+	testimg.ppm	The output of djpeg 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 testimg.ppm and testimg.jpg then you probably have a
+working port.
+
+With most of the makefiles, "make test" will perform the necessary
+comparisons.  If you're using a makefile that doesn't provide this option, run
+djpeg and cjpeg to generate testout.ppm and testout.jpg, then compare these to
+testimg.* with whatever file comparison tool you have.  The files should be
+bit-for-bit identical.
+
+NOTE: this is far from an exhaustive test of the JPEG software; some modules,
+such as color quantization and GIF I/O, are not exercised at all.  It's just a
+quick test to give you some confidence that you haven't missed something
+major.
+
+If the test passes, you can copy the executable files cjpeg and djpeg to
+wherever you normally install programs.  Read the file USAGE to learn more
+about using the programs.
+
+
+OPTIONAL STUFF
+==============
+
+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).
+
+If you want to incorporate the JPEG code as subroutines in a larger program,
+we recommend that you make libjpeg.a.  Then use the jconfig.h and jpegdata.h
+files as your interface to the JPEG functions, and link libjpeg.a with your
+program.  Your surrounding program will have to provide functionality similar
+to what's in jcmain.c or jdmain.c, and you may want to replace jerror.c and
+possibly other modules depending on your needs.  See the "architecture" file
+for more info.  If it seems to you that the system structure doesn't
+accommodate what you want to do, please contact the authors.
+
+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.
+
+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, config.c is fairly new and not
+yet thoroughly tested; if it's wrong about how to configure the JPEG software
+for your system, please let us know.
+
+
+HP/Apollo DOMAIN:
+
+At least in version 10.3.5, the C compiler is ANSI but the system include
+files are not.  Use makefile.ansi and add -DNONANSI_INCLUDES to CFLAGS.
+
+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.  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 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).
+
+IBM RS/6000 AIX:
+
+The CFLAGS switch to make the compiler define __STDC__ is "-qlanglvl=ansi".
+
+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 should be able to just turn on __STDC__
+through the compiler switch that enables that.  With version 4.0 you must
+manually edit jconfig.h.  (You can #define __STDC__, but also #define const.)
+
+Microsoft C for MS-DOS:
+
+Some 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 -d -d, but at least you can compile.
+
+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
new file mode 100644
index 0000000..409cb41
--- /dev/null
+++ b/USAGE
@@ -0,0 +1,162 @@
+USAGE instructions for the Independent JPEG Group's JPEG software
+=================================================================
+
+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 intended for
+"real-world" scenes; cartoons and other non-realistic images are not its
+strong suit.  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 images of real-world scenes,
+very good compression levels can be obtained with no visible change, and
+amazingly high compression levels can be obtained if you can tolerate a
+low-quality image.
+
+This file describes usage of the standard programs "cjpeg" and "djpeg" that
+can be built directly from the distributed software.  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.
+
+NOTE: at some point we will probably redesign the user interface, so the
+command line switches described here will change.
+
+
+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 PC, Macintosh, and Amiga systems, you say:
+	cjpeg [switches] imagefile jpegfile
+or
+	djpeg [switches] jpegfile  imagefile
+i.e., both 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; see SETUP.)
+
+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.
+
+The only JPEG file format currently supported is the JFIF format.  Support for
+the TIFF/JPEG format will probably be added at some future date.
+
+
+The command line switches for cjpeg are:
+
+	-Q quality	Scale quantization tables to adjust image quality.
+			Quality is 0 (worst) to 100 (best); default is 75.
+			(See below for more info.)
+
+	-o		Perform optimization of entropy encoding parameters.
+			Without this, default encoding parameters are used.
+			-o usually makes the JPEG file a little smaller, but
+			cjpeg runs much slower.  Image quality and speed of
+			decompression are unaffected by -o.
+
+	-T		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
+			-T to force cjpeg to treat the input as Targa format.
+
+	-I		Generate noninterleaved JPEG file (not yet supported).
+
+	-a		Use arithmetic coding rather than Huffman coding.
+			(Not currently supported for legal reasons.)
+
+	-d		Enable debug printout.  More -d's give more printout.
+			Also, version information is printed at startup.
+
+The -Q switch lets you trade off compressed file size against quality of the
+reconstructed image: the higher the -Q 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 -Q setting (smallest file) that decompresses into something
+visually indistinguishable from the original image.  For this purpose the -Q
+setting should be between 50 and 95; the default of 75 is often about right.
+If you see defects at -Q 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.)
+
+-Q 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.  -Q 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, -Q 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 -Q 2 (or so) for some
+amusing Cubist effects.  (Note: -Q 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 -Q value, because some
+commercial JPEG programs may be unable to decode the resulting file.)
+
+
+The command line switches for djpeg are:
+
+	-G		Select GIF output format (implies -q, with default
+			of 256 colors).
+
+	-P		Select PPM or PGM output format (this is the default).
+			PGM is emitted if the JPEG file is gray-scale or if -g
+			is specified.
+
+	-R		Select RLE output format.  Requires URT library.
+
+	-T		Select Targa output format.  Gray-scale format is
+			emitted if the JPEG file is gray-scale or if -g is
+			specified; otherwise, colormapped format is emitted
+			if -q is specified; otherwise, 24-bit full-color
+			format is emitted.
+
+	-b		Perform cross-block smoothing.  This is quite
+			memory-intensive and only seems to improve the image
+			at very low quality settings (-Q 10 to 20 or so).
+			At normal -Q settings it may make the image worse.
+
+	-g		Force gray-scale output even if input is color.
+
+	-q N		Quantize to N colors.
+
+	-D		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 -D.
+
+	-2		Use two-pass color quantization (not yet supported).
+
+	-d		Enable debug printout.  More -d's give more printout.
+			Also, version information is printed at startup.
+
+Color quantization currently uses a rather shoddy algorithm (although it's not
+as horrible when dithered).  Because of this, the GIF output mode is NOT
+RECOMMENDED in the current release, except for gray-scale output.  You can get
+better results by applying ppmquant to the unquantized (PPM) output of djpeg,
+then converting to GIF with ppmtogif.  (See SUPPORTING SOFTWARE in the README
+file.)  We expect to provide a considerably better quantization algorithm in a
+future release.  (The same applies to colormapped RLE or Targa output, of
+course.)
+
+Note that djpeg *can* read noninterleaved JPEG files even though cjpeg can't
+yet generate them.  For most applications this is a nonissue, since hardly
+anybody seems to be using noninterleaved format.
+
+On a non-virtual-memory machine, you may run out of memory if you use -I or -o
+in cjpeg, or -q ... -2 in djpeg, or try to read an interlaced GIF file, or try
+to read or write an RLE file, or try to read an interlaced or bottom-up Targa
+file.  This will be addressed soon by replacing jvirtmem.c with something that
+uses temporary files for large images.
diff --git a/ansi2knr.c b/ansi2knr.c
index 77d3d81..04e4789 100644
--- a/ansi2knr.c
+++ b/ansi2knr.c
@@ -1,6 +1,7 @@
 /*
  * Received from Peter Deutsch (ghost@aladdin.com)
  * Fri, 26 Apr 91 10:10:10 PDT
+ * Small portability improvements by Tom Lane
  */
 
 /* Copyright (C) 1989, 1991 Aladdin Enterprises.  All rights reserved.
@@ -174,34 +175,32 @@
 
 /* ansi2knr.c */
 /* Convert ANSI function declarations to K&R syntax */
+
 #include <stdio.h>
 #include <ctype.h>
 
 #ifdef BSD
-#  include <strings.h>
-#  define strchr index
+#include <strings.h>
+#define strchr index
 #else
-#  ifdef VMS
+#ifdef VMS
 	extern char *strcat(), *strchr(), *strcpy(), *strupr();
 	extern int strcmp(), strlen(), strncmp();
-#  else
-#    include <string.h>
-#  endif
+#else
+#include <string.h>
+#endif
 #endif
 
 #ifdef MSDOS
-#  include <malloc.h>
+#include <malloc.h>
 #else
-#  ifdef VMS
+#ifdef VMS
      extern char *malloc();
      extern void free();
-#  else
-#    ifdef BSD
-       extern char *malloc();
-#    else
-#      include <malloc.h>
-#    endif
-#  endif
+#else
+     extern char *malloc();
+     extern int free();
+#endif
 #endif
 
 /* Usage:
@@ -226,12 +225,13 @@
 #define isidchar(ch) (isalnum(ch) || (ch) == '_')
 #define isidfirstchar(ch) (isalpha(ch) || (ch) == '_')
 
+int
 main(argc, argv)
     int argc;
     char *argv[];
 {	FILE *in, *out;
 #define bufsize 500			/* arbitrary size */
-	char buf[bufsize];
+	char buf[bufsize+1];
 	char *line;
 	switch ( argc )
 	   {
@@ -296,12 +296,13 @@
 /*
  * Write blanks over part of a string.
  */
-void
+int
 writeblanks(start, end)
     char *start;
     char *end;
 {	char *p;
 	for ( p = start; p < end; p++ ) *p = ' ';
+	return 0;
 }
 
 /*
@@ -313,6 +314,7 @@
  *	-1 - may be the beginning of a function definition,
  *		append another line and look again.
  */
+int
 test1(buf)
     char *buf;
 {	register char *p = buf;
@@ -359,6 +361,7 @@
 	return contin;
 }
 
+int
 convert1(buf, out)
     char *buf;
     FILE *out;
diff --git a/cjpeg.1 b/cjpeg.1
new file mode 100644
index 0000000..9a18322
--- /dev/null
+++ b/cjpeg.1
@@ -0,0 +1,130 @@
+.TH CJPEG 1 "11 December 1991"
+.SH NAME
+cjpeg \- compress an image file to a JPEG file
+.SH SYNOPSIS
+.B cjpeg
+[
+.BI \-Q " quality"
+]
+[
+.B \-oTIad
+]
+[
+.I filename
+]
+.LP
+.SH DESCRIPTION
+.LP
+.B cjpeg
+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 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.)
+.SH OPTIONS
+.TP
+.BI \-Q " quality"
+Scale quantization tables to adjust image quality.  Quality is 0 (worst) to
+100 (best); default is 75.  (See below for more info.)
+.TP
+.B \-o
+Perform optimization of entropy encoding parameters.  Without this, default
+encoding parameters are used.
+.B \-o
+usually makes the JPEG file a little smaller, but
+.B cjpeg
+runs much slower.  Image quality and speed of decompression are unaffected by
+.BR \-o .
+.TP
+.B \-T
+Input file is Targa format.  Targa files that contain an "identification"
+field will not be automatically recognized by
+.BR cjpeg ;
+for such files you must specify
+.B \-T
+to force
+.B cjpeg
+to treat the input as Targa format.
+.TP
+.B \-I
+Generate noninterleaved JPEG file (not yet supported).
+.TP
+.B \-a
+Use arithmetic coding rather than Huffman coding (not currently
+supported for legal reasons).
+.TP
+.B \-d
+Enable debug printout.  More
+.BR \-d 's
+give more output.  Also, version information is printed at startup.
+.PP
+The
+.B \-Q
+switch lets you trade off compressed file size against quality of the
+reconstructed image: the higher the
+.B \-Q
+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
+.B \-Q
+setting (smallest file) that decompresses into something visually
+indistinguishable from the original image.  For this purpose the
+.B \-Q
+setting should be between 50 and 95; the default of 75 is often about right.
+If you see defects at 
+.B \-Q
+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.)
+.PP
+.B \-Q
+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.  
+.B \-Q
+values above about 95 are
+.B not
+recommended for normal use; the compressed file size goes up dramatically for
+hardly any gain in output image quality.
+.PP
+In the other direction, 
+.B \-Q
+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
+.B \-Q
+2 (or so) for some amusing Cubist effects.  (Note: 
+.B \-Q
+values below about 25 generate 2-byte quantization tables, which are
+considered optional in the JPEG standard.  
+.B cjpeg
+emits a warning message when you give such a
+.B \-Q
+value, because some commercial JPEG programs may be unable to decode the
+resulting file.)
+.SH EXAMPLES
+.LP
+This example compresses the PPM file foo.ppm with a quality factor of
+60 and saves the output as foo.jpg:
+.IP
+.B cjpeg \-Q
+.I 60 foo.ppm
+.B >
+.I foo.jpg
+.SH SEE ALSO
+.BR djpeg (1)
+.br
+Wallace, Gregory K.  "The JPEG Still Picture Compression Standard",
+Communications of the ACM, April 1991 (vol. 34, no. 4), pp. 30-44.
+.SH AUTHOR
+Independent JPEG Group
+.SH BUGS
+Arithmetic coding and interleaved output not yet supported.
+.PP
+Not all variants of Targa file format are supported.
+.PP
+The
+.B -T
+switch is not a bug, it's a feature.  (It would be a bug if the Targa format
+designers had not been clueless.)
+.PP
+Not as fast as we'd like.
diff --git a/config.c b/config.c
new file mode 100644
index 0000000..938fd19
--- /dev/null
+++ b/config.c
@@ -0,0 +1,403 @@
+/*
+ * config.c
+ *
+ * Copyright (C) 1991, 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 program is intended to help you determine how to configure the JPEG
+ * 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.
+ *
+ * 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.
+ * Many C compilers will issue lots of spurious error messages once they
+ * have gotten confused.  Go to the line indicated in the first error message,
+ * and read the comments preceding that line to see what to change.
+ *
+ * Almost all of the edits you may need to make to this program consist of
+ * changing a line that reads "#define SOME_SYMBOL" to "#undef SOME_SYMBOL",
+ * or vice versa.  This is called defining or undefining that symbol.
+ */
+
+
+/* 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.
+ */
+
+#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. */
+#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 */
+
+#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.
+ */
+
+#undef BSD
+
+#ifdef BSD
+#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.
+ */
+
+#undef NEED_SPECIAL_INCLUDE	/* assume we DON'T need it, for starters */
+
+#ifdef NEED_SPECIAL_INCLUDE
+#include <someincludefile.h>
+#endif
+
+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
+ * 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.
+ */
+
+#define HAVE_ANSI_DEFINITIONS
+
+#ifdef HAVE_ANSI_DEFINITIONS
+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 testfunction (int arg1, int * arg2) /* check definitions */
+{
+  return arg2[arg1];
+}
+#endif
+
+
+/* Now we want to find out if your compiler knows what "unsigned char" means.
+ * If you get an error on the "unsigned char un_char;" line,
+ * then undefine HAVE_UNSIGNED_CHAR.
+ */
+
+#define HAVE_UNSIGNED_CHAR
+
+#ifdef HAVE_UNSIGNED_CHAR
+unsigned char un_char;
+#endif
+
+
+/* Now we want to find out if your compiler knows what "unsigned short" means.
+ * If you get an error on the "unsigned short un_short;" line,
+ * then undefine HAVE_UNSIGNED_SHORT.
+ */
+
+#define HAVE_UNSIGNED_SHORT
+
+#ifdef HAVE_UNSIGNED_SHORT
+unsigned short un_short;
+#endif
+
+
+/* Now we want to find out if your compiler understands type "void".
+ * If you get an error anywhere in here, undefine HAVE_VOID.
+ */
+
+#define HAVE_VOID
+
+#ifdef HAVE_VOID
+typedef void * void_ptr;	/* check void * */
+typedef void (*void_func) ();	/* check ptr to function returning void */
+
+void testfunction2 (arg1, arg2)	/* check void function result */
+     void_ptr arg1;
+     void_func arg2;
+{
+  char * locptr = (char *) arg1; /* check casting to and from void * */
+  arg1 = (void *) locptr;
+  (*arg2) (1, 2);		/* check call of fcn returning void */
+}
+#endif
+
+
+/* Now we want to find out if your compiler knows what "const" means.
+ * If you get an error here, undefine HAVE_CONST.
+ */
+
+#define HAVE_CONST
+
+#ifdef HAVE_CONST
+static const int carray[3] = {1, 2, 3};
+
+int testfunction3 (arg1)
+     const int arg1;
+{
+  return carray[arg1];
+}
+#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.
+ ************************************************************************
+ */
+
+
+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 system doesn't use makefiles,\n");
+    printf("or if your compiler doesn't support -D, then you must change jconfig.h.\n");
+    any_changes = 1;
+  }
+  printf("\n");			/* blank line before each problem report */
+  return 0;
+}
+
+
+int test_char_sign (arg)
+     int arg;
+{
+  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");
+  }
+  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");
+  }
+  return 0;
+}
+
+
+int test_shifting (arg)
+     long arg;
+/* 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");
+  }
+  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");
+  }
+  return 0;
+}
+
+
+int main (argc, argv)
+     int argc;
+     char ** argv;
+{
+  char signed_char_check = (char) (-67);
+
+  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 MY__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 MY__STDC__
+  new_change();
+  printf("Your compiler doesn't claim to be ANSI-compliant, but it is close enough\n");
+  printf("for me.  Either add -D__STDC__ to CFLAGS, or add #define __STDC__ at the\n");
+  printf("beginning of jinclude.h (NOT jconfig.h).\n");
+  printf("Some compilers will not let you do this: they will complain that __STDC__\n");
+  printf("is a reserved name.  In that case you have a compiler that really is ANSI,\n");
+  printf("but you have to give it a special switch (often -ansi) to make it so.\n");
+  printf("Check your compiler documentation and add the proper switch to CFLAGS.\n");
+#define MY__STDC__
+#endif
+#else /* !HAVE_ALL_ANSI_FEATURES */
+#ifdef MY__STDC__
+  new_change();
+  printf("Your compiler claims to be ANSI-compliant, but it is lying!\n");
+  printf("Either add -U__STDC__ to CFLAGS, or add #undef __STDC__\n");
+  printf("at the beginning of jinclude.h (NOT jconfig.h).\n");
+#undef MY__STDC__
+#endif
+#endif /* HAVE_ALL_ANSI_FEATURES */
+
+#ifndef MY__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 __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 __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 __STDC__/#endif lines surrounding it in jconfig.h.\n");
+#endif
+#endif /* HAVE_UNSIGNED_CHAR */
+
+#ifdef HAVE_CONST
+  new_change();
+  printf("You can delete the #define const line from jconfig.h.\n");
+  printf("(But things should still work if you don't.)\n");
+#endif
+
+#endif /* MY__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 MY__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 MY__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");
+  }
+
+  return any_changes;
+}
diff --git a/djpeg.1 b/djpeg.1
new file mode 100644
index 0000000..5eec670
--- /dev/null
+++ b/djpeg.1
@@ -0,0 +1,114 @@
+.TH DJPEG 1 "11 December 1991"
+.SH NAME
+djpeg \- decompress a JPEG file to an image file
+.SH SYNOPSIS
+.B djpeg
+[
+.B \-GPRTbgD2d
+]
+[
+.BI \-q " N"
+]
+[
+.I filename
+]
+.LP
+.SH DESCRIPTION
+.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.  PPM, GIF, Targa, or RLE
+output format can be selected.  (RLE is supported only if the URT library is
+available.)
+.LP
+The color quantization algorithm is currently shoddy.  Because of this, the
+GIF output mode is not recommended in the current release, except for
+gray-scale output (obtained with
+.BR \-g ).
+.SH OPTIONS
+.TP
+.B \-G
+Select GIF output format (implies
+.BR \-q ,
+with default of 256 colors).
+Currently the color quantization uses a shoddy algorithm and external
+quantization (e.g.
+.IR ppmquant ,
+.IR rlequant )
+is recommended before conversion to GIF format.
+.TP
+.B \-P
+Select PPM or PGM output format (this is the default).  PGM is emitted if the
+JPEG file is gray-scale or if
+.B \-g
+is specified.
+.TP
+.B \-R
+Select RLE output format.  Requires URT library.
+.TP
+.B \-T
+Select Targa output format.  Gray-scale format is emitted if the JPEG file is
+gray-scale or if
+.B \-g
+is specified; otherwise, colormapped format is emitted if
+.B \-q
+is specified; otherwise, 24-bit full-color format is emitted.
+.TP
+.B \-b
+Perform cross-block smoothing.  This is quite memory-intensive and only seems
+to improve the image at low quality settings (\fB\-Q\fR 10 to 20 or so).
+At normal
+.B \-Q
+settings it may make the image worse.
+.TP
+.B \-g
+Force gray-scale output even if input is color.
+.TP
+.BI \-q " N"
+Quantize to N colors.
+.TP
+.B \-D
+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 \-D .
+.TP
+.B \-2
+Use two-pass color quantization (not yet supported).
+.TP
+.B \-d
+Enable debug printout.  More
+.BR \-d 's
+give more output.  Also, version information is printed at startup.
+.SH EXAMPLES
+.LP
+This example decompresses the JPEG file foo.jpg and saves the output
+as a gray-scale image in foo.pgm:
+.IP
+.B djpeg \-g
+.I foo.jpg
+.B >
+.I foo.pgm
+.SH SEE ALSO
+.BR cjpeg (1)
+.br
+.BR ppmquant (1)
+[From the PBMplus distribution]
+.br
+.BR rlequant (1)
+[From the Utah Raster Toolkit distribution]
+.br
+Wallace, Gregory K.  "The JPEG Still Picture Compression Standard",
+Communications of the ACM, April 1991 (vol. 34, no. 4), pp. 30-44.
+.SH AUTHOR
+Independent JPEG Group
+.SH BUGS
+.B djpeg
+currently uses a shoddy color quantization algorithm.  This leads to
+poor GIF file output.  Two-pass color quantization is not yet
+supported.
+.PP
+Arithmetic coding is not supported for legal reasons.
+.PP
+Not as fast as we'd like.
diff --git a/egetopt.c b/egetopt.c
index 8183d35..dbfd7fd 100644
--- a/egetopt.c
+++ b/egetopt.c
@@ -40,21 +40,27 @@
  *	UUCP:		...!ames!fxgrp!ljz
  *
  *    	May, 1988
+ *
+ * Modified for use in free JPEG code:
+ *
+ *	Ed Hanway
+ *	UUCP:	uunet!sisd!jeh
+ *
+ *	October, 1991
  */
 
-/*
- * If you want, include stdio.h or something where EOF and NULL are defined.
- * However, egetopt() is written so as not to need stdio.h, which should
- * make it significantly smaller on some systems.
+/* The original egetopt.c was written not to need stdio.h.
+ * For the JPEG code this is an unnecessary and unportable assumption.
+ * Also, we make all the variables and routines "static" to avoid
+ * possible conflicts with a system-library version of getopt.
+ *
+ * In the JPEG code, this file is compiled by #including it in jcmain.c
+ * or jdmain.c.  Since ANSI2KNR does not process include files, we can't
+ * rely on it to convert function definitions to K&R style.  Hence we
+ * provide both styles of function header with an explicit #ifdef PROTO (ick).
  */
 
-#ifndef EOF
-# define EOF		(-1)
-#endif /* ! EOF */
-
-#ifndef NULL
-# define NULL		(char *)0
-#endif /* ! NULL */
+#define GVAR static		/* make empty to export these variables */
 
 /*
  * None of these constants are referenced in the executable portion of
@@ -63,23 +69,21 @@
 #define BADCH		(int)'?'
 #define NEEDSEP		(int)':'
 #define MAYBESEP	(int)'\0'
-#define ERRFD		2
 #define EMSG		""
 #define START		"-"
 
 /*
  * Here are all the pertinent global variables.
  */
-int opterr = 1;		/* if true, output error message */
-int optind = 1;		/* index into parent argv vector */
-int optopt;		/* character checked for validity */
-int optbad = BADCH;	/* character returned on error */
-int optchar = 0;	/* character that begins returned option */
-int optneed = NEEDSEP;	/* flag for mandatory argument */
-int optmaybe = MAYBESEP;/* flag for optional argument */
-int opterrfd = ERRFD;	/* file descriptor for error text */
-char *optarg;		/* argument associated with option */
-char *optstart = START;	/* list of characters that start options */
+GVAR int opterr = 1;		/* if true, output error message */
+GVAR int optind = 1;		/* index into parent argv vector */
+GVAR int optopt;		/* character checked for validity */
+GVAR int optbad = BADCH;	/* character returned on error */
+GVAR int optchar = 0;		/* character that begins returned option */
+GVAR int optneed = NEEDSEP;	/* flag for mandatory argument */
+GVAR int optmaybe = MAYBESEP;	/* flag for optional argument */
+GVAR const char *optarg;	/* argument associated with option */
+GVAR const char *optstart = START; /* list of characters that start options */
 
 
 /*
@@ -88,17 +92,11 @@
 
 /*
  * Conditionally print out an error message and return (depends on the
- * setting of 'opterr' and 'opterrfd').  Note that this version of
- * TELL() doesn't require the existence of stdio.h.
+ * setting of 'opterr').
  */
 #define TELL(S)	{ \
-	if (opterr && opterrfd >= 0) { \
-		char option = optopt; \
-		write(opterrfd, *nargv, strlen(*nargv)); \
-		write(opterrfd, (S), strlen(S)); \
-		write(opterrfd, &option, 1); \
-		write(opterrfd, "\n", 1); \
-	} \
+	if (opterr) \
+		fprintf(stderr, "%s%s%c\n", *nargv, (S), optopt); \
 	return (optbad); \
 }
 
@@ -106,10 +104,16 @@
  * This works similarly to index() and strchr().  I include it so that you
  * don't need to be concerned as to which one your system has.
  */
-static char *
-_sindex(string, ch)
-char *string;
-int ch;
+
+#ifdef PROTO
+LOCAL const char *
+_sindex (const char *string, int ch)
+#else
+LOCAL const char *
+_sindex (string, ch)
+     const char *string;
+     int ch;
+#endif
 {
 	if (string != NULL) {
 		for (; *string != '\0'; ++string) {
@@ -125,15 +129,21 @@
 /*
  * Here it is:
  */
-int
-egetopt(nargc, nargv, ostr)
-int nargc;
-char **nargv;
-char *ostr;
+
+#ifdef PROTO
+LOCAL int
+egetopt (int nargc, char **nargv, const char *ostr)
+#else
+LOCAL int
+egetopt (nargc, nargv, ostr)
+     int nargc;
+     char **nargv;
+     const char *ostr;
+#endif
 {
-	static char *place = EMSG;	/* option letter processing */
-	register char *oli;		/* option letter list index */
-	register char *osi = NULL;	/* option start list index */
+	static const char *place = EMSG; /* option letter processing */
+	register const char *oli;	 /* option letter list index */
+	register const char *osi = NULL; /* option start list index */
 
 	if (nargv == (char **)NULL) {
 		return (EOF);
diff --git a/jbsmooth.c b/jbsmooth.c
index ad2138d..ee58c91 100644
--- a/jbsmooth.c
+++ b/jbsmooth.c
@@ -94,7 +94,7 @@
 
 #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] = (_ac)
+#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);
diff --git a/jccolor.c b/jccolor.c
index 7fd198c..bd0e1a2 100644
--- a/jccolor.c
+++ b/jccolor.c
@@ -66,11 +66,14 @@
        * must be too; do not need an explicit range-limiting operation.
        */
       /* Y */
-      *outptr0++ = (   306*r +  601*g +  117*b + (INT32) 512) >> 10;
+      *outptr0++ = (JSAMPLE)
+	((   306*r +  601*g +  117*b + (INT32) 512) >> 10);
       /* Cb */
-      *outptr1++ = ((-173)*r -  339*g +  512*b + (INT32) 512*(MAXJSAMPLE+1)) >> 10;
+      *outptr1++ = (JSAMPLE)
+	(((-173)*r -  339*g +  512*b + (INT32) 512*(MAXJSAMPLE+1)) >> 10);
       /* Cr */
-      *outptr2++ = (   512*r -  429*g -   83*b + (INT32) 512*(MAXJSAMPLE+1)) >> 10;
+      *outptr2++ = (JSAMPLE)
+	((   512*r -  429*g -   83*b + (INT32) 512*(MAXJSAMPLE+1)) >> 10);
     }
   }
 }
diff --git a/jcdeflts.c b/jcdeflts.c
index cd1624a..1503989 100644
--- a/jcdeflts.c
+++ b/jcdeflts.c
@@ -6,6 +6,8 @@
  * 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"
@@ -17,11 +19,11 @@
 /* Define a Huffman table */
 {
   if (*htblptr == NULL)
-    *htblptr = (*cinfo->emethods->alloc_small) (SIZEOF(HUFF_TBL));
+    *htblptr = (HUFF_TBL *) (*cinfo->emethods->alloc_small) (SIZEOF(HUFF_TBL));
   
-  memcpy((void *) (*htblptr)->bits, (void *) bits,
+  memcpy((void *) (*htblptr)->bits, (const void *) bits,
 	 SIZEOF((*htblptr)->bits));
-  memcpy((void *) (*htblptr)->huffval, (void *) val,
+  memcpy((void *) (*htblptr)->huffval, (const void *) val,
 	 SIZEOF((*htblptr)->huffval));
 
   /* Initialize sent_table FALSE so table will be written to JPEG file.
@@ -152,7 +154,7 @@
   long temp;
 
   if (*qtblptr == NULL)
-    *qtblptr = (*cinfo->emethods->alloc_small) (SIZEOF(QUANT_TBL));
+    *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;
@@ -207,14 +209,16 @@
  *
  * 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.
+ * 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' parameter.  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.
+ * 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 sets up for a color image; to output a grayscale image,
+ * 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.)
@@ -223,17 +227,17 @@
  * a JFIF header (set write_JFIF_header = FALSE).
  *
  * CAUTION: if you want to compress multiple images per run, it's safest
- * to call j_default_compression before *each* call to jpeg_compress (and
- * j_free_defaults afterwards).  If this isn't practical, you'll have to
+ * to call j_c_defaults before *each* call to jpeg_compress (and
+ * j_c_free_defaults afterwards).  If this isn't practical, you'll have to
  * be careful to reset any individual parameters that may change during
- * the compression run.  The main thing you need to worry about as this
- * is written is that the sent_table boolean in each Huffman table must
- * be reset to FALSE before each compression; otherwise, Huffman tables
- * won't get emitted for the second and subsequent images.
+ * the compression run.  The main thing you need to worry about at present
+ * is that the sent_table boolean in each Huffman table must be reset to
+ * FALSE before each compression; otherwise, Huffman tables won't get
+ * emitted for the second and subsequent images.
  */
 
 GLOBAL void
-j_default_compression (compress_info_ptr cinfo, int quality)
+j_c_defaults (compress_info_ptr cinfo, int quality, boolean force_baseline)
 /* NB: the external methods must already be set up. */
 {
   short i;
@@ -260,8 +264,8 @@
   cinfo->write_JFIF_header = TRUE;
   cinfo->jpeg_color_space = CS_YCbCr;
   cinfo->num_components = 3;
-  cinfo->comp_info = (*cinfo->emethods->alloc_small)
-			(4 * SIZEOF(jpeg_component_info));
+  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.
    */
@@ -294,8 +298,7 @@
   compptr->ac_tbl_no = 1;
 
   /* Set up two quantization tables using the specified quality scaling */
-  /* Baseline compatibility is forced (a nonissue for reasonable defaults) */
-  j_set_quality(cinfo, quality, TRUE);
+  j_set_quality(cinfo, quality, force_baseline);
 
   /* Set up two Huffman tables in case user interface wants Huffman coding */
   std_huff_tables(cinfo);
@@ -327,7 +330,7 @@
 
 GLOBAL void
 j_monochrome_default (compress_info_ptr cinfo)
-/* Change the j_default_compression() values to emit a monochrome JPEG file. */
+/* Change the j_c_defaults() values to emit a monochrome JPEG file. */
 {
   jpeg_component_info * compptr;
 
@@ -341,13 +344,13 @@
 
 
 
-/* This routine releases storage allocated by j_default_compression.
+/* This routine releases storage allocated by j_c_defaults.
  * Note that freeing the method pointer structs and the compress_info_struct
  * itself are the responsibility of the user interface.
  */
 
 GLOBAL void
-j_free_defaults (compress_info_ptr cinfo)
+j_c_free_defaults (compress_info_ptr cinfo)
 {
   short i;
 
diff --git a/jchuff.c b/jchuff.c
index 531bc75..44a0885 100644
--- a/jchuff.c
+++ b/jchuff.c
@@ -39,8 +39,8 @@
 
   p = 0;
   for (l = 1; l <= 16; l++) {
-    for (i = 1; i <= htbl->bits[l]; i++)
-      huffsize[p++] = l;
+    for (i = 1; i <= (int) htbl->bits[l]; i++)
+      huffsize[p++] = (char) l;
   }
   huffsize[p] = 0;
   lastp = p;
@@ -52,7 +52,7 @@
   si = huffsize[0];
   p = 0;
   while (huffsize[p]) {
-    while (huffsize[p] == si) {
+    while (((int) huffsize[p]) == si) {
       huffcode[p++] = code;
       code++;
     }
@@ -95,10 +95,10 @@
 }
 
 
-#define emit_byte(val)	((bytes_in_buffer >= JPEG_BUF_SIZE ? \
-				(flush_bytes(), 0) : 0), \
-			 output_buffer[bytes_in_buffer] = (val), \
-			 bytes_in_buffer++)
+#define emit_byte(val)  \
+  MAKESTMT( if (bytes_in_buffer >= JPEG_BUF_SIZE) \
+	      flush_bytes(); \
+	    output_buffer[bytes_in_buffer++] = (char) (val); )
 
 
 
@@ -157,16 +157,22 @@
 LOCAL void
 encode_one_block (JBLOCK block, HUFF_TBL *dctbl, HUFF_TBL *actbl)
 {
-  register INT32 temp;
+  register int temp, temp2;
   register int nbits;
   register int k, r, i;
   
   /* Encode the DC coefficient difference per section 7.3.5.1 */
   
-  /* Find the number of bits needed for the magnitude of the coefficient */
-  temp = block[0];
-  if (temp < 0) temp = -temp;
+  temp = temp2 = block[0];
+
+  if (temp < 0) {
+    temp = -temp;		/* temp is abs value of input */
+    /* For a negative input, want temp2 = bitwise complement of abs(input) */
+    /* This code assumes we are on a two's complement machine */
+    temp2--;
+  }
   
+  /* Find the number of bits needed for the magnitude of the coefficient */
   nbits = 0;
   while (temp) {
     nbits++;
@@ -175,13 +181,10 @@
   
   /* Emit the Huffman-coded symbol for the number of bits */
   emit_bits(dctbl->ehufco[nbits], dctbl->ehufsi[nbits]);
-  
-  /* If positive, emit nbits low order bits; */
-  /* if negative, emit nbits low order bits of value-1 */
-  if ((temp = block[0]) < 0)
-    temp--;
-  
-  emit_bits((UINT16) temp, nbits);
+
+  /* Emit that number of bits of the value, if positive, */
+  /* or the complement of its magnitude, if negative. */
+  emit_bits((UINT16) temp2, nbits);
   
   /* Encode the AC coefficients per section 7.3.5.2 */
   
@@ -196,10 +199,15 @@
 	emit_bits(actbl->ehufco[0xF0], actbl->ehufsi[0xF0]);
 	r -= 16;
       }
+
+      temp2 = temp;
+      if (temp < 0) {
+	temp = -temp;		/* temp is abs value of input */
+	/* This code assumes we are on a two's complement machine */
+	temp2--;
+      }
       
       /* Find the number of bits needed for the magnitude of the coefficient */
-      if (temp < 0) temp = -temp;
-
       nbits = 1;		/* there must be at least one 1 bit */
       while (temp >>= 1)
 	nbits++;
@@ -208,12 +216,9 @@
       i = (r << 4) + nbits;
       emit_bits(actbl->ehufco[i], actbl->ehufsi[i]);
       
-      /* If positive, emit nbits low order bits; */
-      /* if negative, emit nbits low order bits of value-1 */
-      if ((temp = block[k]) < 0)
-	temp--;
-      
-      emit_bits((UINT16) temp, nbits);
+      /* Emit that number of bits of the value, if positive, */
+      /* or the complement of its magnitude, if negative. */
+      emit_bits((UINT16) temp2, nbits);
       
       r = 0;
     }
@@ -488,7 +493,7 @@
   for (i = 1; i <= MAX_CLEN; i++) {
     for (j = 0; j <= 255; j++) {
       if (codesize[j] == i) {
-	htbl->huffval[p] = j;
+	htbl->huffval[p] = (UINT8) j;
 	p++;
       }
     }
@@ -645,7 +650,7 @@
     if (dc_count_ptrs[tbl] != NULL) {
       htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
       if (*htblptr == NULL)
-	*htblptr = (*cinfo->emethods->alloc_small) (SIZEOF(HUFF_TBL));
+	*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 */
@@ -656,7 +661,7 @@
     if (ac_count_ptrs[tbl] != NULL) {
       htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
       if (*htblptr == NULL)
-	*htblptr = (*cinfo->emethods->alloc_small) (SIZEOF(HUFF_TBL));
+	*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 */
diff --git a/jcmain.c b/jcmain.c
index f71d5ad..3b00b40 100644
--- a/jcmain.c
+++ b/jcmain.c
@@ -21,7 +21,7 @@
  */
 
 #include "jinclude.h"
-#ifdef __STDC__
+#ifdef INCLUDES_ARE_ANSI
 #include <stdlib.h>		/* to declare exit() */
 #endif
 
@@ -37,20 +37,14 @@
 #define WRITE_BINARY	"wb"
 #endif
 
+#include "jversion.h"		/* for version message */
+
 
 /*
- * If your system has getopt(3), you can use your library version by
- * defining HAVE_GETOPT.  By default, we use the PD 'egetopt'.
+ * PD version of getopt(3).
  */
 
-#ifdef HAVE_GETOPT
-extern int getopt PP((int argc, char **argv, char *optstring));
-extern char * optarg;
-extern int optind;
-#else
 #include "egetopt.c"
-#define getopt(argc,argv,opt)	egetopt(argc,argv,opt)
-#endif
 
 
 /*
@@ -58,24 +52,44 @@
  * and selects the appropriate input-reading module.
  *
  * To determine which family of input formats the file belongs to,
- * we look only at the first byte of the file, since C does not
+ * 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.
- * This is sufficient for the currently envisioned set of input formats.
- *
- * If you need to look at more than one character to select an input module,
- * you can either
- *     1) assume you can fseek() the input file (may fail for piped input);
- *     2) assume you can push back more than one character (works in
+ * 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);
- * or  3) don't put back the data, and modify the various input_init
- *        methods to assume they start reading after the start of file.
+ *     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 accept a -T switch to force Targa input mode.
  */
 
+static boolean is_targa;	/* records user -T 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");
 
@@ -90,8 +104,22 @@
     jselrppm(cinfo);
     break;
 #endif
+#ifdef RLE_SUPPORTED
+  case 'R':
+    jselrrle(cinfo);
+    break;
+#endif
+#ifdef TARGA_SUPPORTED
+  case 0x00:
+    jselrtarga(cinfo);
+    break;
+#endif
   default:
-    ERREXIT(cinfo->emethods, "Unsupported input file format");
+#ifdef TARGA_SUPPORTED
+    ERREXIT(cinfo->emethods, "Unrecognized input file format --- did you forget -T ?");
+#else
+    ERREXIT(cinfo->emethods, "Unrecognized input file format");
+#endif
     break;
   }
 
@@ -126,7 +154,7 @@
 /* complain about bad command line */
 {
   fprintf(stderr, "usage: %s ", progname);
-  fprintf(stderr, "[-I] [-Q quality 0..100] [-a] [-o] [-d]");
+  fprintf(stderr, "[-Q quality 0..100] [-o] [-T] [-I] [-a] [-d]");
 #ifdef TWO_FILE_COMMANDLINE
   fprintf(stderr, " inputfile outputfile\n");
 #else
@@ -160,18 +188,13 @@
   jselvirtmem(&e_methods);	/* memory allocation routines */
   c_methods.c_ui_method_selection = c_ui_method_selection;
 
-  /* Set up default input and output file references. */
-  /* (These may be overridden below.) */
-  cinfo.input_file = stdin;
-  cinfo.output_file = stdout;
+  /* Set up default JPEG parameters. */
+  j_c_defaults(&cinfo, 75, FALSE); /* default quality level = 75 */
+  is_targa = FALSE;
 
-  /* Set up default parameters. */
-  e_methods.trace_level = 0;
-  j_default_compression(&cinfo, 75); /* default quality level */
-
-  /* Scan parameters */
+  /* Scan command line options, adjust parameters */
   
-  while ((c = getopt(argc, argv, "IQ:aod")) != EOF)
+  while ((c = egetopt(argc, argv, "IQ:Taod")) != EOF)
     switch (c) {
     case 'I':			/* Create noninterleaved file. */
 #ifdef MULTISCAN_FILES_SUPPORTED
@@ -188,13 +211,16 @@
 	  usage(argv[0]);
 	if (sscanf(optarg, "%d", &val) != 1)
 	  usage(argv[0]);
-	/* Note: for now, we leave force_baseline FALSE.
-	 * In a production user interface, probably should make it TRUE
-	 * unless overridden by a separate switch.
+	/* Note: for now, 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);
       }
       break;
+    case 'T':			/* Input file is Targa format. */
+      is_targa = TRUE;
+      break;
     case 'a':			/* Use arithmetic coding. */
 #ifdef ARITH_CODING_SUPPORTED
       cinfo.arith_code = TRUE;
@@ -222,6 +248,11 @@
       break;
     }
 
+  /* If -d appeared, print version identification */
+  if (e_methods.trace_level > 0)
+    fprintf(stderr, "Independent JPEG Group's CJPEG, version %s\n%s\n",
+	    JVERSION, JCOPYRIGHT);
+
   /* Select the input and output files */
 
 #ifdef TWO_FILE_COMMANDLINE
@@ -241,6 +272,9 @@
 
 #else /* not TWO_FILE_COMMANDLINE -- use Unix style */
 
+  cinfo.input_file = stdin;	/* default input file */
+  cinfo.output_file = stdout;	/* always the output file */
+
   if (optind < argc-1) {
     fprintf(stderr, "%s: only one input file\n", argv[0]);
     usage(argv[0]);
@@ -261,9 +295,9 @@
   jpeg_compress(&cinfo);
 
   /* Release memory. */
-  j_free_defaults(&cinfo);
+  j_c_free_defaults(&cinfo);
 #ifdef MEM_STATS
-  if (e_methods.trace_level > 0)
+  if (e_methods.trace_level > 0) /* Optional memory-usage statistics */
     j_mem_stats();
 #endif
 
diff --git a/jconfig.h b/jconfig.h
index 3b22acb..9d6883b 100644
--- a/jconfig.h
+++ b/jconfig.h
@@ -21,7 +21,7 @@
  */
 
 /* Does your compiler support function prototypes? */
-/* (If not, you also need to use ansi2knr, see README) */
+/* (If not, you also need to use ansi2knr, see SETUP) */
 
 #ifdef __STDC__			/* ANSI C compilers always have prototypes */
 #define PROTO
@@ -139,6 +139,8 @@
  */
 
 typedef int boolean;
+#undef FALSE			/* in case these macros already exist */
+#undef TRUE
 #define FALSE	0		/* values of boolean */
 #define TRUE	1
 
@@ -171,8 +173,10 @@
 #define JFIF_SUPPORTED		/* JFIF or "raw JPEG" files */
 #undef  JTIFF_SUPPORTED		/* JPEG-in-TIFF (not yet implemented) */
 /* these defines indicate which image (non-JPEG) file formats are allowed */
-#define PPM_SUPPORTED		/* PPM/PGM image file format */
 #define GIF_SUPPORTED		/* GIF image file format */
+/* #define RLE_SUPPORTED */	/* RLE image file format */
+#define PPM_SUPPORTED		/* PPM/PGM image file format */
+#define TARGA_SUPPORTED		/* Targa image file format */
 #undef  TIFF_SUPPORTED		/* TIFF image file format (not yet impl.) */
 
 /* more capability options later, no doubt */
@@ -205,6 +209,8 @@
 /* First define the representation of a single pixel element value. */
 
 #ifdef EIGHT_BIT_SAMPLES
+#define BITS_IN_JSAMPLE  8
+
 /* JSAMPLE should be the smallest type that will hold the values 0..255.
  * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  * If you have only signed chars, and you are more worried about speed than
@@ -237,6 +243,8 @@
 
 
 #ifdef TWELVE_BIT_SAMPLES
+#define BITS_IN_JSAMPLE  12
+
 /* JSAMPLE should be the smallest type that will hold the values 0..4095. */
 /* On nearly all machines "short" will do nicely. */
 
@@ -250,6 +258,8 @@
 
 
 #ifdef SIXTEEN_BIT_SAMPLES
+#define BITS_IN_JSAMPLE  16
+
 /* JSAMPLE should be the smallest type that will hold the values 0..65535. */
 
 #ifdef HAVE_UNSIGNED_SHORT
@@ -312,9 +322,13 @@
 
 /* INT16 must hold at least the values -32768..32767. */
 
+#ifndef XMD_H			/* X11/xmd.h correctly defines INT16 */
 typedef short INT16;
+#endif
 
 /* INT32 must hold signed 32-bit values; if your machine happens */
 /* to have 64-bit longs, you might want to change this. */
 
+#ifndef XMD_H			/* X11/xmd.h correctly defines INT32 */
 typedef long INT32;
+#endif
diff --git a/jcpipe.c b/jcpipe.c
index f58e7db..a911487 100644
--- a/jcpipe.c
+++ b/jcpipe.c
@@ -248,7 +248,7 @@
  * row of whole_scan_MCUs as we can get without exceeding 64KB per row.
  */
 
-#define MAX_WHOLE_ROW_BLOCKS	(65500 / SIZEOF(JBLOCK)) /* max blocks/row */
+#define MAX_WHOLE_ROW_BLOCKS	((int) (65500 / SIZEOF(JBLOCK))) /* max blocks/row */
 
 static big_barray_ptr whole_scan_MCUs; /* Big array for saving the MCUs */
 static int MCUs_in_big_row;	/* # of MCUs in each row of whole_scan_MCUs */
@@ -407,7 +407,8 @@
     
     /* Obtain rows_this_time pixel rows and expand to rows_in_mem rows. */
     /* Then we have exactly DCTSIZE row groups for subsampling. */   
-    rows_this_time = MIN(rows_in_mem, cinfo->image_height - cur_pixel_row);
+    rows_this_time = (int) MIN((long) rows_in_mem,
+			       cinfo->image_height - cur_pixel_row);
  
     (*cinfo->methods->get_sample_rows) (cinfo, rows_this_time,
 					fullsize_data[whichss]);
@@ -569,7 +570,8 @@
     
     /* Obtain rows_this_time pixel rows and expand to rows_in_mem rows. */
     /* Then we have exactly DCTSIZE row groups for subsampling. */   
-    rows_this_time = MIN(rows_in_mem, cinfo->image_height - cur_pixel_row);
+    rows_this_time = (int) MIN((long) rows_in_mem,
+			       cinfo->image_height - cur_pixel_row);
  
     (*cinfo->methods->get_sample_rows) (cinfo, rows_this_time,
 					fullsize_data[whichss]);
diff --git a/jcsample.c b/jcsample.c
index d23e23a..f86034e 100644
--- a/jcsample.c
+++ b/jcsample.c
@@ -63,10 +63,10 @@
       for (v = 0; v < v_expand; v++) {
 	inptr = input_data[inrow+v] + (outcol*h_expand);
 	for (h = 0; h < h_expand; h++) {
-	  outvalue += GETJSAMPLE(*inptr++);
+	  outvalue += (INT32) GETJSAMPLE(*inptr++);
 	}
       }
-      *outptr++ = (outvalue + numpix2) / numpix;
+      *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
     }
     inrow += v_expand;
   }
diff --git a/jdcolor.c b/jdcolor.c
index a39ebff..bc718b7 100644
--- a/jdcolor.c
+++ b/jdcolor.c
@@ -61,15 +61,15 @@
       x = y          + 1436*v + 512; /* red */
       if (x < 0) x = 0;
       if (x > ((INT32) MAXJSAMPLE*1024)) x = (INT32) MAXJSAMPLE*1024;
-      *outptr0++ = x >> 10;
+      *outptr0++ = (JSAMPLE) (x >> 10);
       x = y -  352*u -  731*v + 512; /* green */
       if (x < 0) x = 0;
       if (x > ((INT32) MAXJSAMPLE*1024)) x = (INT32) MAXJSAMPLE*1024;
-      *outptr1++ = x >> 10;
+      *outptr1++ = (JSAMPLE) (x >> 10);
       x = y + 1815*u          + 512; /* blue */
       if (x < 0) x = 0;
       if (x > ((INT32) MAXJSAMPLE*1024)) x = (INT32) MAXJSAMPLE*1024;
-      *outptr2++ = x >> 10;
+      *outptr2++ = (JSAMPLE) (x >> 10);
     }
   }
 }
diff --git a/jddeflts.c b/jddeflts.c
new file mode 100644
index 0000000..ffcc108
--- /dev/null
+++ b/jddeflts.c
@@ -0,0 +1,117 @@
+/*
+ * jddeflts.c
+ *
+ * Copyright (C) 1991, 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 decompressor.
+ * User interfaces do not have to use this file, but those that don't use it
+ * must know more about the innards of the JPEG code.
+ */
+
+#include "jinclude.h"
+
+
+/*
+ * Reload the input buffer after it's been emptied, and return the next byte.
+ * See the JGETC macro for calling conditions.
+ *
+ * This routine is used only if the system-dependent user interface passes
+ * standard_buffering = TRUE to j_d_defaults.  Otherwise, the UI must supply
+ * a corresponding routine.  Note that in any case, this routine is likely
+ * to be used only for JFIF or similar serial-access JPEG file formats.
+ * The input file control module for a random-access format such as TIFF/JPEG
+ * would need to override the read_jpeg_data method with its own routine.
+ *
+ * This routine would need to be replaced if reading JPEG data from something
+ * other than a stdio stream.
+ */
+
+METHODDEF int
+read_jpeg_data (decompress_info_ptr cinfo)
+{
+  cinfo->next_input_byte = cinfo->input_buffer + MIN_UNGET;
+
+  cinfo->bytes_in_buffer = (int) FREAD(cinfo->input_file,
+				       cinfo->next_input_byte,
+				       JPEG_BUF_SIZE);
+  
+  if (cinfo->bytes_in_buffer <= 0)
+    ERREXIT(cinfo->emethods, "Unexpected EOF in JPEG file");
+
+  return JGETC(cinfo);
+}
+
+
+
+/* Default parameter setup for decompression.
+ *
+ * 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).
+ *
+ * standard_buffering should be TRUE if the JPEG data is to come from
+ * a stdio stream and the user interface isn't interested in changing
+ * the normal input-buffering logic.  If FALSE is passed, the user
+ * interface must provide its own read_jpeg_data method and must
+ * set up its own input buffer.  (Alternately, you can pass TRUE to
+ * let the buffer be allocated here, then override read_jpeg_data with
+ * your own routine.)
+ */
+
+GLOBAL void
+j_d_defaults (decompress_info_ptr cinfo, boolean standard_buffering)
+/* NB: the external methods must already be set up. */
+{
+  /* Default to RGB output */
+  /* UI can override by changing out_color_space */
+  cinfo->out_color_space = CS_RGB;
+  cinfo->jpeg_color_space = CS_UNKNOWN;
+  /* Setting any other value in jpeg_color_space overrides heuristics in */
+  /* jrdjfif.c.  That might be useful when reading non-JFIF JPEG files, */
+  /* but ordinarily the UI shouldn't change it. */
+  
+  /* Default to no gamma correction of output */
+  cinfo->output_gamma = 1.0;
+  
+  /* Default to no color quantization */
+  cinfo->quantize_colors = FALSE;
+  /* but set reasonable default parameters for quantization, */
+  /* so that turning on quantize_colors is sufficient to do something useful */
+  cinfo->two_pass_quantize = FALSE; /* may change to TRUE later */
+  cinfo->use_dithering = TRUE;
+  cinfo->desired_number_of_colors = 256;
+  
+  /* Default to no smoothing */
+  cinfo->do_block_smoothing = FALSE;
+  cinfo->do_pixel_smoothing = FALSE;
+  
+  if (standard_buffering) {
+    /* Allocate memory for input buffer. */
+    cinfo->input_buffer = (char *) (*cinfo->emethods->alloc_small)
+					((size_t) (JPEG_BUF_SIZE + MIN_UNGET));
+    cinfo->bytes_in_buffer = 0;	/* initialize buffer to empty */
+
+    /* Install standard buffer-reloading method. */
+    cinfo->methods->read_jpeg_data = read_jpeg_data;
+  }
+}
+
+
+/* This routine releases storage allocated by j_d_defaults.
+ * Note that freeing the method pointer structs and the decompress_info_struct
+ * itself are the responsibility of the user interface.
+ *
+ * standard_buffering must agree with what was passed to j_d_defaults.
+ */
+
+GLOBAL void
+j_d_free_defaults (decompress_info_ptr cinfo, boolean standard_buffering)
+{
+  if (standard_buffering) {
+    (*cinfo->emethods->free_small) ((void *) cinfo->input_buffer);
+  }
+}
diff --git a/jdhuff.c b/jdhuff.c
index e9af688..dd429fc 100644
--- a/jdhuff.c
+++ b/jdhuff.c
@@ -17,7 +17,7 @@
 
 static decompress_info_ptr dcinfo;
 
-static unsigned int get_buffer; /* current bit-extraction buffer */
+static INT32 get_buffer;	/* current bit-extraction buffer */
 static int bits_left;		/* # of unused bits in it */
 
 
@@ -35,8 +35,8 @@
 
   p = 0;
   for (l = 1; l <= 16; l++) {
-    for (i = 1; i <= htbl->bits[l]; i++)
-      huffsize[p++] = l;
+    for (i = 1; i <= (int) htbl->bits[l]; i++)
+      huffsize[p++] = (char) l;
   }
   huffsize[p] = 0;
   lastp = p;
@@ -48,7 +48,7 @@
   si = huffsize[0];
   p = 0;
   while (huffsize[p]) {
-    while (huffsize[p] == si) {
+    while (((int) huffsize[p]) == si) {
       huffcode[p++] = code;
       code++;
     }
@@ -77,10 +77,11 @@
       htbl->maxcode[l] = -1;
     }
   }
+  htbl->maxcode[17] = 0xFFFFFL;	/* ensures huff_DECODE terminates */
 }
 
 
-/* Extract the next N bits from the input stream (N <= 8) */
+/* Extract the next N bits from the input stream (N <= 15) */
 
 LOCAL int
 get_bits (int nbits)
@@ -90,7 +91,8 @@
   while (nbits > bits_left) {
     int c = JGETC(dcinfo);
     
-    get_buffer = (get_buffer << 8) + c;
+    get_buffer <<= 8;
+    get_buffer |= c;
     bits_left += 8;
     /* If it's 0xFF, check and discard stuffed zero byte */
     if (c == 0xff) {
@@ -102,14 +104,14 @@
   }
   
   bits_left -= nbits;
-  result = (get_buffer >> bits_left) & ((1 << nbits) - 1);
+  result = ((int) (get_buffer >> bits_left)) & ((1 << nbits) - 1);
   return result;
 }
 
 /* Macro to make things go at some speed! */
 
 #define get_bit()	(bits_left ? \
-			 ((get_buffer >> (--bits_left)) & 1) : \
+			 ((int) (get_buffer >> (--bits_left))) & 1 : \
 			 get_bits(1))
 
 
@@ -127,15 +129,23 @@
     code = (code << 1) + get_bit();
     l++;
   }
+
+  /* With garbage input we may reach the sentinel value l = 17. */
+
+  if (l > 16) {
+    ERREXIT(dcinfo->emethods, "Corrupted data in JPEG file");
+  }
+
+  p = (int) (htbl->valptr[l] + (code - htbl->mincode[l]));
   
-  p = htbl->valptr[l] + (code - htbl->mincode[l]);
-  
-  return htbl->huffval[p];
+  return (int) htbl->huffval[p];
 }
 
 
 /* Figure 13.4.2.1.1: extend sign bit */
 
+/* NB: on some compilers this will only work for s > 0 */
+
 #define huff_EXTEND(x, s)	((x) < (1 << ((s)-1)) ? \
 				 (x) + (-1 << (s)) + 1 : \
 				 (x))
@@ -156,9 +166,12 @@
   /* Section 13.4.2.1: decode the DC coefficient difference */
 
   s = huff_DECODE(dctbl);
-  r = get_bits(s);
-  block[0] = huff_EXTEND(r, s);
-  
+  if (s) {
+    r = get_bits(s);
+    s = huff_EXTEND(r, s);
+  }
+  block[0] = s;
+
   /* Section 13.4.2.2: decode the AC coefficients */
   
   for (k = 1; k < DCTSIZE2; k++) {
@@ -168,7 +181,7 @@
     n = r >> 4;
     
     if (s) {
-      k = k + n;
+      k += n;
       r = get_bits(s);
       block[k] = huff_EXTEND(r, s);
     } else {
diff --git a/jdmain.c b/jdmain.c
index 109d124..3b60a9d 100644
--- a/jdmain.c
+++ b/jdmain.c
@@ -21,7 +21,7 @@
  */
 
 #include "jinclude.h"
-#ifdef __STDC__
+#ifdef INCLUDES_ARE_ANSI
 #include <stdlib.h>		/* to declare exit() */
 #endif
 
@@ -37,28 +37,35 @@
 #define WRITE_BINARY	"wb"
 #endif
 
+#include "jversion.h"		/* for version message */
+
 
 /*
- * If your system has getopt(3), you can use your library version by
- * defining HAVE_GETOPT.  By default, we use the PD 'egetopt'.
+ * PD version of getopt(3).
  */
 
-#ifdef HAVE_GETOPT
-extern int getopt PP((int argc, char **argv, char *optstring));
-extern char * optarg;
-extern int optind;
-#else
 #include "egetopt.c"
-#define getopt(argc,argv,opt)	egetopt(argc,argv,opt)
-#endif
 
 
-typedef enum {			/* defines known output image formats */
-	FMT_PPM,		/* PPM/PGM (PBMPLUS formats) */
+/*
+ * 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_GIF,		/* GIF format */
+	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;
 
 
@@ -93,6 +100,16 @@
     jselwppm(cinfo);
     break;
 #endif
+#ifdef RLE_SUPPORTED
+  case FMT_RLE:
+    jselwrle(cinfo);
+    break;
+#endif
+#ifdef TARGA_SUPPORTED
+  case FMT_TARGA:
+    jselwtarga(cinfo);
+    break;
+#endif
   default:
     ERREXIT(cinfo->emethods, "Unsupported output file format");
     break;
@@ -100,37 +117,12 @@
 }
 
 
-/*
- * Reload the input buffer after it's been emptied, and return the next byte.
- * See the JGETC macro for calling conditions.
- *
- * This routine would need to be replaced if reading JPEG data from something
- * other than a stdio stream.
- */
-
-METHODDEF int
-read_jpeg_data (decompress_info_ptr cinfo)
-{
-  cinfo->bytes_in_buffer = fread(cinfo->input_buffer + MIN_UNGET,
-				 1, JPEG_BUF_SIZE,
-				 cinfo->input_file);
-  
-  cinfo->next_input_byte = cinfo->input_buffer + MIN_UNGET;
-  
-  if (cinfo->bytes_in_buffer <= 0)
-    ERREXIT(cinfo->emethods, "Unexpected EOF in JPEG file");
-
-  return JGETC(cinfo);
-}
-
-
-
 LOCAL void
 usage (char * progname)
 /* complain about bad command line */
 {
   fprintf(stderr, "usage: %s ", progname);
-  fprintf(stderr, "[-b] [-q colors] [-2] [-d] [-g] [-G]");
+  fprintf(stderr, "[-G] [-P] [-R] [-T] [-b] [-g] [-q colors] [-2] [-D] [-d]");
 #ifdef TWO_FILE_COMMANDLINE
   fprintf(stderr, " inputfile outputfile\n");
 #else
@@ -163,45 +155,36 @@
   jselerror(&e_methods);	/* error/trace message routines */
   jselvirtmem(&e_methods);	/* memory allocation routines */
   dc_methods.d_ui_method_selection = d_ui_method_selection;
-  dc_methods.read_jpeg_data = read_jpeg_data;
 
-  /* Allocate memory for input buffer. */
-  cinfo.input_buffer = (char *) (*cinfo.emethods->alloc_small)
-					((size_t) (JPEG_BUF_SIZE + MIN_UNGET));
-  cinfo.bytes_in_buffer = 0;	/* initialize buffer to empty */
+  /* Set up default JPEG parameters. */
+  j_d_defaults(&cinfo, TRUE);
+  requested_fmt = DEFAULT_FMT;	/* set default output file format */
 
-  /* Set up default input and output file references. */
-  /* (These may be overridden below.) */
-  cinfo.input_file = stdin;
-  cinfo.output_file = stdout;
-
-  /* Set up default parameters. */
-  e_methods.trace_level = 0;
-  cinfo.output_gamma = 1.0;
-  cinfo.quantize_colors = FALSE;
-  cinfo.two_pass_quantize = FALSE;
-  cinfo.use_dithering = FALSE;
-  cinfo.desired_number_of_colors = 256;
-  cinfo.do_block_smoothing = FALSE;
-  cinfo.do_pixel_smoothing = FALSE;
-  cinfo.out_color_space = CS_RGB;
-  cinfo.jpeg_color_space = CS_UNKNOWN;
-  /* setting any other value in jpeg_color_space overrides heuristics */
-  /* in jrdjfif.c ... */
-  /* You may wanta change the default output format; here's the place: */
-#ifdef PPM_SUPPORTED
-  requested_fmt = FMT_PPM;
-#else
-  requested_fmt = FMT_GIF;
-#endif
-
-  /* Scan parameters */
+  /* Scan command line options, adjust parameters */
   
-  while ((c = getopt(argc, argv, "bq:2DdgG")) != EOF)
+  while ((c = egetopt(argc, argv, "GPRTbdgq:2D")) != EOF)
     switch (c) {
+    case 'G':			/* GIF output format. */
+      requested_fmt = FMT_GIF;
+      break;
+    case 'P':			/* PPM output format. */
+      requested_fmt = FMT_PPM;
+      break;
+    case 'R':			/* RLE output format. */
+      requested_fmt = FMT_RLE;
+      break;
+    case 'T':			/* Targa output format. */
+      requested_fmt = FMT_TARGA;
+      break;
     case 'b':			/* Enable cross-block smoothing. */
       cinfo.do_block_smoothing = TRUE;
       break;
+    case 'd':			/* Debugging. */
+      e_methods.trace_level++;
+      break;
+    case 'g':			/* Force grayscale output. */
+      cinfo.out_color_space = CS_GRAYSCALE;
+      break;
     case 'q':			/* Do color quantization. */
       { int val;
 	if (optarg == NULL)
@@ -215,17 +198,8 @@
     case '2':			/* Use two-pass quantization. */
       cinfo.two_pass_quantize = TRUE;
       break;
-    case 'D':			/* Use dithering in color quantization. */
-      cinfo.use_dithering = TRUE;
-      break;
-    case 'd':			/* Debugging. */
-      e_methods.trace_level++;
-      break;
-    case 'g':			/* Force grayscale output. */
-      cinfo.out_color_space = CS_GRAYSCALE;
-      break;
-    case 'G':			/* GIF output format. */
-      requested_fmt = FMT_GIF;
+    case 'D':			/* Suppress dithering in color quantization. */
+      cinfo.use_dithering = FALSE;
       break;
     case '?':
     default:
@@ -233,6 +207,11 @@
       break;
     }
 
+  /* If -d appeared, print version identification */
+  if (e_methods.trace_level > 0)
+    fprintf(stderr, "Independent JPEG Group's DJPEG, version %s\n%s\n",
+	    JVERSION, JCOPYRIGHT);
+
   /* Select the input and output files */
 
 #ifdef TWO_FILE_COMMANDLINE
@@ -252,6 +231,9 @@
 
 #else /* not TWO_FILE_COMMANDLINE -- use Unix style */
 
+  cinfo.input_file = stdin;	/* default input file */
+  cinfo.output_file = stdout;	/* always the output file */
+
   if (optind < argc-1) {
     fprintf(stderr, "%s: only one input file\n", argv[0]);
     usage(argv[0]);
@@ -278,9 +260,9 @@
   jpeg_decompress(&cinfo);
 
   /* Release memory. */
-  (*cinfo.emethods->free_small) ((void *) cinfo.input_buffer);
+  j_d_free_defaults(&cinfo, TRUE);
 #ifdef MEM_STATS
-  if (e_methods.trace_level > 0)
+  if (e_methods.trace_level > 0) /* Optional memory-usage statistics */
     j_mem_stats();
 #endif
 
diff --git a/jdpipe.c b/jdpipe.c
index 8e08874..cdfdf2d 100644
--- a/jdpipe.c
+++ b/jdpipe.c
@@ -1230,7 +1230,8 @@
     }
 
     emit_1pass (cinfo,
-		(int) MIN(rows_in_mem, cinfo->image_height-pixel_rows_output),
+		(int) MIN((long) rows_in_mem,
+			  cinfo->image_height - pixel_rows_output),
 		fullsize_ptrs, color_data);
   }
 
diff --git a/jerror.c b/jerror.c
index 591b185..f719dbc 100644
--- a/jerror.c
+++ b/jerror.c
@@ -21,7 +21,7 @@
  */
 
 #include "jinclude.h"
-#ifdef __STDC__
+#ifdef INCLUDES_ARE_ANSI
 #include <stdlib.h>		/* to declare exit() */
 #endif
 
@@ -30,7 +30,7 @@
 
 
 METHODDEF void
-trace_message (char *msgtext)
+trace_message (const char *msgtext)
 {
   fprintf(stderr, msgtext,
 	  methods->message_parm[0], methods->message_parm[1],
@@ -42,7 +42,7 @@
 
 
 METHODDEF void
-error_exit (char *msgtext)
+error_exit (const char *msgtext)
 {
   trace_message(msgtext);
   exit(1);
diff --git a/jfwddct.c b/jfwddct.c
index 58291ac..21d8448 100644
--- a/jfwddct.c
+++ b/jfwddct.c
@@ -17,96 +17,145 @@
 #include "jinclude.h"
 
 
-/* The poop on this scaling stuff is as follows:
- *
- * Most of the numbers (after multiplication by the constants) are
- * (logically) shifted left by LG2_DCT_SCALE. This is undone by UNFIXH
- * before assignment to the output array. Note that we want an additional
- * division by 2 on the output (required by the equations).
- *
- * If right shifts are unsigned, then there is a potential problem.
- * However, shifting right by 16 and then assigning to a short
- * (assuming short = 16 bits) will keep the sign right!!
- *
- * For other shifts,
- *
- *     ((x + (1 << 30)) >> shft) - (1 << (30 - shft))
- *
- * gives a nice right shift with sign (assuming no overflow). However, all the
- * scaling is such that this isn't a problem. (Is this true?)
+/* We assume that right shift corresponds to signed division by 2 with
+ * rounding towards minus infinity.  This is correct for typical "arithmetic
+ * shift" instructions that shift in copies of the sign bit.  But some
+ * C compilers implement >> with an unsigned shift.  For these machines you
+ * must define RIGHT_SHIFT_IS_UNSIGNED.
+ * RIGHT_SHIFT provides a signed right shift of an INT32 quantity.
+ * It is only applied with constant shift counts.
  */
 
-
-#define ONE 1L			/* remove L if long > 32 bits */
-
 #ifdef RIGHT_SHIFT_IS_UNSIGNED
-#define LG2_DCT_SCALE 15
-#define RIGHT_SHIFT(_x,_shft)   ((((_x) + (ONE << 30)) >> (_shft)) - (ONE << (30 - (_shft))))
+#define SHIFT_TEMPS	INT32 shift_temp;
+#define RIGHT_SHIFT(x,shft)  \
+	((shift_temp = (x)) < 0 ? \
+	 (shift_temp >> (shft)) | ((~0) << (32-(shft))) : \
+	 (shift_temp >> (shft)))
 #else
-#define LG2_DCT_SCALE 16
-#define RIGHT_SHIFT(_x,_shft)   ((_x) >> (_shft))
+#define SHIFT_TEMPS
+#define RIGHT_SHIFT(x,shft)	((x) >> (shft))
 #endif
 
+
+/* The poop on this scaling stuff is as follows:
+ *
+ * We have to do addition and subtraction of the integer inputs, which
+ * is no problem, and multiplication by fractional constants, which is
+ * a problem to do in integer arithmetic.  We multiply all the constants
+ * by DCT_SCALE and convert them to integer constants (thus retaining
+ * LG2_DCT_SCALE bits of precision in the constants).  After doing a
+ * multiplication we have to divide the product by DCT_SCALE, with proper
+ * rounding, to produce the correct output.  The division can be implemented
+ * cheaply as a right shift of LG2_DCT_SCALE bits.  The DCT equations also
+ * specify an additional division by 2 on the final outputs; this can be
+ * folded into the right-shift by shifting one more bit (see UNFIXH).
+ *
+ * If you are planning to recode this in assembler, you might want to set
+ * LG2_DCT_SCALE to 15.  This loses a bit of precision, but then all the
+ * multiplications are between 16-bit quantities (given 8-bit JSAMPLEs!)
+ * so you could use a signed 16x16=>32 bit multiply instruction instead of
+ * full 32x32 multiply.  Unfortunately there's no way to describe such a
+ * multiply portably in C, so we've gone for the extra bit of accuracy here.
+ */
+
+#ifdef EIGHT_BIT_SAMPLES
+#define LG2_DCT_SCALE 16
+#else
+#define LG2_DCT_SCALE 15	/* lose a little precision to avoid overflow */
+#endif
+
+#define ONE	((INT32) 1)
+
 #define DCT_SCALE (ONE << LG2_DCT_SCALE)
 
+/* In some places we shift the inputs left by a couple more bits, */
+/* so that they can be added to fractional results without too much */
+/* loss of precision. */
 #define LG2_OVERSCALE 2
-#define OVERSCALE (ONE << LG2_OVERSCALE)
+#define OVERSCALE  (ONE << LG2_OVERSCALE)
+#define OVERSHIFT(x)  ((x) <<= LG2_OVERSCALE)
 
-#define FIX(x)  ((INT32) ((x) * DCT_SCALE + 0.5))
+/* Scale a fractional constant by DCT_SCALE */
+#define FIX(x)	((INT32) ((x) * DCT_SCALE + 0.5))
+
+/* Scale a fractional constant by DCT_SCALE/OVERSCALE */
+/* Such a constant can be multiplied with an overscaled input */
+/* to produce something that's scaled by DCT_SCALE */
 #define FIXO(x)  ((INT32) ((x) * DCT_SCALE / OVERSCALE + 0.5))
-#define UNFIX(x)   RIGHT_SHIFT((x) + (ONE << (LG2_DCT_SCALE-1)), LG2_DCT_SCALE)
-#define UNFIXH(x)  RIGHT_SHIFT((x) + (ONE << LG2_DCT_SCALE), LG2_DCT_SCALE+1)
-#define UNFIXO(x)  RIGHT_SHIFT((x) + (ONE << (LG2_DCT_SCALE-1-LG2_OVERSCALE)), LG2_DCT_SCALE-LG2_OVERSCALE)
-#define OVERSH(x)   ((x) << LG2_OVERSCALE)
 
-#define SIN_1_4 FIX(0.7071067811856476)
+/* Descale and correctly round a value that's scaled by DCT_SCALE */
+#define UNFIX(x)   RIGHT_SHIFT((x) + (ONE << (LG2_DCT_SCALE-1)), LG2_DCT_SCALE)
+
+/* Same with an additional division by 2, ie, correctly rounded UNFIX(x/2) */
+#define UNFIXH(x)  RIGHT_SHIFT((x) + (ONE << LG2_DCT_SCALE), LG2_DCT_SCALE+1)
+
+/* Take a value scaled by DCT_SCALE and round to integer scaled by OVERSCALE */
+#define UNFIXO(x)  RIGHT_SHIFT((x) + (ONE << (LG2_DCT_SCALE-1-LG2_OVERSCALE)),\
+			       LG2_DCT_SCALE-LG2_OVERSCALE)
+
+/* Here are the constants we need */
+/* SIN_i_j is sine of i*pi/j, scaled by DCT_SCALE */
+/* COS_i_j is cosine of i*pi/j, scaled by DCT_SCALE */
+
+#define SIN_1_4 FIX(0.707106781)
 #define COS_1_4 SIN_1_4
 
-#define SIN_1_8 FIX(0.3826834323650898)
-#define COS_1_8 FIX(0.9238795325112870)
+#define SIN_1_8 FIX(0.382683432)
+#define COS_1_8 FIX(0.923879533)
 #define SIN_3_8 COS_1_8
 #define COS_3_8 SIN_1_8
 
-#define SIN_1_16 FIX(0.1950903220161282)
-#define COS_1_16 FIX(0.9807852804032300)
+#define SIN_1_16 FIX(0.195090322)
+#define COS_1_16 FIX(0.980785280)
 #define SIN_7_16 COS_1_16
 #define COS_7_16 SIN_1_16
 
-#define SIN_3_16 FIX(0.5555702330196022)
-#define COS_3_16 FIX(0.8314696123025450)
+#define SIN_3_16 FIX(0.555570233)
+#define COS_3_16 FIX(0.831469612)
 #define SIN_5_16 COS_3_16
 #define COS_5_16 SIN_3_16
 
-#define OSIN_1_4 FIXO(0.707106781185647)
+/* OSIN_i_j is sine of i*pi/j, scaled by DCT_SCALE/OVERSCALE */
+/* OCOS_i_j is cosine of i*pi/j, scaled by DCT_SCALE/OVERSCALE */
+
+#define OSIN_1_4 FIXO(0.707106781)
 #define OCOS_1_4 OSIN_1_4
 
-#define OSIN_1_8 FIXO(0.3826834323650898)
-#define OCOS_1_8 FIXO(0.9238795325112870)
+#define OSIN_1_8 FIXO(0.382683432)
+#define OCOS_1_8 FIXO(0.923879533)
 #define OSIN_3_8 OCOS_1_8
 #define OCOS_3_8 OSIN_1_8
 
-#define OSIN_1_16 FIXO(0.1950903220161282)
-#define OCOS_1_16 FIXO(0.9807852804032300)
+#define OSIN_1_16 FIXO(0.195090322)
+#define OCOS_1_16 FIXO(0.980785280)
 #define OSIN_7_16 OCOS_1_16
 #define OCOS_7_16 OSIN_1_16
 
-#define OSIN_3_16 FIXO(0.5555702330196022)
-#define OCOS_3_16 FIXO(0.8314696123025450)
+#define OSIN_3_16 FIXO(0.555570233)
+#define OCOS_3_16 FIXO(0.831469612)
 #define OSIN_5_16 OCOS_3_16
 #define OCOS_5_16 OSIN_3_16
 
 
+/*
+ * Perform a 1-dimensional DCT.
+ * Note that this code is specialized to the case DCTSIZE = 8.
+ */
+
 INLINE
 LOCAL void
 fast_dct_8 (DCTELEM *in, int stride)
 {
-  /* tmp1x are new values of tmpx -- flashy register colourers
+  /* many tmps have nonoverlapping lifetime -- flashy register colourers
    * should be able to do this lot very well
    */
-  INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
-  INT32 tmp10, tmp11, tmp12, tmp13, tmp14, tmp15, tmp16, tmp17;
-  INT32 tmp25, tmp26;
   INT32 in0, in1, in2, in3, in4, in5, in6, in7;
+  INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
+  INT32 tmp10, tmp11, tmp12, tmp13;
+  INT32 tmp14, tmp15, tmp16, tmp17;
+  INT32 tmp25, tmp26;
+  SHIFT_TEMPS
   
   in0 = in[       0];
   in1 = in[stride  ];
@@ -126,44 +175,42 @@
   tmp6 = in1 - in6;
   tmp7 = in0 - in7;
   
-  tmp10 = tmp3 + tmp0 ;
-  tmp11 = tmp2 + tmp1 ;
-  tmp12 = tmp1 - tmp2 ;
-  tmp13 = tmp0 - tmp3 ;
+  tmp10 = tmp3 + tmp0;
+  tmp11 = tmp2 + tmp1;
+  tmp12 = tmp1 - tmp2;
+  tmp13 = tmp0 - tmp3;
   
-  /* Now using tmp10, tmp11, tmp12, tmp13 */
+  in[       0] = (DCTELEM) UNFIXH((tmp10 + tmp11) * SIN_1_4);
+  in[stride*4] = (DCTELEM) UNFIXH((tmp10 - tmp11) * COS_1_4);
   
-  in[       0] = UNFIXH((tmp10 + tmp11) * SIN_1_4);
-  in[stride*4] = UNFIXH((tmp10 - tmp11) * COS_1_4);
-  
-  in[stride*2] = UNFIXH(tmp13*COS_1_8 + tmp12*SIN_1_8);
-  in[stride*6] = UNFIXH(tmp13*SIN_1_8 - tmp12*COS_1_8);
-  
+  in[stride*2] = (DCTELEM) UNFIXH(tmp13*COS_1_8 + tmp12*SIN_1_8);
+  in[stride*6] = (DCTELEM) UNFIXH(tmp13*SIN_1_8 - tmp12*COS_1_8);
+
   tmp16 = UNFIXO((tmp6 + tmp5) * SIN_1_4);
   tmp15 = UNFIXO((tmp6 - tmp5) * COS_1_4);
+
+  OVERSHIFT(tmp4);
+  OVERSHIFT(tmp7);
+
+  /* tmp4, tmp7, tmp15, tmp16 are overscaled by OVERSCALE */
+
+  tmp14 = tmp4 + tmp15;
+  tmp25 = tmp4 - tmp15;
+  tmp26 = tmp7 - tmp16;
+  tmp17 = tmp7 + tmp16;
   
-  /* Now using tmp10, tmp11, tmp13, tmp14, tmp15, tmp16 */
-  
-  tmp14 = OVERSH(tmp4) + tmp15;
-  tmp25 = OVERSH(tmp4) - tmp15;
-  tmp26 = OVERSH(tmp7) - tmp16;
-  tmp17 = OVERSH(tmp7) + tmp16;
-  
-  /* These are now overscaled by OVERSCALE */
-  
-  /* tmp10, tmp11, tmp12, tmp13, tmp14, tmp25, tmp26, tmp17 */
-  
-  in[stride  ] = UNFIXH(tmp17*OCOS_1_16 + tmp14*OSIN_1_16);
-  in[stride*7] = UNFIXH(tmp17*OCOS_7_16 - tmp14*OSIN_7_16);
-  in[stride*5] = UNFIXH(tmp26*OCOS_5_16 + tmp25*OSIN_5_16);
-  in[stride*3] = UNFIXH(tmp26*OCOS_3_16 - tmp25*OSIN_3_16);
+  in[stride  ] = (DCTELEM) UNFIXH(tmp17*OCOS_1_16 + tmp14*OSIN_1_16);
+  in[stride*7] = (DCTELEM) UNFIXH(tmp17*OCOS_7_16 - tmp14*OSIN_7_16);
+  in[stride*5] = (DCTELEM) UNFIXH(tmp26*OCOS_5_16 + tmp25*OSIN_5_16);
+  in[stride*3] = (DCTELEM) UNFIXH(tmp26*OCOS_3_16 - tmp25*OSIN_3_16);
 }
 
 
 /*
  * Perform the forward DCT on one block of samples.
  *
- * Note that this code is specialized to the case DCTSIZE = 8.
+ * A 2-D DCT can be done by 1-D DCT on each row
+ * followed by 1-D DCT on each column.
  */
 
 GLOBAL void
diff --git a/jinclude.h b/jinclude.h
index ec7a7e8..779c61d 100644
--- a/jinclude.h
+++ b/jinclude.h
@@ -14,6 +14,19 @@
 
 
 /*
+ * Normally the __STDC__ macro can be taken as indicating that the system
+ * include files conform to the ANSI C standard.  However, if you are running
+ * GCC on a machine with non-ANSI system include files, that is not the case.
+ * In that case change the following, or add -DNONANSI_INCLUDES to your CFLAGS.
+ */
+
+#ifdef __STDC__
+#ifndef NONANSI_INCLUDES
+#define INCLUDES_ARE_ANSI	/* this is what's tested before including */
+#endif
+#endif
+
+/*
  * <stdio.h> is included to get the FILE typedef and NULL macro.
  * Note that the core portable-JPEG files do not actually do any I/O
  * using the stdio library; only the user interface, error handler,
@@ -27,11 +40,15 @@
  * We need the size_t typedef, which defines the parameter type of malloc().
  * In an ANSI-conforming implementation this is provided by <stdio.h>,
  * but on non-ANSI systems it's more likely to be in <sys/types.h>.
+ * On some not-quite-ANSI systems you may find it in <stddef.h>.
  */
 
-#ifndef __STDC__		/* shouldn't need this if __STDC__ */
+#ifndef INCLUDES_ARE_ANSI	/* shouldn't need this if ANSI C */
 #include <sys/types.h>
 #endif
+#ifdef __SASC			/* Amiga SAS C provides it in stddef.h. */
+#include <stddef.h>
+#endif
 
 /*
  * In ANSI C, and indeed any rational implementation, size_t is also the
@@ -41,9 +58,21 @@
  * we always use this SIZEOF() macro in place of using sizeof() directly.
  */
 
+#undef SIZEOF			/* in case you included X11/xmd.h */
 #define SIZEOF(object)	((size_t) sizeof(object))
 
 /*
+ * fread() and fwrite() are always invoked through these macros.
+ * On some systems you may need to twiddle the argument casts.
+ * CAUTION: argument order is different from underlying functions!
+ */
+
+#define FREAD(file,buf,sizeofbuf)  \
+  ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
+#define FWRITE(file,buf,sizeofbuf)  \
+  ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
+
+/*
  * We need the memcpy() and strcmp() functions, plus memory zeroing.
  * ANSI and System V implementations declare these in <string.h>.
  * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
@@ -51,10 +80,10 @@
  * Insert casts in these macros if not!
  */
 
-#ifdef __STDC__
+#ifdef INCLUDES_ARE_ANSI
 #include <string.h>
 #define MEMZERO(voidptr,size)	memset((voidptr), 0, (size))
-#else /* not STDC */
+#else /* not ANSI */
 #ifdef BSD
 #include <strings.h>
 #define MEMZERO(voidptr,size)	bzero((voidptr), (size))
@@ -63,7 +92,7 @@
 #include <string.h>
 #define MEMZERO(voidptr,size)	memset((voidptr), 0, (size))
 #endif /* BSD */
-#endif /* STDC */
+#endif /* ANSI */
 
 
 /* Now include the portable JPEG definition files. */
diff --git a/jpegdata.h b/jpegdata.h
index 3e4d753..947a8af 100644
--- a/jpegdata.h
+++ b/jpegdata.h
@@ -200,7 +200,8 @@
 	UINT16 ehufco[256];	/* code for each symbol */
 	char ehufsi[256];	/* length of code for each symbol */
 	UINT16 mincode[17];	/* smallest code of length k */
-	INT32 maxcode[17];	/* largest code of length k (-1 if none) */
+	INT32 maxcode[18];	/* largest code of length k (-1 if none) */
+	/* maxcode[17] is a sentinel to ensure huff_DECODE terminates */
 	short valptr[17];	/* huffval[] index of 1st symbol of length k */
 } HUFF_TBL;
 
@@ -220,7 +221,7 @@
  * All of these fields shall be established by the user interface before
  * calling jpeg_compress, or by the input_init or c_ui_method_selection
  * methods.
- * Most parameters can be set to reasonable defaults by j_default_compression.
+ * Most parameters can be set to reasonable defaults by j_c_defaults.
  * Note that the UI must supply the storage for the main methods struct,
  * though it sets only a few of the methods there.
  */
@@ -309,8 +310,10 @@
 struct decompress_info_struct {
 /*
  * These fields shall be established by the user interface before
- * calling jpeg_decompress.  Note that the UI must supply the storage for
- * the main methods struct, though it sets only a few of the methods there.
+ * calling jpeg_decompress.
+ * Most parameters can be set to reasonable defaults by j_d_defaults.
+ * Note that the UI must supply the storage for the main methods struct,
+ * though it sets only a few of the methods there.
  */
 	decompress_methods_ptr methods; /* Points to list of methods to use */
 
@@ -425,7 +428,7 @@
 #ifdef CHAR_IS_UNSIGNED
 #define JGETC(cinfo)	( --(cinfo)->bytes_in_buffer < 0 ? \
 			 (*(cinfo)->methods->read_jpeg_data) (cinfo) : \
-			 (int) *(cinfo)->next_input_byte++ )
+			 (int) (*(cinfo)->next_input_byte++) )
 #else
 #define JGETC(cinfo)	( --(cinfo)->bytes_in_buffer < 0 ? \
 			 (*(cinfo)->methods->read_jpeg_data) (cinfo) : \
@@ -435,17 +438,34 @@
 #define JUNGETC(ch,cinfo)  ((cinfo)->bytes_in_buffer++, \
 			    *(--((cinfo)->next_input_byte)) = (ch))
 
-#define MIN_UNGET	2	/* may always do at least 2 JUNGETCs */
+#define MIN_UNGET	4	/* may always do at least 4 JUNGETCs */
 
 
 /* A virtual image has a control block whose contents are private to the
  * memory manager module (and may differ between managers).  The rest of the
- * code only refers to virtual images by these pointer types.
+ * code only refers to virtual images by these pointer types, and never
+ * dereferences the pointer.
  */
 
 typedef struct big_sarray_control * big_sarray_ptr;
 typedef struct big_barray_control * big_barray_ptr;
 
+/* Although a real ANSI C compiler can deal perfectly well with pointers to
+ * unspecified structures (see "incomplete types" in the spec), a few pre-ANSI
+ * and pseudo-ANSI compilers get confused.  To keep one of these bozos happy,
+ * add -DINCOMPLETE_TYPES_BROKEN to CFLAGS in your Makefile.  Then we will
+ * pseudo-define the structs as containing a single "dummy" field.
+ * The memory manager(s) #define AM_MEMORY_MANAGER before including this file,
+ * so that they can make their own definitions of the structs.
+ */
+
+#ifdef INCOMPLETE_TYPES_BROKEN
+#ifndef AM_MEMORY_MANAGER
+struct big_sarray_control { long dummy; };
+struct big_barray_control { long dummy; };
+#endif
+#endif
+
 
 /* Method types that need typedefs */
 
@@ -490,8 +510,8 @@
 	/* by an enumerated-type code so that non-English error messages */
 	/* can be substituted easily.  This will not be done until all the */
 	/* code is in place, so that we know what messages are needed. */
-	METHOD(void, error_exit, (char *msgtext));
-	METHOD(void, trace_message, (char *msgtext));
+	METHOD(void, error_exit, (const char *msgtext));
+	METHOD(void, trace_message, (const char *msgtext));
 
 	/* Working data for error/trace facility */
 	/* See macros below for the usage of these variables */
@@ -559,42 +579,36 @@
 					 (emeth)->message_parm[3] = (p4), \
 					 (*(emeth)->error_exit) (msg))
 
+#define MAKESTMT(stuff)		do { stuff } while (0)
+
 #define TRACEMS(emeth,lvl,msg)    \
-  ( (emeth)->trace_level >= (lvl) ? \
-   ((*(emeth)->trace_message) (msg), 0) : 0)
+  MAKESTMT( if ((emeth)->trace_level >= (lvl)) { \
+		(*(emeth)->trace_message) (msg); } )
 #define TRACEMS1(emeth,lvl,msg,p1)    \
-  ( (emeth)->trace_level >= (lvl) ? \
-   ((emeth)->message_parm[0] = (p1), \
-    (*(emeth)->trace_message) (msg), 0) : 0)
+  MAKESTMT( if ((emeth)->trace_level >= (lvl)) { \
+		(emeth)->message_parm[0] = (p1); \
+		(*(emeth)->trace_message) (msg); } )
 #define TRACEMS2(emeth,lvl,msg,p1,p2)    \
-  ( (emeth)->trace_level >= (lvl) ? \
-   ((emeth)->message_parm[0] = (p1), \
-    (emeth)->message_parm[1] = (p2), \
-    (*(emeth)->trace_message) (msg), 0) : 0)
+  MAKESTMT( if ((emeth)->trace_level >= (lvl)) { \
+		(emeth)->message_parm[0] = (p1); \
+		(emeth)->message_parm[1] = (p2); \
+		(*(emeth)->trace_message) (msg); } )
 #define TRACEMS3(emeth,lvl,msg,p1,p2,p3)    \
-  ( (emeth)->trace_level >= (lvl) ? \
-   ((emeth)->message_parm[0] = (p1), \
-    (emeth)->message_parm[1] = (p2), \
-    (emeth)->message_parm[2] = (p3), \
-    (*(emeth)->trace_message) (msg), 0) : 0)
+  MAKESTMT( if ((emeth)->trace_level >= (lvl)) { \
+		int * _mp = (emeth)->message_parm; \
+		*_mp++ = (p1); *_mp++ = (p2); *_mp = (p3); \
+		(*(emeth)->trace_message) (msg); } )
 #define TRACEMS4(emeth,lvl,msg,p1,p2,p3,p4)    \
-  ( (emeth)->trace_level >= (lvl) ? \
-   ((emeth)->message_parm[0] = (p1), \
-    (emeth)->message_parm[1] = (p2), \
-    (emeth)->message_parm[2] = (p3), \
-    (emeth)->message_parm[3] = (p4), \
-    (*(emeth)->trace_message) (msg), 0) : 0)
+  MAKESTMT( if ((emeth)->trace_level >= (lvl)) { \
+		int * _mp = (emeth)->message_parm; \
+		*_mp++ = (p1); *_mp++ = (p2); *_mp++ = (p3); *_mp = (p4); \
+		(*(emeth)->trace_message) (msg); } )
 #define TRACEMS8(emeth,lvl,msg,p1,p2,p3,p4,p5,p6,p7,p8)    \
-  ( (emeth)->trace_level >= (lvl) ? \
-   ((emeth)->message_parm[0] = (p1), \
-    (emeth)->message_parm[1] = (p2), \
-    (emeth)->message_parm[2] = (p3), \
-    (emeth)->message_parm[3] = (p4), \
-    (emeth)->message_parm[4] = (p5), \
-    (emeth)->message_parm[5] = (p6), \
-    (emeth)->message_parm[6] = (p7), \
-    (emeth)->message_parm[7] = (p8), \
-    (*(emeth)->trace_message) (msg), 0) : 0)
+  MAKESTMT( if ((emeth)->trace_level >= (lvl)) { \
+		int * _mp = (emeth)->message_parm; \
+		*_mp++ = (p1); *_mp++ = (p2); *_mp++ = (p3); *_mp++ = (p4); \
+		*_mp++ = (p5); *_mp++ = (p6); *_mp++ = (p7); *_mp = (p8); \
+		(*(emeth)->trace_message) (msg); } )
 
 
 /* Methods used during JPEG compression. */
@@ -740,16 +754,24 @@
 
 /* main entry for compression */
 EXTERN void jpeg_compress PP((compress_info_ptr cinfo));
+
 /* default parameter setup for compression */
-EXTERN void j_default_compression PP((compress_info_ptr cinfo, int quality));
+EXTERN void j_c_defaults PP((compress_info_ptr cinfo, int quality,
+			     boolean force_baseline));
 EXTERN void j_monochrome_default PP((compress_info_ptr cinfo));
 EXTERN void j_set_quality PP((compress_info_ptr cinfo, int quality,
 			      boolean force_baseline));
-EXTERN void j_free_defaults PP((compress_info_ptr cinfo));
+EXTERN void j_c_free_defaults PP((compress_info_ptr cinfo));
 
 /* main entry for decompression */
 EXTERN void jpeg_decompress PP((decompress_info_ptr cinfo));
 
+/* default parameter setup for decompression */
+EXTERN void j_d_defaults PP((decompress_info_ptr cinfo,
+			     boolean standard_buffering));
+EXTERN void j_d_free_defaults PP((decompress_info_ptr cinfo,
+				  boolean standard_buffering));
+
 /* forward DCT */
 EXTERN void j_fwd_dct PP((DCTBLOCK data));
 /* inverse DCT */
@@ -775,6 +797,8 @@
 /* The user interface should call one of these to select input format: */
 EXTERN void jselrgif PP((compress_info_ptr cinfo)); /* jrdgif.c */
 EXTERN void jselrppm PP((compress_info_ptr cinfo)); /* jrdppm.c */
+EXTERN void jselrrle PP((compress_info_ptr cinfo)); /* jrdrle.c */
+EXTERN void jselrtarga PP((compress_info_ptr cinfo)); /* jrdtarga.c */
 /* and one of these to select output header format: */
 EXTERN void jselwjfif PP((compress_info_ptr cinfo)); /* jwrjfif.c */
 
@@ -793,6 +817,8 @@
 /* and one of these to select output image format: */
 EXTERN void jselwgif PP((decompress_info_ptr cinfo)); /* jwrgif.c */
 EXTERN void jselwppm PP((decompress_info_ptr cinfo)); /* jwrppm.c */
+EXTERN void jselwrle PP((decompress_info_ptr cinfo)); /* jwrrle.c */
+EXTERN void jselwtarga PP((decompress_info_ptr cinfo)); /* jwrtarga.c */
 
 /* method selection routines for system-dependent modules */
 EXTERN void jselerror PP((external_methods_ptr emethods)); /* jerror.c */
@@ -805,7 +831,9 @@
 
 /* Miscellaneous useful macros */
 
+#undef MAX
 #define MAX(a,b)	((a) > (b) ? (a) : (b))
+#undef MIN
 #define MIN(a,b)	((a) < (b) ? (a) : (b))
 
 
diff --git a/jquant1.c b/jquant1.c
index 49dfd97..ea01c23 100644
--- a/jquant1.c
+++ b/jquant1.c
@@ -60,7 +60,7 @@
  */
 
 #ifdef EIGHT_BIT_SAMPLES
-typedef short FSERROR;		/* 16 bits should be enough */
+typedef INT16 FSERROR;		/* 16 bits should be enough */
 #else
 typedef INT32 FSERROR;		/* may need more than 16 bits? */
 #endif
@@ -135,11 +135,13 @@
     nci = Ncolors[i];		/* # of distinct values for this color */
     blksize = blkdist / nci;
     for (j = 0; j < nci; j++) {
-      val = (j * MAXJSAMPLE + (nci-1)/2) / (nci-1); /* j'th value of color */
+      /* Compute j'th output value (out of nci) for component */
+      val = (j * MAXJSAMPLE + (nci-1)/2) / (nci-1);
+      /* Fill in all colormap entries that have this value of this component */
       for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
 	/* fill in blksize entries beginning at ptr */
 	for (k = 0; k < blksize; k++)
-	  colormap[i][ptr+k] = val;
+	  colormap[i][ptr+k] = (JSAMPLE) val;
       }
     }
     blkdist = blksize;		/* blksize of this color is blkdist of next */
@@ -149,8 +151,7 @@
       /* compute index of color closest to pixel value j */
       val = (j * (nci-1) + CENTERJSAMPLE) / MAXJSAMPLE;
       /* premultiply so that no multiplication needed in main processing */
-      val *= blksize;
-      colorindex[i][j] = val;
+      colorindex[i][j] = (JSAMPLE) (val * blksize);
     }
   }
 
@@ -196,7 +197,7 @@
 	pixcode += GETJSAMPLE(colorindex[ci]
 			      [GETJSAMPLE(input_data[ci][row][col])]);
       }
-      output_data[row][col] = pixcode;
+      output_data[row][col] = (JSAMPLE) pixcode;
     }
   }
 }
@@ -222,7 +223,7 @@
       pixcode  = GETJSAMPLE(colorindex[0][GETJSAMPLE(*ptr0++)]);
       pixcode += GETJSAMPLE(colorindex[1][GETJSAMPLE(*ptr1++)]);
       pixcode += GETJSAMPLE(colorindex[2][GETJSAMPLE(*ptr2++)]);
-      *ptrout++ = pixcode;
+      *ptrout++ = (JSAMPLE) pixcode;
     }
   }
 }
@@ -255,7 +256,7 @@
 	  /* compute pixel value + accumulated error */
 	  val = (((FSERROR) GETJSAMPLE(input_data[ci][row][col])) << 4)
 		+ thisrowerr[ci];
-	  if (val < 0) val = 0;	/* must watch for range overflow! */
+	  if (val <= 0) val = 0; /* must watch for range overflow! */
 	  else {
 	    val += 8;		/* divide by 16 with proper rounding */
 	    val >>= 4;
@@ -264,10 +265,10 @@
 	  thisrowerr[ci] = val;	/* save for error propagation */
 	  pixcode += GETJSAMPLE(colorindex[ci][val]);
 	}
-	output_data[row][col] = pixcode;
+	output_data[row][col] = (JSAMPLE) pixcode;
 	/* propagate error to adjacent pixels */
 	for (ci = 0; ci < nc; ci++) {
-	  val = thisrowerr[ci] - GETJSAMPLE(colormap[ci][pixcode]);
+	  val = thisrowerr[ci] - (FSERROR) GETJSAMPLE(colormap[ci][pixcode]);
 	  thisrowerr[ci-nc] += val * 7;
 	  nextrowerr[ci+nc] += val * 3;
 	  nextrowerr[ci   ] += val * 5;
@@ -290,7 +291,7 @@
 	  /* compute pixel value + accumulated error */
 	  val = (((FSERROR) GETJSAMPLE(input_data[ci][row][col])) << 4)
 		+ thisrowerr[ci];
-	  if (val < 0) val = 0;	/* must watch for range overflow! */
+	  if (val <= 0) val = 0; /* must watch for range overflow! */
 	  else {
 	    val += 8;		/* divide by 16 with proper rounding */
 	    val >>= 4;
@@ -299,10 +300,10 @@
 	  thisrowerr[ci] = val;	/* save for error propagation */
 	  pixcode += GETJSAMPLE(colorindex[ci][val]);
 	}
-	output_data[row][col] = pixcode;
+	output_data[row][col] = (JSAMPLE) pixcode;
 	/* propagate error to adjacent pixels */
 	for (ci = 0; ci < nc; ci++) {
-	  val = thisrowerr[ci] - GETJSAMPLE(colormap[ci][pixcode]);
+	  val = thisrowerr[ci] - (FSERROR) GETJSAMPLE(colormap[ci][pixcode]);
 	  thisrowerr[ci+nc] += val * 7;
 	  nextrowerr[ci-nc] += val * 3;
 	  nextrowerr[ci   ] += val * 5;
diff --git a/jrdgif.c b/jrdgif.c
index e2d4b33..7b6bd6d 100644
--- a/jrdgif.c
+++ b/jrdgif.c
@@ -62,7 +62,7 @@
 #define INTERLACE	0x40	/* mask for bit signifying interlaced image */
 #define COLORMAPFLAG	0x80	/* mask for bit signifying colormap presence */
 
-#define	ReadOK(file,buffer,len)	(fread(buffer, 1, len, file) == (len))
+#define	ReadOK(file,buffer,len)	(FREAD(file,buffer,len) == ((size_t) (len)))
 
 /* Static vars for GetCode and LZWReadByte */
 
@@ -261,7 +261,7 @@
 
   /* If any codes are stacked from a previously read symbol, return them */
   if (sp > symbol_stack)
-    return *(--sp);
+    return (int) *(--sp);
 
   code = GetCode(cinfo);
 
@@ -286,7 +286,7 @@
   incode = code;		/* save for a moment */
   
   if (code >= max_code) {	/* special case for not-yet-defined symbol */
-    *sp++ = firstcode;		/* it will be defined as oldcode/firstcode */
+    *sp++ = (UINT8) firstcode;	/* it will be defined as oldcode/firstcode */
     code = oldcode;
   }
 
@@ -302,7 +302,7 @@
   if ((code = max_code) < LZW_TABLE_SIZE) {
     /* Define a new symbol = prev sym + head of this sym's expansion */
     symbol_head[code] = oldcode;
-    symbol_tail[code] = firstcode;
+    symbol_tail[code] = (UINT8) firstcode;
     max_code++;
     /* Is it time to increase code_size? */
     if ((max_code >= limit_code) && (code_size < MAX_LZW_BITS)) {
@@ -323,9 +323,9 @@
   int i;
 
   for (i = 0; i < cmaplen; i++) {
-    cmap[CM_RED][i]   = ReadByte(cinfo);
-    cmap[CM_GREEN][i] = ReadByte(cinfo);
-    cmap[CM_BLUE][i]  = ReadByte(cinfo);
+    cmap[CM_RED][i]   = (JSAMPLE) ReadByte(cinfo);
+    cmap[CM_GREEN][i] = (JSAMPLE) ReadByte(cinfo);
+    cmap[CM_BLUE][i]  = (JSAMPLE) ReadByte(cinfo);
   }
 }
 
@@ -457,7 +457,7 @@
      * of get_input_row.
      */
     interlaced_image = (*cinfo->emethods->request_big_sarray)
-		((long) width, (long) height, (long) 1);
+		((long) width, (long) height, 1L);
     cinfo->methods->get_input_row = load_interlaced_image;
   }
 
@@ -519,7 +519,7 @@
     for (col = cinfo->image_width; col > 0; col--) {
       if ((c = LZWReadByte(cinfo)) < 0)
 	ERREXIT(cinfo->emethods, "Premature end of GIF image");
-      *sptr++ = c;
+      *sptr++ = (JSAMPLE) c;
     }
   }
 
diff --git a/jrdjfif.c b/jrdjfif.c
index 5ff14ba..0729b67 100644
--- a/jrdjfif.c
+++ b/jrdjfif.c
@@ -98,11 +98,11 @@
 METHODDEF int
 read_jpeg_data (decompress_info_ptr cinfo)
 {
-  cinfo->bytes_in_buffer = fread(cinfo->input_buffer + MIN_UNGET,
-				 1, JPEG_BUF_SIZE,
-				 cinfo->input_file);
-  
   cinfo->next_input_byte = cinfo->input_buffer + MIN_UNGET;
+
+  cinfo->bytes_in_buffer = (int) FREAD(cinfo->input_file,
+				       cinfo->next_input_byte,
+				       JPEG_BUF_SIZE);
   
   if (cinfo->bytes_in_buffer <= 0)
     ERREXIT(cinfo->emethods, "Unexpected EOF in JPEG file");
@@ -138,7 +138,7 @@
   length = get_2bytes(cinfo);
   
   TRACEMS2(cinfo->emethods, 1,
-	   "Skipping marker 0x%02x, length %d", code, length);
+	   "Skipping marker 0x%02x, length %u", code, (int) length);
   
   for (length -= 2; length > 0; length--)
     (void) JGETC(cinfo);
@@ -165,7 +165,7 @@
     bits[0] = 0;
     count = 0;
     for (i = 1; i <= 16; i++) {
-      bits[i] = JGETC(cinfo);
+      bits[i] = (UINT8) JGETC(cinfo);
       count += bits[i];
     }
 
@@ -180,7 +180,7 @@
       ERREXIT(cinfo->emethods, "Bogus DHT counts");
 
     for (i = 0; i < count; i++)
-      huffval[i] = JGETC(cinfo);
+      huffval[i] = (UINT8) JGETC(cinfo);
 
     length -= 1 + 16 + count;
 
@@ -195,7 +195,7 @@
       ERREXIT1(cinfo->emethods, "Bogus DHT index %d", index);
 
     if (*htblptr == NULL)
-      *htblptr = (*cinfo->emethods->alloc_small) (SIZEOF(HUFF_TBL));
+      *htblptr = (HUFF_TBL *) (*cinfo->emethods->alloc_small) (SIZEOF(HUFF_TBL));
   
     memcpy((void *) (*htblptr)->bits, (void *) bits,
 	   SIZEOF((*htblptr)->bits));
@@ -225,10 +225,10 @@
       ERREXIT1(cinfo->emethods, "Bogus DAC index %d", index);
 
     if (index >= NUM_ARITH_TBLS) { /* define AC table */
-      cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = val;
+      cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
     } else {			/* define DC table */
-      cinfo->arith_dc_L[index] = val & 0x0F;
-      cinfo->arith_dc_U[index] = val >> 4;
+      cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
+      cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
       if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
 	ERREXIT1(cinfo->emethods, "Bogus DAC value 0x%x", val);
     }
@@ -261,7 +261,8 @@
       ERREXIT1(cinfo->emethods, "Bogus table number %d", n);
       
     if (cinfo->quant_tbl_ptrs[n] == NULL)
-      cinfo->quant_tbl_ptrs[n] = (*cinfo->emethods->alloc_small) (SIZEOF(QUANT_TBL));
+      cinfo->quant_tbl_ptrs[n] = (QUANT_TBL_PTR)
+	(*cinfo->emethods->alloc_small) (SIZEOF(QUANT_TBL));
     quant_ptr = cinfo->quant_tbl_ptrs[n];
 
     for (i = 0; i < DCTSIZE2; i++) {
@@ -290,7 +291,7 @@
   if (get_2bytes(cinfo) != 4)
     ERREXIT(cinfo->emethods, "Bogus length in DRI");
 
-  cinfo->restart_interval = get_2bytes(cinfo);
+  cinfo->restart_interval = (UINT16) get_2bytes(cinfo);
 
   TRACEMS1(cinfo->emethods, 1,
 	   "Define Restart Interval %d", cinfo->restart_interval);
@@ -312,7 +313,7 @@
 
   if (length >= JFIF_LEN) {
     for (buffp = 0; buffp < JFIF_LEN; buffp++)
-      b[buffp] = JGETC(cinfo);
+      b[buffp] = (UINT8) JGETC(cinfo);
     length -= JFIF_LEN;
 
     if (b[0]=='J' && b[1]=='F' && b[2]=='I' && b[3]=='F' && b[4]==0) {
@@ -364,8 +365,8 @@
   cinfo->num_components = JGETC(cinfo);
 
   TRACEMS4(cinfo->emethods, 1,
-	   "Start Of Frame 0x%02x: width=%d, height=%d, components=%d",
-	   code, cinfo->image_width, cinfo->image_height,
+	   "Start Of Frame 0x%02x: width=%u, height=%u, components=%d",
+	   code, (int) cinfo->image_width, (int) cinfo->image_height,
 	   cinfo->num_components);
 
   /* We don't support files in which the image height is initially specified */
@@ -391,7 +392,7 @@
   if (length != (cinfo->num_components * 3 + 8))
     ERREXIT(cinfo->emethods, "Bogus SOF length");
 
-  cinfo->comp_info = (*cinfo->emethods->alloc_small)
+  cinfo->comp_info = (jpeg_component_info *) (*cinfo->emethods->alloc_small)
 			(cinfo->num_components * SIZEOF(jpeg_component_info));
   
   for (ci = 0; ci < cinfo->num_components; ci++) {
@@ -538,7 +539,7 @@
     case M_SOI:
     case M_EOI:
     case M_SOS:
-      return c;
+      return ((JPEG_MARKER) c);
       
     case M_DHT:
       get_dht(cinfo);
diff --git a/jrdppm.c b/jrdppm.c
index 15e2393..f10e0f6 100644
--- a/jrdppm.c
+++ b/jrdppm.c
@@ -6,7 +6,8 @@
  * For conditions of distribution and use, see the accompanying README file.
  *
  * This file contains routines to read input images in PPM format.
- * The PBMPLUS library is required (well, it will be in the real version).
+ * The PBMPLUS library is NOT required to compile this software,
+ * but it is highly useful as a set of PPM image manipulation programs.
  *
  * These routines may need modification for non-Unix environments or
  * specialized applications.  As they stand, they assume input from
@@ -24,6 +25,194 @@
 #ifdef PPM_SUPPORTED
 
 
+static JSAMPLE * rescale;	/* => maxval-remapping array, or NULL */
+
+
+/* Portions of this code are based on the PBMPLUS library, which is:
+**
+** Copyright (C) 1988 by Jef Poskanzer.
+**
+** Permission to use, copy, modify, and distribute this software and its
+** documentation for any purpose and without fee is hereby granted, provided
+** that the above copyright notice appear in all copies and that both that
+** copyright notice and this permission notice appear in supporting
+** documentation.  This software is provided "as is" without express or
+** implied warranty.
+*/
+
+
+LOCAL int
+pbm_getc (FILE * file)
+/* Read next char, skipping over any comments */
+/* 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 unsigned int
+read_pbm_integer (compress_info_ptr cinfo)
+/* Read an unsigned decimal integer from the PPM file */
+/* Swallows one trailing character after the integer */
+/* Note that on a 16-bit-int machine, only values up to 64k can be read. */
+/* This should not be a problem in practice. */
+{
+  register int ch;
+  register unsigned int val;
+  
+  /* Skip any leading whitespace */
+  do {
+    ch = pbm_getc(cinfo->input_file);
+    if (ch == EOF)
+      ERREXIT(cinfo->emethods, "Premature EOF in PPM file");
+  } while (ch == ' ' || ch == '\t' || ch == '\n');
+  
+  if (ch < '0' || ch > '9')
+    ERREXIT(cinfo->emethods, "Bogus data in PPM file");
+  
+  val = ch - '0';
+  while ((ch = pbm_getc(cinfo->input_file)) >= '0' && ch <= '9') {
+    val *= 10;
+    val += ch - '0';
+  }
+  return val;
+}
+
+
+/*
+ * Read one row of pixels.
+ *
+ * We provide several different versions depending on input file format.
+ * In all cases, input is scaled to the size of JSAMPLE; it's possible that
+ * when JSAMPLE is 12 bits, this would not really be desirable.
+ *
+ * Note that a really fast path is provided for reading raw files with
+ * maxval = MAXJSAMPLE, which is the normal case (at least for 8-bit JSAMPLEs).
+ */
+
+
+METHODDEF void
+get_text_gray_row (compress_info_ptr cinfo, JSAMPARRAY pixel_row)
+/* This version is for reading text-format PGM files with any maxval */
+{
+  register JSAMPROW ptr0;
+  register unsigned int val;
+  register long col;
+  
+  ptr0 = pixel_row[0];
+  for (col = cinfo->image_width; col > 0; col--) {
+    val = read_pbm_integer(cinfo);
+    if (rescale != NULL)
+      val = rescale[val];
+    *ptr0++ = (JSAMPLE) val;
+  }
+}
+
+
+METHODDEF void
+get_text_rgb_row (compress_info_ptr cinfo, JSAMPARRAY pixel_row)
+/* This version is for reading text-format PPM files with any maxval */
+{
+  register JSAMPROW ptr0, ptr1, ptr2;
+  register unsigned int val;
+  register long col;
+  
+  ptr0 = pixel_row[0];
+  ptr1 = pixel_row[1];
+  ptr2 = pixel_row[2];
+  for (col = cinfo->image_width; col > 0; col--) {
+    val = read_pbm_integer(cinfo);
+    if (rescale != NULL)
+      val = rescale[val];
+    *ptr0++ = (JSAMPLE) val;
+    val = read_pbm_integer(cinfo);
+    if (rescale != NULL)
+      val = rescale[val];
+    *ptr1++ = (JSAMPLE) val;
+    val = read_pbm_integer(cinfo);
+    if (rescale != NULL)
+      val = rescale[val];
+    *ptr2++ = (JSAMPLE) val;
+  }
+}
+
+
+METHODDEF void
+get_scaled_gray_row (compress_info_ptr cinfo, JSAMPARRAY pixel_row)
+/* This version is for reading raw-format PGM files with any maxval */
+{
+  register FILE * infile = cinfo->input_file;
+  register JSAMPROW ptr0;
+  register long col;
+  
+  ptr0 = pixel_row[0];
+  for (col = cinfo->image_width; col > 0; col--) {
+    *ptr0++ = rescale[getc(infile)];
+  }
+}
+
+
+METHODDEF void
+get_scaled_rgb_row (compress_info_ptr cinfo, JSAMPARRAY pixel_row)
+/* This version is for reading raw-format PPM files with any maxval */
+{
+  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 = cinfo->image_width; col > 0; col--) {
+    *ptr0++ = rescale[getc(infile)];
+    *ptr1++ = rescale[getc(infile)];
+    *ptr2++ = rescale[getc(infile)];
+  }
+}
+
+
+METHODDEF void
+get_raw_gray_row (compress_info_ptr cinfo, JSAMPARRAY pixel_row)
+/* This version is for reading raw-format PGM files with maxval = MAXJSAMPLE */
+{
+  register FILE * infile = cinfo->input_file;
+  register JSAMPROW ptr0;
+  register long col;
+  
+  ptr0 = pixel_row[0];
+  for (col = cinfo->image_width; col > 0; col--) {
+    *ptr0++ = (JSAMPLE) getc(infile);
+  }
+}
+
+
+METHODDEF void
+get_raw_rgb_row (compress_info_ptr cinfo, JSAMPARRAY pixel_row)
+/* This version is for reading raw-format PPM files with maxval = MAXJSAMPLE */
+{
+  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 = cinfo->image_width; col > 0; col--) {
+    *ptr0++ = (JSAMPLE) getc(infile);
+    *ptr1++ = (JSAMPLE) getc(infile);
+    *ptr2++ = (JSAMPLE) getc(infile);
+  }
+}
+
+
 /*
  * Read the file header; return image size and component count.
  */
@@ -31,19 +220,45 @@
 METHODDEF void
 input_init (compress_info_ptr cinfo)
 {
-  int c, w, h, prec;
+  int c;
+  unsigned int w, h, maxval;
 
   if (getc(cinfo->input_file) != 'P')
     ERREXIT(cinfo->emethods, "Not a PPM file");
 
-  c = getc(cinfo->input_file);
+  c = getc(cinfo->input_file);	/* save format discriminator for a sec */
+
+  w = read_pbm_integer(cinfo);	/* while we fetch the header info */
+  h = read_pbm_integer(cinfo);
+  maxval = read_pbm_integer(cinfo);
+
   switch (c) {
-  case '5':			/* it's a PGM file */
+  case '2':			/* it's a text-format PGM file */
+    cinfo->methods->get_input_row = get_text_gray_row;
     cinfo->input_components = 1;
     cinfo->in_color_space = CS_GRAYSCALE;
     break;
 
-  case '6':			/* it's a PPM file */
+  case '3':			/* it's a text-format PPM file */
+    cinfo->methods->get_input_row = get_text_rgb_row;
+    cinfo->input_components = 3;
+    cinfo->in_color_space = CS_RGB;
+    break;
+
+  case '5':			/* it's a raw-format PGM file */
+    if (maxval == MAXJSAMPLE)
+      cinfo->methods->get_input_row = get_raw_gray_row;
+    else
+      cinfo->methods->get_input_row = get_scaled_gray_row;
+    cinfo->input_components = 1;
+    cinfo->in_color_space = CS_GRAYSCALE;
+    break;
+
+  case '6':			/* it's a raw-format PPM file */
+    if (maxval == MAXJSAMPLE)
+      cinfo->methods->get_input_row = get_raw_rgb_row;
+    else
+      cinfo->methods->get_input_row = get_scaled_rgb_row;
     cinfo->input_components = 3;
     cinfo->in_color_space = CS_RGB;
     break;
@@ -53,44 +268,29 @@
     break;
   }
 
-  if (fscanf(cinfo->input_file, " %d %d %d", &w, &h, &prec) != 3)
+  if (w <= 0 || h <= 0 || maxval <= 0) /* error check */
     ERREXIT(cinfo->emethods, "Not a PPM file");
 
-  if (getc(cinfo->input_file) != '\n' || w <= 0 || h <= 0 || prec != 255)
-    ERREXIT(cinfo->emethods, "Not a PPM file");
+  /* Compute the rescaling array if necessary */
+  /* This saves per-pixel calculation */
+  if (maxval == MAXJSAMPLE)
+    rescale = NULL;		/* no rescaling required */
+  else {
+    INT32 val, half_maxval;
+
+    /* On 16-bit-int machines we have to be careful of maxval = 65535 */
+    rescale = (JSAMPLE *) (*cinfo->emethods->alloc_small)
+			((size_t) (((long) maxval + 1L) * SIZEOF(JSAMPLE)));
+    half_maxval = maxval / 2;
+    for (val = 0; val <= (INT32) maxval; val++) {
+      /* The multiplication here must be done in 32 bits to avoid overflow */
+      rescale[val] = (JSAMPLE) ((val * MAXJSAMPLE + half_maxval) / maxval);
+    }
+  }
 
   cinfo->image_width = w;
   cinfo->image_height = h;
-  cinfo->data_precision = 8;
-}
-
-
-/*
- * Read one row of pixels.
- */
-
-METHODDEF void
-get_input_row (compress_info_ptr cinfo, JSAMPARRAY pixel_row)
-{
-  register FILE * infile = cinfo->input_file;
-  register JSAMPROW ptr0, ptr1, ptr2;
-  register long col;
-  
-  if (cinfo->input_components == 1) {
-    ptr0 = pixel_row[0];
-    for (col = cinfo->image_width; col > 0; col--) {
-      *ptr0++ = getc(infile);
-    }
-  } else {
-    ptr0 = pixel_row[0];
-    ptr1 = pixel_row[1];
-    ptr2 = pixel_row[2];
-    for (col = cinfo->image_width; col > 0; col--) {
-      *ptr0++ = getc(infile);
-      *ptr1++ = getc(infile);
-      *ptr2++ = getc(infile);
-    }
-  }
+  cinfo->data_precision = BITS_IN_JSAMPLE;
 }
 
 
@@ -101,7 +301,8 @@
 METHODDEF void
 input_term (compress_info_ptr cinfo)
 {
-  /* no work required */
+  if (rescale != NULL)
+    (*cinfo->emethods->free_small) ((void *) rescale);
 }
 
 
@@ -117,7 +318,7 @@
 jselrppm (compress_info_ptr cinfo)
 {
   cinfo->methods->input_init = input_init;
-  cinfo->methods->get_input_row = get_input_row;
+  /* cinfo->methods->get_input_row is set by input_init */
   cinfo->methods->input_term = input_term;
 }
 
diff --git a/jrdrle.c b/jrdrle.c
new file mode 100644
index 0000000..0571d2c
--- /dev/null
+++ b/jrdrle.c
@@ -0,0 +1,372 @@
+/*
+ * jrdrle.c
+ *
+ * Copyright (C) 1991, 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 read input images in Utah RLE format.
+ * The Utah Raster Toolkit library is required (version 3.0).
+ *
+ * These routines may need modification for non-Unix environments or
+ * specialized applications.  As they stand, they assume input from
+ * an ordinary stdio stream.  They further assume that reading begins
+ * at the start of the file; input_init may need work if the
+ * user interface has already read some data (e.g., to determine that
+ * the file is indeed RLE format).
+ *
+ * These routines are invoked via the methods get_input_row
+ * and input_init/term.
+ *
+ * Based on code contributed by Mike Lijewski.
+ */
+
+#include "jinclude.h"
+
+#ifdef RLE_SUPPORTED
+
+/* rle.h is provided by the Utah Raster Toolkit. */
+
+#include <rle.h>
+
+
+/*
+ * load_image assumes that JSAMPLE has the same representation as rle_pixel,
+ * to wit, "unsigned char".  Hence we can't cope with 12- or 16-bit samples.
+ */
+
+#ifndef EIGHT_BIT_SAMPLES
+  Sorry, this code only copes with 8-bit JSAMPLEs. /* deliberate syntax err */
+#endif
+
+
+/*
+ * We support the following types of RLE files:
+ *   
+ *   GRAYSCALE   - 8 bits, no colormap
+ *   PSEUDOCOLOR - 8 bits, colormap
+ *   TRUECOLOR   - 24 bits, colormap
+ *   DIRECTCOLOR - 24 bits, no colormap
+ *
+ * For now, we ignore any alpha channel in the image.
+ */
+
+typedef enum { GRAYSCALE, PSEUDOCOLOR, TRUECOLOR, DIRECTCOLOR } rle_kind;
+
+static rle_kind visual;		/* actual type of input file */
+
+/*
+ * Since RLE stores scanlines bottom-to-top, we have to invert the image
+ * to conform to JPEG's top-to-bottom order.  To do this, we read the
+ * incoming image into a virtual array on the first get_input_row call,
+ * then fetch the required row from the virtual array on subsequent calls.
+ */
+
+static big_sarray_ptr image;	/* single array for GRAYSCALE/PSEUDOCOLOR */
+static big_sarray_ptr red_channel; /* three arrays for TRUECOLOR/DIRECTCOLOR */
+static big_sarray_ptr green_channel;
+static big_sarray_ptr blue_channel;
+static long cur_row_number;	/* last row# read from virtual array */
+
+static rle_hdr header;		/* Input file information */
+static rle_map *colormap;	/* RLE colormap, if any */
+
+
+/*
+ * Read the file header; return image size and component count.
+ */
+
+METHODDEF void
+input_init (compress_info_ptr cinfo)
+{
+  long width, height;
+
+  /* Use RLE library routine to get the header info */
+  header.rle_file = cinfo->input_file;
+  switch (rle_get_setup(&header)) {
+  case RLE_SUCCESS:
+    /* A-OK */
+    break;
+  case RLE_NOT_RLE:
+    ERREXIT(cinfo->emethods, "Not an RLE file");
+    break;
+  case RLE_NO_SPACE:
+    ERREXIT(cinfo->emethods, "Insufficient memory for RLE header");
+    break;
+  case RLE_EMPTY:
+    ERREXIT(cinfo->emethods, "Empty RLE file");
+    break;
+  case RLE_EOF:
+    ERREXIT(cinfo->emethods, "Premature EOF in RLE header");
+    break;
+  default:
+    ERREXIT(cinfo->emethods, "Bogus RLE error code");
+    break;
+  }
+
+  /* Figure out what we have, set private vars and return values accordingly */
+  
+  width  = header.xmax - header.xmin + 1;
+  height = header.ymax - header.ymin + 1;
+  header.xmin = 0;		/* realign horizontally */
+  header.xmax = width-1;
+
+  cinfo->image_width      = width;
+  cinfo->image_height     = height;
+  cinfo->data_precision   = 8;  /* we can only handle 8 bit data */
+
+  if (header.ncolors == 1 && header.ncmap == 0) {
+    visual     = GRAYSCALE;
+    TRACEMS(cinfo->emethods, 1, "Gray-scale RLE file");
+  } else if (header.ncolors == 1 && header.ncmap == 3) {
+    visual     = PSEUDOCOLOR;
+    colormap   = header.cmap;
+    TRACEMS1(cinfo->emethods, 1, "Colormapped RLE file with map of length %d",
+	     1 << header.cmaplen);
+  } else if (header.ncolors == 3 && header.ncmap == 3) {
+    visual     = TRUECOLOR;
+    colormap   = header.cmap;
+    TRACEMS1(cinfo->emethods, 1, "Full-color RLE file with map of length %d",
+	     1 << header.cmaplen);
+  } else if (header.ncolors == 3 && header.ncmap == 0) {
+    visual     = DIRECTCOLOR;
+    TRACEMS(cinfo->emethods, 1, "Full-color RLE file");
+  } else
+    ERREXIT(cinfo->emethods, "Can't handle this RLE setup");
+  
+  switch (visual) {
+  case GRAYSCALE:
+    /* request one big array to hold the grayscale image */
+    image = (*cinfo->emethods->request_big_sarray) (width, height, 1L);
+    cinfo->in_color_space   = CS_GRAYSCALE;
+    cinfo->input_components = 1;
+    break;
+  case PSEUDOCOLOR:
+    /* request one big array to hold the pseudocolor image */
+    image = (*cinfo->emethods->request_big_sarray) (width, height, 1L);
+    cinfo->in_color_space   = CS_RGB;
+    cinfo->input_components = 3;
+    break;
+  case TRUECOLOR:
+  case DIRECTCOLOR:
+    /* request three big arrays to hold the RGB channels */
+    red_channel   = (*cinfo->emethods->request_big_sarray) (width, height, 1L);
+    green_channel = (*cinfo->emethods->request_big_sarray) (width, height, 1L);
+    blue_channel  = (*cinfo->emethods->request_big_sarray) (width, height, 1L);
+    cinfo->in_color_space   = CS_RGB;
+    cinfo->input_components = 3;
+    break;
+  }
+}
+
+
+/*
+ * Read one row of pixels.
+ * These are called only after load_image has read the image into
+ * the virtual array(s).
+ */
+
+
+METHODDEF void
+get_grayscale_row (compress_info_ptr cinfo, JSAMPARRAY pixel_row)
+/* This is used for GRAYSCALE images */
+{
+  JSAMPROW inputrows[1];	/* a pseudo JSAMPARRAY structure */
+
+  cur_row_number--;		/* work down in array */
+  
+  inputrows[0] = *((*cinfo->emethods->access_big_sarray)
+			(image, cur_row_number, FALSE));
+
+  jcopy_sample_rows(inputrows, 0, pixel_row, 0, 1, cinfo->image_width);
+}
+
+
+METHODDEF void
+get_pseudocolor_row (compress_info_ptr cinfo, JSAMPARRAY pixel_row)
+/* This is used for PSEUDOCOLOR images */
+{
+  long col;
+  JSAMPROW image_ptr, ptr0, ptr1, ptr2;
+  int val;
+
+  cur_row_number--;		/* work down in array */
+  
+  image_ptr = *((*cinfo->emethods->access_big_sarray)
+		(image, cur_row_number, FALSE));
+
+  ptr0 = pixel_row[0];
+  ptr1 = pixel_row[1];
+  ptr2 = pixel_row[2];
+  
+  for (col = cinfo->image_width; col > 0; col--) {
+    val = GETJSAMPLE(*image_ptr++);
+    *ptr0++ = colormap[val      ] >> 8;
+    *ptr1++ = colormap[val + 256] >> 8;
+    *ptr2++ = colormap[val + 512] >> 8;
+  }
+}
+
+
+METHODDEF void
+get_truecolor_row (compress_info_ptr cinfo, JSAMPARRAY pixel_row)
+/* This is used for TRUECOLOR images */
+/* The colormap consists of 3 independent lookup tables */
+{
+  long col;
+  JSAMPROW red_ptr, green_ptr, blue_ptr, ptr0, ptr1, ptr2;
+  
+  cur_row_number--;		/* work down in array */
+  
+  red_ptr   = *((*cinfo->emethods->access_big_sarray)
+		(red_channel, cur_row_number, FALSE));
+  green_ptr = *((*cinfo->emethods->access_big_sarray)
+		(green_channel, cur_row_number, FALSE));
+  blue_ptr  = *((*cinfo->emethods->access_big_sarray)
+		(blue_channel, cur_row_number, FALSE));
+  
+  ptr0 = pixel_row[0];
+  ptr1 = pixel_row[1];
+  ptr2 = pixel_row[2];
+  
+  for (col = cinfo->image_width; col > 0; col--) {
+    *ptr0++ = colormap[GETJSAMPLE(*red_ptr++)        ] >> 8;
+    *ptr1++ = colormap[GETJSAMPLE(*green_ptr++) + 256] >> 8;
+    *ptr2++ = colormap[GETJSAMPLE(*blue_ptr++)  + 512] >> 8;
+  }
+}
+
+
+METHODDEF void
+get_directcolor_row (compress_info_ptr cinfo, JSAMPARRAY pixel_row)
+/* This is used for DIRECTCOLOR images */
+{
+  JSAMPROW inputrows[3];	/* a pseudo JSAMPARRAY structure */
+
+  cur_row_number--;		/* work down in array */
+  
+  inputrows[0] = *((*cinfo->emethods->access_big_sarray)
+			(red_channel, cur_row_number, FALSE));
+  inputrows[1] = *((*cinfo->emethods->access_big_sarray)
+			(green_channel, cur_row_number, FALSE));
+  inputrows[2] = *((*cinfo->emethods->access_big_sarray)
+			(blue_channel, cur_row_number, FALSE));
+
+  jcopy_sample_rows(inputrows, 0, pixel_row, 0, 3, cinfo->image_width);
+}
+
+
+/*
+ * Load the color channels into separate arrays.  We have to do
+ * this because RLE files start at the lower left while the JPEG standard
+ * has them starting in the upper left.  This is called the first time
+ * we want to get a row of input.  What we do is load the RLE data into
+ * big arrays and then call the appropriate routine to read one row from
+ * the big arrays.  We also change cinfo->methods->get_input_row so that
+ * subsequent calls go straight to the row-reading routine.
+ */
+
+METHODDEF void
+load_image (compress_info_ptr cinfo, JSAMPARRAY pixel_row)
+{
+  long row;
+  rle_pixel *rle_row[3];
+  
+  /* Read the RLE data into our virtual array(s).
+   * We assume here that (a) rle_pixel is represented the same as JSAMPLE,
+   * and (b) we are not on a machine where FAR pointers differ from regular.
+   */
+  RLE_CLR_BIT(header, RLE_ALPHA); /* don't read the alpha channel */
+
+  switch (visual) {
+  case GRAYSCALE:
+  case PSEUDOCOLOR:
+    for (row = 0; row < cinfo->image_height; row++) {
+      /*
+       * Read a row of the image directly into our big array.
+       * Too bad this doesn't seem to return any indication of errors :-(.
+       */
+      rle_row[0] = (rle_pixel *) *((*cinfo->emethods->access_big_sarray)
+					(image, row, TRUE));
+      rle_getrow(&header, rle_row);
+    }
+    break;
+  case TRUECOLOR:
+  case DIRECTCOLOR:
+    for (row = 0; row < cinfo->image_height; row++) {
+      /*
+       * Read a row of the image directly into our big arrays.
+       * Too bad this doesn't seem to return any indication of errors :-(.
+       */
+      rle_row[0] = (rle_pixel *) *((*cinfo->emethods->access_big_sarray)
+					(red_channel, row, TRUE));
+      rle_row[1] = (rle_pixel *) *((*cinfo->emethods->access_big_sarray)
+					(green_channel, row, TRUE));
+      rle_row[2] = (rle_pixel *) *((*cinfo->emethods->access_big_sarray)
+					(blue_channel, row, TRUE));
+      rle_getrow(&header, rle_row);
+    }
+    break;
+  }
+  
+  /* Set up to call proper row-extraction routine in future */
+  switch (visual) {
+  case GRAYSCALE:
+    cinfo->methods->get_input_row = get_grayscale_row;
+    break;
+  case PSEUDOCOLOR:
+    cinfo->methods->get_input_row = get_pseudocolor_row;
+    break;
+  case TRUECOLOR:
+    cinfo->methods->get_input_row = get_truecolor_row;
+    break;
+  case DIRECTCOLOR:
+    cinfo->methods->get_input_row = get_directcolor_row;
+    break;
+  }
+
+  /* And fetch the topmost (bottommost) row */
+  cur_row_number = cinfo->image_height;
+  (*cinfo->methods->get_input_row) (cinfo, pixel_row);   
+}
+
+
+/*
+ * Finish up at the end of the file.
+ */
+
+METHODDEF void
+input_term (compress_info_ptr cinfo)
+{
+  switch (visual) {
+  case GRAYSCALE:
+  case PSEUDOCOLOR:
+    (*cinfo->emethods->free_big_sarray) (image);
+    break;
+  case TRUECOLOR:
+  case DIRECTCOLOR:
+    (*cinfo->emethods->free_big_sarray) (red_channel);
+    (*cinfo->emethods->free_big_sarray) (green_channel);
+    (*cinfo->emethods->free_big_sarray) (blue_channel);
+    break;
+  }
+}
+
+
+/*
+ * The method selection routine for RLE format input.
+ * Note that this must be called by the user interface before calling
+ * jpeg_compress.  If multiple input formats are supported, the
+ * user interface is responsible for discovering the file format and
+ * calling the appropriate method selection routine.
+ */
+
+GLOBAL void
+jselrrle (compress_info_ptr cinfo)
+{
+  cinfo->methods->input_init    = input_init;
+  cinfo->methods->get_input_row = load_image; /* until first call */
+  cinfo->methods->input_term    = input_term;
+}
+
+#endif /* RLE_SUPPORTED */
diff --git a/jrdtarga.c b/jrdtarga.c
new file mode 100644
index 0000000..b8aa033
--- /dev/null
+++ b/jrdtarga.c
@@ -0,0 +1,483 @@
+/*
+ * jrdtarga.c
+ *
+ * Copyright (C) 1991, 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 read input images in Targa format.
+ *
+ * These routines may need modification for non-Unix environments or
+ * specialized applications.  As they stand, they assume input from
+ * an ordinary stdio stream.  They further assume that reading begins
+ * at the start of the file; input_init may need work if the
+ * user interface has already read some data (e.g., to determine that
+ * the file is indeed Targa format).
+ *
+ * These routines are invoked via the methods get_input_row
+ * and input_init/term.
+ *
+ * Based on code contributed by Lee Daniel Crocker.
+ */
+
+#include "jinclude.h"
+
+#ifdef TARGA_SUPPORTED
+
+
+/* Macros to deal with unsigned chars as efficiently as compiler allows */
+
+#ifdef HAVE_UNSIGNED_CHAR
+typedef unsigned char U_CHAR;
+#define UCH(x)	((int) (x))
+#else /* !HAVE_UNSIGNED_CHAR */
+#ifdef CHAR_IS_UNSIGNED
+typedef char U_CHAR;
+#define UCH(x)	((int) (x))
+#else
+typedef char U_CHAR;
+#define UCH(x)	((int) (x) & 0xFF)
+#endif
+#endif /* HAVE_UNSIGNED_CHAR */
+
+
+#define	ReadOK(file,buffer,len)	(FREAD(file,buffer,len) == ((size_t) (len)))
+
+
+static JSAMPARRAY colormap;	/* Targa colormap (converted to my format) */
+
+static big_sarray_ptr whole_image; /* Needed if funny input row order */
+static long current_row;	/* Current logical row number to read */
+
+/* Pointer to routine to extract next Targa pixel from input file */
+static void (*read_pixel) PP((compress_info_ptr cinfo));
+
+/* Result of read_pixel is delivered here: */
+static U_CHAR tga_pixel[4];
+
+static int pixel_size;		/* Bytes per Targa pixel (1 to 4) */
+
+/* State info for reading RLE-coded pixels; both counts must be init to 0 */
+static int block_count;		/* # of pixels remaining in RLE block */
+static int dup_pixel_count;	/* # of times to duplicate previous pixel */
+
+/* This saves the correct pixel-row-expansion method for preload_image */
+static void (*get_pixel_row) PP((compress_info_ptr cinfo,
+				 JSAMPARRAY pixel_row));
+
+
+/* For expanding 5-bit pixel values to 8-bit with best rounding */
+
+static const UINT8 c5to8bits[32] = {
+    0,   8,  16,  24,  32,  41,  49,  57,
+   65,  74,  82,  90,  98, 106, 115, 123,
+  131, 139, 148, 156, 164, 172, 180, 189,
+  197, 205, 213, 222, 230, 238, 246, 255
+};
+
+
+
+LOCAL int
+read_byte (compress_info_ptr cinfo)
+/* Read next byte from Targa file */
+{
+  register FILE *infile = cinfo->input_file;
+  register int c;
+
+  if ((c = getc(infile)) == EOF)
+    ERREXIT(cinfo->emethods, "Premature EOF in Targa file");
+  return c;
+}
+
+
+LOCAL void
+read_colormap (compress_info_ptr cinfo, int cmaplen, int mapentrysize)
+/* Read the colormap from a Targa file */
+{
+  int i;
+
+  /* Presently only handles 24-bit BGR format */
+  if (mapentrysize != 24)
+    ERREXIT(cinfo->emethods, "Unsupported Targa colormap format");
+
+  for (i = 0; i < cmaplen; i++) {
+    colormap[2][i] = (JSAMPLE) read_byte(cinfo);
+    colormap[1][i] = (JSAMPLE) read_byte(cinfo);
+    colormap[0][i] = (JSAMPLE) read_byte(cinfo);
+  }
+}
+
+
+/*
+ * read_pixel methods: get a single pixel from Targa file into tga_pixel[]
+ */
+
+LOCAL void
+read_non_rle_pixel (compress_info_ptr cinfo)
+/* Read one Targa pixel from the input file; no RLE expansion */
+{
+  register FILE * infile = cinfo->input_file;
+  register int i;
+
+  for (i = 0; i < pixel_size; i++) {
+    tga_pixel[i] = (U_CHAR) getc(infile);
+  }
+}
+
+
+LOCAL void
+read_rle_pixel (compress_info_ptr cinfo)
+/* Read one Targa pixel from the input file, expanding RLE data as needed */
+{
+  register FILE * infile = cinfo->input_file;
+  register int i;
+
+  /* Duplicate previously read pixel? */
+  if (dup_pixel_count > 0) {
+    dup_pixel_count--;
+    return;
+  }
+
+  /* Time to read RLE block header? */
+  if (--block_count < 0) {	/* decrement pixels remaining in block */
+    i = read_byte(cinfo);
+    if (i & 0x80) {		/* Start of duplicate-pixel block? */
+      dup_pixel_count = i & 0x7F; /* number of duplications after this one */
+      block_count = 0;		/* then read new block header */
+    } else {
+      block_count = i & 0x7F;	/* number of pixels after this one */
+    }
+  }
+
+  /* Read next pixel */
+  for (i = 0; i < pixel_size; i++) {
+    tga_pixel[i] = (U_CHAR) getc(infile);
+  }
+}
+
+
+/*
+ * Read one row of pixels.
+ *
+ * We provide several different versions depending on input file format.
+ */
+
+
+METHODDEF void
+get_8bit_gray_row (compress_info_ptr cinfo, JSAMPARRAY pixel_row)
+/* This version is for reading 8-bit grayscale pixels */
+{
+  register JSAMPROW ptr0;
+  register long col;
+  
+  ptr0 = pixel_row[0];
+  for (col = cinfo->image_width; col > 0; col--) {
+    (*read_pixel) (cinfo);	/* Load next pixel into tga_pixel */
+    *ptr0++ = (JSAMPLE) UCH(tga_pixel[0]);
+  }
+}
+
+METHODDEF void
+get_8bit_row (compress_info_ptr cinfo, JSAMPARRAY pixel_row)
+/* This version is for reading 8-bit colormap indexes */
+{
+  register int t;
+  register JSAMPROW ptr0, ptr1, ptr2;
+  register long col;
+  
+  ptr0 = pixel_row[0];
+  ptr1 = pixel_row[1];
+  ptr2 = pixel_row[2];
+  for (col = cinfo->image_width; col > 0; col--) {
+    (*read_pixel) (cinfo);	/* Load next pixel into tga_pixel */
+    t = UCH(tga_pixel[0]);
+    *ptr0++ = colormap[0][t];
+    *ptr1++ = colormap[1][t];
+    *ptr2++ = colormap[2][t];
+  }
+}
+
+METHODDEF void
+get_16bit_row (compress_info_ptr cinfo, JSAMPARRAY pixel_row)
+/* This version is for reading 16-bit pixels */
+{
+  register int t;
+  register JSAMPROW ptr0, ptr1, ptr2;
+  register long col;
+  
+  ptr0 = pixel_row[0];
+  ptr1 = pixel_row[1];
+  ptr2 = pixel_row[2];
+  for (col = cinfo->image_width; col > 0; col--) {
+    (*read_pixel) (cinfo);	/* Load next pixel into tga_pixel */
+    t = UCH(tga_pixel[0]);
+    t += UCH(tga_pixel[1]) << 8;
+    /* We expand 5 bit data to 8 bit sample width.
+     * The format of the 16-bit (LSB first) input word is
+     *     xRRRRRGGGGGBBBBB
+     */
+    *ptr2++ = (JSAMPLE) c5to8bits[t & 0x1F];
+    t >>= 5;
+    *ptr1++ = (JSAMPLE) c5to8bits[t & 0x1F];
+    t >>= 5;
+    *ptr0++ = (JSAMPLE) c5to8bits[t & 0x1F];
+  }
+}
+
+METHODDEF void
+get_24bit_row (compress_info_ptr cinfo, JSAMPARRAY pixel_row)
+/* This version is for reading 24-bit pixels */
+{
+  register JSAMPROW ptr0, ptr1, ptr2;
+  register long col;
+  
+  ptr0 = pixel_row[0];
+  ptr1 = pixel_row[1];
+  ptr2 = pixel_row[2];
+  for (col = cinfo->image_width; col > 0; col--) {
+    (*read_pixel) (cinfo);	/* Load next pixel into tga_pixel */
+    *ptr0++ = (JSAMPLE) UCH(tga_pixel[2]); /* convert BGR to RGB order */
+    *ptr1++ = (JSAMPLE) UCH(tga_pixel[1]);
+    *ptr2++ = (JSAMPLE) UCH(tga_pixel[0]);
+  }
+}
+
+METHODDEF void
+get_32bit_row (compress_info_ptr cinfo, JSAMPARRAY pixel_row)
+/* This version is for reading 32-bit pixels */
+/* Attribute bits are ignored for now */
+{
+  register JSAMPROW ptr0, ptr1, ptr2;
+  register long col;
+
+/* NOTE: there seems to be considerable confusion over whether the order
+ * of the bytes in a 32-bit Targa file is A,B,G,R or B,G,R,A.
+ * On Lee Crocker's authority, we think the attribute byte comes first.
+ * Make ATTR_BYTE_FIRST be 0 if you have files in which it comes last.
+ */
+#ifndef ATTR_BYTE_FIRST    /* so you can say -DATTR_BYTE_FIRST=0 in Makefile */
+#define ATTR_BYTE_FIRST  1	/* must be 0 or 1 */
+#endif
+  
+  ptr0 = pixel_row[0];
+  ptr1 = pixel_row[1];
+  ptr2 = pixel_row[2];
+  for (col = cinfo->image_width; col > 0; col--) {
+    (*read_pixel) (cinfo);	/* Load next pixel into tga_pixel */
+    /* convert ABGR (or BGRA) to RGB order */
+    *ptr0++ = (JSAMPLE) UCH(tga_pixel[2+ATTR_BYTE_FIRST]);
+    *ptr1++ = (JSAMPLE) UCH(tga_pixel[1+ATTR_BYTE_FIRST]);
+    *ptr2++ = (JSAMPLE) UCH(tga_pixel[0+ATTR_BYTE_FIRST]);
+  }
+}
+
+
+/*
+ * This method is for re-reading the input data in standard top-down
+ * row order.  The entire image has already been read into whole_image
+ * with proper conversion of pixel format, but it's in a funny row order.
+ */
+
+METHODDEF void
+get_memory_row (compress_info_ptr cinfo, JSAMPARRAY pixel_row)
+{
+  JSAMPARRAY image_ptr;
+  long source_row;
+
+  /* Compute row of source that maps to current_row of normal order */
+  /* For now, assume image is bottom-up and not interlaced. */
+  /* NEEDS WORK to support interlaced images! */
+  source_row = cinfo->image_height - current_row - 1;
+
+  /* Fetch that row from virtual array */
+  image_ptr = (*cinfo->emethods->access_big_sarray)
+		(whole_image, source_row * cinfo->input_components, FALSE);
+
+  jcopy_sample_rows(image_ptr, 0, pixel_row, 0,
+		    cinfo->input_components, cinfo->image_width);
+
+  current_row++;
+}
+
+
+/*
+ * This method loads the image into whole_image during the first call on
+ * get_input_row.  The get_input_row pointer is then adjusted to call
+ * get_memory_row on subsequent calls.
+ */
+
+METHODDEF void
+preload_image (compress_info_ptr cinfo, JSAMPARRAY pixel_row)
+{
+  JSAMPARRAY image_ptr;
+  long row;
+
+  /* Read the data into a virtual array in input-file row order */
+  for (row = 0; row < cinfo->image_height; row++) {
+    image_ptr = (*cinfo->emethods->access_big_sarray)
+			(whole_image, row * cinfo->input_components, TRUE);
+    (*get_pixel_row) (cinfo, image_ptr);
+  }
+  /* Set up to read from the virtual array in unscrambled order */
+  cinfo->methods->get_input_row = get_memory_row;
+  current_row = 0;
+  /* And read the first row */
+  get_memory_row(cinfo, pixel_row);
+}
+
+
+/*
+ * Read the file header; return image size and component count.
+ */
+
+METHODDEF void
+input_init (compress_info_ptr cinfo)
+{
+  U_CHAR targaheader[18];
+  int idlen, cmaptype, subtype, flags, interlace_type, components;
+  UINT16 width, height, maplen;
+  boolean is_bottom_up;
+
+#define GET_2B(offset)	((unsigned int) UCH(targaheader[offset]) + \
+			 (((unsigned int) UCH(targaheader[offset+1])) << 8))
+  
+  if (! ReadOK(cinfo->input_file, targaheader, 18))
+    ERREXIT(cinfo->emethods, "Unexpected end of file");
+
+  /* Pretend "15-bit" pixels are 16-bit --- we ignore attribute bit anyway */
+  if (targaheader[16] == 15)
+    targaheader[16] = 16;
+
+  idlen = UCH(targaheader[0]);
+  cmaptype = UCH(targaheader[1]);
+  subtype = UCH(targaheader[2]);
+  maplen = GET_2B(5);
+  width = GET_2B(12);
+  height = GET_2B(14);
+  pixel_size = UCH(targaheader[16]) >> 3;
+  flags = UCH(targaheader[17]);	/* Image Descriptor byte */
+
+  is_bottom_up = ((flags & 0x20) == 0);	/* bit 5 set => top-down */
+  interlace_type = flags >> 6;	/* bits 6/7 are interlace code */
+
+  if (cmaptype > 1 ||		/* cmaptype must be 0 or 1 */
+      pixel_size < 1 || pixel_size > 4 ||
+      (UCH(targaheader[16]) & 7) != 0 || /* bits/pixel must be multiple of 8 */
+      interlace_type != 0)	/* currently don't allow interlaced image */
+    ERREXIT(cinfo->emethods, "Invalid or unsupported Targa file");
+  
+  if (subtype > 8) {
+    /* It's an RLE-coded file */
+    read_pixel = read_rle_pixel;
+    block_count = dup_pixel_count = 0;
+    subtype -= 8;
+  } else {
+    /* Non-RLE file */
+    read_pixel = read_non_rle_pixel;
+  }
+
+  /* Now should have subtype 1, 2, or 3 */
+  components = 3;		/* until proven different */
+  cinfo->in_color_space = CS_RGB;
+
+  switch (subtype) {
+  case 1:			/* colormapped image */
+    if (pixel_size == 1 && cmaptype == 1)
+      get_pixel_row = get_8bit_row;
+    else
+      ERREXIT(cinfo->emethods, "Invalid or unsupported Targa file");
+    break;
+  case 2:			/* RGB image */
+    switch (pixel_size) {
+    case 2:
+      get_pixel_row = get_16bit_row;
+      break;
+    case 3:
+      get_pixel_row = get_24bit_row;
+      break;
+    case 4:
+      get_pixel_row = get_32bit_row;
+      break;
+    default:
+      ERREXIT(cinfo->emethods, "Invalid or unsupported Targa file");
+      break;
+    }
+    break;
+  case 3:			/* Grayscale image */
+    components = 1;
+    cinfo->in_color_space = CS_GRAYSCALE;
+    if (pixel_size == 1)
+      get_pixel_row = get_8bit_gray_row;
+    else
+      ERREXIT(cinfo->emethods, "Invalid or unsupported Targa file");
+    break;
+  default:
+    ERREXIT(cinfo->emethods, "Invalid or unsupported Targa file");
+    break;
+  }
+
+  if (is_bottom_up) {
+    whole_image = (*cinfo->emethods->request_big_sarray)
+			((long) width, (long) height * components,
+			 (long) components);
+    cinfo->methods->get_input_row = preload_image;
+  } else {
+    whole_image = NULL;
+    cinfo->methods->get_input_row = get_pixel_row;
+  }
+  
+  while (idlen--)		/* Throw away ID field */
+    (void) read_byte(cinfo);
+
+  if (maplen > 0) {
+    if (maplen > 256 || GET_2B(3) != 0)
+      ERREXIT(cinfo->emethods, "Colormap too large");
+    /* Allocate space to store the colormap */
+    colormap = (*cinfo->emethods->alloc_small_sarray)
+			((long) maplen, 3L);
+    /* and read it from the file */
+    read_colormap(cinfo, (int) maplen, UCH(targaheader[7]));
+  } else {
+    if (cmaptype)		/* but you promised a cmap! */
+      ERREXIT(cinfo->emethods, "Invalid or unsupported Targa file");
+    colormap = NULL;
+  }
+
+  cinfo->input_components = components;
+  cinfo->image_width = width;
+  cinfo->image_height = height;
+  cinfo->data_precision = 8;	/* always, even if 12-bit JSAMPLEs */
+}
+
+
+/*
+ * Finish up at the end of the file.
+ */
+
+METHODDEF void
+input_term (compress_info_ptr cinfo)
+{
+  if (whole_image != NULL)
+    (*cinfo->emethods->free_big_sarray) (whole_image);
+  if (colormap != NULL)
+    (*cinfo->emethods->free_small_sarray) (colormap, 3L);
+}
+
+
+/*
+ * The method selection routine for Targa format input.
+ * Note that this must be called by the user interface before calling
+ * jpeg_compress.  If multiple input formats are supported, the
+ * user interface is responsible for discovering the file format and
+ * calling the appropriate method selection routine.
+ */
+
+GLOBAL void
+jselrtarga (compress_info_ptr cinfo)
+{
+  cinfo->methods->input_init = input_init;
+  /* cinfo->methods->get_input_row is set by input_init */
+  cinfo->methods->input_term = input_term;
+}
+
+#endif /* TARGA_SUPPORTED */
diff --git a/jrevdct.c b/jrevdct.c
index bafbf55..7c6d83f 100644
--- a/jrevdct.c
+++ b/jrevdct.c
@@ -16,99 +16,147 @@
 #include "jinclude.h"
 
 
-/* The poop on this scaling stuff is as follows:
- *
- * Most of the numbers (after multiplication by the constants) are
- * (logically) shifted left by LG2_DCT_SCALE. This is undone by UNFIXH
- * before assignment to the output array. Note that we want an additional
- * division by 2 on the output (required by the equations).
- *
- * If right shifts are unsigned, then there is a potential problem.
- * However, shifting right by 16 and then assigning to a short
- * (assuming short = 16 bits) will keep the sign right!!
- *
- * For other shifts,
- *
- *     ((x + (1 << 30)) >> shft) - (1 << (30 - shft))
- *
- * gives a nice right shift with sign (assuming no overflow). However, all the
- * scaling is such that this isn't a problem. (Is this true?)
+/* We assume that right shift corresponds to signed division by 2 with
+ * rounding towards minus infinity.  This is correct for typical "arithmetic
+ * shift" instructions that shift in copies of the sign bit.  But some
+ * C compilers implement >> with an unsigned shift.  For these machines you
+ * must define RIGHT_SHIFT_IS_UNSIGNED.
+ * RIGHT_SHIFT provides a signed right shift of an INT32 quantity.
+ * It is only applied with constant shift counts.
  */
 
-
-#define ONE 1L			/* remove L if long > 32 bits */
-
 #ifdef RIGHT_SHIFT_IS_UNSIGNED
-#define LG2_DCT_SCALE 15
-#define RIGHT_SHIFT(_x,_shft)   ((((_x) + (ONE << 30)) >> (_shft)) - (ONE << (30 - (_shft))))
+#define SHIFT_TEMPS	INT32 shift_temp;
+#define RIGHT_SHIFT(x,shft)  \
+	((shift_temp = (x)) < 0 ? \
+	 (shift_temp >> (shft)) | ((~0) << (32-(shft))) : \
+	 (shift_temp >> (shft)))
 #else
-#define LG2_DCT_SCALE 16
-#define RIGHT_SHIFT(_x,_shft)   ((_x) >> (_shft))
+#define SHIFT_TEMPS
+#define RIGHT_SHIFT(x,shft)	((x) >> (shft))
 #endif
 
+
+/* The poop on this scaling stuff is as follows:
+ *
+ * We have to do addition and subtraction of the integer inputs, which
+ * is no problem, and multiplication by fractional constants, which is
+ * a problem to do in integer arithmetic.  We multiply all the constants
+ * by DCT_SCALE and convert them to integer constants (thus retaining
+ * LG2_DCT_SCALE bits of precision in the constants).  After doing a
+ * multiplication we have to divide the product by DCT_SCALE, with proper
+ * rounding, to produce the correct output.  The division can be implemented
+ * cheaply as a right shift of LG2_DCT_SCALE bits.  The DCT equations also
+ * specify an additional division by 2 on the final outputs; this can be
+ * folded into the right-shift by shifting one more bit (see UNFIXH).
+ *
+ * If you are planning to recode this in assembler, you might want to set
+ * LG2_DCT_SCALE to 15.  This loses a bit of precision, but then all the
+ * multiplications are between 16-bit quantities (given 8-bit JSAMPLEs!)
+ * so you could use a signed 16x16=>32 bit multiply instruction instead of
+ * full 32x32 multiply.  Unfortunately there's no way to describe such a
+ * multiply portably in C, so we've gone for the extra bit of accuracy here.
+ */
+
+#ifdef EIGHT_BIT_SAMPLES
+#define LG2_DCT_SCALE 16
+#else
+#define LG2_DCT_SCALE 15	/* lose a little precision to avoid overflow */
+#endif
+
+#define ONE	((INT32) 1)
+
 #define DCT_SCALE (ONE << LG2_DCT_SCALE)
 
+/* In some places we shift the inputs left by a couple more bits, */
+/* so that they can be added to fractional results without too much */
+/* loss of precision. */
 #define LG2_OVERSCALE 2
-#define OVERSCALE (ONE << LG2_OVERSCALE)
+#define OVERSCALE  (ONE << LG2_OVERSCALE)
+#define OVERSHIFT(x)  ((x) <<= LG2_OVERSCALE)
 
-#define FIX(x)  ((INT32) ((x) * DCT_SCALE + 0.5))
+/* Scale a fractional constant by DCT_SCALE */
+#define FIX(x)	((INT32) ((x) * DCT_SCALE + 0.5))
+
+/* Scale a fractional constant by DCT_SCALE/OVERSCALE */
+/* Such a constant can be multiplied with an overscaled input */
+/* to produce something that's scaled by DCT_SCALE */
 #define FIXO(x)  ((INT32) ((x) * DCT_SCALE / OVERSCALE + 0.5))
-#define UNFIX(x)   RIGHT_SHIFT((x) + (ONE << (LG2_DCT_SCALE-1)), LG2_DCT_SCALE)
-#define UNFIXH(x)  RIGHT_SHIFT((x) + (ONE << LG2_DCT_SCALE), LG2_DCT_SCALE+1)
-#define UNFIXO(x)  RIGHT_SHIFT((x) + (ONE << (LG2_DCT_SCALE-1-LG2_OVERSCALE)), LG2_DCT_SCALE-LG2_OVERSCALE)
-#define OVERSH(x)   ((x) << LG2_OVERSCALE)
 
-#define SIN_1_4 FIX(0.7071067811856476)
+/* Descale and correctly round a value that's scaled by DCT_SCALE */
+#define UNFIX(x)   RIGHT_SHIFT((x) + (ONE << (LG2_DCT_SCALE-1)), LG2_DCT_SCALE)
+
+/* Same with an additional division by 2, ie, correctly rounded UNFIX(x/2) */
+#define UNFIXH(x)  RIGHT_SHIFT((x) + (ONE << LG2_DCT_SCALE), LG2_DCT_SCALE+1)
+
+/* Take a value scaled by DCT_SCALE and round to integer scaled by OVERSCALE */
+#define UNFIXO(x)  RIGHT_SHIFT((x) + (ONE << (LG2_DCT_SCALE-1-LG2_OVERSCALE)),\
+			       LG2_DCT_SCALE-LG2_OVERSCALE)
+
+/* Here are the constants we need */
+/* SIN_i_j is sine of i*pi/j, scaled by DCT_SCALE */
+/* COS_i_j is cosine of i*pi/j, scaled by DCT_SCALE */
+
+#define SIN_1_4 FIX(0.707106781)
 #define COS_1_4 SIN_1_4
 
-#define SIN_1_8 FIX(0.3826834323650898)
-#define COS_1_8 FIX(0.9238795325112870)
+#define SIN_1_8 FIX(0.382683432)
+#define COS_1_8 FIX(0.923879533)
 #define SIN_3_8 COS_1_8
 #define COS_3_8 SIN_1_8
 
-#define SIN_1_16 FIX(0.1950903220161282)
-#define COS_1_16 FIX(0.9807852804032300)
+#define SIN_1_16 FIX(0.195090322)
+#define COS_1_16 FIX(0.980785280)
 #define SIN_7_16 COS_1_16
 #define COS_7_16 SIN_1_16
 
-#define SIN_3_16 FIX(0.5555702330196022)
-#define COS_3_16 FIX(0.8314696123025450)
+#define SIN_3_16 FIX(0.555570233)
+#define COS_3_16 FIX(0.831469612)
 #define SIN_5_16 COS_3_16
 #define COS_5_16 SIN_3_16
 
-#define OSIN_1_4 FIXO(0.707106781185647)
+/* OSIN_i_j is sine of i*pi/j, scaled by DCT_SCALE/OVERSCALE */
+/* OCOS_i_j is cosine of i*pi/j, scaled by DCT_SCALE/OVERSCALE */
+
+#define OSIN_1_4 FIXO(0.707106781)
 #define OCOS_1_4 OSIN_1_4
 
-#define OSIN_1_8 FIXO(0.3826834323650898)
-#define OCOS_1_8 FIXO(0.9238795325112870)
+#define OSIN_1_8 FIXO(0.382683432)
+#define OCOS_1_8 FIXO(0.923879533)
 #define OSIN_3_8 OCOS_1_8
 #define OCOS_3_8 OSIN_1_8
 
-#define OSIN_1_16 FIXO(0.1950903220161282)
-#define OCOS_1_16 FIXO(0.9807852804032300)
+#define OSIN_1_16 FIXO(0.195090322)
+#define OCOS_1_16 FIXO(0.980785280)
 #define OSIN_7_16 OCOS_1_16
 #define OCOS_7_16 OSIN_1_16
 
-#define OSIN_3_16 FIXO(0.5555702330196022)
-#define OCOS_3_16 FIXO(0.8314696123025450)
+#define OSIN_3_16 FIXO(0.555570233)
+#define OCOS_3_16 FIXO(0.831469612)
 #define OSIN_5_16 OCOS_3_16
 #define OCOS_5_16 OSIN_3_16
 
 
+/*
+ * Perform a 1-dimensional inverse DCT.
+ * Note that this code is specialized to the case DCTSIZE = 8.
+ */
+
 INLINE
 LOCAL void
 fast_idct_8 (DCTELEM *in, int stride)
 {
-  /* tmp1x are new values of tmpx -- flashy register colourers
+  /* many tmps have nonoverlapping lifetime -- flashy register colourers
    * should be able to do this lot very well
    */
+  INT32 in0, in1, in2, in3, in4, in5, in6, in7;
   INT32 tmp10, tmp11, tmp12, tmp13;
   INT32 tmp20, tmp21, tmp22, tmp23;
   INT32 tmp30, tmp31;
   INT32 tmp40, tmp41, tmp42, tmp43;
   INT32 tmp50, tmp51, tmp52, tmp53;
-  INT32 in0, in1, in2, in3, in4, in5, in6, in7;
-  
+  SHIFT_TEMPS
+
   in0 = in[       0];
   in1 = in[stride  ];
   in2 = in[stride*2];
@@ -117,7 +165,9 @@
   in5 = in[stride*5];
   in6 = in[stride*6];
   in7 = in[stride*7];
-  
+
+  /* These values are scaled by DCT_SCALE */
+
   tmp10 = (in0 + in4) * COS_1_4;
   tmp11 = (in0 - in4) * COS_1_4;
   tmp12 = in2 * SIN_1_8 - in6 * COS_1_8;
@@ -127,35 +177,43 @@
   tmp21 = tmp11 + tmp12;
   tmp22 = tmp11 - tmp12;
   tmp23 = tmp10 - tmp13;
-  
+
+  /* These values are scaled by OVERSCALE */
+
   tmp30 = UNFIXO((in3 + in5) * COS_1_4);
   tmp31 = UNFIXO((in3 - in5) * COS_1_4);
-  
-  tmp40 = OVERSH(in1) + tmp30;
-  tmp41 = OVERSH(in7) + tmp31;
-  tmp42 = OVERSH(in1) - tmp30;
-  tmp43 = OVERSH(in7) - tmp31;
-  
+
+  OVERSHIFT(in1);
+  OVERSHIFT(in7);
+
+  tmp40 = in1 + tmp30;
+  tmp41 = in7 + tmp31;
+  tmp42 = in1 - tmp30;
+  tmp43 = in7 - tmp31;
+
+  /* And these are scaled by DCT_SCALE */
+
   tmp50 = tmp40 * OCOS_1_16 + tmp41 * OSIN_1_16;
   tmp51 = tmp40 * OSIN_1_16 - tmp41 * OCOS_1_16;
   tmp52 = tmp42 * OCOS_5_16 + tmp43 * OSIN_5_16;
   tmp53 = tmp42 * OSIN_5_16 - tmp43 * OCOS_5_16;
   
-  in[       0] = UNFIXH(tmp20 + tmp50);
-  in[stride  ] = UNFIXH(tmp21 + tmp53);
-  in[stride*2] = UNFIXH(tmp22 + tmp52);
-  in[stride*3] = UNFIXH(tmp23 + tmp51);
-  in[stride*4] = UNFIXH(tmp23 - tmp51);
-  in[stride*5] = UNFIXH(tmp22 - tmp52);
-  in[stride*6] = UNFIXH(tmp21 - tmp53);
-  in[stride*7] = UNFIXH(tmp20 - tmp50);
+  in[       0] = (DCTELEM) UNFIXH(tmp20 + tmp50);
+  in[stride  ] = (DCTELEM) UNFIXH(tmp21 + tmp53);
+  in[stride*2] = (DCTELEM) UNFIXH(tmp22 + tmp52);
+  in[stride*3] = (DCTELEM) UNFIXH(tmp23 + tmp51);
+  in[stride*4] = (DCTELEM) UNFIXH(tmp23 - tmp51);
+  in[stride*5] = (DCTELEM) UNFIXH(tmp22 - tmp52);
+  in[stride*6] = (DCTELEM) UNFIXH(tmp21 - tmp53);
+  in[stride*7] = (DCTELEM) UNFIXH(tmp20 - tmp50);
 }
 
 
 /*
  * Perform the inverse DCT on one block of coefficients.
  *
- * Note that this code is specialized to the case DCTSIZE = 8.
+ * A 2-D IDCT can be done by 1-D IDCT on each row
+ * followed by 1-D IDCT on each column.
  */
 
 GLOBAL void
diff --git a/jversion.h b/jversion.h
new file mode 100644
index 0000000..a931385
--- /dev/null
+++ b/jversion.h
@@ -0,0 +1,14 @@
+/*
+ * jversion.h
+ *
+ * Copyright (C) 1991, 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 software version identification.
+ */
+
+
+#define JVERSION	"2  13-Dec-91"
+
+#define JCOPYRIGHT	"Copyright (C) 1991, Thomas G. Lane"
diff --git a/jvirtmem.c b/jvirtmem.c
index 4a0627c..6e1d332 100644
--- a/jvirtmem.c
+++ b/jvirtmem.c
@@ -17,9 +17,11 @@
  * They should exit to error_exit if unsuccessful.
  */
 
+#define AM_MEMORY_MANAGER	/* we define big_Xarray_control structs */
+
 #include "jinclude.h"
 
-#ifdef __STDC__
+#ifdef INCLUDES_ARE_ANSI
 #include <stdlib.h>		/* to declare malloc(), free() */
 #else
 extern void * malloc PP((size_t size));
@@ -52,6 +54,20 @@
 
 #endif /* NEED_FAR_POINTERS */
 
+/*
+ * When allocating 2-D arrays we can either ask malloc() for each row
+ * individually, or grab the whole space in one chunk.  The latter is
+ * a lot faster on large arrays, but fails if malloc can't handle big
+ * requests, as is typically true on MS-DOS.
+ * We assume here that big malloc requests are safe whenever
+ * NEED_FAR_POINTERS is not defined, but you can change this if you are
+ * on a weird machine.
+ */
+
+#ifndef NEED_FAR_POINTERS
+#define BIG_MALLOCS_OK		/* safe to ask far_malloc for > 64Kb */
+#endif
+
 
 /*
  * Some important notes:
@@ -220,12 +236,20 @@
 /* Allocate a "small" (all-in-memory) 2-D sample array */
 {
   JSAMPARRAY result;
+#ifdef BIG_MALLOCS_OK
+  JSAMPROW workspace;
+#endif
   long i;
 
 #ifdef MEM_STATS
   total_num_sarray++;
+#ifdef BIG_MALLOCS_OK
+  total_bytes_sarray += numrows * samplesperrow * SIZEOF(JSAMPLE)
+			+ MALLOC_FAR_OVERHEAD;
+#else
   total_bytes_sarray += (samplesperrow * SIZEOF(JSAMPLE) + MALLOC_FAR_OVERHEAD)
 			* numrows;
+#endif
   cur_num_sarray++;
   if (cur_num_sarray > max_num_sarray) max_num_sarray = cur_num_sarray;
 #endif
@@ -234,11 +258,24 @@
   result = (JSAMPARRAY) alloc_small((size_t) (numrows * SIZEOF(JSAMPROW)));
 
   /* Get the rows themselves; on 80x86 these are "far" */
+
+#ifdef BIG_MALLOCS_OK
+  workspace = (JSAMPROW) far_malloc((size_t)
+				(numrows * samplesperrow * SIZEOF(JSAMPLE)));
+  if (workspace == NULL)
+    out_of_memory(3);
   for (i = 0; i < numrows; i++) {
-    result[i] = (JSAMPROW) far_malloc((size_t) (samplesperrow * SIZEOF(JSAMPLE)));
+    result[i] = workspace;
+    workspace += samplesperrow;
+  }
+#else
+  for (i = 0; i < numrows; i++) {
+    result[i] = (JSAMPROW) far_malloc((size_t)
+				      (samplesperrow * SIZEOF(JSAMPLE)));
     if (result[i] == NULL)
       out_of_memory(3);
   }
+#endif
 
   return result;
 }
@@ -248,12 +285,16 @@
 free_small_sarray (JSAMPARRAY ptr, long numrows)
 /* Free a "small" (all-in-memory) 2-D sample array */
 {
+  /* Free the rows themselves; on 80x86 these are "far" */
+#ifdef BIG_MALLOCS_OK
+  far_free((void FAR *) ptr[0]);
+#else
   long i;
 
-  /* Free the rows themselves; on 80x86 these are "far" */
   for (i = 0; i < numrows; i++) {
     far_free((void FAR *) ptr[i]);
   }
+#endif
 
   /* Free space for row pointers; this is always "near" on 80x86 */
   free_small((void *) ptr);
@@ -269,12 +310,20 @@
 /* Allocate a "small" (all-in-memory) 2-D coefficient-block array */
 {
   JBLOCKARRAY result;
+#ifdef BIG_MALLOCS_OK
+  JBLOCKROW workspace;
+#endif
   long i;
 
 #ifdef MEM_STATS
   total_num_barray++;
+#ifdef BIG_MALLOCS_OK
+  total_bytes_barray += numrows * blocksperrow * SIZEOF(JBLOCK)
+			+ MALLOC_FAR_OVERHEAD;
+#else
   total_bytes_barray += (blocksperrow * SIZEOF(JBLOCK) + MALLOC_FAR_OVERHEAD)
 			* numrows;
+#endif
   cur_num_barray++;
   if (cur_num_barray > max_num_barray) max_num_barray = cur_num_barray;
 #endif
@@ -283,11 +332,24 @@
   result = (JBLOCKARRAY) alloc_small((size_t) (numrows * SIZEOF(JBLOCKROW)));
 
   /* Get the rows themselves; on 80x86 these are "far" */
+
+#ifdef BIG_MALLOCS_OK
+  workspace = (JBLOCKROW) far_malloc((size_t)
+				(numrows * blocksperrow * SIZEOF(JBLOCK)));
+  if (workspace == NULL)
+    out_of_memory(4);
   for (i = 0; i < numrows; i++) {
-    result[i] = (JBLOCKROW) far_malloc((size_t) (blocksperrow * SIZEOF(JBLOCK)));
+    result[i] = workspace;
+    workspace += blocksperrow;
+  }
+#else
+  for (i = 0; i < numrows; i++) {
+    result[i] = (JBLOCKROW) far_malloc((size_t)
+				       (blocksperrow * SIZEOF(JBLOCK)));
     if (result[i] == NULL)
       out_of_memory(4);
   }
+#endif
 
   return result;
 }
@@ -297,12 +359,16 @@
 free_small_barray (JBLOCKARRAY ptr, long numrows)
 /* Free a "small" (all-in-memory) 2-D coefficient-block array */
 {
+  /* Free the rows themselves; on 80x86 these are "far" */
+#ifdef BIG_MALLOCS_OK
+  far_free((void FAR *) ptr[0]);
+#else
   long i;
 
-  /* Free the rows themselves; on 80x86 these are "far" */
   for (i = 0; i < numrows; i++) {
     far_free((void FAR *) ptr[i]);
   }
+#endif
 
   /* Free space for row pointers; this is always "near" on 80x86 */
   free_small((void *) ptr);
diff --git a/jwrgif.c b/jwrgif.c
index 44062ec..9423af2 100644
--- a/jwrgif.c
+++ b/jwrgif.c
@@ -97,8 +97,9 @@
 /* flush any accumulated data */
 {
   if (bytesinpkt > 0) {		/* never write zero-length packet */
-    packetbuf[0] = bytesinpkt++;
-    if (fwrite(packetbuf, 1, bytesinpkt, dcinfo->output_file) != bytesinpkt)
+    packetbuf[0] = (char) bytesinpkt++;
+    if (FWRITE(dcinfo->output_file, packetbuf, bytesinpkt)
+	!= (size_t) bytesinpkt)
       ERREXIT(dcinfo->emethods, "Output file write error");
     bytesinpkt = 0;
   }
@@ -106,7 +107,7 @@
 
 
 LOCAL void
-char_out (int c)
+char_out (char c)
 /* Add a character to current packet; flush to disk if necessary */
 {
   packetbuf[++bytesinpkt] = c;
@@ -133,7 +134,7 @@
   cur_bits += n_bits;
 
   while (cur_bits >= 8) {
-    char_out((int) (cur_accum & 0xFF));
+    char_out((char) (cur_accum & 0xFF));
     cur_accum >>= 8;
     cur_bits -= 8;
   }
@@ -225,7 +226,7 @@
     i -= HSIZE;
   
   if (hash_code[i] != 0) {	/* is first probed slot empty? */
-    if (hash_prefix[i] == waiting_code && hash_suffix[i] == c) {
+    if (hash_prefix[i] == waiting_code && hash_suffix[i] == (UINT8) c) {
       waiting_code = hash_code[i];
       return;
     }
@@ -239,7 +240,7 @@
 	i += HSIZE;
       if (hash_code[i] == 0)
 	break;			/* hit empty slot */
-      if (hash_prefix[i] == waiting_code && hash_suffix[i] == c) {
+      if (hash_prefix[i] == waiting_code && hash_suffix[i] == (UINT8) c) {
 	waiting_code = hash_code[i];
 	return;
       }
@@ -251,7 +252,7 @@
   if (free_code < LZW_TABLE_SIZE) {
     hash_code[i] = free_code++;	/* add symbol to hashtable */
     hash_prefix[i] = waiting_code;
-    hash_suffix[i] = c;
+    hash_suffix[i] = (UINT8) c;
   } else
     clear_block();
   waiting_code = c;
@@ -269,7 +270,7 @@
   output(EOFCode);
   /* Flush the bit-packing buffer */
   if (cur_bits > 0) {
-    char_out((int) (cur_accum & 0xFF));
+    char_out((char) (cur_accum & 0xFF));
   }
   /* Flush the packet buffer */
   flush_packet();
@@ -334,7 +335,7 @@
    * Write the GIF header.
    * Note that we generate a plain GIF87 header for maximum compatibility.
    */
-  fwrite("GIF87a", 1, 6, dcinfo->output_file);
+  (void) FWRITE(dcinfo->output_file, "GIF87a", 6);
   /* Write the Logical Screen Descriptor */
   put_word((UINT16) dcinfo->image_width);
   put_word((UINT16) dcinfo->image_height);
diff --git a/jwrjfif.c b/jwrjfif.c
index cc379ac..2881355 100644
--- a/jwrjfif.c
+++ b/jwrjfif.c
@@ -36,7 +36,8 @@
 
 /* Write some bytes from a (char *) buffer */
 #define WRITE_BYTES(cinfo,dataptr,datacount)  \
-  { if (fwrite((dataptr), 1, (datacount), cinfo->output_file) != (datacount)) \
+  { if (FWRITE(cinfo->output_file, dataptr, datacount) \
+	!= (size_t) (datacount)) \
       ERREXIT(cinfo->emethods, "Output file write error"); }
 
 /* Clean up and verify successful output */
@@ -247,6 +248,9 @@
   
   emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
 
+  if (cinfo->image_height > 65535L || cinfo->image_width > 65535L)
+    ERREXIT(cinfo->emethods, "Maximum image dimension for JFIF is 65535 pixels");
+
   emit_byte(cinfo, cinfo->data_precision);
   emit_2bytes(cinfo, (int) cinfo->image_height);
   emit_2bytes(cinfo, (int) cinfo->image_width);
diff --git a/jwrppm.c b/jwrppm.c
index 41687fe..7a5255c 100644
--- a/jwrppm.c
+++ b/jwrppm.c
@@ -21,6 +21,16 @@
 #ifdef PPM_SUPPORTED
 
 
+/*
+ * Haven't yet got around to making this work with text-format output,
+ * hence cannot handle pixels wider than 8 bits.
+ */
+
+#ifndef EIGHT_BIT_SAMPLES
+  Sorry, this code only copes with 8-bit JSAMPLEs. /* deliberate syntax err */
+#endif
+
+
 static JSAMPARRAY color_map;	/* saves color map passed by quantizer */
 
 
diff --git a/jwrrle.c b/jwrrle.c
new file mode 100644
index 0000000..f324758
--- /dev/null
+++ b/jwrrle.c
@@ -0,0 +1,231 @@
+/*
+ * jwrrle.c
+ *
+ * Copyright (C) 1991, 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 output images in RLE format.
+ * The Utah Raster Toolkit library is required (version 3.0).
+ *
+ * These routines may need modification for non-Unix environments or
+ * specialized applications.  As they stand, they assume output to
+ * an ordinary stdio stream.
+ *
+ * These routines are invoked via the methods put_pixel_rows, put_color_map,
+ * and output_init/term.
+ *
+ * Based on code contributed by Mike Lijewski.
+ */
+
+#include "jinclude.h"
+
+#ifdef RLE_SUPPORTED
+
+/* rle.h is provided by the Utah Raster Toolkit. */
+
+#include <rle.h>
+
+
+/*
+ * output_term assumes that JSAMPLE has the same representation as rle_pixel,
+ * to wit, "unsigned char".  Hence we can't cope with 12- or 16-bit samples.
+ */
+
+#ifndef EIGHT_BIT_SAMPLES
+  Sorry, this code only copes with 8-bit JSAMPLEs. /* deliberate syntax err */
+#endif
+
+
+/*
+ * Since RLE stores scanlines bottom-to-top, we have to invert the image
+ * from JPEG's top-to-bottom order.  To do this, we save the outgoing data
+ * in virtual array(s) during put_pixel_row calls, then actually emit the
+ * RLE file during output_term.  We use one virtual array if the output is
+ * grayscale or colormapped, more if it is full color.
+ */
+
+#define MAX_CHANS	4	/* allow up to four color components */
+static big_sarray_ptr channels[MAX_CHANS]; /* Virtual arrays for saved data */
+
+static long cur_output_row;	/* next row# to write to virtual array(s) */
+
+
+/*
+ * For now, if we emit an RLE color map then it is always 256 entries long,
+ * though not all of the entries need be used.
+ */
+
+#define CMAPBITS	8
+#define CMAPLENGTH	(1<<(CMAPBITS))
+
+static rle_map *output_colormap; /* RLE-style color map, or NULL if none */
+static int number_colors;	/* Number of colors actually used */
+
+
+/*
+ * Write the file header.
+ *
+ * In this module it's easier to wait till output_term to actually write
+ * anything; here we just request the big arrays we'll need.
+ */
+
+METHODDEF void
+output_init (decompress_info_ptr cinfo)
+{
+  short ci;
+  
+  if (cinfo->final_out_comps > MAX_CHANS)
+    ERREXIT1(cinfo->emethods, "Cannot handle %d output channels for RLE",
+	     cinfo->final_out_comps);
+  
+  for (ci = 0; ci < cinfo->final_out_comps; ci++) {
+    channels[ci] = (*cinfo->emethods->request_big_sarray)
+			(cinfo->image_width, cinfo->image_height, 1L);
+  }
+  
+  output_colormap = NULL;	/* No output colormap as yet */
+  number_colors = 0;
+  cur_output_row = 0;		/* Start filling virtual arrays at row 0 */
+}
+
+
+/*
+ * Write some pixel data.
+ *
+ * This routine just saves the data away in virtual arrays.
+ */
+
+METHODDEF void
+put_pixel_rows (decompress_info_ptr cinfo, int num_rows,
+		JSAMPIMAGE pixel_data)
+{
+  JSAMPROW outputrow[1];	/* a pseudo JSAMPARRAY structure */
+  int row;
+  short ci;
+  
+  for (row = 0; row < num_rows; row++) {
+    for (ci = 0; ci < cinfo->final_out_comps; ci++) {
+      outputrow[0] = *((*cinfo->emethods->access_big_sarray)
+			(channels[ci], cur_output_row, TRUE));
+      jcopy_sample_rows(pixel_data[ci], row, outputrow, 0,
+			1, cinfo->image_width);
+    }
+    cur_output_row++;
+  }
+}
+
+
+/*
+ * Write the color map.
+ *
+ *  For RLE output we just save the colormap for the output stage.
+ */
+
+METHODDEF void
+put_color_map (decompress_info_ptr cinfo, int num_colors, JSAMPARRAY colormap)
+{
+  size_t cmapsize;
+  short ci;
+  int i;
+
+  if (num_colors > CMAPLENGTH)
+    ERREXIT1(cinfo->emethods, "Cannot handle %d colormap entries for RLE",
+	     num_colors);
+
+  /* Allocate storage for RLE-style cmap, zero any extra entries */
+  cmapsize = cinfo->color_out_comps * CMAPLENGTH * SIZEOF(rle_map);
+  output_colormap = (rle_map *) (*cinfo->emethods->alloc_small) (cmapsize);
+  MEMZERO((void *) output_colormap, cmapsize);
+
+  /* Save away data in RLE format --- note 8-bit left shift! */
+  /* Shifting would need adjustment for JSAMPLEs wider than 8 bits. */
+  for (ci = 0; ci < cinfo->color_out_comps; ci++) {
+    for (i = 0; i < num_colors; i++) {
+      output_colormap[ci * CMAPLENGTH + i] = GETJSAMPLE(colormap[ci][i]) << 8;
+    }
+  }
+  number_colors = num_colors;
+}
+
+
+/*
+ * Finish up at the end of the file.
+ *
+ * Here is where we really output the RLE file.
+ */
+
+METHODDEF void
+output_term (decompress_info_ptr cinfo)
+{
+  rle_hdr header;		/* Output file information */
+  rle_pixel *output_rows[MAX_CHANS];
+  char cmapcomment[80];
+  short ci;
+  long row;
+
+  /* Initialize the header info */
+  MEMZERO((void *) &header, SIZEOF(rle_hdr)); /* make sure all bits are 0 */
+  header.rle_file = cinfo->output_file;
+  header.xmin     = 0;
+  header.xmax     = cinfo->image_width  - 1;
+  header.ymin     = 0;
+  header.ymax     = cinfo->image_height - 1;
+  header.alpha    = 0;
+  header.ncolors  = cinfo->final_out_comps;
+  for (ci = 0; ci < cinfo->final_out_comps; ci++) {
+    RLE_SET_BIT(header, ci);
+  }
+  if (number_colors > 0) {
+    header.ncmap   = cinfo->color_out_comps;
+    header.cmaplen = CMAPBITS;
+    header.cmap    = output_colormap;
+    /* Add a comment to the output image with the true colormap length. */
+    sprintf(cmapcomment, "color_map_length=%d", number_colors);
+    rle_putcom(cmapcomment, &header);
+  }
+  /* Emit the RLE header and color map (if any) */
+  rle_put_setup(&header);
+
+  /* Now output the RLE data from our virtual array(s).
+   * We assume here that (a) rle_pixel is represented the same as JSAMPLE,
+   * and (b) we are not on a machine where FAR pointers differ from regular.
+   */
+  for (row = cinfo->image_height-1; row >= 0; row--) {
+    for (ci = 0; ci < cinfo->final_out_comps; ci++) {
+      output_rows[ci] = (rle_pixel *) *((*cinfo->emethods->access_big_sarray)
+					(channels[ci], row, FALSE));
+    }
+    rle_putrow(output_rows, (int) cinfo->image_width, &header);
+  }
+
+  /* Emit file trailer */
+  rle_puteof(&header);
+  fflush(cinfo->output_file);
+  if (ferror(cinfo->output_file))
+    ERREXIT(cinfo->emethods, "Output file write error");
+
+  /* Release memory */
+  for (ci = 0; ci < cinfo->final_out_comps; ci++) {
+    (*cinfo->emethods->free_big_sarray) (channels[ci]);
+  }
+  if (output_colormap != NULL)
+    (*cinfo->emethods->free_small) ((void *) output_colormap);
+}
+
+
+/*
+ * The method selection routine for RLE format output.
+ * This should be called from d_ui_method_selection if RLE output is wanted.
+ */
+
+GLOBAL void
+jselwrle (decompress_info_ptr cinfo)
+{
+  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;
+}
+
+#endif /* RLE_SUPPORTED */
diff --git a/jwrtarga.c b/jwrtarga.c
new file mode 100644
index 0000000..72259e7
--- /dev/null
+++ b/jwrtarga.c
@@ -0,0 +1,223 @@
+/*
+ * jwrtarga.c
+ *
+ * Copyright (C) 1991, 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 output images in Targa format.
+ *
+ * These routines may need modification for non-Unix environments or
+ * specialized applications.  As they stand, they assume output to
+ * an ordinary stdio stream.
+ *
+ * These routines are invoked via the methods put_pixel_rows, put_color_map,
+ * and output_init/term.
+ *
+ * Based on code contributed by Lee Daniel Crocker.
+ */
+
+#include "jinclude.h"
+
+#ifdef TARGA_SUPPORTED
+
+
+/*
+ * To support 12-bit JPEG data, we'd have to scale output down to 8 bits.
+ * This is not yet implemented.
+ */
+
+#ifndef EIGHT_BIT_SAMPLES
+  Sorry, this code only copes with 8-bit JSAMPLEs. /* deliberate syntax err */
+#endif
+
+
+static JSAMPARRAY color_map;	/* saves color map passed by quantizer */
+
+
+LOCAL void
+write_header (decompress_info_ptr cinfo, int num_colors)
+/* Create and write a Targa header */
+{
+  char targaheader[18];
+
+  /* Set unused fields of header to 0 */
+  MEMZERO((void *) targaheader, SIZEOF(targaheader));
+
+  if (num_colors > 0) {
+    targaheader[1] = 1;		/* color map type 1 */
+    targaheader[5] = (char) (num_colors & 0xFF);
+    targaheader[6] = (char) (num_colors >> 8);
+    targaheader[7] = 24;	/* 24 bits per cmap entry */
+  }
+
+  targaheader[12] = (char) (cinfo->image_width & 0xFF);
+  targaheader[13] = (char) (cinfo->image_width >> 8);
+  targaheader[14] = (char) (cinfo->image_height & 0xFF);
+  targaheader[15] = (char) (cinfo->image_height >> 8);
+  targaheader[17] = 0x20;	/* Top-down, non-interlaced */
+
+  if (cinfo->out_color_space == CS_GRAYSCALE) {
+    targaheader[2] = 3;		/* image type = uncompressed gray-scale */
+    targaheader[16] = 8;	/* bits per pixel */
+  } else {			/* must be RGB */
+    if (num_colors > 0) {
+      targaheader[2] = 1;	/* image type = colormapped RGB */
+      targaheader[16] = 8;
+    } else {
+      targaheader[2] = 2;	/* image type = uncompressed RGB */
+      targaheader[16] = 24;
+    }
+  }
+
+  if (FWRITE(cinfo->output_file, targaheader, 18) != (size_t) 18)
+    ERREXIT(cinfo->emethods, "Could not write Targa header");
+}
+
+
+/*
+ * Write the file header.
+ */
+
+METHODDEF void
+output_init (decompress_info_ptr cinfo)
+{
+  if (cinfo->out_color_space == CS_GRAYSCALE) {
+    /* Targa doesn't have a mapped grayscale format, so we will */
+    /* demap quantized gray output.  Never emit a colormap. */
+    write_header(cinfo, 0);
+  } else if (cinfo->out_color_space == CS_RGB) {
+    /* For quantized output, defer writing header until put_color_map time. */
+    if (! cinfo->quantize_colors)
+      write_header(cinfo, 0);
+  } else {
+    ERREXIT(cinfo->emethods, "Targa output must be grayscale or RGB");
+  }
+}
+
+
+/*
+ * Write some pixel data.
+ */
+
+METHODDEF void
+put_pixel_rows (decompress_info_ptr cinfo, int num_rows,
+		JSAMPIMAGE pixel_data)
+{
+  register FILE * outfile = cinfo->output_file;
+  register JSAMPROW ptr0, ptr1, ptr2;
+  register long col;
+  register long width = cinfo->image_width;
+  register int row;
+  
+  if (cinfo->final_out_comps == 1) {
+    /* here for grayscale or quantized color output */
+    for (row = 0; row < num_rows; row++) {
+      ptr0 = pixel_data[0][row];
+      for (col = width; col > 0; col--) {
+	putc(GETJSAMPLE(*ptr0), outfile);
+	ptr0++;
+      }
+    }
+  } else {
+    /* here for unquantized color output */
+    for (row = 0; row < num_rows; row++) {
+      ptr0 = pixel_data[0][row];
+      ptr1 = pixel_data[1][row];
+      ptr2 = pixel_data[2][row];
+      for (col = width; col > 0; col--) {
+	putc(GETJSAMPLE(*ptr2), outfile); /* write in BGR order */
+	ptr2++;
+	putc(GETJSAMPLE(*ptr1), outfile);
+	ptr1++;
+	putc(GETJSAMPLE(*ptr0), outfile);
+	ptr0++;
+      }
+    }
+  }
+}
+
+
+/*
+ * Write some demapped pixel data when color quantization is in effect.
+ * For Targa, this is only applied to grayscale data.
+ */
+
+METHODDEF void
+put_demapped_rows (decompress_info_ptr cinfo, int num_rows,
+		   JSAMPIMAGE pixel_data)
+{
+  register FILE * outfile = cinfo->output_file;
+  register JSAMPROW ptr;
+  register long col;
+  register long width = cinfo->image_width;
+  register int row;
+  
+  for (row = 0; row < num_rows; row++) {
+    ptr = pixel_data[0][row];
+    for (col = width; col > 0; col--) {
+      putc(GETJSAMPLE(color_map[0][GETJSAMPLE(*ptr)]), outfile);
+      ptr++;
+    }
+  }
+}
+
+
+/*
+ * Write the color map.
+ */
+
+METHODDEF void
+put_color_map (decompress_info_ptr cinfo, int num_colors, JSAMPARRAY colormap)
+{
+  register FILE * outfile = cinfo->output_file;
+  int i;
+
+  if (cinfo->out_color_space == CS_RGB) {
+    /* We only support 8-bit colormap indexes, so only 256 colors */
+    if (num_colors > 256)
+      ERREXIT(cinfo->emethods, "Too many colors for Targa output");
+    /* Time to write the header */
+    write_header(cinfo, num_colors);
+    /* Write the colormap.  Note Targa uses BGR byte order */
+    for (i = 0; i < num_colors; i++) {
+      putc(GETJSAMPLE(colormap[2][i]), outfile);
+      putc(GETJSAMPLE(colormap[1][i]), outfile);
+      putc(GETJSAMPLE(colormap[0][i]), outfile);
+    }
+  } else {
+    color_map = colormap;	/* save for use in output */
+    cinfo->methods->put_pixel_rows = put_demapped_rows;
+  }
+}
+
+
+/*
+ * Finish up at the end of the file.
+ */
+
+METHODDEF void
+output_term (decompress_info_ptr cinfo)
+{
+  /* No work except to make sure we wrote the output file OK */
+  fflush(cinfo->output_file);
+  if (ferror(cinfo->output_file))
+    ERREXIT(cinfo->emethods, "Output file write error");
+}
+
+
+/*
+ * The method selection routine for Targa format output.
+ * This should be called from d_ui_method_selection if Targa output is wanted.
+ */
+
+GLOBAL void
+jselwtarga (decompress_info_ptr cinfo)
+{
+  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;
+}
+
+#endif /* TARGA_SUPPORTED */
diff --git a/makcjpeg.cf b/makcjpeg.cf
index ea93ce4..7c9d736 100644
--- a/makcjpeg.cf
+++ b/makcjpeg.cf
@@ -1,5 +1,6 @@
-L jcmain.mix jerror.mix jcdeflts.mix jrdgif.mix jrdppm.mix jwrjfif.mix
-L jcarith.mix jccolor.mix jcexpand.mix jchuff.mix jcmaster.mix jcmcu.mix
-L jcpipe.mix jcsample.mix jfwddct.mix jutils.mix jvirtmem.mix
+L jcmain.mix jcmaster.mix jcdeflts.mix jcarith.mix jccolor.mix jcexpand.mix
+L jchuff.mix jcmcu.mix jcpipe.mix jcsample.mix jfwddct.mix jwrjfif.mix
+L jrdgif.mix jrdppm.mix jrdrle.mix jrdtarga.mix jutils.mix jvirtmem.mix
+L jerror.mix
 fa;
 b cjpeg,8K,48K,
diff --git a/makcjpeg.lnk b/makcjpeg.lnk
index 23702b2..258f644 100644
--- a/makcjpeg.lnk
+++ b/makcjpeg.lnk
@@ -1,20 +1,22 @@
 jcmain.obj +
-jerror.obj +
+jcmaster.obj +
 jcdeflts.obj +
-jrdgif.obj +
-jrdppm.obj +
-jwrjfif.obj +
 jcarith.obj +
 jccolor.obj +
 jcexpand.obj +
 jchuff.obj +
-jcmaster.obj +
 jcmcu.obj +
 jcpipe.obj +
 jcsample.obj +
 jfwddct.obj +
+jwrjfif.obj +
+jrdgif.obj +
+jrdppm.obj +
+jrdrle.obj +
+jrdtarga.obj +
 jutils.obj +
-jvirtmem.obj
+jvirtmem.obj +
+jerror.obj
 cjpeg.exe /NOI
 nul.map
 
diff --git a/makcjpeg.lst b/makcjpeg.lst
new file mode 100644
index 0000000..aa758b3
--- /dev/null
+++ b/makcjpeg.lst
@@ -0,0 +1,4 @@
+jcmain.obj jcmaster.obj jcdeflts.obj jcarith.obj jccolor.obj jcexpand.obj
+jchuff.obj jcmcu.obj jcpipe.obj jcsample.obj jfwddct.obj jwrjfif.obj
+jrdgif.obj jrdppm.obj jrdrle.obj jrdtarga.obj jutils.obj jvirtmem.obj
+jerror.obj
diff --git a/makdjpeg.cf b/makdjpeg.cf
index 968af31..ea02876 100644
--- a/makdjpeg.cf
+++ b/makdjpeg.cf
@@ -1,6 +1,6 @@
-L jdmain.mix jerror.mix jrdjfif.mix jwrgif.mix jwrppm.mix
-L jbsmooth.mix jdarith.mix jdcolor.mix jdhuff.mix jdmaster.mix jdmcu.mix
-L jdpipe.mix jdsample.mix jquant1.mix jquant2.mix jrevdct.mix jutils.mix
-L jvirtmem.mix
+L jdmain.mix jdmaster.mix jddeflts.mix jbsmooth.mix jdarith.mix jdcolor.mix
+L jdhuff.mix jdmcu.mix jdpipe.mix jdsample.mix jquant1.mix jquant2.mix
+L jrevdct.mix jrdjfif.mix jwrgif.mix jwrppm.mix jwrrle.mix jwrtarga.mix
+L jutils.mix jvirtmem.mix jerror.mix
 fa;
 b djpeg,8K,48K,
diff --git a/makdjpeg.lnk b/makdjpeg.lnk
index 6e9107c..7f909db 100644
--- a/makdjpeg.lnk
+++ b/makdjpeg.lnk
@@ -1,22 +1,25 @@
 jdmain.obj +
-jerror.obj +
-jrdjfif.obj +
-jwrgif.obj +
-jwrppm.obj +
+jdmaster.obj +
+jddeflts.obj +
 jbsmooth.obj +
 jdarith.obj +
 jdcolor.obj +
 jdhuff.obj +
-jdmaster.obj +
 jdmcu.obj +
 jdpipe.obj +
 jdsample.obj +
 jquant1.obj +
 jquant2.obj +
 jrevdct.obj +
+jrdjfif.obj +
+jwrgif.obj +
+jwrppm.obj +
+jwrrle.obj +
+jwrtarga.obj +
 jutils.obj +
-jvirtmem.obj /NOI
-djpeg.exe
+jvirtmem.obj +
+jerror.obj
+djpeg.exe /NOI
 nul.map
 
 nul.def
diff --git a/makdjpeg.lst b/makdjpeg.lst
new file mode 100644
index 0000000..9c9e724
--- /dev/null
+++ b/makdjpeg.lst
@@ -0,0 +1,4 @@
+jdmain.obj jdmaster.obj jddeflts.obj jbsmooth.obj jdarith.obj jdcolor.obj
+jdhuff.obj jdmcu.obj jdpipe.obj jdsample.obj jquant1.obj jquant2.obj
+jrevdct.obj jrdjfif.obj jwrgif.obj jwrppm.obj jwrrle.obj jwrtarga.obj
+jutils.obj jvirtmem.obj jerror.obj
diff --git a/makefile.amiga b/makefile.amiga
deleted file mode 100644
index 2fde93a..0000000
--- a/makefile.amiga
+++ /dev/null
@@ -1,143 +0,0 @@
-# Makefile for Independent JPEG Group's software
-
-# This makefile is suitable for Amiga systems using Manx Aztec C ver 5.x.
-# Thanks to D.J. James for this version.
-
-# See README and edit jconfig.h before saying "make" !!
-
-CC= cc
-
-# You may need to adjust these cc options:
-CFLAGS= -MC -MD -DTWO_FILE_COMMANDLINE
-LDFLAGS=
-LDLIBS= -lml -lcl
-
-# miscellaneous OS-dependent stuff
-LN= ln		# linker
-RM= delete quiet # file deletion command
-AR= lb		# library (.lib) file creation command
-
-
-# source files
-INCLUDES= jinclude.h jconfig.h jpegdata.h 
-SOURCES= jbsmooth.c jcarith.c jccolor.c jcdeflts.c jcexpand.c \
-	 jchuff.c jcmain.c jcmaster.c jcmcu.c jcpipe.c jcsample.c \
-	 jdarith.c jdcolor.c jdhuff.c jdmain.c jdmaster.c jdmcu.c \
-	 jdpipe.c jdsample.c jerror.c jfwddct.c jquant1.c jquant2.c \
-	 jrdjfif.c jrdgif.c jrdppm.c jrevdct.c jutils.c jvirtmem.c \
-	 jwrjfif.c jwrgif.c jwrppm.c egetopt.c
-DOCS= README architecture codingrules
-MAKEFILES= makefile.unix makefile.amiga \
-	   makefile.mc5 makefile.mc6 makcjpeg.lnk makdjpeg.lnk \
-	   makefile.pwc makcjpeg.cf makdjpeg.cf makljpeg.cf
-TESTFILES= testorig.jpg testimg.ppm testimg.jpg
-DISTFILES= $(DOCS) $(MAKEFILES) ansi2knr.c $(SOURCES) $(INCLUDES) $(TESTFILES)
-
-# compression objectfiles
-COBJECTS = jcmain.o jcmaster.o jcdeflts.o jcarith.o jccolor.o jcexpand.o \
-	   jchuff.o jcmcu.o jcpipe.o jcsample.o jfwddct.o \
-	   jrdgif.o jrdppm.o jwrjfif.o \
-	   jutils.o jvirtmem.o jerror.o
-# decompression objectfiles
-DOBJECTS = jdmain.o jdmaster.o jbsmooth.o jdarith.o jdcolor.o jdhuff.o \
-	   jdmcu.o jdpipe.o jdsample.o jquant1.o jquant2.o jrevdct.o \
-	   jrdjfif.o jwrgif.o jwrppm.o \
-	   jutils.o jvirtmem.o jerror.o
-# These objectfiles are included in libjpeg.lib (all but jcmain.o, jdmain.o)
-LIBOBJECTS = jcmaster.o jcdeflts.o jcarith.o jccolor.o jcexpand.o \
-	     jchuff.o jcmcu.o jcpipe.o jcsample.o jfwddct.o \
-	     jrdgif.o jrdppm.o jwrjfif.o \
-	     jdmaster.o jbsmooth.o jdarith.o jdcolor.o jdhuff.o \
-	     jdmcu.o jdpipe.o jdsample.o jquant1.o jquant2.o jrevdct.o \
-	     jrdjfif.o jwrgif.o jwrppm.o \
-	     jutils.o jvirtmem.o jerror.o
-
-
-all: cjpeg djpeg
-# By default, libjpeg.lib is not built unless you explicitly request it.
-
-
-# If you have a C compiler that doesn't understand function prototypes,
-# uncomment the 5 lines below and make sure PROTO is not defined by jconfig.h.
-# Then say "make ansi2knr" before "make".
-
-#.c.o:
-#	./ansi2knr $*.c tmpansi.c
-#	$(CC) $(CFLAGS) -c tmpansi.c
-#	mv tmpansi.o $*.o
-#	$(RM) tmpansi.c
-
-ansi2knr: ansi2knr.c
-	$(CC) -o ansi2knr ansi2knr.c
-# You may need to add one of -DBSD, -DVMS, or -DMSDOS to the line above.
-
-
-cjpeg: $(COBJECTS)
-	$(LN) $(LDFLAGS) -o cjpeg $(COBJECTS) $(LDLIBS)
-
-djpeg: $(DOBJECTS)
-	$(LN) $(LDFLAGS) -o djpeg $(DOBJECTS) $(LDLIBS)
-
-# libjpeg.lib is useful if you are including the JPEG software in a larger
-# program; you'd include it in your link, rather than the individual modules.
-libjpeg.lib: $(LIBOBJECTS)
-	-$(RM) libjpeg.lib
-	$(AR) libjpeg.lib  $(LIBOBJECTS)
-
-# Use the following to test the built library
-#cjpeg: jcmain.o libjpeg.lib
-#	$(LN) $(LDFLAGS) -o cjpeg jcmain.o -llibjpeg $(LDLIBS)
-#
-#djpeg: jdmain.o libjpeg.lib
-#	$(LN) $(LDFLAGS) -o djpeg jdmain.o -llibjpeg $(LDLIBS)
-
-clean:
-	-$(RM) *.o cjpeg djpeg libjpeg.lib ansi2knr core tmpansi.* testout.ppm testout.jpg
-
-distribute:
-	-$(RM) jpegsrc.tar*
-	tar cvf jpegsrc.tar $(DISTFILES)
-	list jpegsrc.tar
-	compress -v jpegsrc.tar
-	list jpegsrc.tar*
-
-test: cjpeg djpeg
-	-$(RM) testout.ppm testout.jpg
-	./djpeg testorig.jpg testout.ppm
-	./cjpeg testimg.ppm testout.jpg
-	cmp testimg.ppm testout.ppm
-	cmp testimg.jpg testout.jpg
-
-
-jbsmooth.o : jbsmooth.c jinclude.h jconfig.h jpegdata.h 
-jcarith.o : jcarith.c jinclude.h jconfig.h jpegdata.h 
-jccolor.o : jccolor.c jinclude.h jconfig.h jpegdata.h 
-jcdeflts.o : jcdeflts.c jinclude.h jconfig.h jpegdata.h 
-jcexpand.o : jcexpand.c jinclude.h jconfig.h jpegdata.h 
-jchuff.o : jchuff.c jinclude.h jconfig.h jpegdata.h 
-jcmain.o : jcmain.c jinclude.h jconfig.h jpegdata.h egetopt.c 
-jcmaster.o : jcmaster.c jinclude.h jconfig.h jpegdata.h 
-jcmcu.o : jcmcu.c jinclude.h jconfig.h jpegdata.h 
-jcpipe.o : jcpipe.c jinclude.h jconfig.h jpegdata.h 
-jcsample.o : jcsample.c jinclude.h jconfig.h jpegdata.h 
-jdarith.o : jdarith.c jinclude.h jconfig.h jpegdata.h 
-jdcolor.o : jdcolor.c jinclude.h jconfig.h jpegdata.h 
-jdhuff.o : jdhuff.c jinclude.h jconfig.h jpegdata.h 
-jdmain.o : jdmain.c jinclude.h jconfig.h jpegdata.h egetopt.c
-jdmaster.o : jdmaster.c jinclude.h jconfig.h jpegdata.h 
-jdmcu.o : jdmcu.c jinclude.h jconfig.h jpegdata.h 
-jdpipe.o : jdpipe.c jinclude.h jconfig.h jpegdata.h 
-jdsample.o : jdsample.c jinclude.h jconfig.h jpegdata.h 
-jerror.o : jerror.c jinclude.h jconfig.h jpegdata.h 
-jfwddct.o : jfwddct.c jinclude.h jconfig.h jpegdata.h 
-jquant1.o : jquant1.c jinclude.h jconfig.h jpegdata.h 
-jquant2.o : jquant2.c jinclude.h jconfig.h jpegdata.h 
-jrdjfif.o : jrdjfif.c jinclude.h jconfig.h jpegdata.h 
-jrdgif.o : jrdgif.c jinclude.h jconfig.h jpegdata.h 
-jrdppm.o : jrdppm.c jinclude.h jconfig.h jpegdata.h 
-jrevdct.o : jrevdct.c jinclude.h jconfig.h jpegdata.h 
-jutils.o : jutils.c jinclude.h jconfig.h jpegdata.h 
-jvirtmem.o : jvirtmem.c jinclude.h jconfig.h jpegdata.h 
-jwrjfif.o : jwrjfif.c jinclude.h jconfig.h jpegdata.h 
-jwrgif.o : jwrgif.c jinclude.h jconfig.h jpegdata.h 
-jwrppm.o : jwrppm.c jinclude.h jconfig.h jpegdata.h 
diff --git a/makefile.ansi b/makefile.ansi
new file mode 100644
index 0000000..4b99f08
--- /dev/null
+++ b/makefile.ansi
@@ -0,0 +1,140 @@
+# Makefile for Independent JPEG Group's software
+
+# This makefile is suitable for Unix-like systems with ANSI-capable compilers.
+# If you have a non-ANSI compiler, makefile.unix is a better starting point.
+
+# Read SETUP instructions before saying "make" !!
+
+# The name of your C compiler:
+CC= cc
+
+# You may need to adjust these cc options:
+CFLAGS= -O
+# In particular:
+#   Add -DBSD if on a pure BSD system (see jinclude.h).
+#   Add -DMEM_STATS to enable gathering of memory usage statistics.
+#   You may also want to add -DTWO_FILE_COMMANDLINE or -D switches for other
+#   symbols listed in jconfig.h, if you prefer not to change jconfig.h.
+
+# Link-time cc options:
+LDFLAGS= 
+
+# To link any special libraries, add the necessary -l commands here.
+# In particular, on some versions of HP-UX (and probably other SysV-derived
+# systems) there is a faster alternate malloc(3) library that you can use
+# by adding "-lmalloc" to this line.
+LDLIBS= 
+
+# miscellaneous OS-dependent stuff
+LN= $(CC)	# linker
+RM= rm -f	# file deletion command
+AR= ar rc	# library (.a) file creation command
+AR2= ranlib	# second step in .a creation (use "touch" if not needed)
+
+
+# source files (independently compilable files)
+SOURCES= jbsmooth.c jcarith.c jccolor.c jcdeflts.c jcexpand.c jchuff.c \
+        jcmain.c jcmaster.c jcmcu.c jcpipe.c jcsample.c jdarith.c jdcolor.c \
+        jddeflts.c jdhuff.c jdmain.c jdmaster.c jdmcu.c jdpipe.c jdsample.c \
+        jerror.c jquant1.c jquant2.c jfwddct.c jrevdct.c jutils.c \
+        jvirtmem.c jrdjfif.c jrdgif.c jrdppm.c jrdrle.c jrdtarga.c \
+        jwrjfif.c jwrgif.c jwrppm.c jwrrle.c jwrtarga.c
+# files included by source files
+INCLUDES= jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c
+# documentation, test, and support files
+DOCS= README SETUP USAGE CHANGELOG cjpeg.1 djpeg.1 architecture codingrules
+MAKEFILES= makefile.ansi makefile.unix makefile.manx makefile.sas \
+        makefile.mc5 makefile.mc6 makcjpeg.lnk makdjpeg.lnk makefile.tc \
+        makcjpeg.lst makdjpeg.lst makefile.pwc makcjpeg.cf makdjpeg.cf \
+        makljpeg.cf
+OTHERFILES= ansi2knr.c config.c
+TESTFILES= testorig.jpg testimg.ppm testimg.jpg
+DISTFILES= $(DOCS) $(MAKEFILES) $(SOURCES) $(INCLUDES) $(OTHERFILES) \
+        $(TESTFILES)
+# objectfiles common to cjpeg and djpeg
+COMOBJECTS= jutils.o jvirtmem.o jerror.o
+# compression objectfiles
+CLIBOBJECTS= jcmaster.o jcdeflts.o jcarith.o jccolor.o jcexpand.o jchuff.o \
+        jcmcu.o jcpipe.o jcsample.o jfwddct.o jwrjfif.o jrdgif.o jrdppm.o \
+        jrdrle.o jrdtarga.o
+COBJECTS= jcmain.o $(CLIBOBJECTS) $(COMOBJECTS)
+# decompression objectfiles
+DLIBOBJECTS= jdmaster.o jddeflts.o jbsmooth.o jdarith.o jdcolor.o jdhuff.o \
+        jdmcu.o jdpipe.o jdsample.o jquant1.o jquant2.o jrevdct.o jrdjfif.o \
+        jwrgif.o jwrppm.o jwrrle.o jwrtarga.o
+DOBJECTS= jdmain.o $(DLIBOBJECTS) $(COMOBJECTS)
+# These objectfiles are included in libjpeg.a
+LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
+
+
+all: cjpeg djpeg
+# By default, libjpeg.a is not built unless you explicitly request it.
+# You can add libjpeg.a to the line above if you want it built by default.
+
+
+cjpeg: $(COBJECTS)
+	$(LN) $(LDFLAGS) -o cjpeg $(COBJECTS) $(LDLIBS)
+
+djpeg: $(DOBJECTS)
+	$(LN) $(LDFLAGS) -o djpeg $(DOBJECTS) $(LDLIBS)
+
+# libjpeg.a is useful if you are including the JPEG software in a larger
+# program; you'd include it in your link, rather than the individual modules.
+libjpeg.a: $(LIBOBJECTS)
+	$(RM) libjpeg.a
+	$(AR) libjpeg.a  $(LIBOBJECTS)
+	$(AR2) libjpeg.a
+
+clean:
+	$(RM) *.o cjpeg djpeg libjpeg.a core testout.ppm testout.jpg
+
+distribute:
+	$(RM) jpegsrc.tar*
+	tar cvf jpegsrc.tar $(DISTFILES)
+	compress -v jpegsrc.tar
+
+test: cjpeg djpeg
+	$(RM) testout.ppm testout.jpg
+	./djpeg testorig.jpg >testout.ppm
+	./cjpeg testimg.ppm >testout.jpg
+	cmp testimg.ppm testout.ppm
+	cmp testimg.jpg testout.jpg
+
+
+jbsmooth.o : jbsmooth.c jinclude.h jconfig.h jpegdata.h 
+jcarith.o : jcarith.c jinclude.h jconfig.h jpegdata.h 
+jccolor.o : jccolor.c jinclude.h jconfig.h jpegdata.h 
+jcdeflts.o : jcdeflts.c jinclude.h jconfig.h jpegdata.h 
+jcexpand.o : jcexpand.c jinclude.h jconfig.h jpegdata.h 
+jchuff.o : jchuff.c jinclude.h jconfig.h jpegdata.h 
+jcmain.o : jcmain.c jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c 
+jcmaster.o : jcmaster.c jinclude.h jconfig.h jpegdata.h 
+jcmcu.o : jcmcu.c jinclude.h jconfig.h jpegdata.h 
+jcpipe.o : jcpipe.c jinclude.h jconfig.h jpegdata.h 
+jcsample.o : jcsample.c jinclude.h jconfig.h jpegdata.h 
+jdarith.o : jdarith.c jinclude.h jconfig.h jpegdata.h 
+jdcolor.o : jdcolor.c jinclude.h jconfig.h jpegdata.h 
+jddeflts.o : jddeflts.c jinclude.h jconfig.h jpegdata.h 
+jdhuff.o : jdhuff.c jinclude.h jconfig.h jpegdata.h 
+jdmain.o : jdmain.c jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c 
+jdmaster.o : jdmaster.c jinclude.h jconfig.h jpegdata.h 
+jdmcu.o : jdmcu.c jinclude.h jconfig.h jpegdata.h 
+jdpipe.o : jdpipe.c jinclude.h jconfig.h jpegdata.h 
+jdsample.o : jdsample.c jinclude.h jconfig.h jpegdata.h 
+jerror.o : jerror.c jinclude.h jconfig.h jpegdata.h 
+jquant1.o : jquant1.c jinclude.h jconfig.h jpegdata.h 
+jquant2.o : jquant2.c jinclude.h jconfig.h jpegdata.h 
+jfwddct.o : jfwddct.c jinclude.h jconfig.h jpegdata.h 
+jrevdct.o : jrevdct.c jinclude.h jconfig.h jpegdata.h 
+jutils.o : jutils.c jinclude.h jconfig.h jpegdata.h 
+jvirtmem.o : jvirtmem.c jinclude.h jconfig.h jpegdata.h 
+jrdjfif.o : jrdjfif.c jinclude.h jconfig.h jpegdata.h 
+jrdgif.o : jrdgif.c jinclude.h jconfig.h jpegdata.h 
+jrdppm.o : jrdppm.c jinclude.h jconfig.h jpegdata.h 
+jrdrle.o : jrdrle.c jinclude.h jconfig.h jpegdata.h 
+jrdtarga.o : jrdtarga.c jinclude.h jconfig.h jpegdata.h 
+jwrjfif.o : jwrjfif.c jinclude.h jconfig.h jpegdata.h 
+jwrgif.o : jwrgif.c jinclude.h jconfig.h jpegdata.h 
+jwrppm.o : jwrppm.c jinclude.h jconfig.h jpegdata.h 
+jwrrle.o : jwrrle.c jinclude.h jconfig.h jpegdata.h 
+jwrtarga.o : jwrtarga.c jinclude.h jconfig.h jpegdata.h 
diff --git a/makefile.manx b/makefile.manx
new file mode 100644
index 0000000..bb89926
--- /dev/null
+++ b/makefile.manx
@@ -0,0 +1,133 @@
+# Makefile for Independent JPEG Group's software
+
+# This makefile is for Amiga systems using Manx Aztec C ver 5.x.
+# Thanks to D.J. James for this version.
+
+# Read SETUP instructions before saying "make" !!
+
+# The name of your C compiler:
+CC= cc
+
+# You may need to adjust these cc options:
+CFLAGS= -MC -MD -DTWO_FILE_COMMANDLINE
+
+# Link-time cc options:
+LDFLAGS= 
+
+# To link any special libraries, add the necessary -l commands here.
+LDLIBS= -lml -lcl
+
+# miscellaneous OS-dependent stuff
+# linker
+LN= ln
+# file deletion command
+RM= delete quiet
+# library (.lib) file creation command
+AR= lb
+
+
+# source files (independently compilable files)
+SOURCES= jbsmooth.c jcarith.c jccolor.c jcdeflts.c jcexpand.c jchuff.c \
+        jcmain.c jcmaster.c jcmcu.c jcpipe.c jcsample.c jdarith.c jdcolor.c \
+        jddeflts.c jdhuff.c jdmain.c jdmaster.c jdmcu.c jdpipe.c jdsample.c \
+        jerror.c jquant1.c jquant2.c jfwddct.c jrevdct.c jutils.c \
+        jvirtmem.c jrdjfif.c jrdgif.c jrdppm.c jrdrle.c jrdtarga.c \
+        jwrjfif.c jwrgif.c jwrppm.c jwrrle.c jwrtarga.c
+# files included by source files
+INCLUDES= jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c
+# documentation, test, and support files
+DOCS= README SETUP USAGE CHANGELOG cjpeg.1 djpeg.1 architecture codingrules
+MAKEFILES= makefile.ansi makefile.unix makefile.manx makefile.sas \
+        makefile.mc5 makefile.mc6 makcjpeg.lnk makdjpeg.lnk makefile.tc \
+        makcjpeg.lst makdjpeg.lst makefile.pwc makcjpeg.cf makdjpeg.cf \
+        makljpeg.cf
+OTHERFILES= ansi2knr.c config.c
+TESTFILES= testorig.jpg testimg.ppm testimg.jpg
+DISTFILES= $(DOCS) $(MAKEFILES) $(SOURCES) $(INCLUDES) $(OTHERFILES) \
+        $(TESTFILES)
+# objectfiles common to cjpeg and djpeg
+COMOBJECTS= jutils.o jvirtmem.o jerror.o
+# compression objectfiles
+CLIBOBJECTS= jcmaster.o jcdeflts.o jcarith.o jccolor.o jcexpand.o jchuff.o \
+        jcmcu.o jcpipe.o jcsample.o jfwddct.o jwrjfif.o jrdgif.o jrdppm.o \
+        jrdrle.o jrdtarga.o
+COBJECTS= jcmain.o $(CLIBOBJECTS) $(COMOBJECTS)
+# decompression objectfiles
+DLIBOBJECTS= jdmaster.o jddeflts.o jbsmooth.o jdarith.o jdcolor.o jdhuff.o \
+        jdmcu.o jdpipe.o jdsample.o jquant1.o jquant2.o jrevdct.o jrdjfif.o \
+        jwrgif.o jwrppm.o jwrrle.o jwrtarga.o
+DOBJECTS= jdmain.o $(DLIBOBJECTS) $(COMOBJECTS)
+# These objectfiles are included in libjpeg.lib
+LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
+
+
+all: cjpeg djpeg
+# By default, libjpeg.lib is not built unless you explicitly request it.
+# You can add libjpeg.lib to the line above if you want it built by default.
+
+
+cjpeg: $(COBJECTS)
+	$(LN) $(LDFLAGS) -o cjpeg $(COBJECTS) $(LDLIBS)
+
+djpeg: $(DOBJECTS)
+	$(LN) $(LDFLAGS) -o djpeg $(DOBJECTS) $(LDLIBS)
+
+# libjpeg.lib is useful if you are including the JPEG software in a larger
+# program; you'd include it in your link, rather than the individual modules.
+libjpeg.lib: $(LIBOBJECTS)
+	-$(RM) libjpeg.lib
+	$(AR) libjpeg.lib  $(LIBOBJECTS)
+
+clean:
+	-$(RM) *.o cjpeg djpeg libjpeg.lib core testout.ppm testout.jpg
+
+distribute:
+	-$(RM) jpegsrc.tar*
+	tar cvf jpegsrc.tar $(DISTFILES)
+	compress -v jpegsrc.tar
+
+test: cjpeg djpeg
+	-$(RM) testout.ppm testout.jpg
+	djpeg testorig.jpg testout.ppm
+	cjpeg testimg.ppm testout.jpg
+	cmp testimg.ppm testout.ppm
+	cmp testimg.jpg testout.jpg
+
+
+jbsmooth.o : jbsmooth.c jinclude.h jconfig.h jpegdata.h 
+jcarith.o : jcarith.c jinclude.h jconfig.h jpegdata.h 
+jccolor.o : jccolor.c jinclude.h jconfig.h jpegdata.h 
+jcdeflts.o : jcdeflts.c jinclude.h jconfig.h jpegdata.h 
+jcexpand.o : jcexpand.c jinclude.h jconfig.h jpegdata.h 
+jchuff.o : jchuff.c jinclude.h jconfig.h jpegdata.h 
+jcmain.o : jcmain.c jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c 
+jcmaster.o : jcmaster.c jinclude.h jconfig.h jpegdata.h 
+jcmcu.o : jcmcu.c jinclude.h jconfig.h jpegdata.h 
+jcpipe.o : jcpipe.c jinclude.h jconfig.h jpegdata.h 
+jcsample.o : jcsample.c jinclude.h jconfig.h jpegdata.h 
+jdarith.o : jdarith.c jinclude.h jconfig.h jpegdata.h 
+jdcolor.o : jdcolor.c jinclude.h jconfig.h jpegdata.h 
+jddeflts.o : jddeflts.c jinclude.h jconfig.h jpegdata.h 
+jdhuff.o : jdhuff.c jinclude.h jconfig.h jpegdata.h 
+jdmain.o : jdmain.c jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c 
+jdmaster.o : jdmaster.c jinclude.h jconfig.h jpegdata.h 
+jdmcu.o : jdmcu.c jinclude.h jconfig.h jpegdata.h 
+jdpipe.o : jdpipe.c jinclude.h jconfig.h jpegdata.h 
+jdsample.o : jdsample.c jinclude.h jconfig.h jpegdata.h 
+jerror.o : jerror.c jinclude.h jconfig.h jpegdata.h 
+jquant1.o : jquant1.c jinclude.h jconfig.h jpegdata.h 
+jquant2.o : jquant2.c jinclude.h jconfig.h jpegdata.h 
+jfwddct.o : jfwddct.c jinclude.h jconfig.h jpegdata.h 
+jrevdct.o : jrevdct.c jinclude.h jconfig.h jpegdata.h 
+jutils.o : jutils.c jinclude.h jconfig.h jpegdata.h 
+jvirtmem.o : jvirtmem.c jinclude.h jconfig.h jpegdata.h 
+jrdjfif.o : jrdjfif.c jinclude.h jconfig.h jpegdata.h 
+jrdgif.o : jrdgif.c jinclude.h jconfig.h jpegdata.h 
+jrdppm.o : jrdppm.c jinclude.h jconfig.h jpegdata.h 
+jrdrle.o : jrdrle.c jinclude.h jconfig.h jpegdata.h 
+jrdtarga.o : jrdtarga.c jinclude.h jconfig.h jpegdata.h 
+jwrjfif.o : jwrjfif.c jinclude.h jconfig.h jpegdata.h 
+jwrgif.o : jwrgif.c jinclude.h jconfig.h jpegdata.h 
+jwrppm.o : jwrppm.c jinclude.h jconfig.h jpegdata.h 
+jwrrle.o : jwrrle.c jinclude.h jconfig.h jpegdata.h 
+jwrtarga.o : jwrtarga.c jinclude.h jconfig.h jpegdata.h 
diff --git a/makefile.mc5 b/makefile.mc5
index eee9f21..31a6a9b 100644
--- a/makefile.mc5
+++ b/makefile.mc5
@@ -2,7 +2,7 @@
 
 # This makefile is for Microsoft C for MS-DOS, version 5.x.
 
-# See README and edit jconfig.h before saying "make" !!
+# Read SETUP instructions before saying "make" !!
 
 # Microsoft's brain-damaged version of make uses nonstandard syntax (a blank
 # line is needed to terminate a command list) and it simply scans the rules
@@ -13,23 +13,48 @@
 # from the library.  The objectfiles are also kept separately as timestamps.
 
 # You may need to adjust these cc options:
-CFLAGS=  /AS /I. /W3 /Oail /Gs /DMEM_STATS  # NB: /Gs turns off stack oflo checks
-LDFLAGS= /Fm /F 2000  # /F hhhh  sets stack size (in hex)
+CFLAGS=  /AS /I. /W3 /Oail /Gs   # NB: /Gs turns off stack oflo checks
+LDFLAGS= /Fm /F 2000             # /F hhhh  sets stack size (in hex)
 # In particular:
 #   Add /DMSDOS if your compiler doesn't automatically #define MSDOS.
-#   Add /DHAVE_GETOPT if your library includes getopt(3) (see jcmain.c, jdmain.c).
-#   /DMEM_STATS is optional -- it enables gathering of memory usage statistics.
+#   Add /DMEM_STATS to enable gathering of memory usage statistics.
+# You might also want to add /G2 if you have an 80286, etc.
 
+
+# source files (independently compilable files)
+SOURCES= jbsmooth.c jcarith.c jccolor.c jcdeflts.c jcexpand.c jchuff.c \
+        jcmain.c jcmaster.c jcmcu.c jcpipe.c jcsample.c jdarith.c jdcolor.c \
+        jddeflts.c jdhuff.c jdmain.c jdmaster.c jdmcu.c jdpipe.c jdsample.c \
+        jerror.c jquant1.c jquant2.c jfwddct.c jrevdct.c jutils.c \
+        jvirtmem.c jrdjfif.c jrdgif.c jrdppm.c jrdrle.c jrdtarga.c \
+        jwrjfif.c jwrgif.c jwrppm.c jwrrle.c jwrtarga.c
+# files included by source files
+INCLUDES= jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c
+# documentation, test, and support files
+DOCS= README SETUP USAGE CHANGELOG cjpeg.1 djpeg.1 architecture codingrules
+MAKEFILES= makefile.ansi makefile.unix makefile.manx makefile.sas \
+        makefile.mc5 makefile.mc6 makcjpeg.lnk makdjpeg.lnk makefile.tc \
+        makcjpeg.lst makdjpeg.lst makefile.pwc makcjpeg.cf makdjpeg.cf \
+        makljpeg.cf
+OTHERFILES= ansi2knr.c config.c
+TESTFILES= testorig.jpg testimg.ppm testimg.jpg
+DISTFILES= $(DOCS) $(MAKEFILES) $(SOURCES) $(INCLUDES) $(OTHERFILES) \
+        $(TESTFILES)
+# objectfiles common to cjpeg and djpeg
+COMOBJECTS= jutils.obj jvirtmem.obj jerror.obj
 # compression objectfiles
-COBJECTS = jcmain.obj jcmaster.obj jcdeflts.obj jcarith.obj jccolor.obj jcexpand.obj \
-	   jchuff.obj jcmcu.obj jcpipe.obj jcsample.obj jfwddct.obj \
-	   jrdgif.obj jrdppm.obj jwrjfif.obj \
-	   jutils.obj jvirtmem.obj jerror.obj
+CLIBOBJECTS= jcmaster.obj jcdeflts.obj jcarith.obj jccolor.obj jcexpand.obj \
+        jchuff.obj jcmcu.obj jcpipe.obj jcsample.obj jfwddct.obj \
+        jwrjfif.obj jrdgif.obj jrdppm.obj jrdrle.obj jrdtarga.obj
+COBJECTS= jcmain.obj $(CLIBOBJECTS) $(COMOBJECTS)
 # decompression objectfiles
-DOBJECTS = jdmain.obj jdmaster.obj jbsmooth.obj jdarith.obj jdcolor.obj jdhuff.obj \
-	   jdmcu.obj jdpipe.obj jdsample.obj jquant1.obj jquant2.obj jrevdct.obj \
-	   jrdjfif.obj jwrgif.obj jwrppm.obj \
-	   jutils.obj jvirtmem.obj jerror.obj
+DLIBOBJECTS= jdmaster.obj jddeflts.obj jbsmooth.obj jdarith.obj jdcolor.obj \
+        jdhuff.obj jdmcu.obj jdpipe.obj jdsample.obj jquant1.obj \
+        jquant2.obj jrevdct.obj jrdjfif.obj jwrgif.obj jwrppm.obj \
+        jwrrle.obj jwrtarga.obj
+DOBJECTS= jdmain.obj $(DLIBOBJECTS) $(COMOBJECTS)
+# These objectfiles are included in libjpeg.lib
+LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
 
 
 # inference rule used for all compilations except jcmain.c, jdmain.c
@@ -38,74 +63,83 @@
 	cl $(CFLAGS) /c $*.c
 	lib libjpeg -+$*.obj;
 
-# these two objectfiles are not inserted into libjpeg
-# because they have duplicate global symbol names (notably main()).
-jcmain.obj: jcmain.c jinclude.h jconfig.h jpegdata.h egetopt.c 
+
+jbsmooth.obj : jbsmooth.c jinclude.h jconfig.h jpegdata.h
+
+jcarith.obj : jcarith.c jinclude.h jconfig.h jpegdata.h
+
+jccolor.obj : jccolor.c jinclude.h jconfig.h jpegdata.h
+
+jcdeflts.obj : jcdeflts.c jinclude.h jconfig.h jpegdata.h
+
+jcexpand.obj : jcexpand.c jinclude.h jconfig.h jpegdata.h
+
+jchuff.obj : jchuff.c jinclude.h jconfig.h jpegdata.h
+
+jcmain.obj : jcmain.c jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c
 	cl $(CFLAGS) /c $*.c
 
-jdmain.obj: jdmain.c jinclude.h jconfig.h jpegdata.h egetopt.c
+jcmaster.obj : jcmaster.c jinclude.h jconfig.h jpegdata.h
+
+jcmcu.obj : jcmcu.c jinclude.h jconfig.h jpegdata.h
+
+jcpipe.obj : jcpipe.c jinclude.h jconfig.h jpegdata.h
+
+jcsample.obj : jcsample.c jinclude.h jconfig.h jpegdata.h
+
+jdarith.obj : jdarith.c jinclude.h jconfig.h jpegdata.h
+
+jdcolor.obj : jdcolor.c jinclude.h jconfig.h jpegdata.h
+
+jddeflts.obj : jddeflts.c jinclude.h jconfig.h jpegdata.h
+
+jdhuff.obj : jdhuff.c jinclude.h jconfig.h jpegdata.h
+
+jdmain.obj : jdmain.c jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c
 	cl $(CFLAGS) /c $*.c
 
+jdmaster.obj : jdmaster.c jinclude.h jconfig.h jpegdata.h
 
-jbsmooth.obj: jbsmooth.c jinclude.h jconfig.h jpegdata.h 
+jdmcu.obj : jdmcu.c jinclude.h jconfig.h jpegdata.h
 
-jcarith.obj: jcarith.c jinclude.h jconfig.h jpegdata.h 
+jdpipe.obj : jdpipe.c jinclude.h jconfig.h jpegdata.h
 
-jccolor.obj: jccolor.c jinclude.h jconfig.h jpegdata.h 
+jdsample.obj : jdsample.c jinclude.h jconfig.h jpegdata.h
 
-jcdeflts.obj: jcdeflts.c jinclude.h jconfig.h jpegdata.h 
+jerror.obj : jerror.c jinclude.h jconfig.h jpegdata.h
 
-jcexpand.obj: jcexpand.c jinclude.h jconfig.h jpegdata.h 
+jquant1.obj : jquant1.c jinclude.h jconfig.h jpegdata.h
 
-jchuff.obj: jchuff.c jinclude.h jconfig.h jpegdata.h 
+jquant2.obj : jquant2.c jinclude.h jconfig.h jpegdata.h
 
-jcmaster.obj: jcmaster.c jinclude.h jconfig.h jpegdata.h 
+jfwddct.obj : jfwddct.c jinclude.h jconfig.h jpegdata.h
 
-jcmcu.obj: jcmcu.c jinclude.h jconfig.h jpegdata.h 
+jrevdct.obj : jrevdct.c jinclude.h jconfig.h jpegdata.h
 
-jcpipe.obj: jcpipe.c jinclude.h jconfig.h jpegdata.h 
+jutils.obj : jutils.c jinclude.h jconfig.h jpegdata.h
 
-jcsample.obj: jcsample.c jinclude.h jconfig.h jpegdata.h 
+jvirtmem.obj : jvirtmem.c jinclude.h jconfig.h jpegdata.h
 
-jdarith.obj: jdarith.c jinclude.h jconfig.h jpegdata.h 
+jrdjfif.obj : jrdjfif.c jinclude.h jconfig.h jpegdata.h
 
-jdcolor.obj: jdcolor.c jinclude.h jconfig.h jpegdata.h 
+jrdgif.obj : jrdgif.c jinclude.h jconfig.h jpegdata.h
 
-jdhuff.obj: jdhuff.c jinclude.h jconfig.h jpegdata.h 
+jrdppm.obj : jrdppm.c jinclude.h jconfig.h jpegdata.h
 
-jdmaster.obj: jdmaster.c jinclude.h jconfig.h jpegdata.h 
+jrdrle.obj : jrdrle.c jinclude.h jconfig.h jpegdata.h
 
-jdmcu.obj: jdmcu.c jinclude.h jconfig.h jpegdata.h 
+jrdtarga.obj : jrdtarga.c jinclude.h jconfig.h jpegdata.h
 
-jdpipe.obj: jdpipe.c jinclude.h jconfig.h jpegdata.h 
+jwrjfif.obj : jwrjfif.c jinclude.h jconfig.h jpegdata.h
 
-jdsample.obj: jdsample.c jinclude.h jconfig.h jpegdata.h 
+jwrgif.obj : jwrgif.c jinclude.h jconfig.h jpegdata.h
 
-jerror.obj: jerror.c jinclude.h jconfig.h jpegdata.h 
+jwrppm.obj : jwrppm.c jinclude.h jconfig.h jpegdata.h
 
-jfwddct.obj: jfwddct.c jinclude.h jconfig.h jpegdata.h 
+jwrrle.obj : jwrrle.c jinclude.h jconfig.h jpegdata.h
 
-jquant1.obj: jquant1.c jinclude.h jconfig.h jpegdata.h 
+jwrtarga.obj : jwrtarga.c jinclude.h jconfig.h jpegdata.h
 
-jquant2.obj: jquant2.c jinclude.h jconfig.h jpegdata.h 
-
-jrdjfif.obj: jrdjfif.c jinclude.h jconfig.h jpegdata.h 
-
-jrdgif.obj: jrdgif.c jinclude.h jconfig.h jpegdata.h 
-
-jrdppm.obj: jrdppm.c jinclude.h jconfig.h jpegdata.h 
-
-jrevdct.obj: jrevdct.c jinclude.h jconfig.h jpegdata.h 
-
-jutils.obj: jutils.c jinclude.h jconfig.h jpegdata.h 
-
-jvirtmem.obj: jvirtmem.c jinclude.h jconfig.h jpegdata.h 
-
-jwrjfif.obj: jwrjfif.c jinclude.h jconfig.h jpegdata.h 
-
-jwrgif.obj: jwrgif.c jinclude.h jconfig.h jpegdata.h 
-
-jwrppm.obj: jwrppm.c jinclude.h jconfig.h jpegdata.h 
 
 
 cjpeg.exe: $(COBJECTS)
diff --git a/makefile.mc6 b/makefile.mc6
index b9ca60f..8007209 100644
--- a/makefile.mc6
+++ b/makefile.mc6
@@ -3,71 +3,100 @@
 # This makefile is for Microsoft C for MS-DOS, version 6.x (use NMAKE).
 # Thanks to Alan Wright and Chris Turner of Olivetti Research Ltd.
 
-# See README and edit jconfig.h before saying "make" !!
-
-all: cjpeg.exe djpeg.exe
+# Read SETUP instructions before saying "make" !!
 
 # compiler flags. -D gives a #define to the sources:
 #       -O              default optimisation
 #       -W3             warning level 3
 #       -Za             ANSI conformance, defines__STDC__ but undefines far
-#                       and near!
+#                       and near, so we DON'T use it.
 #       -D__STDC__      pretend we have full ANSI compliance. MSC is near
 #                       enough anyway
 #       -DMSDOS         we are on an MSDOS machine
 #       -DMEM_STATS     enable memory usage statistics (optional)
-#       -DHAVE_GETOPT   library has getopt routine to parse cmnd line options
 #       -c              compile, don't link (implicit in inference rules)
+# You might also want to add -G2 if you have an 80286, etc.
 
-CFLAGS = -c -O -W3 -DMSDOS -D__STDC__ -DMEM_STATS
+CFLAGS = -c -O -W3 -D__STDC__ -DMSDOS
 
 
+# source files (independently compilable files)
+SOURCES= jbsmooth.c jcarith.c jccolor.c jcdeflts.c jcexpand.c jchuff.c \
+        jcmain.c jcmaster.c jcmcu.c jcpipe.c jcsample.c jdarith.c jdcolor.c \
+        jddeflts.c jdhuff.c jdmain.c jdmaster.c jdmcu.c jdpipe.c jdsample.c \
+        jerror.c jquant1.c jquant2.c jfwddct.c jrevdct.c jutils.c \
+        jvirtmem.c jrdjfif.c jrdgif.c jrdppm.c jrdrle.c jrdtarga.c \
+        jwrjfif.c jwrgif.c jwrppm.c jwrrle.c jwrtarga.c
+# files included by source files
+INCLUDES= jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c
+# documentation, test, and support files
+DOCS= README SETUP USAGE CHANGELOG cjpeg.1 djpeg.1 architecture codingrules
+MAKEFILES= makefile.ansi makefile.unix makefile.manx makefile.sas \
+        makefile.mc5 makefile.mc6 makcjpeg.lnk makdjpeg.lnk makefile.tc \
+        makcjpeg.lst makdjpeg.lst makefile.pwc makcjpeg.cf makdjpeg.cf \
+        makljpeg.cf
+OTHERFILES= ansi2knr.c config.c
+TESTFILES= testorig.jpg testimg.ppm testimg.jpg
+DISTFILES= $(DOCS) $(MAKEFILES) $(SOURCES) $(INCLUDES) $(OTHERFILES) \
+        $(TESTFILES)
+# objectfiles common to cjpeg and djpeg
+COMOBJECTS= jutils.obj jvirtmem.obj jerror.obj
 # compression objectfiles
-COBJECTS = jcmain.obj jcmaster.obj jcdeflts.obj jcarith.obj jccolor.obj jcexpand.obj \
-	   jchuff.obj jcmcu.obj jcpipe.obj jcsample.obj jfwddct.obj \
-	   jrdgif.obj jrdppm.obj jwrjfif.obj \
-	   jutils.obj jvirtmem.obj jerror.obj
+CLIBOBJECTS= jcmaster.obj jcdeflts.obj jcarith.obj jccolor.obj jcexpand.obj \
+        jchuff.obj jcmcu.obj jcpipe.obj jcsample.obj jfwddct.obj \
+        jwrjfif.obj jrdgif.obj jrdppm.obj jrdrle.obj jrdtarga.obj
+COBJECTS= jcmain.obj $(CLIBOBJECTS) $(COMOBJECTS)
 # decompression objectfiles
-DOBJECTS = jdmain.obj jdmaster.obj jbsmooth.obj jdarith.obj jdcolor.obj jdhuff.obj \
-	   jdmcu.obj jdpipe.obj jdsample.obj jquant1.obj jquant2.obj jrevdct.obj \
-	   jrdjfif.obj jwrgif.obj jwrppm.obj \
-	   jutils.obj jvirtmem.obj jerror.obj
+DLIBOBJECTS= jdmaster.obj jddeflts.obj jbsmooth.obj jdarith.obj jdcolor.obj \
+        jdhuff.obj jdmcu.obj jdpipe.obj jdsample.obj jquant1.obj \
+        jquant2.obj jrevdct.obj jrdjfif.obj jwrgif.obj jwrppm.obj \
+        jwrrle.obj jwrtarga.obj
+DOBJECTS= jdmain.obj $(DLIBOBJECTS) $(COMOBJECTS)
+# These objectfiles are included in libjpeg.lib
+LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
 
 
+all: cjpeg.exe djpeg.exe
+
 # default rules in nmake will use cflags and compile the list below
 
-jbsmooth.o : jbsmooth.c jinclude.h jconfig.h jpegdata.h 
-jcarith.o : jcarith.c jinclude.h jconfig.h jpegdata.h 
-jccolor.o : jccolor.c jinclude.h jconfig.h jpegdata.h 
-jcdeflts.o : jcdeflts.c jinclude.h jconfig.h jpegdata.h 
-jcexpand.o : jcexpand.c jinclude.h jconfig.h jpegdata.h 
-jchuff.o : jchuff.c jinclude.h jconfig.h jpegdata.h 
-jcmain.o : jcmain.c jinclude.h jconfig.h jpegdata.h egetopt.c 
-jcmaster.o : jcmaster.c jinclude.h jconfig.h jpegdata.h 
-jcmcu.o : jcmcu.c jinclude.h jconfig.h jpegdata.h 
-jcpipe.o : jcpipe.c jinclude.h jconfig.h jpegdata.h 
-jcsample.o : jcsample.c jinclude.h jconfig.h jpegdata.h 
-jdarith.o : jdarith.c jinclude.h jconfig.h jpegdata.h 
-jdcolor.o : jdcolor.c jinclude.h jconfig.h jpegdata.h 
-jdhuff.o : jdhuff.c jinclude.h jconfig.h jpegdata.h 
-jdmain.o : jdmain.c jinclude.h jconfig.h jpegdata.h egetopt.c
-jdmaster.o : jdmaster.c jinclude.h jconfig.h jpegdata.h 
-jdmcu.o : jdmcu.c jinclude.h jconfig.h jpegdata.h 
-jdpipe.o : jdpipe.c jinclude.h jconfig.h jpegdata.h 
-jdsample.o : jdsample.c jinclude.h jconfig.h jpegdata.h 
-jerror.o : jerror.c jinclude.h jconfig.h jpegdata.h 
-jfwddct.o : jfwddct.c jinclude.h jconfig.h jpegdata.h 
-jquant1.o : jquant1.c jinclude.h jconfig.h jpegdata.h 
-jquant2.o : jquant2.c jinclude.h jconfig.h jpegdata.h 
-jrdjfif.o : jrdjfif.c jinclude.h jconfig.h jpegdata.h 
-jrdgif.o : jrdgif.c jinclude.h jconfig.h jpegdata.h 
-jrdppm.o : jrdppm.c jinclude.h jconfig.h jpegdata.h 
-jrevdct.o : jrevdct.c jinclude.h jconfig.h jpegdata.h 
-jutils.o : jutils.c jinclude.h jconfig.h jpegdata.h 
-jvirtmem.o : jvirtmem.c jinclude.h jconfig.h jpegdata.h 
-jwrjfif.o : jwrjfif.c jinclude.h jconfig.h jpegdata.h 
-jwrgif.o : jwrgif.c jinclude.h jconfig.h jpegdata.h 
-jwrppm.o : jwrppm.c jinclude.h jconfig.h jpegdata.h 
+jbsmooth.obj : jbsmooth.c jinclude.h jconfig.h jpegdata.h
+jcarith.obj : jcarith.c jinclude.h jconfig.h jpegdata.h
+jccolor.obj : jccolor.c jinclude.h jconfig.h jpegdata.h
+jcdeflts.obj : jcdeflts.c jinclude.h jconfig.h jpegdata.h
+jcexpand.obj : jcexpand.c jinclude.h jconfig.h jpegdata.h
+jchuff.obj : jchuff.c jinclude.h jconfig.h jpegdata.h
+jcmain.obj : jcmain.c jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c
+jcmaster.obj : jcmaster.c jinclude.h jconfig.h jpegdata.h
+jcmcu.obj : jcmcu.c jinclude.h jconfig.h jpegdata.h
+jcpipe.obj : jcpipe.c jinclude.h jconfig.h jpegdata.h
+jcsample.obj : jcsample.c jinclude.h jconfig.h jpegdata.h
+jdarith.obj : jdarith.c jinclude.h jconfig.h jpegdata.h
+jdcolor.obj : jdcolor.c jinclude.h jconfig.h jpegdata.h
+jddeflts.obj : jddeflts.c jinclude.h jconfig.h jpegdata.h
+jdhuff.obj : jdhuff.c jinclude.h jconfig.h jpegdata.h
+jdmain.obj : jdmain.c jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c
+jdmaster.obj : jdmaster.c jinclude.h jconfig.h jpegdata.h
+jdmcu.obj : jdmcu.c jinclude.h jconfig.h jpegdata.h
+jdpipe.obj : jdpipe.c jinclude.h jconfig.h jpegdata.h
+jdsample.obj : jdsample.c jinclude.h jconfig.h jpegdata.h
+jerror.obj : jerror.c jinclude.h jconfig.h jpegdata.h
+jquant1.obj : jquant1.c jinclude.h jconfig.h jpegdata.h
+jquant2.obj : jquant2.c jinclude.h jconfig.h jpegdata.h
+jfwddct.obj : jfwddct.c jinclude.h jconfig.h jpegdata.h
+jrevdct.obj : jrevdct.c jinclude.h jconfig.h jpegdata.h
+jutils.obj : jutils.c jinclude.h jconfig.h jpegdata.h
+jvirtmem.obj : jvirtmem.c jinclude.h jconfig.h jpegdata.h
+jrdjfif.obj : jrdjfif.c jinclude.h jconfig.h jpegdata.h
+jrdgif.obj : jrdgif.c jinclude.h jconfig.h jpegdata.h
+jrdppm.obj : jrdppm.c jinclude.h jconfig.h jpegdata.h
+jrdrle.obj : jrdrle.c jinclude.h jconfig.h jpegdata.h
+jrdtarga.obj : jrdtarga.c jinclude.h jconfig.h jpegdata.h
+jwrjfif.obj : jwrjfif.c jinclude.h jconfig.h jpegdata.h
+jwrgif.obj : jwrgif.c jinclude.h jconfig.h jpegdata.h
+jwrppm.obj : jwrppm.c jinclude.h jconfig.h jpegdata.h
+jwrrle.obj : jwrrle.c jinclude.h jconfig.h jpegdata.h
+jwrtarga.obj : jwrtarga.c jinclude.h jconfig.h jpegdata.h
 
 
 # use linker response files because file list > 128 chars
diff --git a/makefile.pwc b/makefile.pwc
index f41dd48..f89e840 100644
--- a/makefile.pwc
+++ b/makefile.pwc
@@ -4,22 +4,19 @@
 # and Dan Grayson's pd make 2.14 under MS-DOS.
 # Thanks to Bob Hardy for this version.
 
-# See README and edit jconfig.h before saying "make" !!
+# Read SETUP instructions before saying "make" !!
 
-# NOTE: make sure you have converted end-of-line markers to CR/LF in this file
-# and in the three mak*.cf files; otherwise pd make and the Mix linker will
-# choke.  Power C doesn't seem to care whether end-of-lines are CR/LF or just
-# LF in the *.h and *.c files.  If you blindly converted LF to CR/LF in ALL
-# the files, then you broke the test*.* files, which contain binary data.
-
+# The name of your C compiler:
 CC=pc
 
 # You may need to adjust these cc options:
 MODEL=m
-CFLAGS=-dMEM_STATS -dMSDOS -m$(MODEL)
-LDFLAGS=
+CFLAGS= -dMSDOS -m$(MODEL)
 # In particular:
-#   -dMEM_STATS is optional -- it enables gathering of memory usage statistics.
+#   Add -dMEM_STATS to enable gathering of memory usage statistics.
+
+# Link-time cc options:
+LDFLAGS=
 LDLIBS=
 
 # miscellaneous OS-dependent stuff
@@ -31,16 +28,31 @@
 AR=merge
 
 
+# source files (independently compilable files)
+SOURCES= jbsmooth.c jcarith.c jccolor.c jcdeflts.c jcexpand.c jchuff.c jcmain.c jcmaster.c jcmcu.c jcpipe.c jcsample.c jdarith.c jdcolor.c jddeflts.c jdhuff.c jdmain.c jdmaster.c jdmcu.c jdpipe.c jdsample.c jerror.c jquant1.c jquant2.c jfwddct.c jrevdct.c jutils.c jvirtmem.c jrdjfif.c jrdgif.c jrdppm.c jrdrle.c jrdtarga.c jwrjfif.c jwrgif.c jwrppm.c jwrrle.c jwrtarga.c
+# files included by source files
+INCLUDES= jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c
+# documentation, test, and support files
+DOCS= README SETUP USAGE CHANGELOG cjpeg.1 djpeg.1 architecture codingrules
+MAKEFILES= makefile.ansi makefile.unix makefile.manx makefile.sas makefile.mc5 makefile.mc6 makcjpeg.lnk makdjpeg.lnk makefile.tc makcjpeg.lst makdjpeg.lst makefile.pwc makcjpeg.cf makdjpeg.cf makljpeg.cf
+OTHERFILES= ansi2knr.c config.c
+TESTFILES= testorig.jpg testimg.ppm testimg.jpg
+DISTFILES= $(DOCS) $(MAKEFILES) $(SOURCES) $(INCLUDES) $(OTHERFILES) $(TESTFILES)
+# objectfiles common to cjpeg and djpeg
+COMOBJECTS= jutils.mix jvirtmem.mix jerror.mix
 # compression objectfiles
-COBJECTS = jcmain.mix jcmaster.mix jcdeflts.mix jcarith.mix jccolor.mix jcexpand.mix jchuff.mix jcmcu.mix jcpipe.mix jcsample.mix jfwddct.mix jrdgif.mix jrdppm.mix jwrjfif.mix jutils.mix jvirtmem.mix jerror.mix
+CLIBOBJECTS= jcmaster.mix jcdeflts.mix jcarith.mix jccolor.mix jcexpand.mix jchuff.mix jcmcu.mix jcpipe.mix jcsample.mix jfwddct.mix jwrjfif.mix jrdgif.mix jrdppm.mix jrdrle.mix jrdtarga.mix
+COBJECTS= jcmain.mix $(CLIBOBJECTS) $(COMOBJECTS)
 # decompression objectfiles
-DOBJECTS = jdmain.mix jdmaster.mix jbsmooth.mix jdarith.mix jdcolor.mix jdhuff.mix jdmcu.mix jdpipe.mix jdsample.mix jquant1.mix jquant2.mix jrevdct.mix jrdjfif.mix jwrgif.mix jwrppm.mix jutils.mix jvirtmem.mix jerror.mix
-# These objectfiles are included in libjpeg.mix (all but jcmain, jdmain)
-LIBOBJECTS = jcmaster.mix jcdeflts.mix jcarith.mix jccolor.mix jcexpand.mix jchuff.mix jcmcu.mix jcpipe.mix jcsample.mix jfwddct.mix jrdgif.mix jrdppm.mix jwrjfif.mix jdmaster.mix jbsmooth.mix jdarith.mix jdcolor.mix jdhuff.mix jdmcu.mix jdpipe.mix jdsample.mix jquant1.mix jquant2.mix jrevdct.mix jrdjfif.mix jwrgif.mix jwrppm.mix jutils.mix jvirtmem.mix jerror.mix
+DLIBOBJECTS= jdmaster.mix jddeflts.mix jbsmooth.mix jdarith.mix jdcolor.mix jdhuff.mix jdmcu.mix jdpipe.mix jdsample.mix jquant1.mix jquant2.mix jrevdct.mix jrdjfif.mix jwrgif.mix jwrppm.mix jwrrle.mix jwrtarga.mix
+DOBJECTS= jdmain.mix $(DLIBOBJECTS) $(COMOBJECTS)
+# These objectfiles are included in libjpeg.mix
+LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
 
 
-all: cjpeg.exe djpeg.exe test
+all: cjpeg.exe djpeg.exe
 # By default, libjpeg.mix is not built unless you explicitly request it.
+# You can add libjpeg.mix to the line above if you want it built by default.
 
 
 cjpeg.exe: $(COBJECTS)
@@ -66,35 +78,40 @@
 	fc testimg.jpg testout.jpg
 
 
-jbsmooth.mix : jbsmooth.c jinclude.h jconfig.h jpegdata.h 
-jcarith.mix : jcarith.c jinclude.h jconfig.h jpegdata.h 
-jccolor.mix : jccolor.c jinclude.h jconfig.h jpegdata.h 
-jcdeflts.mix : jcdeflts.c jinclude.h jconfig.h jpegdata.h 
-jcexpand.mix : jcexpand.c jinclude.h jconfig.h jpegdata.h 
-jchuff.mix : jchuff.c jinclude.h jconfig.h jpegdata.h 
-jcmain.mix : jcmain.c jinclude.h jconfig.h jpegdata.h egetopt.c 
-jcmaster.mix : jcmaster.c jinclude.h jconfig.h jpegdata.h 
-jcmcu.mix : jcmcu.c jinclude.h jconfig.h jpegdata.h 
-jcpipe.mix : jcpipe.c jinclude.h jconfig.h jpegdata.h 
-jcsample.mix : jcsample.c jinclude.h jconfig.h jpegdata.h 
-jdarith.mix : jdarith.c jinclude.h jconfig.h jpegdata.h 
-jdcolor.mix : jdcolor.c jinclude.h jconfig.h jpegdata.h 
-jdhuff.mix : jdhuff.c jinclude.h jconfig.h jpegdata.h 
-jdmain.mix : jdmain.c jinclude.h jconfig.h jpegdata.h egetopt.c
-jdmaster.mix : jdmaster.c jinclude.h jconfig.h jpegdata.h 
-jdmcu.mix : jdmcu.c jinclude.h jconfig.h jpegdata.h 
-jdpipe.mix : jdpipe.c jinclude.h jconfig.h jpegdata.h 
-jdsample.mix : jdsample.c jinclude.h jconfig.h jpegdata.h 
-jerror.mix : jerror.c jinclude.h jconfig.h jpegdata.h 
-jfwddct.mix : jfwddct.c jinclude.h jconfig.h jpegdata.h 
-jquant1.mix : jquant1.c jinclude.h jconfig.h jpegdata.h 
-jquant2.mix : jquant2.c jinclude.h jconfig.h jpegdata.h 
-jrdjfif.mix : jrdjfif.c jinclude.h jconfig.h jpegdata.h 
-jrdgif.mix : jrdgif.c jinclude.h jconfig.h jpegdata.h 
-jrdppm.mix : jrdppm.c jinclude.h jconfig.h jpegdata.h 
-jrevdct.mix : jrevdct.c jinclude.h jconfig.h jpegdata.h 
-jutils.mix : jutils.c jinclude.h jconfig.h jpegdata.h 
-jvirtmem.mix : jvirtmem.c jinclude.h jconfig.h jpegdata.h 
-jwrjfif.mix : jwrjfif.c jinclude.h jconfig.h jpegdata.h 
-jwrgif.mix : jwrgif.c jinclude.h jconfig.h jpegdata.h 
-jwrppm.mix : jwrppm.c jinclude.h jconfig.h jpegdata.h 
+jbsmooth.mix : jbsmooth.c jinclude.h jconfig.h jpegdata.h
+jcarith.mix : jcarith.c jinclude.h jconfig.h jpegdata.h
+jccolor.mix : jccolor.c jinclude.h jconfig.h jpegdata.h
+jcdeflts.mix : jcdeflts.c jinclude.h jconfig.h jpegdata.h
+jcexpand.mix : jcexpand.c jinclude.h jconfig.h jpegdata.h
+jchuff.mix : jchuff.c jinclude.h jconfig.h jpegdata.h
+jcmain.mix : jcmain.c jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c
+jcmaster.mix : jcmaster.c jinclude.h jconfig.h jpegdata.h
+jcmcu.mix : jcmcu.c jinclude.h jconfig.h jpegdata.h
+jcpipe.mix : jcpipe.c jinclude.h jconfig.h jpegdata.h
+jcsample.mix : jcsample.c jinclude.h jconfig.h jpegdata.h
+jdarith.mix : jdarith.c jinclude.h jconfig.h jpegdata.h
+jdcolor.mix : jdcolor.c jinclude.h jconfig.h jpegdata.h
+jddeflts.mix : jddeflts.c jinclude.h jconfig.h jpegdata.h
+jdhuff.mix : jdhuff.c jinclude.h jconfig.h jpegdata.h
+jdmain.mix : jdmain.c jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c
+jdmaster.mix : jdmaster.c jinclude.h jconfig.h jpegdata.h
+jdmcu.mix : jdmcu.c jinclude.h jconfig.h jpegdata.h
+jdpipe.mix : jdpipe.c jinclude.h jconfig.h jpegdata.h
+jdsample.mix : jdsample.c jinclude.h jconfig.h jpegdata.h
+jerror.mix : jerror.c jinclude.h jconfig.h jpegdata.h
+jquant1.mix : jquant1.c jinclude.h jconfig.h jpegdata.h
+jquant2.mix : jquant2.c jinclude.h jconfig.h jpegdata.h
+jfwddct.mix : jfwddct.c jinclude.h jconfig.h jpegdata.h
+jrevdct.mix : jrevdct.c jinclude.h jconfig.h jpegdata.h
+jutils.mix : jutils.c jinclude.h jconfig.h jpegdata.h
+jvirtmem.mix : jvirtmem.c jinclude.h jconfig.h jpegdata.h
+jrdjfif.mix : jrdjfif.c jinclude.h jconfig.h jpegdata.h
+jrdgif.mix : jrdgif.c jinclude.h jconfig.h jpegdata.h
+jrdppm.mix : jrdppm.c jinclude.h jconfig.h jpegdata.h
+jrdrle.mix : jrdrle.c jinclude.h jconfig.h jpegdata.h
+jrdtarga.mix : jrdtarga.c jinclude.h jconfig.h jpegdata.h
+jwrjfif.mix : jwrjfif.c jinclude.h jconfig.h jpegdata.h
+jwrgif.mix : jwrgif.c jinclude.h jconfig.h jpegdata.h
+jwrppm.mix : jwrppm.c jinclude.h jconfig.h jpegdata.h
+jwrrle.mix : jwrrle.c jinclude.h jconfig.h jpegdata.h
+jwrtarga.mix : jwrtarga.c jinclude.h jconfig.h jpegdata.h
diff --git a/makefile.sas b/makefile.sas
new file mode 100644
index 0000000..877edc5
--- /dev/null
+++ b/makefile.sas
@@ -0,0 +1,152 @@
+# Makefile for Independent JPEG Group's software
+
+# This makefile is for Amiga systems using SAS C 5.10b.
+# Contributed by Ed Hanway (sisd!jeh@uunet.uu.net).
+
+# Read SETUP instructions before saying "make" !!
+
+# The name of your C compiler:
+CC= lc
+
+# Uncomment the following lines for generic 680x0 version
+ARCHFLAGS=
+SUFFIX=
+
+# Uncomment the following lines for 68030-only version
+#ARCHFLAGS= -m3
+#SUFFIX=.030
+
+# You may need to adjust these cc options:
+CFLAGS= -v -b -rr -O -j104 -D__STDC__ -DTWO_FILE_COMMANDLINE -DINCOMPLETE_TYPES_BROKEN $(ARCHFLAGS)
+# -j104 disables warnings for mismatched const qualifiers
+
+# Link-time cc options:
+LDFLAGS= SC SD ND BATCH
+
+# To link any special libraries, add the necessary commands here.
+LDLIBS= LIB LIB:lcr.lib
+
+# miscellaneous OS-dependent stuff
+# linker
+LN= blink
+# file deletion command
+RM= delete quiet
+# library (.lib) file creation command
+AR= oml
+
+
+# source files (independently compilable files)
+SOURCES= jbsmooth.c jcarith.c jccolor.c jcdeflts.c jcexpand.c jchuff.c \
+        jcmain.c jcmaster.c jcmcu.c jcpipe.c jcsample.c jdarith.c jdcolor.c \
+        jddeflts.c jdhuff.c jdmain.c jdmaster.c jdmcu.c jdpipe.c jdsample.c \
+        jerror.c jquant1.c jquant2.c jfwddct.c jrevdct.c jutils.c \
+        jvirtmem.c jrdjfif.c jrdgif.c jrdppm.c jrdrle.c jrdtarga.c \
+        jwrjfif.c jwrgif.c jwrppm.c jwrrle.c jwrtarga.c
+# files included by source files
+INCLUDES= jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c
+# documentation, test, and support files
+DOCS= README SETUP USAGE CHANGELOG cjpeg.1 djpeg.1 architecture codingrules
+MAKEFILES= makefile.ansi makefile.unix makefile.manx makefile.sas \
+        makefile.mc5 makefile.mc6 makcjpeg.lnk makdjpeg.lnk makefile.tc \
+        makcjpeg.lst makdjpeg.lst makefile.pwc makcjpeg.cf makdjpeg.cf \
+        makljpeg.cf
+OTHERFILES= ansi2knr.c config.c
+TESTFILES= testorig.jpg testimg.ppm testimg.jpg
+DISTFILES= $(DOCS) $(MAKEFILES) $(SOURCES) $(INCLUDES) $(OTHERFILES) \
+        $(TESTFILES)
+# objectfiles common to cjpeg and djpeg
+COMOBJECTS= jutils.o jvirtmem.o jerror.o
+# compression objectfiles
+CLIBOBJECTS= jcmaster.o jcdeflts.o jcarith.o jccolor.o jcexpand.o jchuff.o \
+        jcmcu.o jcpipe.o jcsample.o jfwddct.o jwrjfif.o jrdgif.o jrdppm.o \
+        jrdrle.o jrdtarga.o
+COBJECTS= jcmain.o $(CLIBOBJECTS) $(COMOBJECTS)
+# decompression objectfiles
+DLIBOBJECTS= jdmaster.o jddeflts.o jbsmooth.o jdarith.o jdcolor.o jdhuff.o \
+        jdmcu.o jdpipe.o jdsample.o jquant1.o jquant2.o jrevdct.o jrdjfif.o \
+        jwrgif.o jwrppm.o jwrrle.o jwrtarga.o
+DOBJECTS= jdmain.o $(DLIBOBJECTS) $(COMOBJECTS)
+# These objectfiles are included in libjpeg.lib
+LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
+
+
+all: cjpeg$(SUFFIX) djpeg$(SUFFIX)
+# By default, libjpeg.lib is not built unless you explicitly request it.
+# You can add libjpeg.lib to the line above if you want it built by default.
+
+
+cjpeg$(SUFFIX): $(COBJECTS)
+	$(LN) <WITH <
+$(LDFLAGS)
+TO cjpeg$(SUFFIX)
+FROM LIB:c.o $(COBJECTS)
+$(LDLIBS)
+<
+
+djpeg$(SUFFIX): $(DOBJECTS)
+	$(LN) <WITH <
+$(LDFLAGS)
+TO djpeg$(SUFFIX)
+FROM LIB:c.o $(DOBJECTS)
+$(LDLIBS)
+<
+
+# libjpeg.lib is useful if you are including the JPEG software in a larger
+# program; you'd include it in your link, rather than the individual modules.
+libjpeg.lib: $(LIBOBJECTS)
+	-$(RM) libjpeg.lib
+	$(AR) libjpeg.lib r $(LIBOBJECTS)
+
+clean:
+	-$(RM) *.o cjpeg djpeg cjpeg.030 djpeg.030 libjpeg.lib core testout.ppm testout.jpg
+
+distribute:
+	-$(RM) jpegsrc.tar*
+	tar cvf jpegsrc.tar $(DISTFILES)
+	compress -v jpegsrc.tar
+
+test: cjpeg djpeg
+	-$(RM) testout.ppm testout.jpg
+	djpeg testorig.jpg testout.ppm
+	cjpeg testimg.ppm testout.jpg
+	cmp testimg.ppm testout.ppm
+	cmp testimg.jpg testout.jpg
+
+
+jbsmooth.o : jbsmooth.c jinclude.h jconfig.h jpegdata.h 
+jcarith.o : jcarith.c jinclude.h jconfig.h jpegdata.h 
+jccolor.o : jccolor.c jinclude.h jconfig.h jpegdata.h 
+jcdeflts.o : jcdeflts.c jinclude.h jconfig.h jpegdata.h 
+jcexpand.o : jcexpand.c jinclude.h jconfig.h jpegdata.h 
+jchuff.o : jchuff.c jinclude.h jconfig.h jpegdata.h 
+jcmain.o : jcmain.c jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c 
+jcmaster.o : jcmaster.c jinclude.h jconfig.h jpegdata.h 
+jcmcu.o : jcmcu.c jinclude.h jconfig.h jpegdata.h 
+jcpipe.o : jcpipe.c jinclude.h jconfig.h jpegdata.h 
+jcsample.o : jcsample.c jinclude.h jconfig.h jpegdata.h 
+jdarith.o : jdarith.c jinclude.h jconfig.h jpegdata.h 
+jdcolor.o : jdcolor.c jinclude.h jconfig.h jpegdata.h 
+jddeflts.o : jddeflts.c jinclude.h jconfig.h jpegdata.h 
+jdhuff.o : jdhuff.c jinclude.h jconfig.h jpegdata.h 
+jdmain.o : jdmain.c jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c 
+jdmaster.o : jdmaster.c jinclude.h jconfig.h jpegdata.h 
+jdmcu.o : jdmcu.c jinclude.h jconfig.h jpegdata.h 
+jdpipe.o : jdpipe.c jinclude.h jconfig.h jpegdata.h 
+jdsample.o : jdsample.c jinclude.h jconfig.h jpegdata.h 
+jerror.o : jerror.c jinclude.h jconfig.h jpegdata.h 
+jquant1.o : jquant1.c jinclude.h jconfig.h jpegdata.h 
+jquant2.o : jquant2.c jinclude.h jconfig.h jpegdata.h 
+jfwddct.o : jfwddct.c jinclude.h jconfig.h jpegdata.h 
+jrevdct.o : jrevdct.c jinclude.h jconfig.h jpegdata.h 
+jutils.o : jutils.c jinclude.h jconfig.h jpegdata.h 
+jvirtmem.o : jvirtmem.c jinclude.h jconfig.h jpegdata.h 
+jrdjfif.o : jrdjfif.c jinclude.h jconfig.h jpegdata.h 
+jrdgif.o : jrdgif.c jinclude.h jconfig.h jpegdata.h 
+jrdppm.o : jrdppm.c jinclude.h jconfig.h jpegdata.h 
+jrdrle.o : jrdrle.c jinclude.h jconfig.h jpegdata.h 
+jrdtarga.o : jrdtarga.c jinclude.h jconfig.h jpegdata.h 
+jwrjfif.o : jwrjfif.c jinclude.h jconfig.h jpegdata.h 
+jwrgif.o : jwrgif.c jinclude.h jconfig.h jpegdata.h 
+jwrppm.o : jwrppm.c jinclude.h jconfig.h jpegdata.h 
+jwrrle.o : jwrrle.c jinclude.h jconfig.h jpegdata.h 
+jwrtarga.o : jwrtarga.c jinclude.h jconfig.h jpegdata.h 
diff --git a/makefile.tc b/makefile.tc
new file mode 100644
index 0000000..6c8eba0
--- /dev/null
+++ b/makefile.tc
@@ -0,0 +1,113 @@
+# Makefile for Independent JPEG Group's software
+
+# This makefile is suitable for Borland C (Turbo C) on MS-DOS.
+# It is set up for Borland C++ revision 2.0; if you have an older
+# version of Turbo C, you need to say "CC= tc" below.
+# Thanks to Tom Wright for this version.
+
+# Read SETUP instructions before saying "make" !!
+
+# The name of your C compiler:
+CC= bcc
+
+# You may need to adjust these cc options:
+CFLAGS= -c -ml -DINCOMPLETE_TYPES_BROKEN
+# -DINCOMPLETE_TYPES_BROKEN suppresses warnings about undefined structures
+
+# Link-time cc options:
+LDFLAGS= -ml
+
+
+# source files (independently compilable files)
+SOURCES= jbsmooth.c jcarith.c jccolor.c jcdeflts.c jcexpand.c jchuff.c \
+        jcmain.c jcmaster.c jcmcu.c jcpipe.c jcsample.c jdarith.c jdcolor.c \
+        jddeflts.c jdhuff.c jdmain.c jdmaster.c jdmcu.c jdpipe.c jdsample.c \
+        jerror.c jquant1.c jquant2.c jfwddct.c jrevdct.c jutils.c \
+        jvirtmem.c jrdjfif.c jrdgif.c jrdppm.c jrdrle.c jrdtarga.c \
+        jwrjfif.c jwrgif.c jwrppm.c jwrrle.c jwrtarga.c
+# files included by source files
+INCLUDES= jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c
+# documentation, test, and support files
+DOCS= README SETUP USAGE CHANGELOG cjpeg.1 djpeg.1 architecture codingrules
+MAKEFILES= makefile.ansi makefile.unix makefile.manx makefile.sas \
+        makefile.mc5 makefile.mc6 makcjpeg.lnk makdjpeg.lnk makefile.tc \
+        makcjpeg.lst makdjpeg.lst makefile.pwc makcjpeg.cf makdjpeg.cf \
+        makljpeg.cf
+OTHERFILES= ansi2knr.c config.c
+TESTFILES= testorig.jpg testimg.ppm testimg.jpg
+DISTFILES= $(DOCS) $(MAKEFILES) $(SOURCES) $(INCLUDES) $(OTHERFILES) \
+        $(TESTFILES)
+# objectfiles common to cjpeg and djpeg
+COMOBJECTS= jutils.obj jvirtmem.obj jerror.obj
+# compression objectfiles
+CLIBOBJECTS= jcmaster.obj jcdeflts.obj jcarith.obj jccolor.obj jcexpand.obj \
+        jchuff.obj jcmcu.obj jcpipe.obj jcsample.obj jfwddct.obj \
+        jwrjfif.obj jrdgif.obj jrdppm.obj jrdrle.obj jrdtarga.obj
+COBJECTS= jcmain.obj $(CLIBOBJECTS) $(COMOBJECTS)
+# decompression objectfiles
+DLIBOBJECTS= jdmaster.obj jddeflts.obj jbsmooth.obj jdarith.obj jdcolor.obj \
+        jdhuff.obj jdmcu.obj jdpipe.obj jdsample.obj jquant1.obj \
+        jquant2.obj jrevdct.obj jrdjfif.obj jwrgif.obj jwrppm.obj \
+        jwrrle.obj jwrtarga.obj
+DOBJECTS= jdmain.obj $(DLIBOBJECTS) $(COMOBJECTS)
+# These objectfiles are included in libjpeg.lib
+LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
+
+
+all: cjpeg.exe djpeg.exe
+
+
+cjpeg.exe: $(COBJECTS)
+	$(CC) $(LDFLAGS) -ecjpeg.exe @makcjpeg.lst
+
+djpeg.exe: $(DOBJECTS)
+	$(CC) $(LDFLAGS) -edjpeg.exe @makdjpeg.lst
+
+.c.obj:
+	$(CC) $(CFLAGS) $<
+
+test:
+	del testout.*
+	djpeg testorig.jpg testout.ppm
+	cjpeg testimg.ppm testout.jpg
+	fc testimg.ppm testout.ppm
+	fc testimg.jpg testout.jpg
+
+
+jbsmooth.o : jbsmooth.c jinclude.h jconfig.h jpegdata.h 
+jcarith.o : jcarith.c jinclude.h jconfig.h jpegdata.h 
+jccolor.o : jccolor.c jinclude.h jconfig.h jpegdata.h 
+jcdeflts.o : jcdeflts.c jinclude.h jconfig.h jpegdata.h 
+jcexpand.o : jcexpand.c jinclude.h jconfig.h jpegdata.h 
+jchuff.o : jchuff.c jinclude.h jconfig.h jpegdata.h 
+jcmain.o : jcmain.c jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c 
+jcmaster.o : jcmaster.c jinclude.h jconfig.h jpegdata.h 
+jcmcu.o : jcmcu.c jinclude.h jconfig.h jpegdata.h 
+jcpipe.o : jcpipe.c jinclude.h jconfig.h jpegdata.h 
+jcsample.o : jcsample.c jinclude.h jconfig.h jpegdata.h 
+jdarith.o : jdarith.c jinclude.h jconfig.h jpegdata.h 
+jdcolor.o : jdcolor.c jinclude.h jconfig.h jpegdata.h 
+jddeflts.o : jddeflts.c jinclude.h jconfig.h jpegdata.h 
+jdhuff.o : jdhuff.c jinclude.h jconfig.h jpegdata.h 
+jdmain.o : jdmain.c jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c 
+jdmaster.o : jdmaster.c jinclude.h jconfig.h jpegdata.h 
+jdmcu.o : jdmcu.c jinclude.h jconfig.h jpegdata.h 
+jdpipe.o : jdpipe.c jinclude.h jconfig.h jpegdata.h 
+jdsample.o : jdsample.c jinclude.h jconfig.h jpegdata.h 
+jerror.o : jerror.c jinclude.h jconfig.h jpegdata.h 
+jquant1.o : jquant1.c jinclude.h jconfig.h jpegdata.h 
+jquant2.o : jquant2.c jinclude.h jconfig.h jpegdata.h 
+jfwddct.o : jfwddct.c jinclude.h jconfig.h jpegdata.h 
+jrevdct.o : jrevdct.c jinclude.h jconfig.h jpegdata.h 
+jutils.o : jutils.c jinclude.h jconfig.h jpegdata.h 
+jvirtmem.o : jvirtmem.c jinclude.h jconfig.h jpegdata.h 
+jrdjfif.o : jrdjfif.c jinclude.h jconfig.h jpegdata.h 
+jrdgif.o : jrdgif.c jinclude.h jconfig.h jpegdata.h 
+jrdppm.o : jrdppm.c jinclude.h jconfig.h jpegdata.h 
+jrdrle.o : jrdrle.c jinclude.h jconfig.h jpegdata.h 
+jrdtarga.o : jrdtarga.c jinclude.h jconfig.h jpegdata.h 
+jwrjfif.o : jwrjfif.c jinclude.h jconfig.h jpegdata.h 
+jwrgif.o : jwrgif.c jinclude.h jconfig.h jpegdata.h 
+jwrppm.o : jwrppm.c jinclude.h jconfig.h jpegdata.h 
+jwrrle.o : jwrrle.c jinclude.h jconfig.h jpegdata.h 
+jwrtarga.o : jwrtarga.c jinclude.h jconfig.h jpegdata.h 
diff --git a/makefile.unix b/makefile.unix
index 0f11afa..c0a131f 100644
--- a/makefile.unix
+++ b/makefile.unix
@@ -1,30 +1,31 @@
 # Makefile for Independent JPEG Group's software
 
-# This makefile is suitable for Unix-like systems.
+# This makefile is suitable for Unix-like systems with non-ANSI compilers.
+# If you have an ANSI compiler, makefile.ansi is a better starting point.
 
-# See README and edit jconfig.h before saying "make" !!
+# Read SETUP instructions before saying "make" !!
 
-# Comment out this line if you don't have gcc:
-CC=gcc
+# The name of your C compiler:
+CC= cc
 
 # You may need to adjust these cc options:
-CFLAGS= -O -g -Wall -DHAVE_GETOPT -DMEM_STATS
-LDFLAGS= -g
+CFLAGS= -O
 # In particular:
-#   Remove -g and -Wall if not using gcc.
 #   Add -DBSD if on a pure BSD system (see jinclude.h).
-#   Remove -DHAVE_GETOPT if you don't have getopt(3) (see jcmain.c, jdmain.c).
-#   -DMEM_STATS is optional -- it enables gathering of memory usage statistics.
+#   Add -DVMS if on a VMS system (see ansi2knr.c).
+#   Add -DMSDOS if on an MSDOS system (see ansi2knr.c).
+#   Add -DMEM_STATS to enable gathering of memory usage statistics.
 #   You may also want to add -DTWO_FILE_COMMANDLINE or -D switches for other
 #   symbols listed in jconfig.h, if you prefer not to change jconfig.h.
-# If your compiler is non-ANSI, also see the .c.o rule below.
 
-# On HP-UX (and probably other SysV systems) the alternate malloc(3X) is a lot
-# faster than the standard malloc; this makes a noticeable difference in the
-# startup time when handling big noninterleaved images.  I say "-lmalloc" to
-# get the alternate allocator.  On most non-SysV systems you can just
-# define LDLIBS as empty.
-LDLIBS= -lmalloc
+# Link-time cc options:
+LDFLAGS= 
+
+# To link any special libraries, add the necessary -l commands here.
+# In particular, on some versions of HP-UX (and probably other SysV-derived
+# systems) there is a faster alternate malloc(3) library that you can use
+# by adding "-lmalloc" to this line.
+LDLIBS= 
 
 # miscellaneous OS-dependent stuff
 LN= $(CC)	# linker
@@ -33,69 +34,68 @@
 AR2= ranlib	# second step in .a creation (use "touch" if not needed)
 
 
-# source files
-INCLUDES= jinclude.h jconfig.h jpegdata.h 
-SOURCES= jbsmooth.c jcarith.c jccolor.c jcdeflts.c jcexpand.c \
-	 jchuff.c jcmain.c jcmaster.c jcmcu.c jcpipe.c jcsample.c \
-	 jdarith.c jdcolor.c jdhuff.c jdmain.c jdmaster.c jdmcu.c \
-	 jdpipe.c jdsample.c jerror.c jfwddct.c jquant1.c jquant2.c \
-	 jrdjfif.c jrdgif.c jrdppm.c jrevdct.c jutils.c jvirtmem.c \
-	 jwrjfif.c jwrgif.c jwrppm.c egetopt.c
-DOCS= README architecture codingrules
-MAKEFILES= makefile.unix makefile.amiga \
-	   makefile.mc5 makefile.mc6 makcjpeg.lnk makdjpeg.lnk \
-	   makefile.pwc makcjpeg.cf makdjpeg.cf makljpeg.cf
+# source files (independently compilable files)
+SOURCES= jbsmooth.c jcarith.c jccolor.c jcdeflts.c jcexpand.c jchuff.c \
+        jcmain.c jcmaster.c jcmcu.c jcpipe.c jcsample.c jdarith.c jdcolor.c \
+        jddeflts.c jdhuff.c jdmain.c jdmaster.c jdmcu.c jdpipe.c jdsample.c \
+        jerror.c jquant1.c jquant2.c jfwddct.c jrevdct.c jutils.c \
+        jvirtmem.c jrdjfif.c jrdgif.c jrdppm.c jrdrle.c jrdtarga.c \
+        jwrjfif.c jwrgif.c jwrppm.c jwrrle.c jwrtarga.c
+# files included by source files
+INCLUDES= jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c
+# documentation, test, and support files
+DOCS= README SETUP USAGE CHANGELOG cjpeg.1 djpeg.1 architecture codingrules
+MAKEFILES= makefile.ansi makefile.unix makefile.manx makefile.sas \
+        makefile.mc5 makefile.mc6 makcjpeg.lnk makdjpeg.lnk makefile.tc \
+        makcjpeg.lst makdjpeg.lst makefile.pwc makcjpeg.cf makdjpeg.cf \
+        makljpeg.cf
+OTHERFILES= ansi2knr.c config.c
 TESTFILES= testorig.jpg testimg.ppm testimg.jpg
-DISTFILES= $(DOCS) $(MAKEFILES) ansi2knr.c $(SOURCES) $(INCLUDES) $(TESTFILES)
-
+DISTFILES= $(DOCS) $(MAKEFILES) $(SOURCES) $(INCLUDES) $(OTHERFILES) \
+        $(TESTFILES)
+# objectfiles common to cjpeg and djpeg
+COMOBJECTS= jutils.o jvirtmem.o jerror.o
 # compression objectfiles
-COBJECTS = jcmain.o jcmaster.o jcdeflts.o jcarith.o jccolor.o jcexpand.o \
-	   jchuff.o jcmcu.o jcpipe.o jcsample.o jfwddct.o \
-	   jrdgif.o jrdppm.o jwrjfif.o \
-	   jutils.o jvirtmem.o jerror.o
+CLIBOBJECTS= jcmaster.o jcdeflts.o jcarith.o jccolor.o jcexpand.o jchuff.o \
+        jcmcu.o jcpipe.o jcsample.o jfwddct.o jwrjfif.o jrdgif.o jrdppm.o \
+        jrdrle.o jrdtarga.o
+COBJECTS= jcmain.o $(CLIBOBJECTS) $(COMOBJECTS)
 # decompression objectfiles
-DOBJECTS = jdmain.o jdmaster.o jbsmooth.o jdarith.o jdcolor.o jdhuff.o \
-	   jdmcu.o jdpipe.o jdsample.o jquant1.o jquant2.o jrevdct.o \
-	   jrdjfif.o jwrgif.o jwrppm.o \
-	   jutils.o jvirtmem.o jerror.o
-# These objectfiles are included in libjpeg.a (all but jcmain.o, jdmain.o)
-LIBOBJECTS = jcmaster.o jcdeflts.o jcarith.o jccolor.o jcexpand.o \
-	     jchuff.o jcmcu.o jcpipe.o jcsample.o jfwddct.o \
-	     jrdgif.o jrdppm.o jwrjfif.o \
-	     jdmaster.o jbsmooth.o jdarith.o jdcolor.o jdhuff.o \
-	     jdmcu.o jdpipe.o jdsample.o jquant1.o jquant2.o jrevdct.o \
-	     jrdjfif.o jwrgif.o jwrppm.o \
-	     jutils.o jvirtmem.o jerror.o
+DLIBOBJECTS= jdmaster.o jddeflts.o jbsmooth.o jdarith.o jdcolor.o jdhuff.o \
+        jdmcu.o jdpipe.o jdsample.o jquant1.o jquant2.o jrevdct.o jrdjfif.o \
+        jwrgif.o jwrppm.o jwrrle.o jwrtarga.o
+DOBJECTS= jdmain.o $(DLIBOBJECTS) $(COMOBJECTS)
+# These objectfiles are included in libjpeg.a
+LIBOBJECTS= $(CLIBOBJECTS) $(DLIBOBJECTS) $(COMOBJECTS)
 
 
-all: cjpeg djpeg
+all: ansi2knr cjpeg djpeg
 # By default, libjpeg.a is not built unless you explicitly request it.
+# You can add libjpeg.a to the line above if you want it built by default.
 
 
-# If you have a C compiler that doesn't understand function prototypes,
-# uncomment the 5 lines below and make sure PROTO is not defined by jconfig.h.
-# Then say "make ansi2knr" before "make".
+# This rule causes ansi2knr to be invoked.  If you use this makefile,
+# make sure PROTO is not defined by jconfig.h.
 
-#.c.o:
-#	./ansi2knr $*.c tmpansi.c
-#	$(CC) $(CFLAGS) -c tmpansi.c
-#	mv tmpansi.o $*.o
-#	$(RM) tmpansi.c
+.c.o:
+	./ansi2knr $*.c tmpansi.c
+	$(CC) $(CFLAGS) -c tmpansi.c
+	mv tmpansi.o $*.o
+	$(RM) tmpansi.c
 
 ansi2knr: ansi2knr.c
-	$(CC) -o ansi2knr ansi2knr.c
-# You may need to add one of -DBSD, -DVMS, or -DMSDOS to the line above.
+	$(CC) $(CFLAGS) -o ansi2knr ansi2knr.c
 
 
-cjpeg: $(COBJECTS)
+cjpeg: ansi2knr $(COBJECTS)
 	$(LN) $(LDFLAGS) -o cjpeg $(COBJECTS) $(LDLIBS)
 
-djpeg: $(DOBJECTS)
+djpeg: ansi2knr $(DOBJECTS)
 	$(LN) $(LDFLAGS) -o djpeg $(DOBJECTS) $(LDLIBS)
 
 # libjpeg.a is useful if you are including the JPEG software in a larger
 # program; you'd include it in your link, rather than the individual modules.
-libjpeg.a: $(LIBOBJECTS)
+libjpeg.a: ansi2knr $(LIBOBJECTS)
 	$(RM) libjpeg.a
 	$(AR) libjpeg.a  $(LIBOBJECTS)
 	$(AR2) libjpeg.a
@@ -106,9 +106,7 @@
 distribute:
 	$(RM) jpegsrc.tar*
 	tar cvf jpegsrc.tar $(DISTFILES)
-	ls -l jpegsrc.tar
 	compress -v jpegsrc.tar
-	ls -l jpegsrc.tar*
 
 test: cjpeg djpeg
 	$(RM) testout.ppm testout.jpg
@@ -124,29 +122,34 @@
 jcdeflts.o : jcdeflts.c jinclude.h jconfig.h jpegdata.h 
 jcexpand.o : jcexpand.c jinclude.h jconfig.h jpegdata.h 
 jchuff.o : jchuff.c jinclude.h jconfig.h jpegdata.h 
-jcmain.o : jcmain.c jinclude.h jconfig.h jpegdata.h egetopt.c 
+jcmain.o : jcmain.c jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c 
 jcmaster.o : jcmaster.c jinclude.h jconfig.h jpegdata.h 
 jcmcu.o : jcmcu.c jinclude.h jconfig.h jpegdata.h 
 jcpipe.o : jcpipe.c jinclude.h jconfig.h jpegdata.h 
 jcsample.o : jcsample.c jinclude.h jconfig.h jpegdata.h 
 jdarith.o : jdarith.c jinclude.h jconfig.h jpegdata.h 
 jdcolor.o : jdcolor.c jinclude.h jconfig.h jpegdata.h 
+jddeflts.o : jddeflts.c jinclude.h jconfig.h jpegdata.h 
 jdhuff.o : jdhuff.c jinclude.h jconfig.h jpegdata.h 
-jdmain.o : jdmain.c jinclude.h jconfig.h jpegdata.h egetopt.c
+jdmain.o : jdmain.c jinclude.h jconfig.h jpegdata.h jversion.h egetopt.c 
 jdmaster.o : jdmaster.c jinclude.h jconfig.h jpegdata.h 
 jdmcu.o : jdmcu.c jinclude.h jconfig.h jpegdata.h 
 jdpipe.o : jdpipe.c jinclude.h jconfig.h jpegdata.h 
 jdsample.o : jdsample.c jinclude.h jconfig.h jpegdata.h 
 jerror.o : jerror.c jinclude.h jconfig.h jpegdata.h 
-jfwddct.o : jfwddct.c jinclude.h jconfig.h jpegdata.h 
 jquant1.o : jquant1.c jinclude.h jconfig.h jpegdata.h 
 jquant2.o : jquant2.c jinclude.h jconfig.h jpegdata.h 
-jrdjfif.o : jrdjfif.c jinclude.h jconfig.h jpegdata.h 
-jrdgif.o : jrdgif.c jinclude.h jconfig.h jpegdata.h 
-jrdppm.o : jrdppm.c jinclude.h jconfig.h jpegdata.h 
+jfwddct.o : jfwddct.c jinclude.h jconfig.h jpegdata.h 
 jrevdct.o : jrevdct.c jinclude.h jconfig.h jpegdata.h 
 jutils.o : jutils.c jinclude.h jconfig.h jpegdata.h 
 jvirtmem.o : jvirtmem.c jinclude.h jconfig.h jpegdata.h 
+jrdjfif.o : jrdjfif.c jinclude.h jconfig.h jpegdata.h 
+jrdgif.o : jrdgif.c jinclude.h jconfig.h jpegdata.h 
+jrdppm.o : jrdppm.c jinclude.h jconfig.h jpegdata.h 
+jrdrle.o : jrdrle.c jinclude.h jconfig.h jpegdata.h 
+jrdtarga.o : jrdtarga.c jinclude.h jconfig.h jpegdata.h 
 jwrjfif.o : jwrjfif.c jinclude.h jconfig.h jpegdata.h 
 jwrgif.o : jwrgif.c jinclude.h jconfig.h jpegdata.h 
 jwrppm.o : jwrppm.c jinclude.h jconfig.h jpegdata.h 
+jwrrle.o : jwrrle.c jinclude.h jconfig.h jpegdata.h 
+jwrtarga.o : jwrtarga.c jinclude.h jconfig.h jpegdata.h 
diff --git a/makljpeg.cf b/makljpeg.cf
index 3325bf4..176fcf3 100644
--- a/makljpeg.cf
+++ b/makljpeg.cf
@@ -1,5 +1,6 @@
-jbsmooth.mix,jcarith.mix,jccolor.mix,jcdeflts.mix,jcexpand.mix,jchuff.mix
-jcmaster.mix,jcmcu.mix,jcpipe.mix,jcsample.mix,jdarith.mix,jdcolor.mix
-jdhuff.mix,jdmaster.mix,jdmcu.mix,jdpipe.mix,jdsample.mix,jerror.mix
-jfwddct.mix,jquant1.mix,jquant2.mix,jrdgif.mix,jrdjfif.mix,jrdppm.mix
-jrevdct.mix,jutils.mix,jvirtmem.mix,jwrgif.mix,jwrjfif.mix,jwrppm.mix
+jcmaster.mix,jcdeflts.mix,jcarith.mix,jccolor.mix,jcexpand.mix,jchuff.mix
+jcmcu.mix,jcpipe.mix,jcsample.mix,jfwddct.mix,jwrjfif.mix,jrdgif.mix
+jrdppm.mix,jrdrle.mix,jrdtarga.mix,jdmaster.mix,jddeflts.mix,jbsmooth.mix
+jdarith.mix,jdcolor.mix,jdhuff.mix,jdmcu.mix,jdpipe.mix,jdsample.mix
+jquant1.mix,jquant2.mix,jrevdct.mix,jrdjfif.mix,jwrgif.mix,jwrppm.mix
+jwrrle.mix,jwrtarga.mix,jutils.mix,jvirtmem.mix,jerror.mix
diff --git a/testimg.jpg b/testimg.jpg
index b6b68bc..220ac8f 100644
--- a/testimg.jpg
+++ b/testimg.jpg
Binary files differ
diff --git a/testimg.ppm b/testimg.ppm
index c7dab37..b00bd76 100644
--- a/testimg.ppm
+++ b/testimg.ppm
Binary files differ
diff --git a/testorig.jpg b/testorig.jpg
index 1a628fc..d37b1da 100644
--- a/testorig.jpg
+++ b/testorig.jpg
Binary files differ