#include <time.h>

#include <exec/types.h>
#include <exec/io.h>

#include <libraries/dosextens.h>

#include <dlg/cron.h>

#include <proto/exec.h>
#include <proto/dos.h>
#include <proto/dlg.h>

#include <pragmas/dlg.h>

extern struct DosLibrary *DOSBase;

ULONG  __saveds __asm LIBAmigaTime(void);

LONG __saveds __asm LIBCronEvent(register __d0 UBYTE messtype,
                                 register __d1 ULONG time,
                                 register __a0 char *command)

{struct MsgPort     *cronctl;
 struct MsgPort     *myport;
 struct CronMessage  cmess;

 Forbid();
 cronctl = FindPort(CRONCONTROL);
 Permit();
 if (!cronctl)
      if (messtype==WHENEVENT)
          return(0);
        else
          return(NOCRON);

 myport = CreateMsgPort();
 if (!myport)  return(OUTOFMEM);

 cmess.mess.mn_Node.ln_Type = NT_MESSAGE;
 cmess.mess.mn_ReplyPort    = myport;
 cmess.mess.mn_Length       = sizeof(struct CronMessage);
 cmess.type                 = messtype;
 cmess.minutes              = time;
 cmess.command              = command;
 cmess.ofh                  = Output();

 PutMsg(cronctl,(struct Message *)&cmess);
 while(!GetMsg(myport))
        WaitPort(myport);
 DeleteMsgPort(myport);

 if (messtype==CRONEXIT)
     return(CNOERR);
   else
     if (messtype==WHENEVENT)
         return((LONG)cmess.minutes);
       else
         return((LONG)cmess.type);
}


LONG __saveds __asm LIBWhenEvent(register __a0 char *string)

{ULONG a;
 ULONG ctime;
 ULONG ttime;

 if (!(a = LIBCronEvent(WHENEVENT,0,string)))
       return(-1);

 ctime = LIBAmigaTime();
 ttime = ctime / 60 * 60;
 if (ctime-ttime > 30)  ttime += 60;
 
 return((long)((a - ttime) / 60));
}
