
#include <stdio.h>
#include <libraries/dos.h>
#include <functions.h>

char    version[] = "\nMRMan, V1.0 - Mark Rinfret, 1989\n";

static char *viewer;

extern char *ManSearch();
extern char *GetViewerName();

unsigned verbose = 0;

main(argc, argv)
    int argc;
    char    **argv;
{
    char    *manFile;
    char    *dirName = NULL;
    char    *subject;

    while (--argc > 0) {
        ++argv;                /* Advance to next arg string. */
        if (**argv != '-') break;
        if (! strcmp(*argv, "-d")) {
            --argc;
            ++argv;
            dirName = *argv;
        }
        else if (! strcmp(*argv, "-v")) {
            verbose = 1;
            Printf(version);
        }
        else {
            Printf("Usage: MRMan [-d <directory>] <subject>\n");
            goto done;
        }
    }
    viewer = GetViewerName();
    while (argc--) {
        manFile = ManSearch(dirName, *argv);
        if (manFile) 
            ViewManFile(manFile);
        else
            Printf("Man file for subject '%s' not found.\n", *argv);
        ++argv;
    }
done: ;
}

ViewManFile(manFile)
    char *manFile;
{
    static char TEMPDESC[] = "# Temp file name for compressed files (32) ->";
    static char tempName[33] = "T:MRManXXXXXX";
    int         c1, c2;
    char        commandLine[300];
    char        fileName[256];
    struct FileHandle *outFile;
    unsigned    retries;
    
    FILE    *theFile;

    theFile = fopen(manFile, "r");
    if (theFile == NULL) {
        Printf("MRMan: '%s' would not open!\n", manFile);
    }
    else {
        /* Is the file compressed?  Look for magic header. */
        c1 = (getc(theFile) & 0xFF);
        c2 = (getc(theFile) & 0xFF);
        fclose(theFile);
        if ((c1 == 0x1F) && (c2 == 0x9D)) {
            mktemp(tempName);
            outFile = (struct FileHandle *) Open(tempName, MODE_NEWFILE);
            if (! outFile) {
                Printf("MRMan: could not open output for zcat!\n");
                return;
            }
            if (verbose)
                Printf("Decompressing...\n");

            SyncRun("zcat", manFile, NULL, outFile);
            Close(outFile);
#ifdef undef
            printf("Temporary name = '%s'\n", tempName);
#endif
            SyncRun(viewer, tempName, 0L, 0L);
            /* fexecl(viewer, viewer, tempName, 0L); */
            /* This next bit of messiness is an attempt to accommodate
             * file viewers such as TxView, which detach and run in an
             * asynchronous manner. MRMan will try for up to a minute
             * to delete the temporary file created by zcat.
             */
            for (retries = 0; retries < 60; ++retries) {
                Delay(50L);
                if (DeleteFile(tempName)) break;
            }  
            if (retries >= 60)
                Printf("I couldn't delete '%s'\n", tempName);
        }
        else
            fexecl(viewer, viewer, manFile, 0L);
    }
}