/* 17 Mar 1994 */
#include "mem:h/main.h"
#define KEYMATRIXSIZE 24

/* __saveds not needed when using compiler option STRMER */
LONG __asm capslock( register __d0 int cmdlen, register __a0 char *cmd ) {
   struct DosLibrary *DOSBase;
   struct IOStdReq KeyIO;
   char KeyMatrix[ KEYMATRIXSIZE ];
   LONG result = RETURN_FAIL;

   /* Note: Should check for Workbench message and exit appropriatly */

   if( DOSBase = (DL_S*) OpenLibrary( "dos.library", 0 )) {
     register struct IOStdReq *keyio = &KeyIO;
     register char *errarg = NULL;
     register ULONG i1;
     register LONG capsresult = RETURN_WARN;  /* default */

     /* check for command line options */
     for( i1 = 0; i1 < cmdlen; i1++ ) {
       register char c = *(cmd + i1) | ' ';

       if( c == '?' ) {
         cmd = "Script Usage> CapsLock [option]\n"
               "option w = if CAPSLOCK lit return WARN (default)\n"
               "       e = if CAPSLOCK lit return ERROR\n"
               "       f = if CAPSLOCK lit return FAIL"; goto exitsub;
       }
       if( c == 'e' ) capsresult = RETURN_ERROR;
       if( c == 'f' ) capsresult = RETURN_FAIL;
     }

     /* fill stuff with zero */
     for( i1 = 0; i1 < KEYMATRIXSIZE; i1++ ) KeyMatrix[i1] = 0;

     errarg = (char *) keyio;
     for( i1 = 0; i1 < sizeof( IOSR_S ); i1++ ) *(errarg + i1) = 0;

     cmd = "no "; errarg = "keyboard.device";
     if( !OpenDevice( errarg, NULL, (IOR_S *) keyio, NULL )) {
       register struct ExecBase *ExecBase = (EB_S*) *((ULONG *) 4L);

       /* Must check for version and set io_Length accordingly:
          Kickstart v34 or earlier uses length 13,
          v35 or greater [<--assumption] than use length 20 */
       if( ExecBase->LibNode.lib_Version < 35 ) keyio->io_Length = 13;
       else keyio->io_Length = 20;

       keyio->io_Command = KBD_READMATRIX;
       keyio->io_Data = (APTR) &KeyMatrix[0];

       /* io_Length must be 13 for Kickstart V34 (Workbench 1.3)
          else DoIO() will return fail */
       cmd = "io err"; errarg = NULL;
       if( !(DoIO( (IOR_S *) keyio ))) {
         if( KeyMatrix[12] & (1 << 2) ) result = capsresult;
         else result = RETURN_OK;
         cmd = NULL;    /* no errors to report */
       }
       CloseDevice( (IOR_S *) keyio );
     }
exitsub:
     if( cmd ) {
       register LONG ofh = (LONG) Output();
       Write( (BPTR) ofh, cmd, strlen( cmd ));
       if( errarg ) Write( (BPTR) ofh, errarg, strlen( errarg ));
       Write( (BPTR) ofh, "\n", 1 ); }
     CloseLibrary( (L_S*) DOSBase );
   }
   return( result );
}
