#include <stdio.h>
#include <dos.h>
#include <bios.h>
#include <conio.h>

#define TCK 0x1c  /* use timer tick interrupt  to update screen */
#define END 0x61  /* use reserved interrupt to uninstall ISR */

int count;
int display=0;

void far interrupt  (*oldint)(void);
void far interrupt  (*oldintend)(unsigned bp,unsigned di,unsigned si,
			     unsigned ds,unsigned es,unsigned dx,
			     unsigned cx,unsigned bx,unsigned ax);

void far interrupt keyupdate(void)
{
  count++;
  count&=0x0f;  /* Divide timer tick rate with 16 */

  if(count == 0)
    {
       int xx,yy;

       xx = wherex(); /* save old cursor position */
       yy = wherey();

     gotoxy(1,2);
     if(display==0)  {
       cprintf("0 Now display is 0");
       display=1;
     }
     else  {
       cprintf("1 Now display is 1");
       display=0;
     }
     gotoxy(xx,yy); /* move cursor to old position */
   }
   (*oldint)();  /* Call  old interrupt */
}

void far interrupt uninstall(unsigned bp,unsigned di,unsigned si,
			 unsigned ds,unsigned es,unsigned dx,
			 unsigned cx,unsigned bx,unsigned ax)
{
   /*  Restore old interrupt vector */
   setvect(TCK,oldint);
   setvect(END,oldintend);
   es = _psp;  /* send PSP segment address to uninstall section */
}


void main(int argc,char *argv[])
{
   unsigned int ch,oldseg;

   printf("Key checking program version1.0\n");
   printf("===============================\n");

   /*******   install routine *******/

   if(argc == 1)  /*  no parameter */
     {
       oldint = getvect(TCK);   /* save old timer interrupt */
       setvect(TCK,keyupdate);  /* set new interrupt */
       oldintend = getvect(END);/* save old interrupt */
       setvect(END,uninstall);  /* set new interrupt */

       printf("Stay resident now...\n");

       keep(0, (_SS + (_SP/16) - _psp)); /* Use _SS and _psp
					     to calculate program area */
       return;
     }
   else    /*  Uninstall  resident  */
     {
       geninterrupt(END);  /* return old PSP  segment in ES */

       oldseg = _ES;  /* store old PSP segment */
       ch = peek(_ES,0x2c);   /* read environment segment */
       _ES = ch;      /* prepare parameter to free program memory*/
       _AH = 0x49;    /*  Free memory function */
       geninterrupt(0x21); /* call DOS API (Kernel) */
       _ES = oldseg;  /*  Free PSP memory */
       _AH = 0x49;
       geninterrupt(0x21);

       printf("Uninstalled resident program... \n");
     }
}
