home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 1994 November / macformat-018.iso / Utility Spectacular / Developer / macgzip_022-src / gzip.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-07-26  |  55.6 KB  |  1,902 lines  |  [TEXT/KAHL]

  1. /* gzip (GNU zip) -- compress files with zip algorithm and 'compress' interface
  2.  * Copyright (C) 1992-1993 Jean-loup Gailly
  3.  * The unzip code was written and put in the public domain by Mark Adler.
  4.  * Portions of the lzw code are derived from the public domain 'compress'
  5.  * written by Spencer Thomas, Joe Orost, James Woods, Jim McKie, Steve Davies,
  6.  * Ken Turkowski, Dave Mack and Peter Jannesen.
  7.  *
  8.  * See the license_msg below and the file COPYING for the software license.
  9.  * See the file algorithm.doc for the compression algorithms and file formats.
  10.  */
  11.  
  12. /*
  13.  * Modified:1993 by SPDsoft for MacGzip
  14.  *
  15.  */
  16.  
  17. static char  *license_msg[] = {
  18. "   Copyright (C) 1992-1993 Jean-loup Gailly",
  19. "   This program is free software; you can redistribute it and/or modify",
  20. "   it under the terms of the GNU General Public License as published by",
  21. "   the Free Software Foundation; either version 2, or (at your option)",
  22. "   any later version.",
  23. "",
  24. "   This program is distributed in the hope that it will be useful,",
  25. "   but WITHOUT ANY WARRANTY; without even the implied warranty of",
  26. "   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the",
  27. "   GNU General Public License for more details.",
  28. "",
  29. "   You should have received a copy of the GNU General Public License",
  30. "   along with this program; if not, write to the Free Software",
  31. "   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.",
  32. 0};
  33.  
  34. /* Compress files with zip algorithm and 'compress' interface.
  35.  * See usage() and help() functions below for all options.
  36.  * Outputs:
  37.  *        file.gz:   compressed file with same mode, owner, and utimes
  38.  *     or stdout with -c option or if stdin used as input.
  39.  * If the output file name had to be truncated, the original name is kept
  40.  * in the compressed file.
  41.  * On MSDOS, file.tmp -> file.tmz. On VMS, file.tmp -> file.tmp-gz.
  42.  *
  43.  * Using gz on MSDOS would create too many file name conflicts. For
  44.  * example, foo.txt -> foo.tgz (.tgz must be reserved as shorthand for
  45.  * tar.gz). Similarly, foo.dir and foo.doc would both be mapped to foo.dgz.
  46.  * I also considered 12345678.txt -> 12345txt.gz but this truncates the name
  47.  * too heavily. There is no ideal solution given the MSDOS 8+3 limitation. 
  48.  *
  49.  * For the meaning of all compilation flags, see comments in Makefile.in.
  50.  */
  51.  
  52. #ifdef RCSID
  53. static char rcsid[] = "$Id: gzip.c,v 0.24 1993/06/24 10:52:07 jloup Exp $";
  54. #endif
  55.  
  56. #include <ctype.h>
  57. #include <sys/types.h>
  58. #include <signal.h>
  59. #include <sys/stat.h>
  60. #include <errno.h>
  61.  
  62. #include "tailor.h"
  63. #include "gzip.h"
  64. #include "lzw.h"
  65. #include "revision.h"
  66. #include "getopt.h"
  67.  
  68.         /* configuration */
  69.         
  70. #ifdef MACOS
  71. #include "ThinkCPosix.h"
  72. char *PreferenceName=".gzip_prefs"; /* not used, but required by ThinkCPosix */
  73. /*#include <console.h>*/
  74. #include "MacErrors.h"
  75. #include "ThePrefs.h"
  76. #include "SPDProg.h"
  77.  
  78. local void    init_globals( void );
  79. extern void    FixMacFile( char* name, int ascii, int decompress);
  80. extern int    AsciiMode(char *name, int ascii, int compress);
  81.  
  82. #endif /* MACOS */
  83.  
  84. #ifdef NO_TIME_H
  85. #  include <sys/time.h>
  86. #else
  87. #  include <time.h>
  88. #endif
  89.  
  90. #ifndef NO_FCNTL_H
  91. #  include <fcntl.h>
  92. #endif
  93.  
  94. #ifdef HAVE_UNISTD_H
  95. #  include <unistd.h>
  96. #endif
  97.  
  98. #if defined(STDC_HEADERS) || !defined(NO_STDLIB_H)
  99. #  include <stdlib.h>
  100. #else
  101.    extern int errno;
  102. #endif
  103.  
  104. #if defined(DIRENT)
  105. #  include <dirent.h>
  106.    typedef struct dirent dir_type;
  107. #  define NLENGTH(dirent) ((int)strlen((dirent)->d_name))
  108. #  define DIR_OPT "DIRENT"
  109. #else
  110. #  define NLENGTH(dirent) ((dirent)->d_namlen)
  111. #  ifdef SYSDIR
  112. #    include <sys/dir.h>
  113.      typedef struct direct dir_type;
  114. #    define DIR_OPT "SYSDIR"
  115. #  else
  116. #    ifdef SYSNDIR
  117. #      include <sys/ndir.h>
  118.        typedef struct direct dir_type;
  119. #      define DIR_OPT "SYSNDIR"
  120. #    else
  121. #      ifdef NDIR
  122. #        include <ndir.h>
  123.          typedef struct direct dir_type;
  124. #        define DIR_OPT "NDIR"
  125. #      else
  126. #        define NO_DIR
  127. #        define DIR_OPT "NO_DIR"
  128. #      endif
  129. #    endif
  130. #  endif
  131. #endif
  132.  
  133. #ifndef NO_UTIME
  134. #  ifndef NO_UTIME_H
  135. #    include <utime.h>
  136. #    define TIME_OPT "UTIME"
  137. #  else
  138. #    ifdef HAVE_SYS_UTIME_H
  139. #      include <sys/utime.h>
  140. #      define TIME_OPT "SYS_UTIME"
  141. #    else
  142.        struct utimbuf {
  143.          time_t actime;
  144.          time_t modtime;
  145.        };
  146. #      define TIME_OPT ""
  147. #    endif
  148. #  endif
  149. #else
  150. #  define TIME_OPT "NO_UTIME"
  151. #endif
  152.  
  153. #if !defined(S_ISDIR) && defined(S_IFDIR)
  154. #  define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
  155. #endif
  156. #if !defined(S_ISREG) && defined(S_IFREG)
  157. #  define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
  158. #endif
  159.  
  160. typedef RETSIGTYPE (*sig_type) OF((int));
  161.  
  162. #ifndef    O_BINARY
  163. #  define  O_BINARY  0  /* creation mode for open() */
  164. #endif
  165.  
  166. #ifndef O_CREAT
  167.    /* Pure BSD system? */
  168. #  include <sys/file.h>
  169. #  ifndef O_CREAT
  170. #    define O_CREAT FCREAT
  171. #  endif
  172. #  ifndef O_EXCL
  173. #    define O_EXCL FEXCL
  174. #  endif
  175. #endif
  176.  
  177. #ifndef S_IRUSR
  178. #  define S_IRUSR 0400
  179. #endif
  180. #ifndef S_IWUSR
  181. #  define S_IWUSR 0200
  182. #endif
  183. #define RW_USER (S_IRUSR | S_IWUSR)  /* creation mode for open() */
  184.  
  185. #ifndef MAX_PATH_LEN
  186. #  define MAX_PATH_LEN   1024 /* max pathname length */
  187. #endif
  188.  
  189. #ifndef SEEK_END
  190. #  define SEEK_END 2
  191. #endif
  192.  
  193. #ifdef NO_OFF_T
  194.   typedef long off_t;
  195.   off_t lseek OF((int fd, off_t offset, int whence));
  196. #endif
  197.  
  198. /* Separator for file name parts (see shorten_name()) */
  199. #ifdef NO_MULTIPLE_DOTS
  200. #  define PART_SEP "-"
  201. #else
  202. #  define PART_SEP "."
  203. #endif
  204.  
  205.         /* global buffers */
  206.  
  207. DECLARE(uch, inbuf,  INBUFSIZ +INBUF_EXTRA);
  208. DECLARE(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA);
  209. DECLARE(ush, d_buf,  DIST_BUFSIZE);
  210. DECLARE(uch, window, 2L*WSIZE);
  211. #ifndef MAXSEG_64K
  212.     DECLARE(ush, tab_prefix, 1L<<BITS);
  213. #else
  214.     DECLARE(ush, tab_prefix0, 1L<<(BITS-1));
  215.     DECLARE(ush, tab_prefix1, 1L<<(BITS-1));
  216. #endif
  217.  
  218.         /* local variables */
  219.  
  220. int ascii = 0;        /* convert end-of-lines to local OS conventions */
  221. int to_stdout = 0;    /* output to stdout (-c) */
  222. int decompress = 0;   /* decompress (-d) */
  223. int force = 0;        /* don't ask questions, compress links (-f) */
  224. int no_name = -1;     /* don't save or restore the original file name */
  225. int no_time = -1;     /* don't save or restore the original file time */
  226. int recursive = 0;    /* recurse through directories (-r) */
  227. int list = 0;         /* list the file contents (-l) */
  228. int verbose = 0;      /* be verbose (-v) */
  229. int quiet = 0;        /* be very quiet (-q) */
  230. int do_lzw = 0;       /* generate output compatible with old compress (-Z) */
  231. int test = 0;         /* test .gz file integrity */
  232. int foreground;       /* set if program run in foreground */
  233. char *progname;       /* program name */
  234. int maxbits = BITS;   /* max bits per code for LZW */
  235. int method = DEFLATED;/* compression method */
  236. int level = 6;        /* compression level */
  237. int exit_code = OK;   /* program exit code */
  238. int save_orig_name;   /* set if original name must be saved */
  239. int last_member;      /* set for .zip and .Z files */
  240. int part_nb;          /* number of parts in .gz file */
  241. long time_stamp;      /* original time stamp (modification time) */
  242. long ifile_size;      /* input file size, -1 for devices (debug only) */
  243. char *env;            /* contents of GZIP env variable */
  244. char **args = NULL;   /* argv pointer if GZIP env variable defined */
  245. char z_suffix[MAX_SUFFIX+1]; /* default suffix (can be set with --suffix) */
  246. int  z_len;           /* strlen(z_suffix) */
  247.  
  248. long bytes_in;             /* number of input bytes */
  249. long bytes_out;            /* number of output bytes */
  250. long total_in = 0;         /* input bytes for all files */
  251. long total_out = 0;        /* output bytes for all files */
  252. char ifname[MAX_PATH_LEN]; /* input file name */
  253. char ofname[MAX_PATH_LEN]; /* output file name */
  254. int  remove_ofname = 0;       /* remove output file on error */
  255. struct stat istat;         /* status for input file */
  256. int  ifd;                  /* input file descriptor */
  257. int  ofd;                  /* output file descriptor */
  258. unsigned insize;           /* valid bytes in inbuf */
  259. unsigned inptr;            /* index of next byte to be processed in inbuf */
  260. unsigned outcnt;           /* bytes in output buffer */
  261.  
  262. struct option longopts[] =
  263. {
  264.  /* { name  has_arg  *flag  val } */
  265.     {"ascii",      0, 0, 'a'}, /* ascii text mode */
  266.     {"to-stdout",  0, 0, 'c'}, /* write output on standard output */
  267.     {"stdout",     0, 0, 'c'}, /* write output on standard output */
  268.     {"decompress", 0, 0, 'd'}, /* decompress */
  269.     {"uncompress", 0, 0, 'd'}, /* decompress */
  270.  /* {"encrypt",    0, 0, 'e'},    encrypt */
  271.     {"force",      0, 0, 'f'}, /* force overwrite of output file */
  272.     {"help",       0, 0, 'h'}, /* give help */
  273.  /* {"pkzip",      0, 0, 'k'},    force output in pkzip format */
  274.     {"list",       0, 0, 'l'}, /* list .gz file contents */
  275.     {"license",    0, 0, 'L'}, /* display software license */
  276.     {"no-name",    0, 0, 'n'}, /* don't save or restore original name & time */
  277.     {"name",       0, 0, 'N'}, /* save or restore original name & time */
  278.     {"quiet",      0, 0, 'q'}, /* quiet mode */
  279.     {"silent",     0, 0, 'q'}, /* quiet mode */
  280.     {"recursive",  0, 0, 'r'}, /* recurse through directories */
  281.     {"suffix",     1, 0, 'S'}, /* use given suffix instead of .gz */
  282.     {"test",       0, 0, 't'}, /* test compressed file integrity */
  283.     {"no-time",    0, 0, 'T'}, /* don't save or restore the time stamp */
  284.     {"verbose",    0, 0, 'v'}, /* verbose mode */
  285.     {"version",    0, 0, 'V'}, /* display version number */
  286.     {"fast",       0, 0, '1'}, /* compress faster */
  287.     {"best",       0, 0, '9'}, /* compress better */
  288.     {"lzw",        0, 0, 'Z'}, /* make output compatible with old compress */
  289.     {"bits",       1, 0, 'b'}, /* max number of bits per code (implies -Z) */
  290.     { 0, 0, 0, 0 }
  291. };
  292.  
  293. /* local functions */
  294.  
  295. local void usage        OF((void));
  296. local void help         OF((void));
  297. local void license      OF((void));
  298. local void version      OF((void));
  299. local void treat_stdin  OF((void));
  300. local void treat_file   OF((char *iname));
  301. local int create_outfile OF((void));
  302. local int  do_stat      OF((char *name, struct stat *sbuf));
  303.       char *get_suffix  OF((char *name)); /* used in DoOpen for MacGzip */
  304. local int  get_istat    OF((char *iname, struct stat *sbuf));
  305. local int  make_ofname  OF((void));
  306. local int  same_file    OF((struct stat *stat1, struct stat *stat2));
  307. local int name_too_long OF((char *name, struct stat *statb));
  308. local void shorten_name  OF((char *name));
  309. local int  get_method   OF((int in));
  310. local void do_list      OF((int ifd, int method));
  311. local int  check_ofname OF((void));
  312. local void copy_stat    OF((struct stat *ifstat));
  313. local void do_exit      OF((int exitcode));
  314. /*      int main          OF((int argc, char **argv));*/
  315. int (*work) OF((int infile, int outfile)) = zip; /* function to call */
  316.  
  317. #ifndef NO_DIR
  318. local void treat_dir    OF((char *dir));
  319. #endif
  320. #ifndef NO_UTIME
  321. local void reset_times  OF((char *name, struct stat *statb));
  322. #endif
  323.  
  324. #define strequ(s1, s2) (strcmp((s1),(s2)) == 0)
  325.  
  326. /* ======================================================================== */
  327. local void usage()
  328. {
  329.     fprintf(stderr, "usage: %s [-%scdfhlLnN%stvV19] [-S suffix] [file ...]\n",
  330.         progname,
  331. #if O_BINARY
  332.         "a",
  333. #else
  334.         "",
  335. #endif
  336. #ifdef NO_DIR
  337.         ""
  338. #else
  339.         "r"
  340. #endif
  341.         );
  342. }
  343.  
  344. /* ======================================================================== */
  345. local void help()
  346. {
  347.     static char  *help_msg[] = {
  348. #if O_BINARY
  349.  " -a --ascii       ascii text; convert end-of-lines using local conventions",
  350. #endif
  351.  " -c --stdout      write on standard output, keep original files unchanged",
  352.  " -d --decompress  decompress",
  353. /* -e --encrypt     encrypt */
  354.  " -f --force       force overwrite of output file and compress links",
  355.  " -h --help        give this help",
  356. /* -k --pkzip       force output in pkzip format */
  357.  " -l --list        list compressed file contents",
  358.  " -L --license     display software license",
  359. #ifdef UNDOCUMENTED
  360.  " -m --no-time     do not save or restore the original modification time",
  361.  " -M --time        save or restore the original modification time",
  362. #endif
  363.  " -n --no-name     do not save or restore the original name and time stamp",
  364.  " -N --name        save or restore the original name and time stamp",
  365.  " -q --quiet       suppress all warnings",
  366. #ifndef NO_DIR
  367.  " -r --recursive   operate recursively on directories",
  368. #endif
  369.  " -S .suf  --suffix .suf     use suffix .suf on compressed files",
  370.  " -t --test        test compressed file integrity",
  371.  " -v --verbose     verbose mode",
  372.  " -V --version     display version number",
  373.  " -1 --fast        compress faster",
  374.  " -9 --best        compress better",
  375. #ifdef LZW
  376.  " -Z --lzw         produce output compatible with old compress",
  377.  " -b --bits maxbits   max number of bits per code (implies -Z)",
  378. #endif
  379.  " file...          files to (de)compress. If none given, use standard input.",
  380.   0};
  381.     char **p = help_msg;
  382.  
  383.     fprintf(stderr,"%s %s (%s)\n", progname, VERSION, REVDATE);
  384.     usage();
  385.     while (*p) fprintf(stderr, "%s\n", *p++);
  386. }
  387.  
  388. /* ======================================================================== */
  389. local void license()
  390. {
  391.     char **p = license_msg;
  392.  
  393.     fprintf(stderr,"%s %s (%s)\n", progname, VERSION, REVDATE);
  394.     while (*p) fprintf(stderr, "%s\n", *p++);
  395. }
  396.  
  397. /* ======================================================================== */
  398. local void version()
  399. {
  400.     fprintf(stderr,"%s %s (%s)\n", progname, VERSION, REVDATE);
  401.  
  402.     fprintf(stderr, "Compilation options:\n%s %s ", DIR_OPT, TIME_OPT);
  403. #ifdef STDC_HEADERS
  404.     fprintf(stderr, "STDC_HEADERS ");
  405. #endif
  406. #ifdef HAVE_UNISTD_H
  407.     fprintf(stderr, "HAVE_UNISTD_H ");
  408. #endif
  409. #ifdef NO_MEMORY_H
  410.     fprintf(stderr, "NO_MEMORY_H ");
  411. #endif
  412. #ifdef NO_STRING_H
  413.     fprintf(stderr, "NO_STRING_H ");
  414. #endif
  415. #ifdef NO_SYMLINK
  416.     fprintf(stderr, "NO_SYMLINK ");
  417. #endif
  418. #ifdef NO_MULTIPLE_DOTS
  419.     fprintf(stderr, "NO_MULTIPLE_DOTS ");
  420. #endif
  421. #ifdef NO_CHOWN
  422.     fprintf(stderr, "NO_CHOWN ");
  423. #endif
  424. #ifdef PROTO
  425.     fprintf(stderr, "PROTO ");
  426. #endif
  427. #ifdef ASMV
  428.     fprintf(stderr, "ASMV ");
  429. #endif
  430. #ifdef DEBUG
  431.     fprintf(stderr, "DEBUG ");
  432. #endif
  433. #ifdef DYN_ALLOC
  434.     fprintf(stderr, "DYN_ALLOC ");
  435. #endif
  436. #ifdef MAXSEG_64K
  437.     fprintf(stderr, "MAXSEG_64K");
  438. #endif
  439.     fprintf(stderr, "\n");
  440. }
  441.  
  442. /* ======================================================================== */
  443. int gzip_main (argc, argv)
  444.     int argc;
  445.     char **argv;
  446. {
  447.     int file_count;     /* number of files to precess */
  448.     int proglen;        /* length of progname */
  449.     int optc;           /* current option */
  450.  
  451. #ifdef MACOS
  452. /*    argc = ccommand(&argv);*/
  453.     opterr=0;
  454.     init_globals();
  455. #endif
  456.     EXPAND(argc, argv); /* wild card expansion if necessary */
  457.  
  458. /*    progname = basename(argv[0]);*/
  459.     progname = argv[0];
  460.     proglen = strlen(progname);
  461.  
  462.     /* Suppress .exe for MSDOS, OS/2 and VMS: */
  463.     if (proglen > 4 && strequ(progname+proglen-4, ".exe")) {
  464.         progname[proglen-4] = '\0';
  465.     }
  466.  
  467.     /* Add options in GZIP environment variable if there is one */
  468.     env = add_envopt(&argc, &argv, OPTIONS_VAR);
  469.     if (env != NULL) args = argv;
  470.  
  471.     foreground = signal(SIGINT, SIG_IGN) != SIG_IGN;
  472.     if (foreground) {
  473.     (void) signal (SIGINT, (sig_type)abort_gzip);
  474.     }
  475. #ifdef SIGTERM
  476.     if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
  477.     (void) signal(SIGTERM, (sig_type)abort_gzip);
  478.     }
  479. #endif
  480. #ifdef SIGHUP
  481.     if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
  482.     (void) signal(SIGHUP,  (sig_type)abort_gzip);
  483.     }
  484. #endif
  485.  
  486. #ifndef GNU_STANDARD
  487.     /* For compatibility with old compress, use program name as an option.
  488.      * If you compile with -DGNU_STANDARD, this program will behave as
  489.      * gzip even if it is invoked under the name gunzip or zcat.
  490.      *
  491.      * Systems which do not support links can still use -d or -dc.
  492.      * Ignore an .exe extension for MSDOS, OS/2 and VMS.
  493.      */
  494.     if (  strncmp(progname, "un",  2) == 0     /* ungzip, uncompress */
  495.        || strncmp(progname, "gun", 3) == 0) {  /* gunzip */
  496.     decompress = 1;
  497.     } else if (strequ(progname+1, "cat")       /* zcat, pcat, gcat */
  498.         || strequ(progname, "gzcat")) {    /* gzcat */
  499.     decompress = to_stdout = 1;
  500.     }
  501. #endif
  502.  
  503.     strncpy(z_suffix, Z_SUFFIX, sizeof(z_suffix)-1);
  504.     z_len = strlen(z_suffix);
  505.  
  506.     while ((optc = getopt_long (argc, argv, "ab:cdfhH?lLmMnNqrS:tvVZ123456789",
  507.                 longopts, (int *)0)) != EOF) {
  508.     switch (optc) {
  509.         case 'a':
  510.             ascii = 1; break;
  511.     case 'b':
  512.         maxbits = atoi(optarg);
  513.         break;
  514.     case 'c':
  515.         to_stdout = 1; break;
  516.     case 'd':
  517.         decompress = 1; break;
  518.     case 'f':
  519.         force++; break;
  520.     case 'h': case 'H': case '?':
  521.         help(); do_exit(OK); break;
  522.     case 'l':
  523.         list = decompress = to_stdout = 1; break;
  524.     case 'L':
  525.         license(); do_exit(OK); break;
  526.     case 'm': /* undocumented, may change later */
  527.         no_time = 1; break;
  528.     case 'M': /* undocumented, may change later */
  529.         no_time = 0; break;
  530.     case 'n':
  531.         no_name = no_time = 1; break;
  532.     case 'N':
  533.         no_name = no_time = 0; break;
  534.     case 'q':
  535.         quiet = 1; verbose = 0; break;
  536.     case 'r':
  537. #ifdef NO_DIR
  538.         fprintf(stderr, "%s: -r not supported on this system\n", progname);
  539.         usage();
  540.         do_exit(ERROR); break;
  541. #else
  542.         recursive = 1; break;
  543. #endif
  544.     case 'S':
  545. #ifdef NO_MULTIPLE_DOTS
  546.             if (*optarg == '.') optarg++;
  547. #endif
  548.             z_len = strlen(optarg);
  549.             strcpy(z_suffix, optarg);
  550.             break;
  551.     case 't':
  552.         test = decompress = to_stdout = 1;
  553.         break;
  554.     case 'v':
  555.         verbose++; quiet = 0; break;
  556.     case 'V':
  557.         version(); do_exit(OK); break;
  558.     case 'Z':
  559. #ifdef LZW
  560.         do_lzw = 1; break;
  561. #else
  562.         fprintf(stderr, "%s: -Z not supported in this version\n",
  563.             progname);
  564.         usage();
  565.         do_exit(ERROR); break;
  566. #endif
  567.     case '1':  case '2':  case '3':  case '4':
  568.     case '5':  case '6':  case '7':  case '8':  case '9':
  569.         level = optc - '0';
  570.         break;
  571.     default:
  572.         /* Error message already emitted by getopt_long. */
  573.         usage();
  574.         do_exit(ERROR);
  575.     }
  576.     } /* loop on all arguments */
  577.  
  578.     /* By default, save name and timestamp on compression but do not
  579.      * restore them on decompression.
  580.      */
  581.     if (no_time < 0) no_time = decompress;
  582.     if (no_name < 0) no_name = decompress;
  583.  
  584.     file_count = argc - optind;
  585.  
  586. #if O_BINARY
  587. #else
  588.     if (ascii && !quiet) {
  589.     fprintf(stderr, "%s: option --ascii ignored on this system\n",
  590.         progname);
  591.     }
  592. #endif
  593.     if ((z_len == 0 && !decompress) || z_len > MAX_SUFFIX) {
  594.         sprintf(strerr, "incorrect suffix '%s'", optarg);
  595.         Calert(strerr);
  596.         do_exit(ERROR);
  597.     }
  598.     if (do_lzw && !decompress) work = lzw;
  599.  
  600.     /* Allocate all global buffers (for DYN_ALLOC option) */
  601.     ALLOC(uch, inbuf,  INBUFSIZ +INBUF_EXTRA);
  602.     ALLOC(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA);
  603.     ALLOC(ush, d_buf,  DIST_BUFSIZE);
  604.     ALLOC(uch, window, 2L*WSIZE);
  605. #ifndef MAXSEG_64K
  606.     ALLOC(ush, tab_prefix, 1L<<BITS);
  607. #else
  608.     ALLOC(ush, tab_prefix0, 1L<<(BITS-1));
  609.     ALLOC(ush, tab_prefix1, 1L<<(BITS-1));
  610. #endif
  611.  
  612.     /* And get to work */
  613.     if (file_count != 0) {
  614.     if (to_stdout && !test && !list && (!decompress || !ascii)) {
  615.         SET_BINARY_MODE(fileno(stdout));
  616.     }
  617.         while (optind < argc) {
  618.         treat_file(argv[optind++]);
  619.     }
  620.     } else {  /* Standard input */
  621.     treat_stdin();
  622.     }
  623.     if (list && !quiet && file_count > 1) {
  624.     do_list(-1, -1); /* print totals */
  625.     }
  626.     do_exit(exit_code);
  627.     return exit_code; /* just to avoid lint warning */
  628. }
  629.  
  630. /* ========================================================================
  631.  * Compress or decompress stdin
  632.  */
  633. local void treat_stdin()
  634. {
  635.     if (!force && !list &&
  636.     isatty(fileno((FILE *)(decompress ? stdin : stdout)))) {
  637.     /* Do not send compressed data to the terminal or read it from
  638.      * the terminal. We get here when user invoked the program
  639.      * without parameters, so be helpful. According to the GNU standards:
  640.      *
  641.      *   If there is one behavior you think is most useful when the output
  642.      *   is to a terminal, and another that you think is most useful when
  643.      *   the output is a file or a pipe, then it is usually best to make
  644.      *   the default behavior the one that is useful with output to a
  645.      *   terminal, and have an option for the other behavior.
  646.      *
  647.      * Here we use the --force option to get the other behavior.
  648.      */
  649.     fprintf(stderr,
  650.     "%s: compressed data not %s a terminal. Use -f to force %scompression.\n",
  651.         progname, decompress ? "read from" : "written to",
  652.         decompress ? "de" : "");
  653.     fprintf(stderr,"For help, type: %s -h\n", progname);
  654.     do_exit(ERROR);
  655.     }
  656.  
  657.     if (decompress || !ascii) {
  658.     SET_BINARY_MODE(fileno(stdin));
  659.     }
  660.     if (!test && !list && (!decompress || !ascii)) {
  661.     SET_BINARY_MODE(fileno(stdout));
  662.     }
  663.     strcpy(ifname, "stdin");
  664.     strcpy(ofname, "stdout");
  665.  
  666.     /* Get the time stamp on the input file. */
  667.     time_stamp = 0; /* time unknown by default */
  668.  
  669. #ifndef NO_STDIN_FSTAT
  670.     if (list || !no_time) {
  671.     if (fstat(fileno(stdin), &istat) != 0) {
  672.         error("fstat(stdin)");
  673.     }
  674. # ifdef NO_PIPE_TIMESTAMP
  675.     if (S_ISREG(istat.st_mode))
  676. # endif
  677.         time_stamp = istat.st_mtime;
  678.     }
  679. #endif /* NO_STDIN_FSTAT */
  680.  
  681.     ifile_size = -1L; /* convention for unknown size */
  682.  
  683.     clear_bufs(); /* clear input and output buffers */
  684.     to_stdout = 1;
  685.     part_nb = 0;
  686.  
  687.     if (decompress) {
  688.     method = get_method(ifd);
  689.     if (method < 0) {
  690.         do_exit(exit_code); /* error message already emitted */
  691.     }
  692.     }
  693.     if (list) {
  694.         do_list(ifd, method);
  695.         return;
  696.     }
  697.  
  698.     /* Actually do the compression/decompression. Loop over zipped members.
  699.      */
  700.     for (;;) {
  701.     if ((*work)(fileno(stdin), fileno(stdout)) != OK) return;
  702.  
  703.     if (!decompress || last_member || inptr == insize) break;
  704.     /* end of file */
  705.  
  706.     method = get_method(ifd);
  707.     if (method < 0) return; /* error message already emitted */
  708.     bytes_out = 0;            /* required for length check */
  709.     }
  710.  
  711.     if (verbose) {
  712.     if (test) {
  713.         fprintf(stderr, " OK\n");
  714.  
  715.     } else if (!decompress) {
  716.         display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in, stderr);
  717.         fprintf(stderr, "\n");
  718. #ifdef DISPLAY_STDIN_RATIO
  719.     } else {
  720.         display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out,stderr);
  721.         fprintf(stderr, "\n");
  722. #endif
  723.     }
  724.     }
  725. }
  726.  
  727. /* ========================================================================
  728.  * Compress or decompress the given file
  729.  */
  730. local void treat_file(iname)
  731.     char *iname;
  732. {
  733.     /* Accept "-" as synonym for stdin */
  734.     if (strequ(iname, "-")) {
  735.     int cflag = to_stdout;
  736.     treat_stdin();
  737.     to_stdout = cflag;
  738.     return;
  739.     }
  740.  
  741.     /* Check if the input file is present, set ifname and istat: */
  742.     if (get_istat(iname, &istat) != OK) return;
  743.  
  744.     /* If the input name is that of a directory, recurse or ignore: */
  745.     if (S_ISDIR(istat.st_mode)) {
  746. #ifndef NO_DIR
  747.     if (recursive) {
  748.         struct stat st;
  749.         st = istat;
  750.         treat_dir(iname);
  751.         /* Warning: ifname is now garbage */
  752. #  ifndef NO_UTIME
  753.         reset_times (iname, &st);
  754. #  endif
  755.     } else
  756. #endif
  757.     WARN((strerr,"%s: %s is a directory -- ignored", progname, ifname));
  758.     return;
  759.     }
  760.     if (!S_ISREG(istat.st_mode)) {
  761.     WARN((strerr,
  762.           "%s: %s is not a directory or a regular file - ignored",
  763.           progname, ifname));
  764.     return;
  765.     }
  766.     if (istat.st_nlink > 1 && !to_stdout && !force) {
  767.     WARN((strerr, "%s: %s has %d other link%c -- unchanged",
  768.           progname, ifname,
  769.           (int)istat.st_nlink - 1, istat.st_nlink > 2 ? 's' : ' '));
  770.     return;
  771.     }
  772.  
  773.     ifile_size = istat.st_size;
  774.     time_stamp = no_time && !list ? 0 : istat.st_mtime;
  775.  
  776.     /* Generate output file name. For -r and (-t or -l), skip files
  777.      * without a valid gzip suffix (check done in make_ofname).
  778.      */
  779.     if (to_stdout && !list && !test) {
  780.     strcpy(ofname, "stdout");
  781.  
  782.     } else if (make_ofname() != OK) {
  783.     return;
  784.     }
  785.  
  786.  
  787.  
  788. /* HERE */
  789.  
  790.     /* Open the input file and determine compression method. The mode
  791.      * parameter is ignored but required by some systems (VMS) and forbidden
  792.      * on other systems (MacOS).
  793.      */
  794.      
  795.      /* MacGzip 0.2.2 */
  796.     ifd = OPEN(ifname, ascii && !decompress ? O_RDONLY | O_TEXT : O_RDONLY | O_BINARY,
  797.            RW_USER);
  798.            
  799.     if (ifd == -1) {
  800.     PError(ifname);
  801.     exit_code = ERROR;
  802.     return;
  803.     }
  804.     clear_bufs(); /* clear input and output buffers */
  805.     part_nb = 0;
  806.  
  807.     if (decompress) {
  808.     method = get_method(ifd); /* updates ofname if original given */
  809.     if (method < 0) {
  810.         close(ifd);
  811.         return;               /* error message already emitted */
  812.     }
  813.     }
  814.     if (list) {
  815.         do_list(ifd, method);
  816.         close(ifd);
  817.         return;
  818.     }
  819.  
  820.     /* If compressing to a file, check if ofname is not ambiguous
  821.      * because the operating system truncates names. Otherwise, generate
  822.      * a new ofname and save the original name in the compressed file.
  823.      */
  824.     if (to_stdout) {
  825.     ofd = fileno(stdout);
  826.     /* keep remove_ofname as zero */
  827.     } else {
  828.     if (create_outfile() != OK) return;
  829.  
  830.     if (!decompress && save_orig_name && !verbose && !quiet) {
  831.         
  832.         sprintf(strerr, "%s: %s compressed to %s",
  833.             progname, ifname, ofname);
  834.         
  835.         Calert(strerr);
  836.     }
  837.     }
  838.     /* Keep the name even if not truncated except with --no-name: */
  839.     if (!save_orig_name) save_orig_name = !no_name;
  840.  
  841.     if (verbose) {
  842.     fprintf(stderr, "%s:\t%s", ifname, (int)strlen(ifname) >= 15 ? 
  843.         "" : ((int)strlen(ifname) >= 7 ? "\t" : "\t\t"));
  844.     }
  845.  
  846.     /* Actually do the compression/decompression. Loop over zipped members.
  847.      */
  848.     for (;;) {
  849.     
  850. #ifdef _SPD_PROG_
  851.          sprintf(SPDpstr, "%s (%s): %s -> %s",
  852.          progname,
  853.          ascii ? "ascii" : "bin",
  854.          ifname, ofname);
  855.          InitAnimatedCursors(kCalCursorRes);
  856.          InitMovableModal((unsigned long int) istat.st_size);
  857. #endif
  858.     
  859.     if ( (*work)(ifd, ofd) != OK) {
  860.         method = -1; /* force cleanup */
  861.         break;
  862.     }
  863.     
  864.     if (!decompress || last_member || inptr == insize) break;
  865.     /* end of file */
  866.  
  867.     method = get_method(ifd);
  868.     if (method < 0) break;    /* error message already emitted */
  869.     bytes_out = 0;            /* required for length check */
  870.     }
  871.  
  872.     close(ifd);
  873.     if (!to_stdout && close(ofd)) {
  874.     write_error();
  875.     }
  876.     if (method == -1) {
  877.     if (!to_stdout) unlink (ofname);
  878.     return;
  879.     }
  880.     /* Display statistics */
  881.     if(verbose) {
  882.     if (test) {
  883.         fprintf(stderr, " OK");
  884.     } else if (decompress) {
  885.         display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out,stderr);
  886.     } else {
  887.         display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in, stderr);
  888.     }
  889.     if (!test && !to_stdout) {
  890.         fprintf(stderr, " -- replaced with %s", ofname);
  891.     }
  892.     fprintf(stderr, "\n");
  893.     }
  894.     /* Copy modes, times, ownership, and remove the input file */
  895.     if (!to_stdout) {
  896.     copy_stat(&istat);
  897.     }
  898. }
  899.  
  900. /* ========================================================================
  901.  * Create the output file. Return OK or ERROR.
  902.  * Try several times if necessary to avoid truncating the z_suffix. For
  903.  * example, do not create a compressed file of name "1234567890123."
  904.  * Sets save_orig_name to true if the file name has been truncated.
  905.  * IN assertions: the input file has already been open (ifd is set) and
  906.  *   ofname has already been updated if there was an original name.
  907.  * OUT assertions: ifd and ofd are closed in case of error.
  908.  */
  909. local int create_outfile()
  910. {
  911.     struct stat    ostat; /* stat for ofname */
  912.     int flags = O_WRONLY | O_CREAT | O_EXCL | O_BINARY;
  913.  
  914. #ifdef MACOS
  915.     /* if compress, ascii has been set in DoOpen */
  916.     if (decompress)
  917.     {
  918.         ascii = AsciiMode(ofname, ascii, 0);
  919.     }
  920. #endif /* MACOS */
  921.  
  922.     if (ascii && decompress) {
  923. #ifndef MACOS
  924.     flags &= ~O_BINARY; /* force ascii text mode */
  925. #else
  926.     flags = O_WRONLY | O_CREAT | O_EXCL | O_TEXT; /* MacGzip */
  927. #endif /*MACOS*/
  928.     }
  929.     for (;;) {
  930.     /* Make sure that ofname is not an existing file */
  931.     if (check_ofname() != OK) {
  932.         close(ifd);
  933.         return ERROR;
  934.     }
  935.     /* Create the output file */
  936.     remove_ofname = 1;
  937.     ofd = OPEN(ofname, flags, RW_USER);
  938.     if (ofd == -1) {
  939.         PError(ofname);
  940.         close(ifd);
  941.         exit_code = ERROR;
  942.         return ERROR;
  943.     }
  944.     
  945. #ifdef MACOS
  946.     FixMacFile(ofname, ascii, decompress);
  947. #endif /* MACOS */
  948.  
  949.     /* Check for name truncation on new file (1234567890123.gz) */
  950. #ifdef NO_FSTAT
  951.     if (stat(ofname, &ostat) != 0) {
  952. #else
  953.     if (fstat(ofd, &ostat) != 0) {
  954. #endif
  955.         PError(ofname);
  956.         close(ifd); close(ofd);
  957.         unlink(ofname);
  958.         exit_code = ERROR;
  959.         return ERROR;
  960.     }
  961.     if (!name_too_long(ofname, &ostat)) return OK;
  962.  
  963.     if (decompress) {
  964.         /* name might be too long if an original name was saved */
  965.         WARN((strerr, "%s: %s: warning, name truncated",
  966.           progname, ofname));
  967.         return OK;
  968.     }
  969.     close(ofd);
  970.     unlink(ofname);
  971. #ifdef NO_MULTIPLE_DOTS
  972.     /* Should never happen, see check_ofname() */
  973.     sprintf(strerr, "%s: name too long", ofname);
  974.     Calert(strerr);
  975.     do_exit(ERROR);
  976. #endif
  977.     shorten_name(ofname);
  978.     }
  979. }
  980.  
  981. /* ========================================================================
  982.  * Use lstat if available, except for -c or -f. Use stat otherwise.
  983.  * This allows links when not removing the original file.
  984.  */
  985. local int do_stat(name, sbuf)
  986.     char *name;
  987.     struct stat *sbuf;
  988. {
  989.     errno = 0;
  990. #if (defined(S_IFLNK) || defined (S_ISLNK)) && !defined(NO_SYMLINK)
  991.     if (!to_stdout && !force) {
  992.     return lstat(name, sbuf);
  993.     }
  994. #endif
  995.     return stat(name, sbuf);
  996. }
  997.  
  998. /* ========================================================================
  999.  * Return a pointer to the 'z' suffix of a file name, or NULL. For all
  1000.  * systems, ".gz", ".z", ".Z", ".taz", ".tgz", "-gz", "-z" and "_z" are
  1001.  * accepted suffixes, in addition to the value of the --suffix option.
  1002.  * ".tgz" is a useful convention for tar.z files on systems limited
  1003.  * to 3 characters extensions. On such systems, ".?z" and ".??z" are
  1004.  * also accepted suffixes. For Unix, we do not want to accept any
  1005.  * .??z suffix as indicating a compressed file; some people use .xyz
  1006.  * to denote volume data.
  1007.  *   On systems allowing multiple versions of the same file (such as VMS),
  1008.  * this function removes any version suffix in the given name.
  1009.  */
  1010. char *get_suffix(name)
  1011.     char *name;
  1012. {
  1013.     int nlen, slen;
  1014.     char suffix[MAX_SUFFIX+3]; /* last chars of name, forced to lower case */
  1015.     static char *known_suffixes[] =
  1016.        {z_suffix, ".gz", ".z", ".taz", ".tgz", "-gz", "-z", "_z",
  1017. #ifdef MAX_EXT_CHARS
  1018.           "z",
  1019. #endif
  1020.           NULL};
  1021.     char **suf = known_suffixes;
  1022.  
  1023.    if (strequ(z_suffix, "z")) suf++; /* check long suffixes first */
  1024.  
  1025. #ifdef SUFFIX_SEP
  1026.     /* strip a version number from the file name */
  1027.     {
  1028.     char *v = strrchr(name, SUFFIX_SEP);
  1029.      if (v != NULL) *v = '\0';
  1030.     }
  1031. #endif
  1032.     nlen = strlen(name);
  1033.     if (nlen <= MAX_SUFFIX+2) {
  1034.         strcpy(suffix, name);
  1035.     } else {
  1036.         strcpy(suffix, name+nlen-MAX_SUFFIX-2);
  1037.     }
  1038.     strlwr(suffix);
  1039.     slen = strlen(suffix);
  1040.     do {
  1041.        int s = strlen(*suf);
  1042.        if (slen > s && suffix[slen-s-1] != PATH_SEP
  1043.            && strequ(suffix + slen - s, *suf)) {
  1044.            return name+nlen-s;
  1045.        }
  1046.     } while (*++suf != NULL);
  1047.  
  1048.     return NULL;
  1049. }
  1050.  
  1051.  
  1052. /* ========================================================================
  1053.  * Set ifname to the input file name (with a suffix appended if necessary)
  1054.  * and istat to its stats. For decompression, if no file exists with the
  1055.  * original name, try adding successively z_suffix, .gz, .z, -z and .Z.
  1056.  * For MSDOS, we try only z_suffix and z.
  1057.  * Return OK or ERROR.
  1058.  */
  1059. local int get_istat(iname, sbuf)
  1060.     char *iname;
  1061.     struct stat *sbuf;
  1062. {
  1063.     int ilen;  /* strlen(ifname) */
  1064.     static char *suffixes[] = {z_suffix, ".gz", ".z", "-z", ".Z", NULL};
  1065.     char **suf = suffixes;
  1066.     char *s;
  1067. #ifdef NO_MULTIPLE_DOTS
  1068.     char *dot; /* pointer to ifname extension, or NULL */
  1069. #endif
  1070.  
  1071.     strcpy(ifname, iname);
  1072.  
  1073.     /* If input file exists, return OK. */
  1074.     if (do_stat(ifname, sbuf) == 0) return OK;
  1075.  
  1076.     if (!decompress || errno != ENOENT) {
  1077.     PError(ifname);
  1078.     exit_code = ERROR;
  1079.     return ERROR;
  1080.     }
  1081.     /* file.ext doesn't exist, try adding a suffix (after removing any
  1082.      * version number for VMS).
  1083.      */
  1084.     s = get_suffix(ifname);
  1085.     if (s != NULL) {
  1086.     PError(ifname); /* ifname already has z suffix and does not exist */
  1087.     exit_code = ERROR;
  1088.     return ERROR;
  1089.     }
  1090. #ifdef NO_MULTIPLE_DOTS
  1091.     dot = strrchr(ifname, '.');
  1092.     if (dot == NULL) {
  1093.         strcat(ifname, ".");
  1094.         dot = strrchr(ifname, '.');
  1095.     }
  1096. #endif
  1097.     ilen = strlen(ifname);
  1098.     if (strequ(z_suffix, ".gz")) suf++;
  1099.  
  1100.     /* Search for all suffixes */
  1101.     do {
  1102.         s = *suf;
  1103. #ifdef NO_MULTIPLE_DOTS
  1104.         if (*s == '.') s++;
  1105. #endif
  1106. #ifdef MAX_EXT_CHARS
  1107.         strcpy(ifname, iname);
  1108.         /* Needed if the suffixes are not sorted by increasing length */
  1109.  
  1110.         if (*dot == '\0') strcpy(dot, ".");
  1111.         dot[MAX_EXT_CHARS+1-strlen(s)] = '\0';
  1112. #endif
  1113.         strcat(ifname, s);
  1114.         if (do_stat(ifname, sbuf) == 0) return OK;
  1115.     ifname[ilen] = '\0';
  1116.     } while (*++suf != NULL);
  1117.  
  1118.     /* No suffix found, complain using z_suffix: */
  1119. #ifdef MAX_EXT_CHARS
  1120.     strcpy(ifname, iname);
  1121.     if (*dot == '\0') strcpy(dot, ".");
  1122.     dot[MAX_EXT_CHARS+1-z_len] = '\0';
  1123. #endif
  1124.     strcat(ifname, z_suffix);
  1125.     PError(ifname);
  1126.     exit_code = ERROR;
  1127.     return ERROR;
  1128. }
  1129.  
  1130. /* ========================================================================
  1131.  * Generate ofname given ifname. Return OK, or WARNING if file must be skipped.
  1132.  * Sets save_orig_name to true if the file name has been truncated.
  1133.  */
  1134. local int make_ofname()
  1135. {
  1136.     char *suff;            /* ofname z suffix */
  1137.  
  1138.     strcpy(ofname, ifname);
  1139.     /* strip a version number if any and get the gzip suffix if present: */
  1140.     suff = get_suffix(ofname);
  1141.  
  1142.     if (decompress) {
  1143.     if (suff == NULL) {
  1144.         /* Whith -t or -l, try all files (even without .gz suffix)
  1145.          * except with -r (behave as with just -dr).
  1146.              */
  1147.             if (!recursive && (list || test)) return OK;
  1148.  
  1149.         /* Avoid annoying messages with -r */
  1150.         if (verbose || (!recursive && !quiet)) {
  1151.         WARN((strerr,"%s: %s: unknown suffix -- ignored",
  1152.               progname, ifname));
  1153.         }
  1154.         return WARNING;
  1155.     }
  1156.     /* Make a special case for .tgz and .taz: */
  1157.     strlwr(suff);
  1158.     if (strequ(suff, ".tgz") || strequ(suff, ".taz")) {
  1159.         strcpy(suff, ".tar");
  1160.     } else {
  1161.         *suff = '\0'; /* strip the z suffix */
  1162.     }
  1163.         /* ofname might be changed later if infile contains an original name */
  1164.  
  1165.     } else if (suff != NULL) {
  1166.     /* Avoid annoying messages with -r (see treat_dir()) */
  1167.     if (verbose || (!recursive && !quiet)) {
  1168.         sprintf(strerr, "%s already has %s suffix -- unchanged", ifname, suff);
  1169.         Calert(strerr);
  1170.     }
  1171.     if (exit_code == OK) exit_code = WARNING;
  1172.     return WARNING;
  1173.     } else {
  1174.         save_orig_name = 0;
  1175.  
  1176. #ifdef NO_MULTIPLE_DOTS
  1177.     suff = strrchr(ofname, '.');
  1178.     if (suff == NULL) {
  1179.             strcat(ofname, ".");
  1180. #  ifdef MAX_EXT_CHARS
  1181.         if (strequ(z_suffix, "z")) {
  1182.         strcat(ofname, "gz"); /* enough room */
  1183.         return OK;
  1184.         }
  1185.         /* On the Atari and some versions of MSDOS, name_too_long()
  1186.          * does not work correctly because of a bug in stat(). So we
  1187.          * must truncate here.
  1188.          */
  1189.         } else if (strlen(suff)-1 + z_len > MAX_SUFFIX) {
  1190.             suff[MAX_SUFFIX+1-z_len] = '\0';
  1191.             save_orig_name = 1;
  1192. #  endif
  1193.         }
  1194. #endif /* NO_MULTIPLE_DOTS */
  1195.     strcat(ofname, z_suffix);
  1196.  
  1197.     } /* decompress ? */
  1198.     return OK;
  1199. }
  1200.  
  1201.  
  1202. /* ========================================================================
  1203.  * Check the magic number of the input file and update ofname if an
  1204.  * original name was given and to_stdout is not set.
  1205.  * Return the compression method, -1 for error, -2 for warning.
  1206.  * Set inptr to the offset of the next byte to be processed.
  1207.  * Updates time_stamp if there is one and --no-time is not used.
  1208.  * This function may be called repeatedly for an input file consisting
  1209.  * of several contiguous gzip'ed members.
  1210.  * IN assertions: there is at least one remaining compressed member.
  1211.  *   If the member is a zip file, it must be the only one.
  1212.  */
  1213. local int get_method(in)
  1214.     int in;        /* input file descriptor */
  1215. {
  1216.     uch flags;     /* compression flags */
  1217.     char magic[2]; /* magic header */
  1218.     ulg stamp;     /* time stamp */
  1219.  
  1220.     /* If --force and --stdout, zcat == cat, so do not complain about
  1221.      * premature end of file: use try_byte instead of get_byte.
  1222.      */
  1223.     if (force && to_stdout) {
  1224.     magic[0] = (char)try_byte();
  1225.     magic[1] = (char)try_byte();
  1226.     /* If try_byte returned EOF, magic[1] == 0xff */
  1227.     } else {
  1228.     magic[0] = (char)get_byte();
  1229.     magic[1] = (char)get_byte();
  1230.     }
  1231.     method = -1;                 /* unknown yet */
  1232.     part_nb++;                   /* number of parts in gzip file */
  1233.     header_bytes = 0;
  1234.     last_member = RECORD_IO;
  1235.     /* assume multiple members in gzip file except for record oriented I/O */
  1236.  
  1237.     if (memcmp(magic, GZIP_MAGIC, 2) == 0
  1238.         || memcmp(magic, OLD_GZIP_MAGIC, 2) == 0) {
  1239.  
  1240.     method = (int)get_byte();
  1241.     if (method != DEFLATED) {
  1242.         sprintf(strerr,
  1243.             "%s: unknown method %d -- get newer version of gzip", ifname, method);
  1244.         Calert(strerr);
  1245.         exit_code = ERROR;
  1246.         return -1;
  1247.     }
  1248.     work = unzip;
  1249.     flags  = (uch)get_byte();
  1250.     if ((flags & ENCRYPTED) != 0) {
  1251.         sprintf(strerr,
  1252.             "%s is encrypted -- get newer version of gzip", ifname);
  1253.         Calert(strerr);
  1254.         exit_code = ERROR;
  1255.         return -1;
  1256.     }
  1257.     if ((flags & CONTINUATION) != 0) {
  1258.         sprintf(strerr,
  1259.        "%s is a a multi-part gzip file -- get newer version of gzip", ifname);
  1260.        Calert(strerr);
  1261.         exit_code = ERROR;
  1262.         if (force <= 1) return -1;
  1263.     }
  1264.     if ((flags & RESERVED) != 0) {
  1265.         sprintf(strerr,
  1266.             "%s has flags 0x%x -- get newer version of gzip", ifname, flags);
  1267.         Calert(strerr);
  1268.         exit_code = ERROR;
  1269.         if (force <= 1) return -1;
  1270.     }
  1271.     stamp  = (ulg)get_byte();
  1272.     stamp |= ((ulg)get_byte()) << 8;
  1273.     stamp |= ((ulg)get_byte()) << 16;
  1274.     stamp |= ((ulg)get_byte()) << 24;
  1275.     if (stamp != 0 && !no_time) time_stamp = stamp;
  1276.  
  1277.     (void)get_byte();  /* Ignore extra flags for the moment */
  1278.     (void)get_byte();  /* Ignore OS type for the moment */
  1279.  
  1280.     if ((flags & CONTINUATION) != 0) {
  1281.         unsigned part = (unsigned)get_byte();
  1282.         part |= ((unsigned)get_byte())<<8;
  1283.         if (verbose) {
  1284.         fprintf(stderr,"%s: %s: part number %u\n",
  1285.             progname, ifname, part);
  1286.         }
  1287.     }
  1288.     if ((flags & EXTRA_FIELD) != 0) {
  1289.         unsigned len = (unsigned)get_byte();
  1290.         len |= ((unsigned)get_byte())<<8;
  1291.         if (verbose) {
  1292.         fprintf(stderr,"%s: %s: extra field of %u bytes ignored\n",
  1293.             progname, ifname, len);
  1294.         }
  1295.         while (len--) (void)get_byte();
  1296.     }
  1297.  
  1298.     /* Get original file name if it was truncated */
  1299.     if ((flags & ORIG_NAME) != 0) {
  1300.         if (no_name || (to_stdout && !list) || part_nb > 1) {
  1301.         /* Discard the old name */
  1302.         char c; /* dummy used for NeXTstep 3.0 cc optimizer bug */
  1303.         do {c=get_byte();} while (c != 0);
  1304.         } else {
  1305.         /* Copy the base name. Keep a directory prefix intact. */
  1306.                 char *p = basename(ofname);
  1307.                 char *base = p;
  1308.         for (;;) {
  1309.             *p = (char)get_char();
  1310.             if (*p++ == '\0') break;
  1311.             if (p >= ofname+sizeof(ofname)) {
  1312.             error("corrupted input -- file name too large");
  1313.             }
  1314.         }
  1315.                 /* If necessary, adapt the name to local OS conventions: */
  1316.                 if (!list) {
  1317.                    MAKE_LEGAL_NAME(base);
  1318.            if (base) list=0; /* avoid warning about unused variable */
  1319.                 }
  1320.         } /* no_name || to_stdout */
  1321.     } /* ORIG_NAME */
  1322.  
  1323.     /* Discard file comment if any */
  1324.     if ((flags & COMMENT) != 0) {
  1325.         while (get_char() != 0) /* null */ ;
  1326.     }
  1327.     if (part_nb == 1) {
  1328.         header_bytes = inptr + 2*sizeof(long); /* include crc and size */
  1329.     }
  1330.  
  1331.     } else if (memcmp(magic, PKZIP_MAGIC, 2) == 0 && inptr == 2
  1332.         && memcmp((char*)inbuf, PKZIP_MAGIC, 4) == 0) {
  1333.     /* To simplify the code, we support a zip file when alone only.
  1334.          * We are thus guaranteed that the entire local header fits in inbuf.
  1335.          */
  1336.         inptr = 0;
  1337.     work = unzip;
  1338.     if (check_zipfile(in) != OK) return -1;
  1339.     /* check_zipfile may get ofname from the local header */
  1340.     last_member = 1;
  1341.  
  1342.     } else if (memcmp(magic, PACK_MAGIC, 2) == 0) {
  1343.     work = unpack;
  1344.     method = PACKED;
  1345.  
  1346.     } else if (memcmp(magic, LZW_MAGIC, 2) == 0) {
  1347.     work = unlzw;
  1348.     method = COMPRESSED;
  1349.     last_member = 1;
  1350.  
  1351.     } else if (memcmp(magic, LZH_MAGIC, 2) == 0) {
  1352.     work = unlzh;
  1353.     method = LZHED;
  1354.     last_member = 1;
  1355.  
  1356.     } else if (force && to_stdout && !list) { /* pass input unchanged */
  1357.     method = STORED;
  1358.     work = copy;
  1359.         inptr = 0;
  1360.     last_member = 1;
  1361.     }
  1362.     if (method >= 0) return method;
  1363.     if (part_nb == 1) {
  1364.     sprintf(strerr, "%s: not in gzip format", ifname);
  1365.     Calert(strerr);
  1366.     exit_code = ERROR;
  1367.     return -1;
  1368.     } else {
  1369.     WARN((strerr, "%s: %s: decompression OK, trailing garbage ignored",
  1370.           progname, ifname));
  1371.     return -2;
  1372.     }
  1373. }
  1374.  
  1375. /* ========================================================================
  1376.  * Display the characteristics of the compressed file.
  1377.  * If the given method is < 0, display the accumulated totals.
  1378.  * IN assertions: time_stamp, header_bytes and ifile_size are initialized.
  1379.  */
  1380. local void do_list(ifd, method)
  1381.     int ifd;     /* input file descriptor */
  1382.     int method;  /* compression method */
  1383. {
  1384.     ulg crc;  /* original crc */
  1385.     static int first_time = 1;
  1386.     static char* methods[MAX_METHODS] = {
  1387.         "store",  /* 0 */
  1388.         "compr",  /* 1 */
  1389.         "pack ",  /* 2 */
  1390.         "lzh  ",  /* 3 */
  1391.         "", "", "", "", /* 4 to 7 reserved */
  1392.         "defla"}; /* 8 */
  1393.     char *date;
  1394.  
  1395.     if (first_time && method >= 0) {
  1396.     first_time = 0;
  1397.     if (verbose)  {
  1398.         printf("method  crc     date  time  ");
  1399.     }
  1400.     if (!quiet) {
  1401.         printf("compressed  uncompr. ratio uncompressed_name\n");
  1402.     }
  1403.     } else if (method < 0) {
  1404.     if (total_in <= 0 || total_out <= 0) return;
  1405.     if (verbose) {
  1406.         printf("                            %9lu %9lu ",
  1407.            total_in, total_out);
  1408.     } else if (!quiet) {
  1409.         printf("%9ld %9ld ", total_in, total_out);
  1410.     }
  1411.     display_ratio(total_out-(total_in-header_bytes), total_out, stdout);
  1412.     /* header_bytes is not meaningful but used to ensure the same
  1413.      * ratio if there is a single file.
  1414.      */
  1415.     printf(" (totals)\n");
  1416.     return;
  1417.     }
  1418.     crc = (ulg)~0; /* unknown */
  1419.     bytes_out = -1L;
  1420.     bytes_in = ifile_size;
  1421.  
  1422. #if RECORD_IO == 0
  1423.     if (method == DEFLATED && !last_member) {
  1424.         /* Get the crc and uncompressed size for gzip'ed (not zip'ed) files.
  1425.          * If the lseek fails, we could use read() to get to the end, but
  1426.          * --list is used to get quick results.
  1427.          * Use "gunzip < foo.gz | wc -c" to get the uncompressed size if
  1428.          * you are not concerned about speed.
  1429.          */
  1430.         bytes_in = (long)lseek(ifd, (off_t)(-8), SEEK_END);
  1431.         if (bytes_in != -1L) {
  1432.             uch buf[8];
  1433.             bytes_in += 8L;
  1434.             if (read(ifd, (char*)buf, sizeof(buf)) != sizeof(buf)) {
  1435.                 read_error();
  1436.             }
  1437.             crc       = LG(buf);
  1438.         bytes_out = LG(buf+4);
  1439.     }
  1440.     }
  1441. #endif /* RECORD_IO */
  1442.     date = ctime((time_t*)&time_stamp) + 4; /* skip the day of the week */
  1443.     date[12] = '\0';               /* suppress the 1/100sec and the year */
  1444.     if (verbose) {
  1445.         printf("%5s %08lx %11s ", methods[method], crc, date);
  1446.     }
  1447.     printf("%9ld %9ld ", bytes_in, bytes_out);
  1448.     if (bytes_in  == -1L) {
  1449.     total_in = -1L;
  1450.     bytes_in = bytes_out = header_bytes = 0;
  1451.     } else if (total_in >= 0) {
  1452.     total_in  += bytes_in;
  1453.     }
  1454.     if (bytes_out == -1L) {
  1455.     total_out = -1L;
  1456.     bytes_in = bytes_out = header_bytes = 0;
  1457.     } else if (total_out >= 0) {
  1458.     total_out += bytes_out;
  1459.     }
  1460.     display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out, stdout);
  1461.     printf(" %s\n", ofname);
  1462. }
  1463.  
  1464. /* ========================================================================
  1465.  * Return true if the two stat structures correspond to the same file.
  1466.  */
  1467. local int same_file(stat1, stat2)
  1468.     struct stat *stat1;
  1469.     struct stat *stat2;
  1470. {
  1471.     return stat1->st_ino   == stat2->st_ino
  1472.     && stat1->st_dev   == stat2->st_dev
  1473. #ifdef NO_ST_INO
  1474.         /* Can't rely on st_ino and st_dev, use other fields: */
  1475.     && stat1->st_mode  == stat2->st_mode
  1476.     && stat1->st_uid   == stat2->st_uid
  1477.     && stat1->st_gid   == stat2->st_gid
  1478.     && stat1->st_size  == stat2->st_size
  1479.     && stat1->st_atime == stat2->st_atime
  1480.     && stat1->st_mtime == stat2->st_mtime
  1481.     && stat1->st_ctime == stat2->st_ctime
  1482. #endif
  1483.         ;
  1484. }
  1485.  
  1486. /* ========================================================================
  1487.  * Return true if a file name is ambiguous because the operating system
  1488.  * truncates file names.
  1489.  */
  1490. local int name_too_long(name, statb)
  1491.     char *name;           /* file name to check */
  1492.     struct stat *statb;   /* stat buf for this file name */
  1493. {
  1494.     int s = strlen(name);
  1495.     char c = name[s-1];
  1496.     struct stat    tstat; /* stat for truncated name */
  1497.     int res;
  1498.  
  1499.     tstat = *statb;      /* Just in case OS does not fill all fields */
  1500.     name[s-1] = '\0';
  1501.     res = stat(name, &tstat) == 0 && same_file(statb, &tstat);
  1502.     name[s-1] = c;
  1503.     Trace((stderr, " too_long(%s) => %d\n", name, res));
  1504.     return res;
  1505. }
  1506.  
  1507. /* ========================================================================
  1508.  * Shorten the given name by one character, or replace a .tar extension
  1509.  * with .tgz. Truncate the last part of the name which is longer than
  1510.  * MIN_PART characters: 1234.678.012.gz -> 123.678.012.gz. If the name
  1511.  * has only parts shorter than MIN_PART truncate the longest part.
  1512.  * For decompression, just remove the last character of the name.
  1513.  *
  1514.  * IN assertion: for compression, the suffix of the given name is z_suffix.
  1515.  */
  1516. local void shorten_name(name)
  1517.     char *name;
  1518. {
  1519.     int len;                 /* length of name without z_suffix */
  1520.     char *trunc = NULL;      /* character to be truncated */
  1521.     int plen;                /* current part length */
  1522.     int min_part = MIN_PART; /* current minimum part length */
  1523.     char *p;
  1524.  
  1525.     len = strlen(name);
  1526.     if (decompress) {
  1527.     if (len <= 1) error("name too short");
  1528.     name[len-1] = '\0';
  1529.     return;
  1530.     }
  1531.     p = get_suffix(name);
  1532.     if (p == NULL) error("can't recover suffix\n");
  1533.     *p = '\0';
  1534.     save_orig_name = 1;
  1535.  
  1536.     /* compress 1234567890.tar to 1234567890.tgz */
  1537.     if (len > 4 && strequ(p-4, ".tar")) {
  1538.     strcpy(p-4, ".tgz");
  1539.     return;
  1540.     }
  1541.     /* Try keeping short extensions intact:
  1542.      * 1234.678.012.gz -> 123.678.012.gz
  1543.      */
  1544.     do {
  1545.     p = strrchr(name, PATH_SEP);
  1546.     p = p ? p+1 : name;
  1547.     while (*p) {
  1548.         plen = strcspn(p, PART_SEP);
  1549.         p += plen;
  1550.         if (plen > min_part) trunc = p-1;
  1551.         if (*p) p++;
  1552.     }
  1553.     } while (trunc == NULL && --min_part != 0);
  1554.  
  1555.     if (trunc != NULL) {
  1556.     do {
  1557.         trunc[0] = trunc[1];
  1558.     } while (*trunc++);
  1559.     trunc--;
  1560.     } else {
  1561.     trunc = strrchr(name, PART_SEP[0]);
  1562.     if (trunc == NULL) error("internal error in shorten_name");
  1563.     if (trunc[1] == '\0') trunc--; /* force truncation */
  1564.     }
  1565.     strcpy(trunc, z_suffix);
  1566. }
  1567.  
  1568. /* ========================================================================
  1569.  * If compressing to a file, check if ofname is not ambiguous
  1570.  * because the operating system truncates names. Otherwise, generate
  1571.  * a new ofname and save the original name in the compressed file.
  1572.  * If the compressed file already exists, ask for confirmation.
  1573.  *    The check for name truncation is made dynamically, because different
  1574.  * file systems on the same OS might use different truncation rules (on SVR4
  1575.  * s5 truncates to 14 chars and ufs does not truncate).
  1576.  *    This function returns -1 if the file must be skipped, and
  1577.  * updates save_orig_name if necessary.
  1578.  * IN assertions: save_orig_name is already set if ofname has been
  1579.  * already truncated because of NO_MULTIPLE_DOTS. The input file has
  1580.  * already been open and istat is set.
  1581.  */
  1582. local int check_ofname()
  1583. {
  1584.     struct stat    ostat; /* stat for ofname */
  1585.  
  1586. #ifdef ENAMETOOLONG
  1587.     /* Check for strictly conforming Posix systems (which return ENAMETOOLONG
  1588.      * instead of silently truncating filenames).
  1589.      */
  1590.     errno = 0;
  1591.     while (stat(ofname, &ostat) != 0) {
  1592.         if (errno != ENAMETOOLONG) return 0; /* ofname does not exist */
  1593.     shorten_name(ofname);
  1594.     }
  1595. #else
  1596. #ifdef MACOS
  1597.     while (strlen(ofname) > 31) shorten_name(ofname);
  1598. #endif
  1599.     if (stat(ofname, &ostat) != 0) return 0;
  1600. #endif
  1601.     /* Check for name truncation on existing file. Do this even on systems
  1602.      * defining ENAMETOOLONG, because on most systems the strict Posix
  1603.      * behavior is disabled by default (silent name truncation allowed).
  1604.      */
  1605.     if (!decompress && name_too_long(ofname, &ostat)) {
  1606.     shorten_name(ofname);
  1607.     if (stat(ofname, &ostat) != 0) return 0;
  1608.     }
  1609.  
  1610.     /* Check that the input and output files are different (could be
  1611.      * the same by name truncation or links).
  1612.      */
  1613.     if (same_file(&istat, &ostat)) {
  1614.     if (strequ(ifname, ofname)) {
  1615.         sprintf(strerr, "%s: cannot %scompress onto itself",ifname, decompress ? "de" : "");
  1616.         Calert(strerr);
  1617.     } else {
  1618.         sprintf(strerr, "%s and %s are the same file", ifname, ofname);
  1619.         Calert(strerr);
  1620.     }
  1621.     exit_code = ERROR;
  1622.     return ERROR;
  1623.     }
  1624.     /* Ask permission to overwrite the existing file */
  1625. #ifndef MACOS
  1626.     if (!force) {
  1627.     char response[80];
  1628.     strcpy(response,"n");
  1629.     fprintf(stderr, "%s: %s already exists;", progname, ofname);
  1630.     if (foreground && isatty(fileno(stdin))) {
  1631.         fprintf(stderr, " do you wish to overwrite (y or n)? ");
  1632.         fflush(stderr);
  1633.         (void)fgets(response, sizeof(response)-1, stdin);
  1634.     }
  1635.     if (tolow(*response) != 'y') {
  1636.         fprintf(stderr, "\tnot overwritten\n");
  1637.         if (exit_code == OK) exit_code = WARNING;
  1638.         return ERROR;
  1639.     }
  1640.     }
  1641.  
  1642. #else
  1643.     if (!force) {
  1644.     sprintf(strerr, " %s already exists; do you wish to overwrite ?", ofname);
  1645.  
  1646.     if (Cask(strerr)==cancel) {
  1647.         if (exit_code == OK) exit_code = WARNING;
  1648.         return ERROR;
  1649.     }
  1650.     }
  1651.  
  1652.  
  1653. #endif /*MACOS*/
  1654.  
  1655.     (void) chmod(ofname, 0777);
  1656.     if (unlink(ofname)) {
  1657.     PError(ofname);
  1658.     exit_code = ERROR;
  1659.     return ERROR;
  1660.     }
  1661.     return OK;
  1662. }
  1663.  
  1664.  
  1665. #ifndef NO_UTIME
  1666. /* ========================================================================
  1667.  * Set the access and modification times from the given stat buffer.
  1668.  */
  1669. local void reset_times (name, statb)
  1670.     char *name;
  1671.     struct stat *statb;
  1672. {
  1673.     struct utimbuf    timep;
  1674.  
  1675.     /* Copy the time stamp */
  1676.     timep.actime  = statb->st_atime;
  1677.     timep.modtime = statb->st_mtime;
  1678.  
  1679.     /* Some systems (at least OS/2) do not support utime on directories */
  1680.     if (utime(name, &timep) && !S_ISDIR(statb->st_mode)) {
  1681.     if (!quiet) PError(ofname);
  1682.     }
  1683. }
  1684. #endif
  1685.  
  1686.  
  1687. /* ========================================================================
  1688.  * Copy modes, times, ownership from input file to output file.
  1689.  * IN assertion: to_stdout is false.
  1690.  */
  1691. local void copy_stat(ifstat)
  1692.     struct stat *ifstat;
  1693. {
  1694. #ifndef NO_UTIME
  1695.     if (decompress && time_stamp != 0 && ifstat->st_mtime != time_stamp) {
  1696.     ifstat->st_mtime = time_stamp;
  1697.     if (verbose > 1) {
  1698.         fprintf(stderr, "%s: time stamp restored\n", ofname);
  1699.     }
  1700.     }
  1701.     reset_times(ofname, ifstat);
  1702. #endif
  1703.     /* Copy the protection modes */
  1704.     if (chmod(ofname, ifstat->st_mode & 07777)) {
  1705.     if (!quiet) PError(ofname);
  1706.     }
  1707. #ifndef NO_CHOWN
  1708.     chown(ofname, ifstat->st_uid, ifstat->st_gid);  /* Copy ownership */
  1709. #endif
  1710.     remove_ofname = 0;
  1711.     /* It's now safe to remove the input file: */
  1712.     
  1713. /* MacGzip 0.2.2 */
  1714.  
  1715.     if(!currPrefs.KeepOriginals)
  1716.     {
  1717.         (void) chmod(ifname, 0777);
  1718.         if (unlink(ifname)) {
  1719.         if (!quiet) PError(ifname);
  1720.         }
  1721.     }
  1722. }
  1723.  
  1724. #ifndef NO_DIR
  1725.  
  1726. /* ========================================================================
  1727.  * Recurse through the given directory. This code is taken from ncompress.
  1728.  */
  1729. local void treat_dir(dir)
  1730.     char *dir;
  1731. {
  1732.     dir_type *dp;
  1733.     DIR      *dirp;
  1734.     char     nbuf[MAX_PATH_LEN];
  1735.     int      len;
  1736.  
  1737.     dirp = opendir(dir);
  1738.     
  1739.     if (dirp == NULL) {
  1740.     sprintf(strerr, "%s unreadable", dir); Calert(strerr);
  1741.     exit_code = ERROR;
  1742.     return ;
  1743.     }
  1744.     /*
  1745.      ** WARNING: the following algorithm could occasionally cause
  1746.      ** compress to produce error warnings of the form "<filename>.gz
  1747.      ** already has .gz suffix - ignored". This occurs when the
  1748.      ** .gz output file is inserted into the directory below
  1749.      ** readdir's current pointer.
  1750.      ** These warnings are harmless but annoying, so they are suppressed
  1751.      ** with option -r (except when -v is on). An alternative
  1752.      ** to allowing this would be to store the entire directory
  1753.      ** list in memory, then compress the entries in the stored
  1754.      ** list. Given the depth-first recursive algorithm used here,
  1755.      ** this could use up a tremendous amount of memory. I don't
  1756.      ** think it's worth it. -- Dave Mack
  1757.      ** (An other alternative might be two passes to avoid depth-first.)
  1758.      */
  1759.     
  1760.     while ((dp = readdir(dirp)) != NULL) {
  1761.  
  1762.     if (strequ(dp->d_name,".") || strequ(dp->d_name,"..")) {
  1763.         continue;
  1764.     }
  1765.     len = strlen(dir);
  1766.     if (len + NLENGTH(dp) + 1 < MAX_PATH_LEN - 1) {
  1767.         strcpy(nbuf,dir);
  1768.         if (len != 0 /* dir = "" means current dir on Amiga */
  1769. #ifdef PATH_SEP2
  1770.         && dir[len-1] != PATH_SEP2
  1771. #endif
  1772. #ifdef PATH_SEP3
  1773.         && dir[len-1] != PATH_SEP3
  1774. #endif
  1775.         ) {
  1776.         nbuf[len++] = PATH_SEP;
  1777.         }
  1778.         strcpy(nbuf+len, dp->d_name);
  1779.         treat_file(nbuf);
  1780.     } else {
  1781.         sprintf(strerr,"%s/%s: pathname too long\n", dir, dp->d_name);
  1782.         Calert(strerr);
  1783.         exit_code = ERROR;
  1784.     }
  1785.     }
  1786.     closedir(dirp);
  1787. }
  1788. #endif /* ? NO_DIR */
  1789.  
  1790. /* ========================================================================
  1791.  * Free all dynamically allocated variables and exit with the given code.
  1792.  */
  1793. local void do_exit(exitcode)
  1794.     int exitcode;
  1795. {
  1796.     static int in_exit = 0;
  1797.  
  1798.     if (in_exit) exit(exitcode);
  1799.     in_exit = 1;
  1800. /*    if (env != NULL)  free(env),  env  = NULL;*/
  1801. /*    if (args != NULL) free((char*)args), args = NULL;*/
  1802.     FREE(inbuf);
  1803.     FREE(outbuf);
  1804.     FREE(d_buf);
  1805.     FREE(window);
  1806. #ifndef MAXSEG_64K
  1807.     FREE(tab_prefix);
  1808. #else
  1809.     FREE(tab_prefix0);
  1810.     FREE(tab_prefix1);
  1811. #endif
  1812. #ifdef MACOS
  1813.      ReleaseAnimatedCursors(kCalCursorRes);
  1814.      ReleaseMovableModal();
  1815. #endif
  1816.     if (exitcode==0)
  1817.     {
  1818.         in_exit = 0;
  1819.         return;
  1820.     }
  1821.     else
  1822.         exit(exitcode);
  1823. }
  1824.  
  1825. /* ========================================================================
  1826.  * Signal and error handler.
  1827.  */
  1828. RETSIGTYPE abort_gzip()
  1829. {
  1830.    if (remove_ofname) {
  1831.        close(ofd);
  1832.        unlink (ofname);
  1833.    }
  1834.    do_exit(ERROR);
  1835. }
  1836.  
  1837. /*________________________________________________________________________
  1838.  *
  1839.  *         INIT THE OPTIONS
  1840.  */
  1841.  
  1842. local void init_globals( void )
  1843. {
  1844. struct option init_longopts[] =
  1845. {
  1846.  /* { name  has_arg  *flag  val } */
  1847.     {"ascii",      0, 0, 'a'}, /* ascii text mode */
  1848.     {"to-stdout",  0, 0, 'c'}, /* write output on standard output */
  1849.     {"stdout",     0, 0, 'c'}, /* write output on standard output */
  1850.     {"decompress", 0, 0, 'd'}, /* decompress */
  1851.     {"uncompress", 0, 0, 'd'}, /* decompress */
  1852.  /* {"encrypt",    0, 0, 'e'},    encrypt */
  1853.     {"force",      0, 0, 'f'}, /* force overwrite of output file */
  1854.     {"help",       0, 0, 'h'}, /* give help */
  1855.  /* {"pkzip",      0, 0, 'k'},    force output in pkzip format */
  1856.     {"list",       0, 0, 'l'}, /* list .gz file contents */
  1857.     {"license",    0, 0, 'L'}, /* display software license */
  1858.     {"no-name",    0, 0, 'n'}, /* don't save or restore original name & time */
  1859.     {"name",       0, 0, 'N'}, /* save or restore original name & time */
  1860.     {"quiet",      0, 0, 'q'}, /* quiet mode */
  1861.     {"silent",     0, 0, 'q'}, /* quiet mode */
  1862.     {"recursive",  0, 0, 'r'}, /* recurse through directories */
  1863.     {"suffix",     1, 0, 'S'}, /* use given suffix instead of .gz */
  1864.     {"test",       0, 0, 't'}, /* test compressed file integrity */
  1865.     {"no-time",    0, 0, 'T'}, /* don't save or restore the time stamp */
  1866.     {"verbose",    0, 0, 'v'}, /* verbose mode */
  1867.     {"version",    0, 0, 'V'}, /* display version number */
  1868.     {"fast",       0, 0, '1'}, /* compress faster */
  1869.     {"best",       0, 0, '9'}, /* compress better */
  1870.     {"lzw",        0, 0, 'Z'}, /* make output compatible with old compress */
  1871.     {"bits",       1, 0, 'b'}, /* max number of bits per code (implies -Z) */
  1872.     { 0, 0, 0, 0 }
  1873. };
  1874.     optind = 0;
  1875.     
  1876.     ascii = 0;        /* convert end-of-lines to local OS conventions */
  1877.     to_stdout = 0;    /* output to stdout (-c) */
  1878.     decompress = 0;   /* decompress (-d) */
  1879.     force = 0;        /* don't ask questions, compress links (-f) */
  1880.     no_name = -1;     /* don't save or restore the original file name */
  1881.     no_time = -1;     /* don't save or restore the original file time */
  1882.     recursive = 0;    /* recurse through directories (-r) */
  1883.     list = 0;         /* list the file contents (-l) */
  1884.     verbose = 0;      /* be verbose (-v) */
  1885.     quiet = 0;        /* be very quiet (-q) */
  1886.     do_lzw = 0;       /* generate output compatible with old compress (-Z) */
  1887.     test = 0;         /* test .gz file integrity */
  1888.     maxbits = BITS;   /* max bits per code for LZW */
  1889.     method = DEFLATED;/* compression method */
  1890.     level = 6;        /* compression level */
  1891.     exit_code = OK;   /* program exit code */
  1892.  
  1893.     total_in = 0;         /* input bytes for all files */
  1894.     total_out = 0;        /* output bytes for all files */
  1895.     remove_ofname = 0;       /* remove output file on error */
  1896.  
  1897.  
  1898.     memcpy(longopts,init_longopts,sizeof(init_longopts));
  1899.     
  1900.     work = zip;
  1901.  
  1902. }