/*  EVENTS.C   SwissBetty: Unit für die Ereignisverwaltung im LPC2220 */

#include "LPC22xx.h"
#include "StdTypes.h"
#include "setup.h"
#include "events.h"


/***********************************/
/*  gepufferte Event-Verwaltung    */
/***********************************/

#if !defined (GCC)
#pragma thumb
#endif

#define eventbuffersize 32
word EventBuffer[eventbuffersize];
word evWZ, evRZ;

/* ladbare Timer, d.h. Down-Counters, die bei Erreichen von 0 einen Event
 in den Eventbuffer einspeisen  */

DTTE CurrTimers[numtimers];


void Event_Init (void)
{ int i;
  evWZ = evRZ = 0;
  i = 0;
  while (i<numtimers)
  { CurrTimers[i].aEvent = 0;
    ++i;
  }
}

byte Event_avail (void) { return (evWZ!=evRZ); }

word Get_Event (void)
{ word w;
  if (evWZ==evRZ) return 0;
  w = EventBuffer[evRZ];
  evRZ = (evRZ+1) & (eventbuffersize-1);
  return w;
}

void Add_Event (word aEvent)
{ word w;
  w = (evWZ+1) & (eventbuffersize-1);
  if (w==evRZ) return;
  EventBuffer[evWZ & (eventbuffersize-1)] = aEvent;
  evWZ = w;
}


bool Add_Delayed_Event (dword millisec, word aEvent)
{ int i;
  i = 0;
  while (i<numtimers)
  { if (CurrTimers[i].aEvent == 0)
    { CurrTimers[i].endzeit = T0TC + millisec;  /* zuerst die Endzeit */
      CurrTimers[i].aEvent  = aEvent;           /* dann scharf machen */
      return true;
    }
    ++i;
  }
  return false;
}

