/*
================================ COPYRIGHT ================================
The contents of this file are subject to the VTech Informations Ltd. License
of VT-OS Ver. 1.1 operating system (the "License"); you may not use this 
file except in compliance with the License.  

Software distributed under the License is distributed on an "AS IS" basis, 
WITHOUT WARRANTY OF ANY KIND, either express or implied.  See the License 
for the specific language governing rights and limitations under the License.
  
The Original Code is VT-OS Ver. 1.1 Operating System, released 
on October 1st, 1999
	
The Initial Developer of the Original Code is VTech Informations Ltd.  All 
codes are Copyright (C) VTech Informations Ltd. 1999.  All Rights Reserved.
===========================================================================
*/

/*
===========================================================================
File        :   main.c
Author(s)   :   Henry Fok, Kenng Ng, Thomas Cheng
Company     :   VTech Informations Ltd.
Project     :   Helio 
Date:	    :   October 1st, 1999
Purpose:	:   system main
Revision    :   1.1
Note        :   None
===========================================================================
*/              


#include "print.h"
#include "uart.h"
#include "intc.h"
#include "tmrapi.h"
#include "eventmgr.h"
#include "uievent.h"
#include "sysetup.h"
#include "dev_pwr.h"
#include "system.h"
#include "kernel.h"
#include "sio.h"
#include "kernel.h"

extern BOOLEAN mem_chk;
extern UWORD *reset_type;
extern mmu_total_free_block;
extern BOOLEAN Welscr();
extern BYTE GPassCheck;
extern AppID prev_appid;
extern REGISTRY app_reg[APP_MAX];
extern CpuChangeSpeed(int);
extern BYTE writable;

BOOLEAN SysEventLoopWhileLoop();
BOOLEAN first_time_startup = FALSE;

#ifdef	DEBUG
#ifdef	PC_SIM
#define	VTRACE			TRACE
#else
#define	VTRACE			printf
#endif	PC_SIM
#else
#define	VTRACE
#endif	DEBUG

//==============================================================================
__main()
{
	UWORD app_id;
	USHORT index;
    RTM time;
    reset_type = BOOT_INFO_ADDRESS;
	
    if ((UWORD)*reset_type == BOOT_WARM_PATT)
	{
		os_mm_init();
		user_mm_init();
		app_id = SysGetActiveAppID();
        if(SysGetAppEntryIndex(app_id, &index) == TRUE)
        {
			ClrAttribute(app_reg[index].attribute, BIT_RUN);
        }
		SysClearAppData(index);
		SysClearSysData();
        mmu_total_free_block += 2;
        MemoryPageTableInit(NULL,NULL,NULL);
        writable = 1;
        TlbInit();
        ResInit();
        TmrInit();
		
        EvtInitHandler();
		
        SibInit();      /* AH */
        SibEnable();    /* AH */
		
        HwSioInit();    /* AH */
        HwHotSyncInit();    /* AH990413 */
		
        Delay(0x1fff);  /* AH */
        BettyReset();   /* AH */
        BettyInit();  //AH990408
        while(BtyRstState!=0); /* AH */  /* wait for betty init complete */
        
        UartInit(UART_A, UART_BAUD115200, UART_DATABIT8|UART_PARITY_NONE|UART_STOPBIT1);
        SndDDInit();     
		IOKeyCtrlInit();
		ELInit();
		
		LcdInit();
		if (((CPU->REG_MFIO_DATA_OUT >>3)&1) ==0)
			LcdTurnOn(); /////
		
		PenInit();      /* AH */    	
		PenRotateInit();
		PowerMgrInit2();
		
		
        BatteryWarningInit();
		UIInit();
        SysBuildAllIntPageTable();
		UartMgrInit();
		AlarmMgrInit();
		GlobalFindInit();
        OnPdaInit();
        SIOInit();
		
		VTRACE ("\nSystem is warm-started %08x", *reset_type);
	}
	else
	{
		InitAll();   
		
		VTRACE ("\nSystem : exit from init.c ");
		
		GPassCheck = FALSE;
		prev_appid = 1;
        PenRestoreDefault();
		
        time.year = 2000;
        time.mon = 2;
        time.mday = 1;
        time.sec = 0;
        time.hour = 0;
        time.min = 0;
        time.msec = 0;
        RtcSetTime(&time);
		
		VTRACE ("\nSystem is cold-started %08x", *reset_type);
	}
#ifdef DEBUG
	VTRACE ("\nMem Chk %d", mem_chk);
	UartPutc(UART_A, 12);
#endif
}

void SysEventLoop()
{
    EvtType 	Event;
    char 		msg[10];
	
	AppID 		app_id;
    BYTE 		cal_status;
    BOOLEAN		system_battery_empty = FALSE;
	
	
    reset_type = BOOT_INFO_ADDRESS;
	
	if ((UWORD)*reset_type == BOOT_WARM_PATT) {			// Q: soft reset ?
		VTRACE ("\nRestore SP start");
		//_kam		RestoreTmpSP();
	} else {
		SySetupSetCalPenMode(1);
		VTRACE ("\nSave SP start");
		//_kam		SaveTmpSP();
	}
	
	__asm("	.globl	SaveTmpSPBack");
	__asm("SaveTmpSPBack:");
	
	VTRACE ("\nSave SP fin");
	
	if (BatDoorOpen() == 0 && CheckBatteryEmpty() == 0) {
		system_battery_empty = !SysEventLoopWhileLoop();
		VTRACE ("\n 1st SysEventLoopWhileLoop battery_empty = %ld", system_battery_empty);
	}
	
	while (BatDoorOpen() == 1 || CheckBatteryEmpty() == 1 || system_battery_empty) {
		EvtQueueCreate(&evtQueue);
		MsgQueueCreate(&msgQueue);
		VTRACE ("\n Enter HwSystemPowerOff() in main.c");
		HwSystemPowerOff();
		VTRACE ("\n Exit HwSystemPowerOff() in main.c");
		system_battery_empty = !SysEventLoopWhileLoop();
		VTRACE ("\n system_battery_empty in main.c = %ld", system_battery_empty);
	}
	
	VTRACE ("\n Exit First While Loop in main.c");
	
	system_battery_empty = FALSE;
	system_battery_empty = !Welscr();
	
	while (BatDoorOpen() == 1 || system_battery_empty) {
		EvtQueueCreate(&evtQueue);
		MsgQueueCreate(&msgQueue);
		
		VTRACE ("\n Enter HwSystemPowerOff after Welcome Screen");
		HwSystemPowerOff();
		
		VTRACE ("\n Just Exit HwSystemPowerOff after Welcome Screen");
		
		if (CheckBatteryEmpty())
			system_battery_empty = TRUE;
		else
			system_battery_empty = FALSE;
		
		VTRACE ("\n Door Status = %ld and Battery Empty = %ld", BatDoorOpen(), system_battery_empty);
		VTRACE ("\n Exit HwSystemPowerOff after Welcome Screen");
	}
	
	//Msg Queue and Event Queue are re-created in order to get rid of other launch event
	EvtQueueCreate(&evtQueue);
	MsgQueueCreate(&msgQueue);
	
	if ((UWORD)*reset_type == BOOT_COLD_PATT) {
		//Hard Reset
		SysGetAppID(SYSETUP, &app_id);
		EvtAppendEvt(EVT_APP_LAUNCH, app_id, LAUNCH_CMD_CAL_PEN, 0, NULL);
	} else {
		if (GPassCheck == TRUE) {
			SysGetAppID(SYPASSWORD, &app_id);
			SystemApplicationInit();
			SysRunApp(app_id, LAUNCH_CMD_NORMAL_LAUNCH, NULL);
		}
		
		SySetupGetCalPenMode(&cal_status);
		
		if (cal_status == 1) {
			SysGetAppID(SYSETUP, &app_id);
			EvtAppendEvt(EVT_APP_LAUNCH, app_id, LAUNCH_CMD_CAL_PEN, 0, NULL);
		} else {
			SysGetAppID(MAINMENU, &app_id);
			EvtAppendEvt(EVT_APP_LAUNCH, app_id, 0, 0, NULL);
		}
	}
	
	((UWORD)*reset_type) = BOOT_WARM_PATT;
	
	do
	{
		EvtGetEvent (&Event);
		ShellHandleEvent(&Event);
	} while (1);
}


/********************************************************
* Function:    SysEventLoopWhileLoop
* Purpose:     The while loop in SysEventLoop
* Scope:		application/internal
* Input:       None
* Output:		None
* Return:      None
* Comment: 	None
*********************************************************/
BOOLEAN	SysEventLoopWhileLoop()
{
	WORD		bat_level = 10;
	EvtType 	event;
	
	VTRACE ("\n\n ======================= Enter SysEventLoopWhileLoop =========================");
	
	
	while (1)
	{
		if (CheckBatteryEmpty() == 1)
		{
			VTRACE ("\n CheckBatteryEmpty = 1 At the start");
			bat_level = 0;
			break;
		}			
        else
        {
			if (BatChkMainLevel() == 1)
			{	
				bat_level = BatChkMainLevelBakup();
				break;
			}	
			else        	
			{        	
				while (1)
				{
					EvtGetEvent(&event);				
					
					if (event.eventType == POWER_EVENT)
					{
						if (event.eventID == BAT_MAIN_LEVEL || event.eventID == BAT_MAIN_LOW)
						{
							bat_level = event.para2;					
							break;
						}							
						else if (event.eventID == BAT_MAIN_EMPTY)
						{
							VTRACE ("\n CheckBatteryEmpty = 1 in the while loop");
							bat_level = 0;
							break;
						}							
					}    					
				}
			}			
		}			
		
		if (bat_level == 0)
			break;	
		else if (bat_level <= 2)
		{
			if (!Lowbatscr())
				bat_level = 0;     			         		
			break;         		    	
		}
		else
			break;
	}
	
	VTRACE ("\n\n bat_level while existing = %ld", bat_level);
	VTRACE ("\n ======================= Exit SysEventLoopWhileLoop =========================");
	
	if (bat_level == 0)
		return FALSE;
	else return TRUE;		
}
