2008-03-31  Juan Manuel Guerrero  <juan.guerrero@gmx.de>

	* bzip2.c [BZ_UNIX, __DJGPP__]: Move macro definition HAS_LFN_SUPPORT
	from inside the __DJGPP__ section into the BZ_UNIX section.  This makes
	sure that the DJGPP patch does not break the posix sources.
	Use new function baseName instead of the libc one.  This makes porting
	easier.
	Use FILENAME_MAX or PATH_MAX to define macro FILE_NAME_LEN before
	defaulting to some arbitrary value.
	(uncompress): Rewrite from scratch SFN handling.
	(license): Add DJGPP specific port version info.
	* bzip2.c [__DJGPP__]: Define new macro BZ_DOS.
	Define macros HAVE_SIGBUS, IS_PATH_SEP(c), MY_LSTAT, MY_STAT,
	MY_S_ISREG, MY_S_ISDIR and MY_STDOUT for no DJGPP systems.
	[BZ_UNIX] [__DJGPP__]: Define macros HAVE_SIGBUS, IS_PATH_SEP,
	HAS_EXTENSION, HAS_TAR_EXTENSION, HAS_LFN_SUPPORT, MY_LSTAT, MY_STDOUT
	and SET_BINARY_MODE.
	[BZ_UNIX] [__CYGWIN__]: Define macro MY_STDOUT.
	[BZ_LCCWIN32]: Define macros HAVE_SIGBUS, IS_PATH_SEP and MY_STDOUT.
	[BZ_DOS]: Define new varaiable dosFileNameRule1.
	Declare and define new function addBZ2Suffix.
	(containsDubiousChars): Perform test if BZ_DOS defined.
	(compress): Use addBZ2Suffix to check for LFN support at run time and
	add the .bz2 extension to the archive instead of using strcat() and
	inconditionally adding the extension violating certain file system
	restrictions.
	(uncompress): Implement naming rules for file systems with severe file
	name restrictions.
	(license): Use MY_STDOUT instead od stderr.
	(usage): Use MY_STDOUT instead od stderr.
	(usage) [BZ_DOS]: Add info about new MSDOS/DJGPP specific options.
	(main) [BZ_DOS]: Set dosFileNameRule1.
	Use feature specific macro HAVE_SIGBUS instead of __DJGPP__ to decide
	if feature is available or not.
	Use macro IS_PATH_SEP to detect OS specific path separator.
	[BZ_DOS]: Add MSDOS/DJGPP specific option to argument decoder list.
	(applySavedFileAttrToOutputFile) [BZ_DOS]: Do not try to restore/modify
	saved file attributes and ownership.  It makes no much sense on MSDOS.

	* bzip2recover.c: Do not include <unistd.h> only for DJGPP.  pathconf
	is always needed by HAS_LFN_SUPPORT macro.
	Define macros HAS_LFN_SUPPORT and HAS_EXTENSION always and not only
	for DJGPP.
	Define BZ_MAX_FILENAME to FILENAME_MAX (ANSI), if not possible define
	to PATH_MAX (Posix), if not possible default to 2000.
	[__DJGPP__]: Define macros IS_DIR_SEPARATOR, HAS_LFN_SUPPORT and
	HAS_EXTENSION.
	(bsGetBit): Initialize errno to 0 before calling getc.
	[__DJGPP__]: Do not use the logic behind macro BZ_SPLIT_SYM, the macro
	IS_DIR_SEPARATOR does the right thing for DJGPP.
	(main): New variables dirNameLength and baseName.
	Compute dirname length and basename.
	[BZ_SPLIT_SYM]: Use this logic only if not compiled with DJGPP.  On
	systems where LFN or SFN support is only known at run time, take care
	not to exceed file system limits.

	* bzlib.h: Add info that files have been modified for DJGPP.

	* bzlib.c [_WIN32], [OS2], [MSDOS]: Include unistad.h for isatty.
	Define SET_BINARY_MODE in such a way that it is checked if stdin/stdout
	is not connected to TTY before switching to binary mode.
	(bzopen_or_bzdopen) [_WIN32], [OS2], [MSDOS]: Check that file is not
	connected to TTY before switching to binary mode.

	* bzdiff: Modified for the use with DJGPP without trying to keep
	compatibility with the original script.  Check for TMPDIR, TMP
	and TEMP before setting the temporary directory to cwd.  Add DJDIR
	to search path.  Use DJGPP port of rm.

	* bzgrep: Modified for the use with DJGPP without trying to keep
	compatibility with the original script.  Add DJDIR to search path.

	* bzip2.1: Added DJGPP specific information concerning the behaviour
	of the port in sort file name (SFN) environment.

	* bzmore: Modified for the use with DJGPP without trying to keep
	compatibility with the original script.  Add DJDIR to search path.

	* Makefile: Added EXEEXT.  PREFIX set to /dev/env/DJDIR.  bunzip.exe
	and bzcat.exe implemented as symlinks insteed of copies.
	Split target install in install-bin and install-lib.

	* words3: Reflect the paths of the stock DJGPP installation tree.



diff -aprNU5 bzip2-1.0.5.orig/Makefile bzip2-1.0.5/Makefile
--- bzip2-1.0.5.orig/Makefile	2008-02-14 12:39:18 +0000
+++ bzip2-1.0.5/Makefile	2008-03-31 16:46:36 +0000
@@ -21,97 +21,98 @@ RANLIB=ranlib
 LDFLAGS=
 
 BIGFILES=-D_FILE_OFFSET_BITS=64
 CFLAGS=-Wall -Winline -O2 -g $(BIGFILES)
 
+EXEEXT=.exe
+
 # Where you want it installed when you do 'make install'
-PREFIX=/usr/local
+PREFIX=/dev/env/DJDIR
 
 
 OBJS= blocksort.o  \
       huffman.o    \
       crctable.o   \
       randtable.o  \
       compress.o   \
       decompress.o \
       bzlib.o
 
-all: libbz2.a bzip2 bzip2recover test
+all: libbz2.a bzip2$(EXEEXT) bzip2recover$(EXEEXT) test
 
-bzip2: libbz2.a bzip2.o
-	$(CC) $(CFLAGS) $(LDFLAGS) -o bzip2 bzip2.o -L. -lbz2
+bzip2$(EXEEXT): libbz2.a bzip2.o
+	$(CC) $(CFLAGS) $(LDFLAGS) -o bzip2$(EXEEXT) bzip2.o -L. -lbz2
 
-bzip2recover: bzip2recover.o
-	$(CC) $(CFLAGS) $(LDFLAGS) -o bzip2recover bzip2recover.o
+bzip2recover$(EXEEXT): bzip2recover.o
+	$(CC) $(CFLAGS) $(LDFLAGS) -o bzip2recover$(EXEEXT) bzip2recover.o
 
 libbz2.a: $(OBJS)
 	rm -f libbz2.a
-	$(AR) cq libbz2.a $(OBJS)
-	@if ( test -f $(RANLIB) -o -f /usr/bin/ranlib -o \
-		-f /bin/ranlib -o -f /usr/ccs/bin/ranlib ) ; then \
-		echo $(RANLIB) libbz2.a ; \
-		$(RANLIB) libbz2.a ; \
-	fi
+	$(AR) cqs libbz2.a $(OBJS)
 
 check: test
-test: bzip2
+test: bzip2$(EXEEXT)
 	@cat words1
-	./bzip2 -1  < sample1.ref > sample1.rb2
-	./bzip2 -2  < sample2.ref > sample2.rb2
-	./bzip2 -3  < sample3.ref > sample3.rb2
-	./bzip2 -d  < sample1.bz2 > sample1.tst
-	./bzip2 -d  < sample2.bz2 > sample2.tst
-	./bzip2 -ds < sample3.bz2 > sample3.tst
+	./bzip2$(EXEEXT) -1  < sample1.ref > sample1.rb2
+	./bzip2$(EXEEXT) -2  < sample2.ref > sample2.rb2
+	./bzip2$(EXEEXT) -3  < sample3.ref > sample3.rb2
+	./bzip2$(EXEEXT) -d  < sample1.bz2 > sample1.tst
+	./bzip2$(EXEEXT) -d  < sample2.bz2 > sample2.tst
+	./bzip2$(EXEEXT) -ds < sample3.bz2 > sample3.tst
 	cmp sample1.bz2 sample1.rb2 
 	cmp sample2.bz2 sample2.rb2
 	cmp sample3.bz2 sample3.rb2
 	cmp sample1.tst sample1.ref
 	cmp sample2.tst sample2.ref
 	cmp sample3.tst sample3.ref
 	@cat words3
 
-install: bzip2 bzip2recover
+install: install-bin install-lib
+
+install-bin: bzip2$(EXEEXT) bzip2recover$(EXEEXT)
 	if ( test ! -d $(PREFIX)/bin ) ; then mkdir -p $(PREFIX)/bin ; fi
-	if ( test ! -d $(PREFIX)/lib ) ; then mkdir -p $(PREFIX)/lib ; fi
 	if ( test ! -d $(PREFIX)/man ) ; then mkdir -p $(PREFIX)/man ; fi
 	if ( test ! -d $(PREFIX)/man/man1 ) ; then mkdir -p $(PREFIX)/man/man1 ; fi
-	if ( test ! -d $(PREFIX)/include ) ; then mkdir -p $(PREFIX)/include ; fi
-	cp -f bzip2 $(PREFIX)/bin/bzip2
-	cp -f bzip2 $(PREFIX)/bin/bunzip2
-	cp -f bzip2 $(PREFIX)/bin/bzcat
-	cp -f bzip2recover $(PREFIX)/bin/bzip2recover
-	chmod a+x $(PREFIX)/bin/bzip2
-	chmod a+x $(PREFIX)/bin/bunzip2
-	chmod a+x $(PREFIX)/bin/bzcat
-	chmod a+x $(PREFIX)/bin/bzip2recover
+	cp -f bzip2$(EXEEXT) $(PREFIX)/bin/bzip2$(EXEEXT)
+	ln -s -f $(PREFIX)/bin/bzip2$(EXEEXT) $(PREFIX)/bin/bunzip2$(EXEEXT)
+	ln -s -f $(PREFIX)/bin/bzip2$(EXEEXT) $(PREFIX)/bin/bzcat$(EXEEXT)
+	cp -f bzip2recover$(EXEEXT) $(PREFIX)/bin/bzip2recover$(EXEEXT)
+	chmod a+x $(PREFIX)/bin/bzip2$(EXEEXT)
+	chmod a+x $(PREFIX)/bin/bunzip2$(EXEEXT)
+	chmod a+x $(PREFIX)/bin/bzcat$(EXEEXT)
+	chmod a+x $(PREFIX)/bin/bzip2recover$(EXEEXT)
 	cp -f bzip2.1 $(PREFIX)/man/man1
 	chmod a+r $(PREFIX)/man/man1/bzip2.1
-	cp -f bzlib.h $(PREFIX)/include
-	chmod a+r $(PREFIX)/include/bzlib.h
-	cp -f libbz2.a $(PREFIX)/lib
-	chmod a+r $(PREFIX)/lib/libbz2.a
 	cp -f bzgrep $(PREFIX)/bin/bzgrep
-	ln -s -f $(PREFIX)/bin/bzgrep $(PREFIX)/bin/bzegrep
-	ln -s -f $(PREFIX)/bin/bzgrep $(PREFIX)/bin/bzfgrep
+	ln -f $(PREFIX)/bin/bzgrep $(PREFIX)/bin/bzegrep
+	ln -f $(PREFIX)/bin/bzgrep $(PREFIX)/bin/bzfgrep
 	chmod a+x $(PREFIX)/bin/bzgrep
 	cp -f bzmore $(PREFIX)/bin/bzmore
-	ln -s -f $(PREFIX)/bin/bzmore $(PREFIX)/bin/bzless
+	ln -f $(PREFIX)/bin/bzmore $(PREFIX)/bin/bzless
 	chmod a+x $(PREFIX)/bin/bzmore
 	cp -f bzdiff $(PREFIX)/bin/bzdiff
-	ln -s -f $(PREFIX)/bin/bzdiff $(PREFIX)/bin/bzcmp
+	ln -f $(PREFIX)/bin/bzdiff $(PREFIX)/bin/bzcmp
 	chmod a+x $(PREFIX)/bin/bzdiff
 	cp -f bzgrep.1 bzmore.1 bzdiff.1 $(PREFIX)/man/man1
 	chmod a+r $(PREFIX)/man/man1/bzgrep.1
 	chmod a+r $(PREFIX)/man/man1/bzmore.1
 	chmod a+r $(PREFIX)/man/man1/bzdiff.1
-	echo ".so man1/bzgrep.1" > $(PREFIX)/man/man1/bzegrep.1
-	echo ".so man1/bzgrep.1" > $(PREFIX)/man/man1/bzfgrep.1
-	echo ".so man1/bzmore.1" > $(PREFIX)/man/man1/bzless.1
-	echo ".so man1/bzdiff.1" > $(PREFIX)/man/man1/bzcmp.1
+	cp -f bzgrep.1 $(PREFIX)/man/man1/bzegrep.1
+	cp -f bzgrep.1 $(PREFIX)/man/man1/bzfgrep.1
+	cp -f bzmore.1 $(PREFIX)/man/man1/bzless.1
+	cp -f bzdiff.1 $(PREFIX)/man/man1/bzcmp.1
+
+install-lib: libbz2.a
+	if ( test ! -d $(PREFIX)/lib ) ; then mkdir -p $(PREFIX)/lib ; fi
+	if ( test ! -d $(PREFIX)/include ) ; then mkdir -p $(PREFIX)/include ; fi
+	cp -f bzlib.h $(PREFIX)/include
+	chmod a+r $(PREFIX)/include/bzlib.h
+	cp -f libbz2.a $(PREFIX)/lib
+	chmod a+r $(PREFIX)/lib/libbz2.a
 
 clean: 
-	rm -f *.o libbz2.a bzip2 bzip2recover \
+	rm -f *.o libbz2.a bzip2$(EXEEXT) bzip2recover$(EXEEXT) \
 	sample1.rb2 sample2.rb2 sample3.rb2 \
 	sample1.tst sample2.tst sample3.tst
 
 blocksort.o: blocksort.c
 	@cat words0
diff -aprNU5 bzip2-1.0.5.orig/bzdiff bzip2-1.0.5/bzdiff
--- bzip2-1.0.5.orig/bzdiff	2007-01-03 02:00:54 +0000
+++ bzip2-1.0.5/bzdiff	2008-03-31 16:45:56 +0000
@@ -10,11 +10,29 @@
 # the  files  compared  are file1 and an uncompressed file1.gz.
 # If two files are specified, then they are  uncompressed  (if
 # necessary) and fed to cmp or diff.  The exit status from cmp
 # or diff is preserved.
 
-PATH="/usr/bin:/bin:$PATH"; export PATH
+#
+# Modified for the use with DJGPP.  There is no intention to
+# keep POSIX/UNIX compatibility because submitted patch to
+# bzip2 author has never been accepted.
+#
+# Juan  Manuel Guerrero.
+#
+
+tmpdir=${TMPDIR-${TMP-${TEMP}}}
+if test ! -d "$tmpdir"; then
+  tmpdir=.
+fi
+
+RM=/bin/rm
+if test -n "$DJGPP$djgpp"; then
+  RM=/dev/env/DJDIR/rm
+fi
+
+PATH="/dev/env/DJDIR/bin;$PATH"; export PATH
 prog=`echo $0 | sed 's|.*/||'`
 case "$prog" in
   *cmp) comp=${CMP-cmp}   ;;
   *)    comp=${DIFF-diff} ;;
 esac
@@ -35,11 +53,11 @@ do
 done
 if test -z "$FILES"; then
 	echo "Usage: $prog [${comp}_options] file [file]"
 	exit 1
 fi
-tmp=`mktemp ${TMPDIR:-/tmp}/bzdiff.XXXXXXXXXX` || {
+tmp=`mktemp ${tmpdir}/bzdiff.XXXXXXXXXX` || {
       echo 'cannot create a temporary file' >&2
       exit 1
 }
 set $FILES
 if test $# -eq 1; then
@@ -54,11 +72,11 @@ elif test $# -eq 2; then
 	        *.bz2)
 			F=`echo "$2" | sed 's|.*/||;s|.bz2$||'`
                         bzip2 -cdfq "$2" > $tmp
                         bzip2 -cdfq "$1" | $comp $OPTIONS - $tmp
                         STAT="$?"
-			/bin/rm -f $tmp;;
+			RM -f $tmp;;
 
                 *)      bzip2 -cdfq "$1" | $comp $OPTIONS - "$2"
                         STAT="$?";;
                 esac;;
         *)      case "$2" in
diff -aprNU5 bzip2-1.0.5.orig/bzgrep bzip2-1.0.5/bzgrep
--- bzip2-1.0.5.orig/bzgrep	2007-01-03 02:00:54 +0000
+++ bzip2-1.0.5/bzgrep	2008-03-31 16:38:00 +0000
@@ -4,11 +4,19 @@
 # adapted from zgrep by Philippe Troin <phil@fifi.org> for Debian GNU/Linux.
 ## zgrep notice:
 ## zgrep -- a wrapper around a grep program that decompresses files as needed
 ## Adapted from a version sent by Charles Levert <charles@comm.polymtl.ca>
 
-PATH="/usr/bin:$PATH"; export PATH
+#
+# Modified for the use with DJGPP.  There is no intention to
+# keep POSIX/UNIX compatibility because submitted patch to
+# bzip2 author has never been accepted.
+#
+# Juan  Manuel Guerrero.
+#
+
+PATH="/dev/env/DJDIR/bin;$PATH"; export PATH
 
 prog=`echo $0 | sed 's|.*/||'`
 case "$prog" in
 	*egrep)	grep=${EGREP-egrep}	;;
 	*fgrep)	grep=${FGREP-fgrep}	;;
diff -aprNU5 bzip2-1.0.5.orig/bzip2.1 bzip2-1.0.5/bzip2.1
--- bzip2-1.0.5.orig/bzip2.1	2007-01-03 02:00:54 +0000
+++ bzip2-1.0.5/bzip2.1	2008-03-31 16:37:28 +0000
@@ -8,18 +8,18 @@ bzcat \- decompresses files to stdout
 bzip2recover \- recovers data from damaged bzip2 files
 
 .SH SYNOPSIS
 .ll +8
 .B bzip2
-.RB [ " \-cdfkqstvzVL123456789 " ]
+.RB [ " \-cdfknqstvzVL123456789 " ]
 [
 .I "filenames \&..."
 ]
 .ll -8
 .br
 .B bunzip2
-.RB [ " \-fkvsVL " ]
+.RB [ " \-fknvsVL " ]
 [ 
 .I "filenames \&..."
 ]
 .br
 .B bzcat
@@ -100,10 +100,72 @@ complains that it cannot
 guess the name of the original file, and uses the original name
 with
 .I .out
 appended.
 
+The above applies also to the DJGPP port of
+.I bzip2
+when LFN support is avaliable.
+If LFN support is not available (plain DOS and WIN9X with LFN=n) the file name
+and the extension will not be properly preserved at the same time.
+This port offers the user the choice between two rules to create the name of the
+compressed file. The first rule (default) will preserve the file name at the cost
+of truncating the extension. The second rule will preserve the extension and truncate
+the file name. The different rules are selected by omitting or setting the
+.I \-n
+flag.
+
+Rule 1: file name preserving and extension truncating.
+This is the default rule. If the
+.I \-n
+flag is omitted then this rule will be used.
+With this rule the following types of file names will be created:
+
+When compressing:
+       filename       becomes   filename.bz2
+       filename.e     becomes   filename.ebz
+       filename.ex    becomes   filename.exb
+       filename.ext   becomes   filename.exb
+       filename.tar   becomes   filename.tbz
+
+When decompressing:
+       filename.bz2   becomes   filename
+       filename.b     becomes   filename
+       filename.ebz   becomes   filename.e
+       filename.exb   becomes   filename.ex
+       filename.tbz   becomes   filename.tar
+       anyothername   becomes   anyothername.out
+
+Rule 2: file name truncating and extension preserving.
+This rule must be explicity enabled by setting the
+.I \-n
+flag.
+With this rule backward compatibility with other MSDOS ports of
+.I bzip2
+is achieved.
+With this rule the following types of file names will be created:
+
+When compressing:
+       filename       becomes   filename.bz2
+       filename.e     becomes   filena_e.bz2
+       filename.ex    becomes   filen_ex.bz2
+       filename.ext   becomes   file_ext.bz2
+       filename.tar   becomes   filename.tbz
+
+When decompressing:
+       filename.bz2   becomes   filename
+       filena_e.bz2   becomes   filena.e
+       filen_ex.bz2   becomes   filen.ex
+       file_ext.bz2   becomes   file.ext
+       filename.tbz   becomes   filename.tar
+       anyothername   becomes   anyothername.out
+
+The same rule must be used for compression and decompression.
+The
+.I \-n
+flag is ignored on WIN9X with LFN=y.
+
 As with compression, supplying no
 filenames causes decompression from 
 standard input to standard output.
 
 .I bunzip2 
@@ -259,10 +321,29 @@ with a dash, for example: bzip2 \-- \-my
 .B \--repetitive-fast --repetitive-best
 These flags are redundant in versions 0.9.5 and above.  They provided
 some coarse control over the behaviour of the sorting algorithm in
 earlier versions, which was sometimes useful.  0.9.5 and above have an
 improved algorithm which renders these flags irrelevant.
+.TP
+.B \-n
+This flag is only available for DJGPP ports of
+.I bzip2
+on plain DOS and WIN9X with LFN=n and is ignored on WIN9X with LFN=y.
+This flag selects one of two rules to create the name of the compressed
+file. If this flag is omitted then rule 1 will be used. Rule 1 preserves
+the original file name and truncates the extension. If the extension has
+the length of one character a 
+.I bz
+will be added to the extension. If the extension has two characters a
+.I b
+character will be added to the extension else the third character of
+the extension will be overwritten with a
+.I b
+character.
+If the flag is set then rule 2 will be used. Rule 2 stores
+the extension truncating the original file name.
+The same rule must be used for compression and decompression.
 
 .SH MEMORY MANAGEMENT
 .I bzip2 
 compresses large files in blocks.  The block size affects
 both the compression ratio achieved, and the amount of memory needed for
@@ -374,10 +455,18 @@ futile to use it on damaged single-block
 damaged  block  cannot  be recovered.  If you wish to minimise 
 any potential data loss through media  or  transmission errors, 
 you might consider compressing with a smaller
 block size.
 
+For the DJGPP port of
+.I bzip2recover
+the following applies:
+If LFN support is available the output file names will be of the same form
+as above described. If LFN support is not available then "rec0001file" will
+become "r0001file", etc. If the file has no extension then an ".bz2" extension
+will be added, else the original extension will be retained.
+
 .SH PERFORMANCE NOTES
 The sorting phase of compression gathers together similar strings in the
 file.  Because of this, files containing very long runs of repeated
 symbols, like "aabaabaabaab ..."  (repeated several hundred times) may
 compress more slowly than normal.  Versions 0.9.5 and above fare much
diff -aprNU5 bzip2-1.0.5.orig/bzip2.c bzip2-1.0.5/bzip2.c
--- bzip2-1.0.5.orig/bzip2.c	2007-12-09 12:22:06 +0000
+++ bzip2-1.0.5/bzip2.c	2008-03-31 16:38:38 +0000
@@ -13,10 +13,13 @@
    Please read the WARNING, DISCLAIMER and PATENTS sections in the 
    README file.
 
    This program is released under the terms of the license contained
    in the file LICENSE.
+
+   Changes required for DJGPP port of bzip2.exe and libbz2.a
+   by Juan Manuel Guerrero <juan.guerrero@gmx.de>  (2008-03-31).
    ------------------------------------------------------------------ */
 
 
 /* Place a 1 beside your platform, and 0 elsewhere.
    Generic 32-bit Unix.
@@ -24,10 +27,21 @@
    This is the default.
 */
 #define BZ_UNIX      1
 
 /*--
+  DJGPP supports DOS and Win32 environments.
+  The actual OS is determinated at run time.
+--*/
+#define BZ_DOS       0
+
+#if defined(__DJGPP__)
+#undef  BZ_DOS
+#define BZ_DOS 1
+#endif
+
+/*--
   Win32, as seen by Jacob Navia's excellent
   port of (Chris Fraser & David Hanson)'s excellent
   lcc compiler.  Or with MS Visual C.
   This is selected automatically if compiled by a compiler which
   defines _WIN32, not including the Cygwin GCC.
@@ -72,15 +86,19 @@
 #   include <utime.h>
 #   include <unistd.h>
 #   include <sys/stat.h>
 #   include <sys/times.h>
 
-#   define PATH_SEP    '/'
-#   define MY_LSTAT    lstat
-#   define MY_STAT     stat
-#   define MY_S_ISREG  S_ISREG
-#   define MY_S_ISDIR  S_ISDIR
+#   define HAVE_SIGBUS    1
+#   define IS_DIR_SEP(c)  ((c) == '/')
+#   define MY_LSTAT       lstat
+#   define MY_STAT        stat
+#   define MY_S_ISREG     S_ISREG
+#   define MY_S_ISDIR     S_ISDIR
+#   define MY_STDOUT      stderr
+
+#   define HAS_LFN_SUPPORT(name)  (pathconf ((name), _PC_NAME_MAX) > 12)
 
 #   define APPEND_FILESPEC(root, name) \
       root=snocString((root), (name))
 
 #   define APPEND_FLAG(root, name) \
@@ -95,26 +113,53 @@
 #   endif
 
 #   ifdef __DJGPP__
 #     include <io.h>
 #     include <fcntl.h>
-#     undef MY_LSTAT
+#     undef  HAVE_SIGBUS
+#     define HAVE_SIGBUS              0
+#     undef  IS_DIR_SEP
+#     define IS_DIR_SEP(c)            ((c) == '/' || (c) == '\\' || (c) == ':')
+#     define HAS_EXTENSION(name)      (strchr ((name), '.') != NULL)
+#     define HAS_TAR_EXTENSION(name)  (strstr ((name), ".tar") != NULL)
+#     ifndef S_ISLNK
+#       undef  MY_LSTAT
+#       define MY_LSTAT     stat
+#     endif
 #     undef MY_STAT
-#     define MY_LSTAT stat
 #     define MY_STAT stat
-#     undef SET_BINARY_MODE
-#     define SET_BINARY_MODE(fd)                        \
+#     undef MY_STDOUT
+#     define MY_STDOUT stdout
+#     if (defined(O_BINARY) != 0)
+/*--
+        Do never switch console input into binary mode, doing so will attempt
+        to read from the console with no echo and no way to signal EOF or even
+        interrupt the program (since special characters like ^Z and ^C are not
+        special in binary mode).  For all practical purposes, a program which
+        does that, wedges the machine.
+        If both stdin and stdout are the console device, don't switch stdout
+        into binary mode either, since that will switch the console device
+        into raw mode, with the same consequences as described above.
+--*/
+#       undef  SET_BINARY_MODE
+#       define SET_BINARY_MODE(fd)                      \
         do {                                            \
-           int retVal = setmode ( fileno ( fd ),        \
-                                  O_BINARY );           \
-           ERROR_IF_MINUS_ONE ( retVal );               \
+           if ( !isatty ( fileno ( fd ) ) )             \
+           {                                            \
+             int retVal = setmode ( fileno ( fd ),      \
+                                   O_BINARY );          \
+             ERROR_IF_MINUS_ONE ( retVal );             \
+           }                                            \
         } while ( 0 )
+#     endif
 #   endif
 
 #   ifdef __CYGWIN__
 #     include <io.h>
 #     include <fcntl.h>
+#     undef MY_STDOUT
+#     define MY_STDOUT stdout
 #     undef SET_BINARY_MODE
 #     define SET_BINARY_MODE(fd)                        \
         do {                                            \
            int retVal = setmode ( fileno ( fd ),        \
                                   O_BINARY );           \
@@ -129,15 +174,19 @@
 #   include <io.h>
 #   include <fcntl.h>
 #   include <sys\stat.h>
 
 #   define NORETURN       /**/
-#   define PATH_SEP       '\\'
+#   define HAVE_SIGBUS    1
+#   define IS_DIR_SEP(c)  ((c) == '\\')
 #   define MY_LSTAT       _stat
 #   define MY_STAT        _stat
 #   define MY_S_ISREG(x)  ((x) & _S_IFREG)
 #   define MY_S_ISDIR(x)  ((x) & _S_IFDIR)
+#   define MY_STDOUT      stdout
+
+#   define HAS_LFN_SUPPORT(name)  (True)
 
 #   define APPEND_FLAG(root, name) \
       root=snocString((root), (name))
 
 #   define APPEND_FILESPEC(root, name)                \
@@ -197,29 +246,40 @@ Int32   exitValue;
 #define OM_TEST          3
 
 Int32   opMode;
 Int32   srcMode;
 
+#ifdef FILENAME_MAX
+#define FILE_NAME_LEN FILENAME_MAX  /*  ANSI  */
+#elif PATH_MAX
+#define FILE_NAME_LEN PATH_MAX  /*  POSIX  */
+#else
 #define FILE_NAME_LEN 1034
+#endif
+
 
 Int32   longestFileName;
 Char    inName [FILE_NAME_LEN];
 Char    outName[FILE_NAME_LEN];
 Char    tmpName[FILE_NAME_LEN];
 Char    *progName;
 Char    progNameReally[FILE_NAME_LEN];
 FILE    *outputHandleJustInCase;
 Int32   workFactor;
+#ifdef BZ_DOS
+Bool    dosFileNameRule1;
+#endif
 
 static void    panic                 ( const Char* ) NORETURN;
 static void    ioError               ( void )        NORETURN;
 static void    outOfMemory           ( void )        NORETURN;
 static void    configError           ( void )        NORETURN;
 static void    crcError              ( void )        NORETURN;
 static void    cleanUpAndFail        ( Int32 )       NORETURN;
 static void    compressedStreamEOF   ( void )        NORETURN;
 
+static void    addBZ2Suffix ( Char* );
 static void    copyFileName ( Char*, Char* );
 static void*   myMalloc     ( Int32 );
 static void    applySavedFileAttrToOutputFile ( IntNative fd );
 
 
@@ -935,10 +995,96 @@ void copyFileName ( Char* to, Char* from
 }
 
 
 /*---------------------------------------------*/
 static 
+Char* baseName ( Char* fileName )
+{
+   Char *baseName = fileName;
+   
+   if (baseName)
+      for (baseName += strlen ( fileName ); baseName > fileName; --baseName)
+         if (IS_DIR_SEP ( *baseName ))
+         {
+            baseName++;
+            break;
+         }
+   return baseName;
+}
+
+
+/*---------------------------------------------*/
+static 
+void addBZ2Suffix ( Char* name )
+{
+#if BZ_DOS
+   if (!HAS_LFN_SUPPORT ( name ))
+   {
+      /*---
+        DJGPP detects at run time if a LFN-API (win32) is available or not (plain dos).
+        MSDOS 8.3 filename restriction.
+      ---*/
+
+      Char* fileName = baseName ( name );
+      if (HAS_EXTENSION ( fileName ))
+      {
+         IntNative extStart = (IntNative)( strchr ( fileName, '.' ) - fileName );
+         if (HAS_TAR_EXTENSION ( &fileName[extStart] ))
+            strcpy ( &fileName[extStart], ".tbz" );
+         else
+         {
+            /* File has extension but not tar extension. */
+
+            IntNative extLen = strlen ( &fileName[extStart] );
+            if (dosFileNameRule1 == True)
+            {
+               /*----------------------------------------------*/
+               /*---   Output file name rule 1 (default):   ---*/
+               /*---   filename.ext -> filename.exb         ---*/
+               /*----------------------------------------------*/
+               extLen--;
+               switch (extLen)
+               {
+               case 1:
+                  strcat ( fileName, "bz" );
+                  break;
+               case 2:
+                  strcat ( fileName, "b" );
+                  break;
+               default:
+                  fileName[extStart + 3] = 'b';
+                  break;
+               }
+            }
+            else
+            {
+               /*-------------------------------------------------------------*/
+               /*---   Output file name rule 2 (selected with flag: -n):   ---*/
+               /*---   filename.ext -> file_ext.bz2                        ---*/
+               /*-------------------------------------------------------------*/
+
+               IntNative fileNameLen = extStart;
+               fileName[extStart] = '_';
+               if (fileNameLen + extLen > 8)
+                  strcpy ( &fileName[8 - extLen], &fileName[extStart] );
+               strcat ( fileName, ".bz2" );
+            }
+         }
+      }
+      else
+         /* no extension at all. */
+         strcat ( fileName, ".bz2" );
+   }
+   else
+      /* no filename restriction. */
+#endif  /* ! BZ_DOS */
+      strcat ( name, ".bz2" ); 
+}
+
+
+/*---------------------------------------------*/
+static 
 Bool fileExists ( Char* name )
 {
    FILE *tmp   = fopen ( name, "rb" );
    Bool exists = (tmp != NULL);
    if (tmp != NULL) fclose ( tmp );
@@ -1062,11 +1208,11 @@ void applySavedTimeInfoToOutputFile ( Ch
 }
 
 static 
 void applySavedFileAttrToOutputFile ( IntNative fd )
 {
-#  if BZ_UNIX
+#  if defined(BZ_UNIX) && !defined(BZ_DOS)
    IntNative retVal;
 
    retVal = fchmod ( fd, fileMetaInfo.st_mode );
    ERROR_IF_NOT_ZERO ( retVal );
 
@@ -1080,11 +1226,11 @@ void applySavedFileAttrToOutputFile ( In
 
 /*---------------------------------------------*/
 static 
 Bool containsDubiousChars ( Char* name )
 {
-#  if BZ_UNIX
+#  if defined(BZ_UNIX) && !defined(BZ_DOS)
    /* On unix, files can contain any characters and the file expansion
     * is performed by the shell.
     */
    return False;
 #  else /* ! BZ_UNIX */
@@ -1148,11 +1294,11 @@ void compress ( Char *name )
          copyFileName ( outName, (Char*)"(stdout)" ); 
          break;
       case SM_F2F: 
          copyFileName ( inName, name );
          copyFileName ( outName, name );
-         strcat ( outName, ".bz2" ); 
+         addBZ2Suffix ( outName );
          break;
       case SM_F2O: 
          copyFileName ( inName, name );
          copyFileName ( outName, (Char*)"(stdout)" ); 
          break;
@@ -1332,13 +1478,72 @@ void uncompress ( Char *name )
          copyFileName ( outName, (Char*)"(stdout)" ); 
          break;
       case SM_F2F: 
          copyFileName ( inName, name );
          copyFileName ( outName, name );
-         for (i = 0; i < BZ_N_SUFFIX_PAIRS; i++)
-            if (mapSuffix(outName,zSuffix[i],unzSuffix[i]))
-               goto zzz; 
+         if (HAS_LFN_SUPPORT ( outName ))
+         {
+            /*---   For file systems with no file name restrictions.   ---*/
+
+            for (i = 0; i < BZ_N_SUFFIX_PAIRS; i++)
+               if (mapSuffix(outName, zSuffix[i], unzSuffix[i]))  /* Test for extensions: .bz2, .tbz2, .bz, .tbz */
+                  goto zzz;
+         }
+         else
+         {
+            Char *fileExtension, *fileName;
+
+
+            /*---   File systems with file name restrictions.   ---*/
+
+            for (i = BZ_N_SUFFIX_PAIRS - 2; i < BZ_N_SUFFIX_PAIRS; i++)
+               if (mapSuffix(outName, zSuffix[i], unzSuffix[i]))  /* Test for extensions: .tbz2, .tbz */
+                  goto zzz;
+
+
+            /*---   Treat all other file extensions for file systems with file name restrictions.   ---*/
+
+            if ((fileName = baseName ( outName )) == NULL)
+               fileName = outName;
+
+            if ((fileExtension = strchr ( fileName, '.' )) != NULL)
+            {
+               if (dosFileNameRule1 == True)
+               {
+                  /*----------------------------------------------*/
+                  /*---   Output file name rule 1 (default):   ---*/
+                  /*---   filename.exb -> filename.ex          ---*/
+                  /*----------------------------------------------*/
+
+                  register IntNative extEnd = strlen ( fileExtension );
+
+                  for (extEnd--; extEnd; extEnd--)
+                     if (fileExtension[extEnd] == 'b')
+                     {
+                        fileExtension[extEnd] = '\0';
+                        goto zzz;
+                     }
+
+                  /* The extension contains no 'b' char.  Remove it to append .out extension.  */
+                  *fileExtension = '\0';
+               }
+               else
+               {
+                  /*-------------------------------------------------------------*/
+                  /*---   Output file name rule 2 (selected with flag: -n):   ---*/
+                  /*---   file_ext.bz2 -> file.ext                            ---*/
+                  /*-------------------------------------------------------------*/
+
+                  *fileExtension = '\0';
+                  if ((fileExtension = strrchr ( fileName, '_' )) != NULL && strlen ( fileExtension ) <= 4)
+                  {
+                     *fileExtension = '.';
+                     goto zzz;
+                  }
+               }
+            }
+         }
          cantGuess = True;
          strcat ( outName, ".out" );
          break;
       case SM_F2O: 
          copyFileName ( inName, name );
@@ -1598,14 +1803,15 @@ void testf ( Char *name )
 
 /*---------------------------------------------*/
 static 
 void license ( void )
 {
-   fprintf ( stderr,
+   fprintf ( MY_STDOUT,
 
     "bzip2, a block-sorting file compressor.  "
     "Version %s.\n"
+    "DJGPP port (r1).\n"
     "   \n"
     "   Copyright (C) 1996-2007 by Julian Seward.\n"
     "   \n"
     "   This program is free software; you can redistribute it and/or modify\n"
     "   it under the terms set out in the LICENSE file, which is included\n"
@@ -1613,10 +1819,13 @@ void license ( void )
     "   \n"
     "   This program is distributed in the hope that it will be useful,\n"
     "   but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
     "   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
     "   LICENSE file for more details.\n"
+    "   \n"
+    "   Changes required for DJGPP port of bzip2.exe and libbz2.a\n"
+    "   by Juan Manuel Guerrero <juan.guerrero@gmx.de>  (2008-03-31).\n"
     "   \n",
     BZ2_bzlibVersion()
    );
 }
 
@@ -1624,11 +1833,11 @@ void license ( void )
 /*---------------------------------------------*/
 static 
 void usage ( Char *fullProgName )
 {
    fprintf (
-      stderr,
+      MY_STDOUT,
       "bzip2, a block-sorting file compressor.  "
       "Version %s.\n"
       "\n   usage: %s [flags and input files in any order]\n"
       "\n"
       "   -h --help           print this message\n"
@@ -1639,10 +1848,18 @@ void usage ( Char *fullProgName )
       "   -t --test           test compressed file integrity\n"
       "   -c --stdout         output to standard out\n"
       "   -q --quiet          suppress noncritical error messages\n"
       "   -v --verbose        be verbose (a 2nd -v gives more)\n"
       "   -L --license        display software version & license\n"
+#ifdef BZ_DOS
+      "   -n                  select output file name rule 2.\n"
+      "                       rule 1: filename preserved, extension truncated.\n"
+      "                       default is output file name rule 1.\n"
+      "                       rule 2: filename truncated, extension preserved.\n"
+      "                       This flag is only available on plain DOS\n"
+      "                       and WIN9X with LFN=n.\n"
+#endif
       "   -V --version        display software version & license\n"
       "   -s --small          use less memory (at most 2500k)\n"
       "   -1 .. -9            set block size to 100k .. 900k\n"
       "   --fast              alias for -1\n"
       "   --best              alias for -9\n"
@@ -1800,27 +2017,30 @@ IntNative main ( IntNative argc, Char *a
    numFileNames            = 0;
    numFilesProcessed       = 0;
    workFactor              = 30;
    deleteOutputOnInterrupt = False;
    exitValue               = 0;
+#ifdef BZ_DOS
+   dosFileNameRule1        = True; /* On MSDOS default to output file name rule 1. */
+#endif
    i = j = 0; /* avoid bogus warning from egcs-1.1.X */
 
    /*-- Set up signal handlers for mem access errors --*/
    signal (SIGSEGV, mySIGSEGVorSIGBUScatcher);
 #  if BZ_UNIX
-#  ifndef __DJGPP__
+#  if HAVE_SIGBUS
    signal (SIGBUS,  mySIGSEGVorSIGBUScatcher);
 #  endif
 #  endif
 
    copyFileName ( inName,  (Char*)"(none)" );
    copyFileName ( outName, (Char*)"(none)" );
 
    copyFileName ( progNameReally, argv[0] );
    progName = &progNameReally[0];
    for (tmp = &progNameReally[0]; *tmp != '\0'; tmp++)
-      if (*tmp == PATH_SEP) progName = tmp + 1;
+      if (IS_DIR_SEP ( *tmp )) progName = tmp + 1;
 
 
    /*-- Copy flags from env var BZIP2, and 
         expand filename wildcards in arg list.
    --*/
@@ -1887,10 +2107,13 @@ IntNative main ( IntNative argc, Char *a
                case '5': blockSize100k    = 5; break;
                case '6': blockSize100k    = 6; break;
                case '7': blockSize100k    = 7; break;
                case '8': blockSize100k    = 8; break;
                case '9': blockSize100k    = 9; break;
+#ifdef BZ_DOS
+               case 'n': dosFileNameRule1 = False; break;
+#endif
                case 'V':
                case 'L': license();            break;
                case 'v': verbosity++; break;
                case 'h': usage ( progName );
                          exit ( 0 );
diff -aprNU5 bzip2-1.0.5.orig/bzip2recover.c bzip2-1.0.5/bzip2recover.c
--- bzip2-1.0.5.orig/bzip2recover.c	2007-12-09 12:28:26 +0000
+++ bzip2-1.0.5/bzip2recover.c	2008-03-31 16:23:26 +0000
@@ -13,19 +13,23 @@
    Please read the WARNING, DISCLAIMER and PATENTS sections in the 
    README file.
 
    This program is released under the terms of the license contained
    in the file LICENSE.
+
+   Changes required for DJGPP port of bzip2.exe and libbz2.a
+   by Juan Manuel Guerrero <juan.guerrero@gmx.de>  (2008-03-31).
    ------------------------------------------------------------------ */
 
 /* This program is a complete hack and should be rewritten properly.
 	 It isn't very complicated. */
 
 #include <stdio.h>
 #include <errno.h>
 #include <stdlib.h>
 #include <string.h>
+#include <unistd.h>
 
 
 /* This program records bit locations in the file to be recovered.
    That means that if 64-bit ints are not supported, we will not
    be able to recover .bz2 files over 512MB (2^32 bits) long.
@@ -55,19 +59,33 @@ typedef  char           Char;
 typedef  unsigned char  Bool;
 #define True    ((Bool)1)
 #define False   ((Bool)0)
 
 
-#define BZ_MAX_FILENAME 2000
+#ifdef FILENAME_MAX
+#  define BZ_MAX_FILENAME FILENAME_MAX  /*  ANSI  */
+#elif PATH_MAX
+#  define BZ_MAX_FILENAME PATH_MAX  /*  POSIX  */
+#else
+#  define BZ_MAX_FILENAME 2000
+#endif
 
 Char inFileName[BZ_MAX_FILENAME];
 Char outFileName[BZ_MAX_FILENAME];
 Char progName[BZ_MAX_FILENAME];
 
 MaybeUInt64 bytesOut = 0;
 MaybeUInt64 bytesIn  = 0;
 
+#define HAS_LFN_SUPPORT(name)  (pathconf ((name), _PC_NAME_MAX) > 12)
+#define HAS_EXTENSION(name)    (strrchr ((name), '.') != NULL)
+#ifdef __DJGPP__
+#  define IS_DIR_SEPARATOR(c)  ((c) == '/' || (c) == '\\' || (c) == ':')
+#else
+#  define IS_DIR_SEPARATOR(c)  ((c) == '/')
+#endif
+
 
 /*---------------------------------------------------*/
 /*--- Header bytes                                ---*/
 /*---------------------------------------------------*/
 
@@ -200,11 +218,13 @@ static Int32 bsGetBit ( BitStream* bs )
 {
    if (bs->buffLive > 0) {
       bs->buffLive --;
       return ( ((bs->buffer) >> (bs->buffLive)) & 0x1 );
    } else {
-      Int32 retVal = getc ( bs->handle );
+      Int32 retVal;
+      errno = 0; /* to avoid program abort with ENOENT set by fopen in main. */
+      retVal = getc ( bs->handle );
       if ( retVal == EOF ) {
          if (errno != 0) readError();
          return 2;
       }
       bs->buffLive = 7;
@@ -272,16 +292,19 @@ static Bool endsInBz2 ( Char* name )
 
 /*---------------------------------------------------*/
 /*---                                             ---*/
 /*---------------------------------------------------*/
 
+/* This logic isn't right at all when it comes to DJGPP. */
+#ifndef __DJGPP__
 /* This logic isn't really right when it comes to Cygwin. */
 #ifdef _WIN32
 #  define  BZ_SPLIT_SYM  '\\'  /* path splitter on Windows platform */
 #else
 #  define  BZ_SPLIT_SYM  '/'   /* path splitter on Unix platform */
 #endif
+#endif
 
 #define BLOCK_HEADER_HI  0x00003141UL
 #define BLOCK_HEADER_LO  0x59265359UL
 
 #define BLOCK_ENDMARK_HI 0x00001772UL
@@ -307,10 +330,13 @@ Int32 main ( Int32 argc, Char** argv )
    MaybeUInt64 bitsRead;
 
    UInt32      buffHi, buffLo, blockCRC;
    Char*       p;
 
+   Int32       dirNameLength;  /* Path length in inFileName including last slash. */
+   Char*       baseName;       /* Pointer to file name (basename) in inFileName. */
+
    strcpy ( progName, argv[0] );
    inFileName[0] = outFileName[0] = 0;
 
    fprintf ( stderr, 
              "bzip2recover 1.0.5: extracts blocks from damaged .bz2 files.\n" );
@@ -346,10 +372,24 @@ Int32 main ( Int32 argc, Char** argv )
       exit(1);
    }
 
    strcpy ( inFileName, argv[1] );
 
+   /*--
+     Make a pointer to the file name in inFileName
+     and compute the length of the path string without
+     the file name part but including the last slash.
+   --*/
+   baseName = inFileName;
+   for (baseName += strlen ( inFileName ); baseName > inFileName; --baseName)
+     if (IS_DIR_SEPARATOR ( *baseName ))
+     {
+       baseName++;
+       break;
+     }
+   dirNameLength = baseName - inFileName;
+
    inFile = fopen ( inFileName, "rb" );
    if (inFile == NULL) {
       fprintf ( stderr, "%s: can't read `%s'\n", progName, inFileName );
       exit(1);
    }
@@ -460,10 +500,11 @@ Int32 main ( Int32 argc, Char** argv )
          }
          if (wrBlock >= rbCtr) break;
          wrBlock++;
       } else
       if (bitsRead == rbStart[wrBlock]) {
+#ifdef BZ_SPLIT_SYM
          /* Create the output file name, correctly handling leading paths. 
             (31.10.2001 by Sergey E. Kusikov) */
          Char* split;
          Int32 ofs, k;
          for (k = 0; k < BZ_MAX_FILENAME; k++) 
@@ -475,15 +516,30 @@ Int32 main ( Int32 argc, Char** argv )
          } else {
             ++split;
 	 }
 	 /* Now split points to the start of the basename. */
          ofs  = split - outFileName;
-         sprintf (split, "rec%5d", wrBlock+1);
-         for (p = split; *p != 0; p++) if (*p == ' ') *p = '0';
-         strcat (outFileName, inFileName + ofs);
-
-         if ( !endsInBz2(outFileName)) strcat ( outFileName, ".bz2" );
+#endif
+         if (dirNameLength > 0) /* Account for a possible path in inFileName. */
+           strncpy ( outFileName, inFileName, dirNameLength );
+         else
+           outFileName[0] = 0;
+
+         if (!HAS_LFN_SUPPORT ( inFileName )) /* There are only 8 characters available. */
+           sprintf ( &outFileName[dirNameLength], "r%4d", wrBlock+1 );
+         else
+           sprintf ( &outFileName[dirNameLength], "rec%4d", wrBlock+1 );
+
+         for (p = outFileName; *p != 0; p++) if (*p == ' ') *p = '0';
+         strcat (outFileName, baseName);
+
+         /* MSDOS 8.3 file name restriction. */
+         if (!HAS_LFN_SUPPORT ( outFileName ) && !HAS_EXTENSION ( baseName ))
+           strcat ( outFileName, ".bz2" );
+         else
+           /* Only if LFN support is available, append an extra extension. */
+           if ( !endsInBz2(outFileName)) strcat ( outFileName, ".bz2" );
 
          fprintf ( stderr, "   writing block %d to `%s' ...\n",
                            wrBlock+1, outFileName );
 
          outFile = fopen ( outFileName, "wb" );
diff -aprNU5 bzip2-1.0.5.orig/bzlib.c bzip2-1.0.5/bzlib.c
--- bzip2-1.0.5.orig/bzlib.c	2007-12-09 13:57:20 +0000
+++ bzip2-1.0.5/bzlib.c	2008-03-31 16:11:52 +0000
@@ -14,10 +14,13 @@
    Please read the WARNING, DISCLAIMER and PATENTS sections in the 
    README file.
 
    This program is released under the terms of the license contained
    in the file LICENSE.
+
+   Changes required for DJGPP port of bzip2.exe and libbz2.a
+   by Juan Manuel Guerrero <juan.guerrero@gmx.de>  (2008-03-31).
    ------------------------------------------------------------------ */
 
 /* CHANGES
    0.9.0    -- original version.
    0.9.0a/b -- no changes in this file.
@@ -1373,11 +1376,26 @@ const char * BZ_API(BZ2_bzlibVersion)(vo
 /*---------------------------------------------------*/
 
 #if defined(_WIN32) || defined(OS2) || defined(MSDOS)
 #   include <fcntl.h>
 #   include <io.h>
-#   define SET_BINARY_MODE(file) setmode(fileno(file),O_BINARY)
+#   include <unistd.h>
+/*--
+    Do never switch console input into binary mode, doing so will attempt
+    to read from the console with no echo and no way to signal EOF or even
+    interrupt the program (since special characters like ^Z and ^C are not
+    special in binary mode).  For all practical purposes, a program which
+    does that, wedges the machine.
+    If both stdin and stdout are the console device, don't switch stdout
+    into binary mode either, since that will switch the console device
+    into raw mode, with the same consequences as described above.
+--*/
+#   define SET_BINARY_MODE(file)          \
+    do {                                  \
+      if (!isatty(fileno(file)))          \
+        setmode(fileno(file), O_BINARY);  \
+    } while (0)
 #else
 #   define SET_BINARY_MODE(file)
 #endif
 static
 BZFILE * bzopen_or_bzdopen
@@ -1413,10 +1431,13 @@ BZFILE * bzopen_or_bzdopen
          }
       }
       mode++;
    }
    strcat(mode2, writing ? "w" : "r" );
+#if defined(_WIN32) || defined(OS2) || defined(MSDOS)
+   if (!isatty(fileno(fp)))  /* switch only to binary mode if not a TTY */
+#endif
    strcat(mode2,"b");   /* binary mode */
 
    if (open_mode==0) {
       if (path==NULL || strcmp(path,"")==0) {
         fp = (writing ? stdout : stdin);
diff -aprNU5 bzip2-1.0.5.orig/bzlib.h bzip2-1.0.5/bzlib.h
--- bzip2-1.0.5.orig/bzlib.h	2007-12-09 12:34:38 +0000
+++ bzip2-1.0.5/bzlib.h	2008-03-31 16:06:30 +0000
@@ -14,10 +14,13 @@
    Please read the WARNING, DISCLAIMER and PATENTS sections in the 
    README file.
 
    This program is released under the terms of the license contained
    in the file LICENSE.
+
+   Changes required for DJGPP port of bzip2.exe and libbz2.a
+   by Juan Manuel Guerrero <juan.guerrero@gmx.de>  (2008-03-31).
    ------------------------------------------------------------------ */
 
 
 #ifndef _BZLIB_H
 #define _BZLIB_H
diff -aprNU5 bzip2-1.0.5.orig/bzmore bzip2-1.0.5/bzmore
--- bzip2-1.0.5.orig/bzmore	2007-01-03 02:00:54 +0000
+++ bzip2-1.0.5/bzmore	2008-03-31 16:05:36 +0000
@@ -1,11 +1,19 @@
 #!/bin/sh
 
 # Bzmore wrapped for bzip2, 
 # adapted from zmore by Philippe Troin <phil@fifi.org> for Debian GNU/Linux.
 
-PATH="/usr/bin:$PATH"; export PATH
+#
+# Modified for the use with DJGPP.  There is no intention to
+# keep POSIX/UNIX compatibility because submitted patch to
+# bzip2 author has never been accepted.
+#
+# Juan  Manuel Guerrero.
+#
+
+PATH="/dev/env/DJDIR/bin;$PATH"; export PATH
 
 prog=`echo $0 | sed 's|.*/||'`
 case "$prog" in
 	*less)	more=less	;;
 	*)	more=more       ;;
diff -aprNU5 bzip2-1.0.5.orig/words3 bzip2-1.0.5/words3
--- bzip2-1.0.5.orig/words3	2007-01-03 02:00:54 +0000
+++ bzip2-1.0.5/words3	2008-03-31 16:03:08 +0000
@@ -1,11 +1,11 @@
 
 If you got this far and the 'cmp's didn't complain, it looks
 like you're in business.  
 
-To install in /usr/local/bin, /usr/local/lib, /usr/local/man and 
-/usr/local/include, type
+To install in /dev/env/DJDIR/bin, /dev/env/DJDIR/lib, /dev/env/DJDIR/man and
+   /dev/env/DJDIR/include, type make install
 
    make install
 
 To install somewhere else, eg, /xxx/yyy/{bin,lib,man,include}, type 
 
