#include    "oldckit.h"          /* For version 2.0 CKit           */
#include    "ckit.h"             /* Include CKIT Header file!      */
#include    "ckitdemo.h"         /* Include file for demo          */
#pragma check_stack (off)


short       OPENED;             /* Flag to know if open_door has been called  */
short       CLOSED;             /* Flag to know if close_door has beeb called */
void        shut_down(void);    /* Shuts door down if normal or error occurs. */

/******************************************************************************
 *                     Start of Main Program                                  *
 *****************************************************************************/
main(int argc, char **argv) {

short   result, i, j;
/******************************************************************************
*                        USER adjustments                                     *
* You will need to set these according to how you want CKIT to handle certain *
* options.  See the CKIT.DOC for more information                             *
* Also see CKITDEMO.H for program name                                        *
*******************************************************************************/
    FORCEOFFHOOK = TRUE;  /* Force modem off-hook on dropped carrier          */
    USERSFILE = FALSE;    /* optional, set to TRUE if user file info desired  */
    DOTS = FALSE;         /* Don't echo dots on input                         */
    set_kybd_time(1,3);   /* Beep time 1, timeout 3 minutes                   */
    if (argc > 1) {

    /* These are all Ckit options, if not defined it will use defaults     */
        logoff_color = (green);          /* Logoff message equals green    */
        ck_logoff_msgs = &logoffs[0];    /* Set message table to our msgs  */
        ck_gen_msgs    = &ckit_msgs[0];  /* Set message table to our msgs  */
    /***********************************************************************/
        result = open_door(argv[1], argv[2]);  /* argv[2] for PORT cmd */
        if(!result) {
            OPENED = TRUE;              /* Door has been opened        */
            atexit(shut_down);          /* call shut_down at exit time */
        } else {
            OPENED = FALSE;
            if(result <= 3) {
                strcat(ckit_errors[result-1], argv[1]);
            } else {
                if(result <= 5) {
                    strcat(ckit_errors[result-1], argv[2]);
                }
            }
            print_error(result-1, ckit_errors);
            exit(1);
        }
        display_info();               /* Display user information  */
        menu();                       /* Main program loop         */
    }
 }
/******************************************************************************
*                       End of Main Program                                   *
******************************************************************************/

/******************************************************************************
*                       Main Menu                                             *
******************************************************************************/
void    menu(void) {
    short   silent;

    silent = TRUE;
    newline();
    if(display_file("ckit.m")) {   /* If error display_file() return NON_ZERO */
        newline();
    }
    force_enter();
    /* main command loop */
    while(DUMP_USER != TRUE) {
          /* prompt for input only if there is not a stacked command pending */
        if ( strlen(cmdline) == 0) {
            color(white);
            newline();
            s_puts("Main menu:\r\n");
            color(red);
            s_puts(" (I)  Display system information\r\n");
            color(green);
            s_puts(" (C)  Take a chance for more time online\r\n");
            color(magenta);
            s_puts(" (T)  Display a test pattern\r\n");
            color(cyan);
            s_puts(" (A)  Ansi graphics demo\r\n");
            color(violet);
            s_puts(" (D)  Display information on CKIT\r\n");
            color(green);
            s_puts(" (F)  Download CKIT.DOC using Zmodem \r\n");
            color(yellow);
            s_puts(" (M)  Graphics Mode On/Off \r\n");
            color(red);
            s_puts(" (Q)  Return to PCBoard\r\n");
            color(green);
            s_puts(" (G)  Logoff  (Disconnect)\r\n");
            color(cyan);
            s_puts("\r\n\
While you are sitting here at the command line. Press some extended key\
board \r\nkeys. If you are on the remote end using Qmodem, go into the DOORWAY\r\n\
mode. Remember this is just a demo/usage for scan_code, so it's nothing \
fancy.\r\n");
            color(yellow);
            do {
                newline();
                display_time();
                color(green);
                s_puts("Command? ");
                get_cmdline();          /* read input into 'cmdline'  */

            } while((DUMP_USER != TRUE) && (strlen(cmdline) == 0) && (scan_code == 0));
        }
        if (DUMP_USER == TRUE) {
            exit(1);
        }
        if (scan_code != 0) {
            color(white);
            read_scancode();
            newline();
        }
        if (get_nextpar()) {  /* scan next parameter from cmdline into par */
            newline();
      /* process commands */
            switch ( par[0] ) {
                case 'A':
                ansi_demo();
                break;
                case 'C':
                take_chance();
                break;
                case 'I':
                display_info();
                break;
                case 'T':
                test_pattern();
                break;
                case 'D':
                color(cyan);
                strcpy(error_msg11, "\a\nUnable to locate CKIT.DOC");
                if(display_file(doc_filename)) {
                    newline();
                };
                break;
                case 'F':
                color(cyan);
                filexfer();
                break;
                case 'M':
                graphics = graphics ^ TRUE;
                break;
                case 'Q':
                option = EXITDOOR;
                return;
                case 'G':
                option = LOGOFF;
                return;
                default:
                newline();
                color(magenta);
                if(silent) {
                    send_byte(BELL);
                } else {
                    s_putc(BELL);
                }
                s_printf(" '%s' is not allowed!  Try again: %s", par, firstname);
                *cmdline = 0;
                break;
            }
        }
    }
}

/******************************************************************************
*                       Display User information                              *
******************************************************************************/
void display_info(void) {
    clr_screen();
    newline();
    color(white);
    s_printf("%s, Here is your User information:", firstname);
    color(green);
    newline();
    s_putv("  Fullname        = ",fullname,"\r\n",NULL); /* could use sprintf() also */

/*    if(!GENERIC) { */
        if (!PCB &!RBBS) {
            s_printf("  Phone number(s) = ");
        }
        if (!WILDCAT && !PCB && !RBBS) {
            s_printf("User Business - %s", user.bphone);
        }
        if (!PCB && !RBBS) {
            s_printf("   Home - %s", user.phone);
            newline();
        }
        if (!PCB) {
            s_printf("  City            = %s\r\n",user.city);
        }
        s_printf("  Modem Baud Rate = %s\r\n",baud_rate);
        if(!RBBS) {
            s_printf("  DTE Baud Rate   = %s\r\n",bps_open);
        }
        s_printf("  Minutes left    = %d\r\n",min_left+time_credit);

        if (!PCB && !RBBS) {
            s_printf("  Protocol is     = %s\r\n",protocol);
        }

        if (!WILDCAT && !PCB && !RBBS) {
            s_printf("  Last call date  = %s\r\n",user.last_date);
        }

        if (!PCB && !WILDCAT && !RBBS) {
            s_printf("  Event runs at   = %s\r\n",event_time);
            s_printf("  Total K bytes   = %s",download_Kbytes);
            newline();
            s_printf("  Total K bytes   = %s\r\n",upload_Kbytes);
        }
        if (!PCB && !RBBS) {
            s_printf("  # of Downloads  = %s",dload_total);
            s_printf("  Today's K bytes = %s\r\n",daily_bytes);
            s_printf("  Allowed K bytes = %d\r\n",dload_limit);
            s_printf("  # of Uploads    = %s\r\n",upload_total);
            s_printf("  Your birthday   = %s\r\n",caller_bday);
            s_printf("  Last file scan  = %s\r\n",last_file_scan);
        }
        if (WILDCAT) {
            s_printf("  Monitor type    = %s\r\n", monitor_type);
            s_printf("  High msg. read  = %s\r\n", high_msg);
            s_printf("  Door opened     = %s\r\n", door_opened);
        }
        if(RBBS) {
            s_printf("  BBS system name = %s", BBSname);
            newline();
        }
        s_puts("  Graphic         = ");
        if  (graphics) {
            s_puts("ON");
        } else {
            s_puts("OFF");
        }
        newline();
        s_printf("  Connected to port %s", aport);
        newline();
        if(!RBBS) {
            s_puts("  Error correction = ");
            if  (error_connection) {
                s_puts("YES");
            } else {
                s_puts("NO");
            }
        newline();
        }
        s_printf("  Page length     = %d\r\n",page_length);
        color(yellow);
        newline();
        force_enter();
/*
 *  *cmdline = NULL;  Use this if you don't want cmd stacking
 */

/*    } */
}

/******************************************************************************
*                       ANSI Demo                                             *
******************************************************************************/
void ansi_demo(void) {

    short x,y;
    register    short  i;

    if (graphics || ansi_ng) {  /* Check if user is in ANSI mode */
        clr_screen();
        for (y=2; y < 24; y++) {
            pos_cursor(y,1);
            s_puts("³");
            pos_cursor(y,79);
            s_puts("³");
        }
        x = 2;
        pos_cursor(1,x);
        for(i = 0; i <= 1; i++) {
            while(x < 79) {
                s_puts("Ä");
                x++;
            }
            x = 2;
            pos_cursor(23,x);
        }
        pos_cursor(1,1);
        s_puts("Ú");
        pos_cursor(1,79);
        s_puts("¿");
        pos_cursor(23,1);
        s_puts("À");
        pos_cursor(23,79);
        s_puts("Ù");

        for(i = blue; i <= white; i++) {
            color(i);
            pos_cursor(i-8+3,11);
            s_puts("ANSI Color display");
        }
        for(i = grey; i >= dkblue; i--) {
            color(i);
            pos_cursor(i+3, 50);
            s_puts("ANSI Color display");
        }
        color(red);
        pos_cursor(13,34);
        s_puts("C - K I T");
        color(yellow);
        pos_cursor(16,14);
        s_puts("This is only a SMALL sample of what C-Kit can do! ");
        color(red);
        pos_cursor(20,26);
    } else {
        newline();
        s_puts("ANSI demo available only in GRAPHICS mode.\r\n");
    }
    force_enter();

/*
 *  *cmdline = NULL;  Use this if you don't want cmd stacking
 */
    clr_screen();
}

/*****************************************************************************
 *  Open  door                                                               *
 *****************************************************************************/
void    test_pattern(void) {
    int  i;

    newline();
    for (i = 1; i < 21; i++) {
           s_puts("(1234567890-abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ-0123456789)\r\n");
    }
/*
 *  *cmdline = NULL;  Use this if you don't want cmd stacking
 */

}


/*****************************************************************************
 *  Filexfer doc file                                                        *
 *****************************************************************************/
void    filexfer(void) {
    color(green);
    s_printf("\nReady to send %s. Press <ENTER> to begin.",doc_filename);
    while(DUMP_USER != TRUE) {
          if( check_CR() ) {
            break;
        }
    }
   sprintf(xfer_file, "dsz portx %X,%X pB4096 pa3000 handshake cts sz %s", \
            uart_base, irq, doc_filename);
    if(dos_shell(xfer_file)) {
        s_puts("\n\aTransfer aborted");
    } else {
        s_puts("\nTransfer complete");
    }
/*
 *  *cmdline = NULL;  Use this if you don't want cmd stacking
 */
}

/******************************************************************************
*  Demostrate scan_code usage                                                 *
******************************************************************************/
void    read_scancode(void) {

     newline();
     newline();
      /* process scancodes */
    switch(scan_code) {
        case 0x3B00:
        s_puts("You pressed F1");
        break;
        case 0x3C00:
        s_puts("You pressed F2");
        break;
        case 0x3D00:
        s_puts("You pressed F3");
        break;
        case 0x3E00:
        s_puts("You pressed F4");
        break;
        case 0x3F00:
        s_puts("You pressed F5");
        break;
        case 0x4000:
        s_puts("You pressed F6");
        break;
        case 0x4100:
        s_puts("You pressed F7");
        break;
        case 0x4200:
        s_puts("You pressed F8");
        break;
        case 0x4300:
        s_puts("You pressed F9");
        break;
        case 0x4400:
        s_puts("You pressed F10");
        break;
        case 0x4800:
        s_puts("You pressed UP Arrow");
        break;
        case 0x5000:
        s_puts("You pressed Dn Arrow");
        break;
        case 0x4D00:
        s_puts("You pressed R Arrow");
        break;
        case 0x4B00:
        s_puts("You pressed L Arrow");
        break;
        case 0x4900:
        s_puts("You pressed PgUp");
        break;
        case 0x5100:
        s_puts("You pressed PgDn");
        break;
        case 0x5200:
        s_puts("You pressed Insert");
        break;
        case 0x5300:
        s_puts("You pressed Delete");
        break;
        case 0x4700:
        s_puts("You pressed Home");
        break;
        case 0x4F00:
        s_puts("You pressed End");
        break;
        case 0x4A00:
        s_puts("You pressed Grey - ");
        break;
        case 0x4E00:
        s_puts("You pressed Grey + ");
        break;
        default:
        break;
    }
    newline();
    s_puts(" - Press a key to continue - ");
    newline();
    while(!(wait_keypress())) {
    }
}

/*****************************************************************************
 *  Take a chance on on-line time                                            *
 *****************************************************************************/
void    take_chance(void) {
    char    thinking_of[5];

    if(PCB) {
        *cmdline = 0;
        itoa(random(10),thinking_of,10);
        if ( strlen(cmdline) == 0) {
            color(cyan);
            s_puts("I'm thinking of a number from 0 to 9.  If you guess the\r\n");
            s_puts("number, you will be given an extra 10 minutes online.  If you\r\n");
            s_puts("get it wrong, your time will be reduced by 2 minutes.\r\n");
            newline();
            color(yellow);
            s_puts("What's your guess? ");
            get_cmdline();
            newline();
        }
        if (get_nextpar()) {  /* scan next parameter from cmdline into par */
            if (!strcmpi(thinking_of, par)) {
                color(green);
                s_puts("That's right!  You get a 10 minute bonus!");
                adjust_time_allowed(10);
            } else {
                color(blue);
                s_printf("Wrong! You lose 2 minutes! I was thinking of %s.",thinking_of);
                adjust_time_allowed(-2);
            }
        }
    } else {
        newline();
        s_puts("Take chance only available with PCBOARD.SYS usage.\r\n");
    }
}

/****************************************************************************
 *      Printf() function for sending output to port                        *
 ****************************************************************************/
void s_printf(char *s_format,...) {
    va_list arg_pointer;
    char buffer[256];
    va_start(arg_pointer, s_format);
    vsprintf(buffer, s_format, arg_pointer);
    s_puts(buffer);
    va_end(arg_pointer);
}

/****************************************************************************
 *      Close door, reset vectors etc.                                      *
 *  Need in case of a run time error occurs in door                         *
 ****************************************************************************/
 void   shut_down(void) {
    if(OPENED && !CLOSED) {
        close_door();
        CLOSED = TRUE;
    }
}

/*****************************************************************************
 *  Print (XXX used, XXX left)  (time in minutes)                            *
 *****************************************************************************/
void display_time(void) {
        color(yellow);
        s_puts("(");
        color(green);
        s_printf("%d used, ", system_time_used()+prev_used);
        color(red);
        s_printf("%d left",  mins_left_system()+time_credit);
        color(yellow);
        s_puts(") ");
 }

/*****************************************************************************
 *  Prints messages, enter with msg table to use                             *
 *****************************************************************************/
void    print_error(short index, char **msg_table) {
    printf(msg_table[index]);
}

/*****************************************************************************
 *  Send a single byte to the remote only                                    *
 *****************************************************************************/
void    send_byte(BYTE data) {
    BYTE byte_out[2];
    *byte_out = data;
    *(byte_out+1) = 0x00;
    transmit_data(byte_out);
}

/****************************************************************************
 *      IF IF IF IF IF IF IF IF IF IF IF IF IF IF IF IF IF IF IF IF         *
 * This #if is needed since TURBOC has it's own random() function           *
 * This is needed for this demo source code only.                           *
 ****************************************************************************/
#if COMPILER == MICROSOFT
int   random(short Modulo) {
    short   seed;
    check_time_left();
    seed = system_time_HHMMSS[7] - 0x30;    /* Strip ASCII off */
    return(RAND(seed));
}
#endif
/****************************************************************************
 *     ENDIF ENDIF ENDIF ENDIF ENDIF ENDIF ENDIF ENDIF ENDIF ENDIF ENDIF    *
 ****************************************************************************/

/****************************************************************************/
/************************ E N D  O F   M O D U L E **************************/

/*  About open_door().

   The 1st arg. must be a string pointer to the system file.
   If you do want user file info for your door, you should set the
   USERSFILE=TRUE, and pass the users path\name as argv[2] to open_door. i.e

   open_door(argv[1], argv[2], argv[3]);  (arg[3] is for the PORT cmd)

   The portnumber could be any argument except the first argv[1], (must be
   the system file), the second arg[2] could be the users file or port change,
   or the third argument would be a port change if the users file was needed
   to be opened.  PORT is optional, Ckit will default to standard addresses
   and irqs if it not used based on the port number read from the BBS file.
   Ckit will assume COM1 = 03F8 IRQ 4, COM2 = 02E8 IRQ3, COM3 = 03E8 IRQ4
   and COM4 = 02E8 IRQ 3.  If the sysop had a different non-standard
   port address and irq, he could then use the PORT cmd to change the
   defaults.  For this reason, you should include the usage of PORT in
   your door program and documenation.
   Below is some examples of how your program would/could be called up
   and how the open_door() function would be called.  Notice PORT is always
   the second or third (last) argument to be passed if a user of your door
   program wanted to use it.


   Note also it does not matter which order on the cmd line the arguments
   are listed. The only thing that matters is which order they are passed
   to the open_door() function itself.

   The CKITDEMO.C demo door was written to accept input for open_door()
   from the command line.  argv[1] for the system file and argv[2] for
   the PORT command, if desired.  So the CKITDEMO will accept either
   CKITDEMO DOOR.SYS   OR   CKITDEMO DOOR.SYS PORT:03E8:5.
   Your door DOESN'T have to be this way since all open_door() wants
   is a string pointer to the filename and the port command.(if used)
   It could also be a string read from a config file defining the location
   of the BBS system files. Such as:

    main(int argc, char **argv) {
    short   handle, bytes_read;
    char    pcbsyspath[81];

    handle = open(argv[1], O_RDONLY);
    bytes_read = read(handle, pcbsyspath, 80);
    pcbsyspath[bytes_read - 1] = '\0';
    close(handle);
    open_door(pcbsyspath, argv[2]); (include arg2 for the PORT cmd)
    close_door();

    }

   Now your door program would require a config file passed on the cmd line.
   Your program would read the BBS filename\path from it and pass it
   to open_door().  For the above it might something like:

    c:\pcb\pcboard.sys
    Data-Comp BBS
    c:\pcb\gen\blt99

   To invoke your door program the sysop would then use either of the
   following:
             doorpgm config.cfg
             doorpgm config.cfg  PORT:03E8 5 ;change port address/irq

   You as a door author should include in your docs about the usage
   of the PORT cmd and pass the second cmd line argument to open_door().
   Ckit knows automatically if the PORT cmd is being used or not but you
   have to pass arg to open_door() in your program.

   open_door() works like this.  It will expect the first pointer to
   be a string pointer to the BBS system file, always.  Next, it checks
   to see if USERSFILE = TRUE.  If so, it will expect the second pointer
   to be a string pointer to a PCBoard users file.  If USERSFILE is
   FALSE it will not look for a users file.  Either case, open_door()
   will search the stack frame pointers for the word "PORT" for the
   2nd and 3rd string pointers passed.  If it finds it, it will utilize
   it.  If not, it will use the default port addresses/irq's defined
   above.  For this reason, open_door() will work whether there is
   actually a port command being passed or not.  You as the door
   author should provide the users of your door the ability to pass
   the port command if they are using NON-STANDARD ports.

*/

