/*
 * ANSIView - A file viewer for ANSI/VT100/VT52.
 *
 * Uses libvt_a, a c68 library giving VT52, VT100 and ANSI (PC) screen
 * emulations.
 *
 * Jonathan Hudson, PO Box 2272, Ruwi 112, Sultanate of Oman.
 * Tel/Fax: +968 699407 
 *
 * v0.01    25/09/93    jh  Initial version
 * v0.02    06/10/93    jh  free was in wrong place (dummy)
 * 
 */
 
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <qdos.h>
#include <qlib.h>
#include <fcntl.h>
#include <sys/stat.h>

char _prog_name[] = "ANSIView";

/*
 * For any PE/Config fans out there
 */
 
#define QVS(p1,p2) struct {short bra; char kets[sizeof(p2)]; } p1 = {0x3c3c,p2};
static QVS(_qcfx_ , "QCFX>>01\x00\x08ANSIView\x00\x040.02\xFF\xFF");

/*
 * We MUST include these two lines to use libvt
 */
 
#include "ansicondef.h"
long (*_conwrite)() = ANSI_conwrite;

/*
 * We accept wild cards (as well as Amex, Visa, Access etc)
 */
 
extern void cmdexpand();
void (*_cmdwildcard)() = cmdexpand;

char *_endmsg = NULL;

/*
 * Unless you want REALLY weird results, you must specify an 80 character
 * display with 24 (or 25 lines)
 */ 
struct WINDOWDEF _condetails =
{
    2,1,0,4,484,252,12,2
};

main(int ac, char **av)
{
    int fd;
    char *buf;
    int i, n;
    struct stat s;

    /*
     * The program displays any files specified on the command line
     * according to a specified ANSI modes
     *
     * The emulation mode is changed by setting the required type in
     * the global variable __ANSICONF__.emulation
     * ( to VT52, VT100, ANSI1 .. ANSI4 etc).  
     */

    /*
     * We set the window's outline as VT100 emulation uses
     * sd_wdef to re-define any scrolling region, and the PE may
     * then zap a bit of our redefined window
     */

    iop_outl(getchid(1), -1, 0, 0, 0, &_condetails.width);
      
    while (++av, --ac)
    {
        if(**av == '-')
        {
            if(*++*av == 'm')
            {
                i = strtol(++*av, NULL, 0);
                if(i < 0 || i > 5)
                {
                    i = 1;
                }
                __ANSICONF__.emulation = 1 << i;
            }
        }
        else if((fd = open(*av, O_RDONLY)) > 0)
        {
            fstat(fd, &s);
            if((buf = malloc((size_t)s.st_size)) != NULL)
            {
                read(fd, buf, s.st_size);
                /*
                 * Home cursor, clear screen, as some
                 * ANSI files don't
                 */
                write(1,"\x1b[H\x1b[2J", 7);
                write(1, buf, s.st_size);
                io_fbyte(getchid(0), 200, (char *)&n);
                free(buf);
	    }
            close(fd);
        }
    }
    return 0;
}
