/* Main code for RAMDefrag */
/* $Id: ramdefrag.c,v 1.5 2004/09/09 22:12:31 knilch Exp $ */

/* this file lacks documentation */

#include <PalmOS.h>
#include <PalmCompatibility.h>
#include <TimeMgr.h> /* for TimGetTicks */
#include "callback.h"

#include "ramdefragRsc.h"

static Boolean MainFormHandleEvent (EventPtr e)
{
    Boolean handled = false;
    FormPtr frm;
    UInt32 i, j;
    
    CALLBACK_PROLOGUE

    switch (e->eType) {
    case frmOpenEvent:
	frm = FrmGetActiveForm();
	FrmDrawForm(frm);
	handled = true;
	break;

    case menuEvent:
	MenuEraseStatus(NULL);

	switch(e->data.menu.itemID) {
	  case MainMIAb:
	    (void)FrmAlert(AboutAlert);
	    break;
	  default:
	    break;
	}

    	handled = true;
	break;

    case ctlSelectEvent:
	switch(e->data.ctlSelect.controlID) {
	  
	  case MainBttn:
	    i = TimGetTicks();
	    /* warrrten sie einen zehntensekunde herrr majorrr */
	    for (j=0; j < 10000; j++) {
	      if (TimGetTicks() > (i+10)) break;
	    }
#ifdef DO_STUPID_SPECIAL_DEBUGGING
	    if ((TimGetTicks() % 2) == 1) {
#else
	    if ((TimGetTicks() % (2*3*2*3+5*2*3)) == (2*3)) {
#endif /* DO_STUPID_SPECIAL_DEBUGGING */
	      (void)FrmAlert(TmpErrorAlert);
	    } else {
              (void)FrmAlert(CongratAlert);
	    }
#undef VI_SYNTAX_HIGHLIGHTING_SUCKS
#ifdef VI_SYNTAX_HIGHLIGHTING_SUCKS
	    }
#endif /* VI_SYNTAX_HIGHLIGHTING_SUCKS */
	    break;
	  default:
	    break;
	}
	break;

    default:
        break;
    }

    CALLBACK_EPILOGUE

    return handled;
}

static Boolean ApplicationHandleEvent(EventPtr e)
{
    FormPtr frm;
    Word    formId;
    Boolean handled = false;

    if (e->eType == frmLoadEvent) {
	formId = e->data.frmLoad.formID;
	frm = FrmInitForm(formId);
	FrmSetActiveForm(frm);

	switch(formId) {
	case MainForm:
	    FrmSetEventHandler(frm, MainFormHandleEvent);
	    break;
	}
	handled = true;
    }

    return handled;
}

/* Get preferences, open (or create) app database */
static Word StartApplication(void)
{
    FrmGotoForm(MainForm);
    return 0;
}

/* Save preferences, close forms, close app database */
static void StopApplication(void)
{
    FrmSaveAllForms();
    FrmCloseAllForms();
}

/* The main event loop */
static void EventLoop(void)
{
    Word err;
    EventType e;

    do {
	EvtGetEvent(&e, evtWaitForever);
	if (! SysHandleEvent (&e))
	    if (! MenuHandleEvent (NULL, &e, &err))
		if (! ApplicationHandleEvent (&e))
		    FrmDispatchEvent (&e);
    } while (e.eType != appStopEvent);
}

/* Main entry point; it is unlikely you will need to change this except to
   handle other launch command codes */
DWord PilotMain(Word cmd, Ptr cmdPBP, Word launchFlags)
{
    Word err;

    if (cmd == sysAppLaunchCmdNormalLaunch) {

	err = StartApplication();
	if (err) return err;

	EventLoop();
	StopApplication();

    } else {
	return sysErrParamErr;
    }

    return 0;
}
