#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <process.h>

// delaycmd.nlm
// This NLM sends a command to the system console after the specified delay
// This NLM is by no means foolproof; it has the following known restrictions
// at this time:
//   - The command will be blasted to the system console regardless of
//     whether any console input is currently being typed on the console by
//     the operator, interleaving with his input.


/*-----------------------------------------------------------------------*/
void main( int argc, char *argv[] );
int  BTISystem( char *command );
/*-----------------------------------------------------------------------*/

void main( int argc, char *argv[] )
{
 unsigned int DelaySecs;
 unsigned int AnyError = 0;

 if (argc == 3)
   {
    DelaySecs = atoi(argv[1]);
    if ((DelaySecs < 1) || (DelaySecs > 3600))
       AnyError = 1;
   }
 else
   {
    AnyError = 1;
   }
 if (AnyError)
   {
    printf("delaycmd Usage:\n"
           "   LOAD DELAYCMD <seconds> \"command to execute\"\n"
           "    where:  <seconds> = 1 to 3600\n"
           "    and the \"command to execute\" must be in quotes\n"
           "For example:\n"
           "   LOAD DELAYCMD 5 \"LOAD MYNLM\"\n");
    exit(0);
   }

 printf("Delaycmd has scheduled \"%s\" in %d seconds\n", argv[2], DelaySecs);
 delay(DelaySecs*1000);
 
 BTISystem(argv[2]);

}


/*-------------------------------------------------------------------------*/
/*  This function sends the supplied string to the NW v3.11 system console */
/*  Input string does not need to include a CR character                   */
/*  There is no return value.                                              */
/*  Return is after the command has been completely sent.                  */
/*  There is not attempt to synchronize multiple threads calling this      */
/*   routine simultaneously; output may interleave.                        */
/*-------------------------------------------------------------------------*/
int BTISystem(char *command)
{
 LONG  OldScrID = GetCurrentScreen();
 LONG  NewScrID = CreateScreen("System Console",0);

//  Set the current screen to the system console

 if( OldScrID != NewScrID)
    SetCurrentScreen(NewScrID);

//  Send the entire string to the console.  Do a ThreadSwitch
//  after each character to allow the console to clear its buffer.

 for( ; *command; command++ )
    ungetch(*command), ThreadSwitch();

//  Send the CR

 ungetch('\r');

//  Restore the screen

 if( OldScrID != NewScrID)
    SetCurrentScreen(OldScrID);

 return 0;
}


