/*
	edemo.C

	Event Handler Demonstration

	Copyright (C) 1993, Geoff Friesen B.Sc.
	All rights reserved.

	Borland C++ 3.1
*/

#include <dos.H>
#include <process.H>
#include <stdio.H>
#include <stdlib.H>
#include <time.H>

#include "event.H"
#include "kbd.H"
#include "mouse.H"
#include "video.H"

int rows = 25;
int cattr = (BLUE << 4) | WHITE;
int bwattr = LIGHTGRAY << 4;

void cleanup (void);

void main (int argc, char **argv)
{
   event e;
   int adaptor = v_aa (), x, y;

   if (_osmajor < 3 || _osmajor == 3 && _osminor < 30)
   {
       fprintf (stderr, "edemo: invalid DOS version number - "
			"needs 3.30+\n");
       exit (ERROR);
   }

   if (argc > 2 ||
       argc == 2 && (rows = atoi (argv [1])) != 43 && rows != 50)
   {
       fprintf (stderr, "edemo: invalid command line\n");
       exit (ERROR);
   }

   atexit (cleanup);
   v_setattr ((v_setup (rows) == C80) ? cattr : bwattr);
   rows = v_getrows ();

   v_cursor (CHIDE);
   v_clear(1, 1, 80, rows);
   v_border (DOUBLE_LINE, 1, 1, 80, rows-1);
   v_gotoxy (1, rows);
   v_cputs ("EDEMO þ Event DEMOnstration þ Press S to suspend");
   v_gotoxy (73, rows);
   v_cputs ("F10-Exit");

   if (e_init (100) == ERROR)
   {
       fprintf (stderr, "edemo: unable to install event handler\n");
       exit (ERROR);
   }

   mrowrange (0, (rows-1)*8);	/* set maximum row (8 pixels/row) */
   mmoveto (0, 0);

   (void) e_settimer (0, 3);
   (void) e_settimer (5, 40);

   (void) e_flush ();
   (void) e_show ();

   randomize();

   while (1)
   {
      (void) e_fetch (&e);

      if (e.type == KEY && e.parm1 == F10)	/* keystroke exit */
	  break;

      if (e.type == KEY && e.parm1 == 'S' ||
	  e.type == MOUSE && (e.parm1 & ME_LBP) &&
	  (e.parm3 >> 3) == 36 && (e.parm4 >> 3) == rows-1)
      {
	  (void) e_suspend ();
	  sleep (3);
	  (void) e_flush ();
	  (void) e_resume ();
	  continue;
      }

      if (e.type == MOUSE && (e.parm1 & ME_LBP))
      {
	  e.parm3 >>= 3;
	  e.parm4 >>= 3;
	  if (e.parm3 >= 72 && e.parm4 == rows-1)
	      break;
	  else
	      continue;
      }

      if (e.type == TIMER && e.parm1 == 5)
      {
	  if (adaptor != MDA)
	      v_setattr ((1+random(7)) << 4);
	  (void) e_hide ();
	  v_clear(2, 2, 78, rows-3);
	  (void) e_show ();
	  continue;
      }

      if (e.type == TIMER && e.parm1 == 0)
      {
	  x = 2+random(74);
	  y = 2+random(rows-3);

	  v_gotoxy (x, y);
	  (void) e_hide ();
	  v_cputs ("EDEMO");
	  (void) e_show ();
	  continue;
      }
   }

   (void) e_hide ();
   (void) e_close ();

   exit (OK);
}

void cleanup (void)
{
   int frequency;

   for (frequency = 100; frequency < 1500; frequency += 100)
   {
	sound (frequency);
	delay (50);
   }

   nosound ();

   v_cleanup ();
}