#define INTHREADING
#include <Threading.h>

int AddThreadingMsg(int class, char *name, char *source, char *type, char *dest, char *data)
{
int t=0,s=0;

/* Find the threading DB no */
while ( t <= 4096 )
   {
   if ( ThreadDB[t].State == PT_RUNNING )
      {
      if ( strcmp(ThreadDB[t].Name,name) == 0 )
         break;
      }
   t++;
   }

if ( t > 4096 )
   return -1;

if ( ThreadDB[t].State != PT_RUNNING )
   return -1;

/* Message no loop over */
if ( ThreadDB[t].CurMsg == 10 )
   {
   /* Wait to make sure 0 has been processed */
   while ( ThreadDB[t].ProcMsg != 10 )
      usleep(EnforcedWait);
   /* loop back to zero */
   pthread_mutex_lock(&ThreadDB[t].Mutex);
   ThreadDB[t].CurMsg = 0;
   ThreadDB[t].ProcMsg = 0;
   pthread_mutex_unlock(&ThreadDB[t].Mutex);
   }

pthread_mutex_lock(&ThreadDB[t].Mutex);

/* get the next que slot */
s = ThreadDB[t].CurMsg;
ThreadDB[t].CurMsg++;

/* Write the messsage out */
ThreadDB[t].MsgQue[s].State = class;
ThreadDB[t].MsgQue[s].Source = malloc(strlen(source)+1);
strcpy(ThreadDB[t].MsgQue[s].Source,source);
ThreadDB[t].MsgQue[s].Type = malloc(strlen(type)+1);
strcpy(ThreadDB[t].MsgQue[s].Type,type);
ThreadDB[t].MsgQue[s].Dest = malloc(strlen(dest)+1);
strcpy(ThreadDB[t].MsgQue[s].Dest,dest);
ThreadDB[t].MsgQue[s].Data = malloc(strlen(data)+1);
strcpy(ThreadDB[t].MsgQue[s].Data,data);
time(&ThreadDB[t].MsgQue[s].TimeStamp);

pthread_mutex_unlock(&ThreadDB[t].Mutex);
return 0; 
}
