home *** CD-ROM | disk | FTP | other *** search
/ The Fred Fish Collection 1.5 / ffcollection-1-5-1992-11.iso / ff_disks / 300-399 / ff345.lzh / UnShar / src / unshar.c < prev    next >
C/C++ Source or Header  |  1990-04-16  |  20KB  |  802 lines

  1. /*
  2.  *                     Unshar V1.3 (C) Copyright Eddy Carroll 1990
  3.  *                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4.  * Usage: Unshar {-overwrite} {-nosort} <filename> ...
  5.  *
  6.  * Extracts files from a SHAR'd archive.
  7.  *
  8.  * This utility has a few advantages over the version of SH on Fish Disk 92.
  9.  * For a start, it doesn't crash if it gets a slightly unusual format! It
  10.  * also has a (limited) capability for extracting files from shar archives
  11.  * which use 'SED' rather than 'CAT' (typically, this is done so that
  12.  * each line in the file may be prefixed with an 'X' or similar, so that
  13.  * indentation is preserved). Unshar will spot 'SED' lines, and treat them
  14.  * the same as 'CAT' (allowing for different parameters of course) with
  15.  * the exception that any leading characters matching the string specified
  16.  * in the SED command are discarded.
  17.  *
  18.  * Unshar checks files being extracted to see if they are to be stored
  19.  * within a sub-directory. If they are, and the sub-directory does not
  20.  * already exist, it is created.
  21.  *
  22.  * One other small addition is that any filenames which are prefixed with
  23.  * the characters "./" have these characters removed. Some shar files
  24.  * use this prefix to ensure that the files are stored in the current
  25.  * directory.
  26.  *
  27.  * Files are extracted into the current directory. As each file is extracted,
  28.  * an appropriate message is printed on the screen. If the file already
  29.  * exists, the user is warned and given the chance to avoid overwriting it
  30.  * "Overwrite file (Yes/No/All)? ". The default is Yes. If All is selected,
  31.  * then this prompt is supressed for the rest of the current file. It may
  32.  * be disabled for all the files by specifying the -o switch on the
  33.  * command line.
  34.  *
  35.  * By default, unshar will do a `prescan' over all the files listed, looking
  36.  * at the first few lines of each for a Subject: line. If one is found, then
  37.  * it examines it for Issue numbers and Part numbers, and unshars those files
  38.  * having the lowest numbers first. This results in the shar files being
  39.  * extracted in the correct order, regardless of what order they were listed
  40.  * in on the command line. You can override this behaviour and unshar files
  41.  * in the command line order by specifying the -n switch.
  42.  * 
  43.  * DISTRIBUTION
  44.  * I retain copyright rights to this source code, though it may be _freely_
  45.  * distributed. The executable file created from this source code is in
  46.  * the Public Domain and may be distributed without any restrictions.
  47.  *
  48.  *
  49.  * N.b. The code is starting to look a bit messy; could be it will get
  50.  *      a complete overhaul for the next revision.
  51.  *
  52.  */
  53.  
  54. /* Compiles under Lattice V5.04 */
  55.  
  56. #ifndef LATTICE_50 
  57. #include "system.h"
  58. #endif
  59.  
  60. #define YES            1
  61. #define NO            0
  62. #define CR            '\015'
  63. #define EOL            '\012'
  64. #define SINGLEQUOTE '\''
  65. #define DOUBLEQUOTE '\042'
  66. #define MAXSTRING    512        /* Maximum length of input line */
  67.  
  68. /*
  69.  *        New handler for Ctrl-C. Checks if CTRL-C received, and if it has,
  70.  *        sets the global CtrlC variable to true.
  71.  */
  72. #define chkabort() (CtrlC |= ((SetSignal(0,0) & SIGBREAKF_CTRL_C)))
  73.  
  74.  
  75. char HelpMsg[] = "\
  76. Unshar V1.3 by Eddy Carroll 1990 Public Domain, extracts Unix shar archives.\
  77. \n\
  78. Usage: unshar {-overwrite} {-nosort} <filename> ...\n";
  79.  
  80. char DiskMsg[]  = "Unshar aborted - Disk write error (disk full?)\n";
  81. char ErrorMsg[] = "Unshar: Invalid CAT or SED command at line ";
  82.  
  83. int linenum;
  84. int CtrlC = NO;
  85.  
  86. /*
  87.  * --------------------------------------------------------------------------
  88.  * The following block may be removed `as-is' and used in other programs.
  89.  * It provides basic buffered i/o on two files, an input file and an output
  90.  * file. It also provides output to the current standard output via
  91.  * print. Buffering is done using buffers of size MAXBUF.
  92.  *
  93.  * The following routines are provided:
  94.  *
  95.  * getc() returns an integer corresponding to the next character read from
  96.  * infile, or EOF if the end of file has been reached.
  97.  *
  98.  * putc(c) outputs a character to outfile. If a diskerror occurs, the global
  99.  * diskerror is set to YES, and all further diskwrites are ignored.
  100.  *
  101.  * getline() returns a pointer to a string containing the next line
  102.  * read in from infile. getline() also checks for CTRL-C via chkabort()
  103.  * 
  104.  * putline(s) outputs a string to outfile, returning non-zero if an
  105.  * error occurred during the write.
  106.  *
  107.  * flushin() resets getc() and getline() for input from a new file
  108.  *
  109.  * flushout() flushes output buffer; call prior to closing output file.
  110.  *
  111.  * input() returns a pointer to a string containing a line from stdin.
  112.  *
  113.  * print(s) prints a message on standard output.
  114.  *
  115.  * print3(s1,s2,s3) outputs three strings on standard output.
  116.  *
  117.  * numtostr(n) returns a pointer to the ascii representation of n.
  118.  *
  119.  * Special Notes
  120.  * ~~~~~~~~~~~~~
  121.  * You should ensure that you use the filenames 'infile' and 'outfile'
  122.  * when you are opening the input and output files in main(). Also,
  123.  * do not #define EOF or MAXBUF elsewhere in your program.
  124.  *
  125.  */
  126.  
  127. #define EOF        -1
  128. #define MAXBUF    10000
  129.  
  130. BPTR infile, outfile;
  131. LONG maxin = MAXBUF, maxout = MAXBUF, inbuf = MAXBUF, outbuf = 0;
  132. unsigned char inbuffer[MAXBUF], outbuffer[MAXBUF];
  133. int diskerror = NO;
  134.  
  135. /*
  136.  *        int getc()
  137.  *        ----------
  138.  *        Returns next character from infile, or EOF if end of file.
  139.  *
  140.  *        Replaced by a macro to improve performance. Original function was:
  141.  *
  142.  *        int getc()
  143.  *        {
  144.  *            if (!maxin)
  145.  *                return (EOF);
  146.  *
  147.  *            if (inbuf >= maxin) {
  148.  *                maxin = Read(infile, inbuffer, MAXBUF);
  149.  *                inbuf = 0;
  150.  *                if (!maxin)
  151.  *                    return (EOF);
  152.  *            }
  153.  *            return (inbuffer[inbuf++]);
  154.  *        }
  155.  *
  156.  */
  157. #define IF(x,y,z) ((x) ? (y) : (z))
  158.  
  159. #define getc()    IF(!maxin, EOF, \
  160.                 IF(inbuf >= maxin, ( \
  161.                     inbuf = 0, maxin = Read(infile, inbuffer, MAXBUF), \
  162.                     IF(!maxin, EOF, inbuffer[inbuf++]) \
  163.                 ), inbuffer[inbuf++])) \
  164.  
  165. /* 
  166.  *        Prepares getc() for input from a new file
  167.  */
  168. #define flushin() (maxin = MAXBUF, inbuf = MAXBUF)
  169.  
  170. /*
  171.  *        putc(ch)
  172.  *        --------
  173.  *        Outputs character ch to disk. If a diskerror is detected, then all
  174.  *        further output is ignored and the global diskerror is set to YES.
  175.  *
  176.  *        Replaced by a macro for performance reasons. Original function was:
  177.  *
  178.  *        void putc(ch)
  179.  *        int ch;
  180.  *        {
  181.  *            if (ch == EOF)
  182.  *                maxout = outbuf;
  183.  *            else
  184.  *                outbuffer[outbuf++] = ch;
  185.  *        
  186.  *            if (outbuf >= maxout) {
  187.  *                if (!diskerror && Write(outfile, outbuffer, maxout) == -1)
  188.  *                    diskerror = YES;
  189.  *                outbuf = 0;
  190.  *                maxout = MAXBUF;
  191.  *            }
  192.  *        }
  193.  */
  194. #define flushout() (maxout = outbuf, \
  195.                     IF(!diskerror && Write(outfile, outbuffer, maxout) == -1, \
  196.                         diskerror = YES, \
  197.                         0), \
  198.                     outbuf = 0, maxout = MAXBUF)
  199.  
  200. #define putc(ch) (outbuffer[outbuf++] = ch, \
  201.                   IF(outbuf >= maxout, \
  202.                       (IF (!diskerror && \
  203.                             Write(outfile, outbuffer, maxout) == -1, \
  204.                         diskerror = YES, \
  205.                         0), \
  206.                      outbuf = 0, maxout = MAXBUF), \
  207.                     0))
  208.  
  209. /*
  210.  *        print(s)
  211.  *        --------
  212.  *        Outputs a message to std output
  213.  */
  214. void print(s)
  215. char *s;
  216. {
  217.     Write(Output(),s,strlen(s));
  218. }
  219.  
  220. /*
  221.  *        print3()
  222.  *        --------
  223.  *        Outputs three strings to std output.
  224.  *        Useful for sequences like print3("string", variable, "string");
  225.  */
  226. void print3(s1,s2,s3)
  227. char *s1,*s2,*s3;
  228. {
  229.     print(s1);
  230.     print(s2);
  231.     print(s3);
  232. }
  233.  
  234. /*
  235.  *        getline()
  236.  *        ---------
  237.  *        Reads in a line from current infile into string, and returns a
  238.  *        pointer to that string. Returns NULL if EOF encountered.
  239.  */
  240. char *getline()
  241. {
  242.     register int ch, i = 0;
  243.     static char line[MAXSTRING];
  244.  
  245.     ch = getc();
  246.     if (ch == EOF)
  247.         return (NULL);
  248.  
  249.     while (i < (MAXSTRING-1) && ch != EOF && ch != EOL) {
  250.         line[i++] = ch;
  251.         ch = getc();
  252.     }
  253.  
  254.     line[i] = '\0';
  255.     linenum++;
  256.     chkabort();
  257.     return (line);
  258. }
  259.  
  260. /*
  261.  *        putline()
  262.  *        ---------
  263.  *        Outputs a string to the current output file (terminating it with LF).
  264.  *        Returns 0 for success, non-zero for disk error
  265.  */
  266. int putline(s)
  267. char *s;
  268. {
  269.     while (*s)
  270.         putc(*s++);
  271.     putc(EOL);
  272.     return (diskerror);
  273. }
  274.  
  275. /*
  276.  *        input()
  277.  *        -------
  278.  *        Reads a line from keyboard and returns pointer to it
  279.  */
  280. char *input()
  281. {
  282.     static char s[80];
  283.     int len;
  284.  
  285.     s[0] = '\0';
  286.     len = Read(Input(),s,75);
  287.     if (len < 0)
  288.         len = 0;
  289.     s[len] = '\0';
  290.     chkabort();
  291.     return(s);
  292. }
  293.  
  294. /*
  295.  *        numtostr()
  296.  *        ----------
  297.  *        Converts integer to string and returns pointer to it.
  298.  */
  299. char *numtostr(n)
  300. int n;
  301. {
  302.     static char s[20];
  303.     int i = 19;
  304.  
  305.     s[19] = '\0';
  306.     if (n)
  307.         while (n)
  308.             s[--i] = '0' + (n % 10), n /= 10;
  309.     else
  310.         s[--i] = '0';
  311.     return(&s[i]);
  312. }
  313.  
  314. /*
  315.  *        --------------------* End of Buffered IO routines *-----------------
  316.  */
  317.  
  318. /*
  319.  *        index()
  320.  *        -------
  321.  *        Like standard Unix index(), but skips over quotes if skip == true.
  322.  *        Also skips over chars prefixed by a \. Returns pointer to first
  323.  *        occurance of char c inside string s, or NULL.
  324.  */
  325. char *index(s,c,skip)
  326. char *s,c;
  327. int skip;
  328. {
  329.     register char *p = s;
  330.     register int noquotes = YES, literal = NO;
  331.  
  332.     while (*p) {
  333.         if (literal) {
  334.             literal = NO;
  335.             p++;
  336.         } else {
  337.             if (skip && ((*p == SINGLEQUOTE) || (*p == DOUBLEQUOTE)))
  338.                 noquotes = !noquotes;
  339.             if (noquotes && (*p == c))
  340.                 return(p);
  341.             literal = (*p == '\\');
  342.             p++;
  343.         }
  344.     }
  345.     return (NULL);
  346. }
  347.  
  348. /*
  349.  *        getname()
  350.  *        ---------
  351.  *        Extracts a string from start of string s1 and stores it in s2.
  352.  *        Leading spaces are discarded, and quotes, if present, are used to
  353.  *        indicate the start and end of the filename. If mode is MODE_FILE,
  354.  *        then if the name starts with either './' or '/', this prefix is
  355.  *        stripped. This doesn't happen if the mode is MODE_TEXT. A pointer
  356.  *        to the first character after the string in s1 is returned. In
  357.  *        addition, any characters prefixed with are passed through without
  358.  *        checking.
  359.  */
  360.  
  361. #define MODE_FILE 1
  362. #define MODE_TEXT 2
  363.  
  364. char *getname(s1,s2,mode)
  365. char *s1,*s2;
  366. {
  367.     char endchar = ' ';
  368.  
  369.     while (*s1 == ' ')
  370.         s1++;
  371.  
  372.     if (*s1 == SINGLEQUOTE || *s1 == DOUBLEQUOTE)
  373.         endchar = *s1++;
  374.  
  375.     if (mode == MODE_FILE) {
  376.         if (s1[0] == '.' && s1[1] == '/')
  377.             s1 += 2;
  378.         while (*s1 == '/')
  379.             s1++;
  380.     }
  381.  
  382.     while (*s1 && *s1 != endchar) {
  383.         if (*s1 == '\\' && *(s1+1))
  384.             s1++;
  385.         *s2++ = *s1++;
  386.     }
  387.     *s2 = '\0';
  388.  
  389.     if (*s1 == endchar)
  390.         return(++s1);
  391.     else
  392.         return(s1);
  393. }
  394.  
  395.  
  396. /*
  397.  *        checkfordir()
  398.  *        -------------
  399.  *        Checks filename to see if it is inside a subdirectory. If it is,
  400.  *        then checks if subdirectory exists, and creates it if it doesn't.
  401.  */
  402. void checkfordir(filename)
  403. char *filename;
  404. {
  405.     char dir[80], *p;
  406.     int i, x;
  407.     BPTR dirlock;
  408.  
  409.     p = filename;
  410.  
  411.     while (p = index(p, '/', 1)) {
  412.  
  413.         /* Dir exists, so copy dir part of filename into dir name area */
  414.  
  415.         x = p - filename;
  416.         for (i = 0; i < x; i++)
  417.             dir[i] = filename[i];
  418.         dir[i] = '\0';
  419.  
  420.         /* Now, see if directory exists, if not then create */
  421.         if ((dirlock = Lock(dir,ACCESS_READ)) == NULL) {
  422.             dirlock = CreateDir(dir);
  423.             if (dirlock) {
  424.                 print3("Creating directory ", dir, "\n");
  425.             }
  426.         }
  427.         if (dirlock)
  428.             UnLock(dirlock);
  429.  
  430.         p++;
  431.     }
  432. }
  433.  
  434. /*
  435.  *        unshar()
  436.  *        --------
  437.  *        Extracts all stored files from a shar file. Returns zero for success,
  438.  *        non-zero if a disk error occurred. If echofilename is non-zero, then
  439.  *        the name of each shar file is output before unsharing it. If
  440.  *        overwrite is non-zero, then existing files are overwritten without
  441.  *        any warning. If title is non-NULL, then it points to a string
  442.  *        which is printed out before any files are extracted.
  443.  */
  444. int unshar(sharfile, title, echofilename, overwrite)
  445. char *sharfile, *title;
  446. int echofilename, overwrite;
  447. {
  448.     register char *s, *p;
  449.     char endmarker[100], filename[100],sedstring[100];
  450.     int endlen, stripfirst, startfile, found = NO, err = NO, skip, sedlen;
  451.     int append;
  452.     BPTR filelock;
  453.  
  454.     if ((infile = Open(sharfile, MODE_OLDFILE)) == NULL) {
  455.         print3("Can't open file ", sharfile, " for input\n");
  456.         return(1);
  457.     }
  458.  
  459.     linenum = 0;
  460.     if (echofilename)
  461.         print3("\033[7m Shar file: ", sharfile, " \033[0m\n");
  462.     if (title)
  463.         print(title);
  464.  
  465.     while (!err && !CtrlC && (s = getline()) != NULL) {
  466.         startfile = NO;
  467.         if (strncmp(s,"cat ",4) == 0) {
  468.             startfile  = YES;
  469.             stripfirst = NO;
  470.         }
  471.         if (strncmp(s,"sed ",4) == 0) {
  472.             startfile  = YES;
  473.             stripfirst = YES;
  474.             sedlen = 0;
  475.             /*
  476.              *        Note - tons of sanity checks done here to ensure that a
  477.              *        sed line of the form:
  478.              *
  479.              *            sed >s/somefile <<'endmarker' -e 's/X//'
  480.              *
  481.              *        Will be interpreted correctly.
  482.              */
  483.  
  484. #define ISPREFIX(ch)    (ch == DOUBLEQUOTE || ch == SINGLEQUOTE || ch == ' ')
  485. #define ISMETA(ch)        (ch == '<' || ch == '>')
  486. #define ISOK(s)            (s[1] == '/' && ISPREFIX(s[-1]) && !ISMETA(s[-2]))
  487.  
  488.             p = s;
  489.             while ((p = index(p,'s',0)) != NULL && !ISOK(p))
  490.                 p++;
  491.             if (p != NULL) {
  492.                 p += 2;                /* Skip over the 's/' bit    */
  493.                 if (*p == '^')        /* Skip past starting char    */
  494.                     p++;
  495.                 while (*p && *p != '/')
  496.                     sedstring[sedlen++] = *p++;
  497.             } 
  498.         }
  499.  
  500.         if (startfile) {    
  501.             if (found == NO) {
  502.                 found = YES;
  503.             }
  504.             if ((p = index(s,'>',1)) == NULL) {
  505.                 print3(ErrorMsg, numtostr(linenum), "(a)\n");
  506.             } else {
  507.                 /*
  508.                  *       This next bit checks to see if we are creating or
  509.                  *       appending to the output file (i.e. >file or >>file)
  510.                  */
  511.                 if (*++p == '>') {
  512.                     p++;
  513.                     append = YES;
  514.                 } else
  515.                     append = NO;
  516.                 getname(p,filename,MODE_FILE);
  517.                 p = s;
  518.                 while ((p = index(p,'<',1)) && (p[1] != '<'))
  519.                     ;
  520.                 if (p)
  521.                     getname(p+2,endmarker,MODE_TEXT);
  522.  
  523.                 endlen = strlen(endmarker);
  524.  
  525.                 if (strlen(filename) && endlen) {
  526.  
  527.                     checkfordir(filename);
  528.  
  529.                     /* Found a valid line so perform extract */
  530.  
  531.                     /* Check if file exists */
  532.  
  533.                     skip = NO;
  534.                     outfile = NULL;
  535.                     if (!overwrite) {
  536.                         filelock = Lock(filename, ACCESS_READ);
  537.                         if (filelock) {
  538.                             UnLock(filelock);
  539.                             if (!append) {
  540.                                 print3("Overwrite file ", filename,
  541.                                     " (Yes, [No], All)? ");
  542.  
  543.                                 switch (tolower(*input())) {
  544.                                     case 'a': overwrite = YES;    break;
  545.                                     case 'y': skip = NO;        break;
  546.                                     default : skip = YES;        break;
  547.                                 }
  548.                             }
  549.                         }
  550.                     }
  551.  
  552.                     /*
  553.                      *        Open as old file and seek to the end if
  554.                      *        appending AND the file already exists. If
  555.                      *        it doesn't exist, then just open as new file.
  556.                      */
  557.                     if (filelock && append) {
  558.                         outfile = Open(filename, MODE_READWRITE);
  559.                         if (outfile)
  560.                             Seek(outfile, 0, OFFSET_END);
  561.                     } else if (!skip)
  562.                         outfile = Open(filename, MODE_NEWFILE);
  563.  
  564.                     if (!outfile && !skip) {
  565.                         print3("Couldn't open file ",filename," for output\n");
  566.                         skip = YES;
  567.                     }
  568.                     if (!skip) {
  569.                         if (filelock && append)
  570.                             print3("Extending file ", filename, "\n");
  571.                         else
  572.                             print3("Unsharing file ", filename, "\n");
  573.                     }
  574.                     s = getline();
  575.                     err = NO;
  576.                     while (s && strncmp(s,endmarker,endlen) && !CtrlC) {
  577.                         if (stripfirst && !strncmp(sedstring,s,sedlen))
  578.                             s += sedlen;
  579.                         if (!skip && (err = putline(s)))
  580.                             break;
  581.                         s = getline();
  582.                     }
  583.                     if (!skip) {
  584.                         flushout();
  585.                         if (err || diskerror)
  586.                             print(DiskMsg), err = YES;
  587.                         Close(outfile);
  588.                     }
  589.                 } else
  590.                     print(ErrorMsg, numtostr(linenum), "\n");
  591.             }
  592.         }
  593.     }
  594.  
  595.     if (!err && !CtrlC)
  596.         if (found)
  597.             print("Unshar done\n");
  598.         else
  599.             print("No files to unshar\n");
  600.     Close(infile);
  601.     flushin();
  602.     return(err);
  603. }
  604.  
  605. /*
  606.  *        readheader()
  607.  *        ------------
  608.  *        Reads in the first few lines (actually 480 bytes) of filename, and
  609.  *        scans for a subject line. If the subject line is found, then
  610.  *        it is stored in subject (up to 100 chars in length), else a null
  611.  *        string is stored. The subject line is also examined, and a sequence
  612.  *        number determined. If the subject line starts with i or I, followed
  613.  *        by a number, then this is taken as the sequence number. Otherwise,
  614.  *        the first number after `Part' or `part' is uses. This sequence
  615.  *        number is returned in seqnum. I-type sequence numbers have 1000
  616.  *        added on to them first of all, to keep them seperated from 'part'
  617.  *        types.
  618.  *
  619.  *        The idea is that successive parts of a set of several shar files
  620.  *        will have increasing sequence numbers.
  621.  *
  622.  *        Zero is returned if an error occurred.
  623.  */
  624. int readheader(filename, subject, seqnum)
  625. char *filename, *subject;
  626. int *seqnum;
  627. {
  628.     static char buf[480];
  629.     BPTR file;
  630.     int len, i;
  631.     char *p;
  632.  
  633.     *subject = '\0';
  634.  
  635.     file = Open(filename, MODE_OLDFILE);
  636.     if (!file) {
  637.         print3("Can't open file ", filename, " for input\n");
  638.         return (0);
  639.     }
  640.  
  641.     len = Read(file, buf, 480);
  642.     Close(file);
  643.     if (len == -1) {
  644.         print3("Error reading header from file ", filename, "\n");
  645.         return (0);
  646.     }
  647.  
  648.     /*
  649.      *        Now analyse file for a Subject: line
  650.      */
  651.     for (i = 0; i < len; i++) {
  652.         if (buf[i] == '\n' && strnicmp(&buf[i+1], "Subject:", 8) == 0) {
  653.             /*
  654.              *        Copy subject line into subject string, ensuring
  655.              *        it is properly terminated with a \n and \0
  656.              */
  657.             i++;
  658.             strncpy(subject, buf + i + 9, 98);
  659.             subject[98] = '\0';
  660.             for (p = subject; *p; p++) {
  661.                 if (*p == '\n') {
  662.                     break;
  663.                 }
  664.             }
  665.             *p++ = '\n';
  666.             *p = '\0';
  667.             /*
  668.              *        Now scan new subject string looking for sequence number
  669.              */
  670.             p = subject;
  671.             while (*p) {
  672.                 if (*p == 'i') {
  673.                     *seqnum = atoi(p+1);
  674.                     if (*seqnum != 0)
  675.                         return 1;
  676.                 }
  677.                 if (strnicmp(p, "Part", 4) == 0) {
  678.                     p += 4;
  679.                     while (*p == ' ')
  680.                         *p++;
  681.                     *seqnum = atoi(p);
  682.                     if (*seqnum != 0) {
  683.                         *seqnum += 1000;
  684.                         return 1;
  685.                     }
  686.                 } else
  687.                     p++;
  688.             }
  689.             *seqnum = 10000;
  690.             return (1);
  691.         }
  692.     }
  693.     *seqnum = 10000;
  694.     return (1);
  695. }
  696.  
  697. /*
  698.  *        Start of mainline
  699.  */
  700. int main(argc,argv)
  701. int argc;
  702. char *argv[];
  703. {
  704.  
  705.     int i, numfiles;
  706.     int overwrite = NO, sortfiles = YES;
  707.     char **filenames;
  708.  
  709.     if ((argc == 1) || (*argv[1] == '?')) {
  710.         print(HelpMsg);
  711.         return (10);
  712.     }
  713.     while (argc > 1 && *argv[1] == '-') {
  714.         switch (tolower(argv[1][1])) {
  715.  
  716.             case 'o':
  717.                 overwrite = YES;
  718.                 break;
  719.  
  720.             case 'n':
  721.                 sortfiles = NO;
  722.                 break;
  723.  
  724.             default:
  725.                 print(HelpMsg);
  726.                 return (10);
  727.         }
  728.         argc--; argv++;
  729.     }
  730.  
  731.     numfiles  = argc - 1;
  732.     filenames = &argv[1];
  733.  
  734.     if (!sortfiles) {
  735.         /*
  736.          *        Just process files in the order they occur
  737.          */
  738.         for (i = 0; i < numfiles && !CtrlC; i++) {
  739.             if (unshar(filenames[i], NULL, numfiles > 1, overwrite) != 0)
  740.                 break;
  741.         }
  742.     } else {
  743.         /*
  744.          *        Do a prescan through all the files, and then unshar them
  745.          *        in the right order.
  746.          */    
  747.         typedef struct SortRecord {
  748.             struct  SortRecord *next;    /* Next record in list                */
  749.             int        index;                /* Index into filenames [] array    */
  750.             int        seqnum;                /* Sequence number of file            */
  751.             char    name[100];            /* Original subject line            */
  752.         } SORT;
  753.  
  754.         SORT *filehdrs, *head = NULL, *cur;
  755.  
  756.         filehdrs = AllocMem(sizeof(SORT) * numfiles, 0);
  757.         if (!filehdrs) {
  758.             print("Couldn't allocate memory to store file headers\n");
  759.             goto endsort;
  760.         }
  761.  
  762.         for (i = 0; i < numfiles && !CtrlC; i++) {
  763.             int seqnum;
  764.             SORT **ptr;
  765.  
  766.             if (!readheader(filenames[i], filehdrs[i].name, &seqnum))
  767.                 continue;    /* If couldn't read file, move to next file */
  768.  
  769.             /*
  770.              *        Now insert name at correct position in linked list
  771.              */
  772.             for (ptr = &head; *ptr && (*ptr)->seqnum <= seqnum;
  773.                                                 ptr = &(*ptr)->next)
  774.                 ;
  775.             filehdrs[i].next = *ptr;
  776.             *ptr = &filehdrs[i];
  777.  
  778.             filehdrs[i].seqnum = seqnum;
  779.             filehdrs[i].index  = i;
  780.         }
  781.         /*
  782.          *        Now we have a sorted list of files, so just walk down
  783.          *        the list unsharing files as we go.
  784.          */
  785.         for (cur = head; cur && !CtrlC; cur = cur->next) {
  786.             if (unshar(filenames[cur->index], cur->name,
  787.                                             numfiles > 1, overwrite) != 0)
  788.                 break;
  789.         }
  790. endsort:
  791.         if (filehdrs)
  792.             FreeMem(filehdrs, sizeof(SORT) * numfiles);
  793.     }
  794.  
  795.     /*
  796.      *        All files handled, now just tidy up and exit. If CtrlC was
  797.      *        pressed, let the user know.
  798.      */
  799.     if (CtrlC)
  800.         print("^C\n");
  801. }
  802.