;@Id: boot.tpl#903 @
;=============================================================================
;  FILENAME:   boot.asm
;
;  DESCRIPTION:
;  M8C Boot Code
;  BootLdrI2C_User_Module
;
;  Copyright (c) Cypress Semiconductor 2013. All Rights Reserved.
;
; NOTES:
; PSoC Designer's Device Editor uses a template file, BOOT.TPL, located in
; the project's root directory to create BOOT.ASM. Any changes made to
; BOOT.ASM will be  overwritten every time the project is generated; therfore
; changes should be made to BOOT.TPL not BOOT.ASM. Care must be taken when
; modifying BOOT.TPL so that replacement strings (such as @PROJECT_NAME)
; are not accidentally modified.
;
;=============================================================================

include ".\lib\GlobalParams.inc"
include ".\lib\PSoCapi.inc"
include "m8c.inc"
include "m8ssc.inc"
include "memory.inc"

;--------------------------------------
; Export Declarations
;--------------------------------------

export __Start
export __StartApp
export __lit_start
IF	(TOOLCHAIN & HITECH)
ELSE
export __bss_start
export __data_start
export __idata_start
export __func_lit_start
export __text_start
ENDIF
export  _bGetPowerSetting
export   bGetPowerSetting
export  _setPowerTrim
export   setPowerTrim


;--------------------------------------
; Optimization flags
;--------------------------------------
;
; To change the value of these flags, modify the file boot.tpl, not
; boot.asm. See the notes in the banner comment at the beginning of
; this file.

; Optimization for Assembly language (only) projects and C-language projects
; that do not depend on the C compiler to initialize the values of RAM variables.
;   Set to 1: Support for C Run-time Environment initialization
;   Set to 0: Support for C not included. Faster start up, smaller code space.
;
IF	(TOOLCHAIN & HITECH)
; The C compiler will customize the startup code - it's not required here

C_LANGUAGE_SUPPORT:              equ 0
ELSE
C_LANGUAGE_SUPPORT:              equ 1
ENDIF


; The following equate is required for proper operation. Reseting its value
; is discouraged.  WAIT_FOR_32K is effective only if the crystal oscillator is
; selected.  If the designer chooses to not wait then stabilization of the ECO
; and PLL_Lock must take place within user code. See the family data sheet for
; the requirements of starting the ECO and PLL lock mode.
;
;   Set to 1: Wait for XTAL (& PLL if selected) to stabilize before
;                invoking main
;   Set to 0: Boot code does not wait; clock may not have stabilized by
;               the time code in main starts executing.
;
WAIT_FOR_32K:                    equ 1


; For historical reasons, by default the boot code uses an lcall instruction
; to invoke the user's _main code. If _main executes a return instruction,
; boot provides an infinite loop. By changing the following equate from zero
; to 1, boot's lcall will be replaced by a ljmp instruction, saving two
; bytes on the stack which are otherwise required for the return address. If
; this option is enabled, _main must not return. (Beginning with the 4.2
; release, the C compiler automatically places an infinite loop at the end
; of main, rather than a return instruction.)
;
ENABLE_LJMP_TO_MAIN:             equ 0


;-----------------------------------------------------------------------------
; Interrupt Vector Table
;-----------------------------------------------------------------------------
;
; Interrupt vector table entries are 4 bytes long.  Each one contains
; a jump instruction to an ISR (Interrupt Service Routine), although
; very short ISRs could be encoded within the table itself. Normally,
; vector jump targets are modified automatically according to the user
; modules selected. This occurs when the 'Generate Application' opera-
; tion is run causing PSoC Designer to create boot.asm and the other
; configuration files. If you need to hard code a vector, update the
; file boot.tpl, not boot.asm. See the banner comment at the beginning
; of this file.
;-----------------------------------------------------------------------------

    AREA TOP (ROM, ABS, CON)

  ;********************************************************************;
 ;*** Blocks 0 and 1 0000h through 007F Write-Protected Jump table ***;
;********************************************************************;

    org   0                        ;Reset Interrupt Vector
IF	(TOOLCHAIN & HITECH)
    ;ljmp bootLoaderVerify		   ;First instruction executed following a Reset  	  ;<-???Note I'm not jumping to a location "__Start"
	                                                                                  ;<-???Function bootLoaderVerify is a checksum routine
																					  ;<-???that will determine the validity of the application
ELSE
    ljmp __Start
    ;ljmp bootLoaderVerify		   ;First instruction executed following a Reset  
ENDIF

    org   04h                      ;Supply Monitor Interrupt Vector
    ljmp INT_VEC1

    org   08h                      ;Analog Column 0 Interrupt Vector
	ljmp INT_VEC2

    org   0Ch                      ;Analog Column 1 Interrupt Vector
	ljmp INT_VEC3

    org   10h                      ;Analog Column 2 Interrupt Vector
	ljmp INT_VEC4

    org   14h                      ;Analog Column 3 Interrupt Vector
	ljmp INT_VEC5

    org   18h                      ;VC3 Interrupt Vector
	ljmp INT_VEC6
    
    org   1Ch                      ;GPIO Interrupt Vector
    ljmp INT_VEC7

    org   20h                      ;PSoC Block DBB00 Interrupt Vector
    ljmp INT_VEC8

    org   24h                      ;PSoC Block DBB01 Interrupt Vector
    ljmp INT_VEC9
    
    org   28h                      ;PSoC Block DCB02 Interrupt Vector
    ljmp INT_VEC10
    
    org   2Ch                      ;PSoC Block DCB03 Interrupt Vector
    ljmp  INT_VEC11
    
    org   30h                      ;PSoC Block DBB10 Interrupt Vector
    ljmp INT_VEC12

    org   34h                      ;PSoC Block DBB11 Interrupt Vector
    ljmp INT_VEC13
    
    org   38h                      ;PSoC Block DCB12 Interrupt Vector
    ljmp INT_VEC14
    
    org   3Ch                      ;PSoC Block DCB13 Interrupt Vector
    ljmp  INT_VEC15
    

    org   60h                      ;PSoC I2C Interrupt Vector
    ljmp BootLdr_ISR				   ;Bootloader I2C

    org   64h                      ;Sleep Timer Interrupt Vector
	ljmp INT_VEC25

;;area bootFlash(rom, abs, con)
;;
;;  reserve the last 12 bytes of the interrupt vector table for a generic bootloader entry point.  An app can always use
;;  this address to dereference the real address of the bootloader start address.  Bootloader will not return other than
;;  via a device reset.
;;
;;
;;  org 74h Actually defined in flashapi.asm (reserved)
;;	ljmp bFlashWriteBlock_internal
;;
;;	org 78h	Actually defined in flashapi.asm (reserved)
;;	ljmp FlashReadBlock_internal
;;
;;
 	org 7Ch
	;;provide a completely generic label that is exported to start the bootloader.
	_ENTER_BOOTLOADER::
	 ENTER_BOOTLOADER::
	ljmp GenericBootloaderEntry
    halt                           ;DO NOT plan on returning here
    

;*******************************************************;
;*** Blocks X and X+1  Writable Boot table ***;
;*******************************************************;

RELOC_INT_VECTORS: equ IntVectorAddr
org RELOC_INT_VECTORS
nop
nop
nop
nop

INT_VEC1: equ   (RELOC_INT_VECTORS + 4h)					  ;Supply Monitor Interrupt Vector
INT_VEC2: equ   (RELOC_INT_VECTORS + 8h)                      ;Analog Column 0 Interrupt Vector
INT_VEC3: equ   (RELOC_INT_VECTORS + Ch)                      ;Analog Column 1 Interrupt Vector
INT_VEC4: equ   (RELOC_INT_VECTORS + 10h)                     ;Analog Column 2 Interrupt Vector
INT_VEC5: equ   (RELOC_INT_VECTORS + 14h)                     ;Analog Column 3 Interrupt Vector
INT_VEC6: equ   (RELOC_INT_VECTORS + 18h)                     ;VC3 Interrupt Vector
INT_VEC7: equ   (RELOC_INT_VECTORS +  1Ch)                     ;GPIO Interrupt Vector
INT_VEC8: equ   (RELOC_INT_VECTORS + 20h)                     ;PSoC Block DBB00 Interrupt Vector
INT_VEC9: equ   (RELOC_INT_VECTORS + 24h)                     ;PSoC Block DBB01 Interrupt Vector
INT_VEC10: equ  (RELOC_INT_VECTORS + 28h)                      ;PSoC Block DCB02 Interrupt Vector
INT_VEC11: equ  (RELOC_INT_VECTORS + 2Ch)                      ;PSoC Block DCB03 Interrupt Vector
INT_VEC12: equ   (RELOC_INT_VECTORS + 30h)                     ;PSoC Block DBB10 Interrupt Vector
INT_VEC13: equ   (RELOC_INT_VECTORS + 34h)                     ;PSoC Block DBB11 Interrupt Vector
INT_VEC14: equ  (RELOC_INT_VECTORS + 38h)                      ;PSoC Block DCB12 Interrupt Vector
INT_VEC15: equ  (RELOC_INT_VECTORS + 3Ch)                      ;PSoC Block DCB13 Interrupt Vector
INT_VEC16: equ  (RELOC_INT_VECTORS + 40h)                      ;USB Reset Interrupt Vector
INT_VEC17: equ  (RELOC_INT_VECTORS + 44h)                      ;USB SOF Interrupt Vector
INT_VEC18: equ  (RELOC_INT_VECTORS + 48h)                      ;USB EP0 Interrupt Vector
INT_VEC19: equ  (RELOC_INT_VECTORS + 4Ch)                      ;USB EP1 Interrupt Vector
INT_VEC20: equ  (RELOC_INT_VECTORS + 50h)                      ;USB EP2 Interrupt Vector
INT_VEC21: equ  (RELOC_INT_VECTORS + 54h)                      ;USB EP3 Interrupt Vector
INT_VEC22: equ  (RELOC_INT_VECTORS + 58h)                      ;USB EP4 Interrupt Vector
INT_VEC23: equ  (RELOC_INT_VECTORS + 5Ch)                      ;USB Wakeup Interrupt Vector
INT_VEC24: equ  (RELOC_INT_VECTORS + 60h)                      ;PSoC I2C Interrupt Vector
INT_VEC25: equ  (RELOC_INT_VECTORS + 64h)                      ;Sleep Timer Interrupt Vector



;;INT_VEC1: equ  RELOC_INT_VECTORS + 4h                      ;Supply Monitor Interrupt Vector
    org INT_VEC1											 ;default definition is a halt
	;
	;remove the halt instruction (below) to be vectored to the interrupt specified below
	;
	halt   
    ;`@INTERRUPT_1`
    reti

    	
;;INT_VEC2: equ  RELOC_INT_VECTORS + 8h                      ;Analog Column 0 Interrupt Vector
    org INT_VEC2
    `@INTERRUPT_2`
    reti

;;INT_VEC3: equ  RELOC_INT_VECTORS + Ch                      ;Analog Column 1 Interrupt Vector
    org INT_VEC3
    `@INTERRUPT_3`
    reti

;;INT_VEC4: equ  RELOC_INT_VECTORS + 10h                      ;Analog Column 2 Interrupt Vector
    org INT_VEC4
    `@INTERRUPT_4`
    reti

;;INT_VEC5: equ  RELOC_INT_VECTORS + 14h                      ;Analog Column 3 Interrupt Vector
    org INT_VEC5
    `@INTERRUPT_5`
    reti

;;INT_VEC6: equ  RELOC_INT_VECTORS + 18h                      ;VC3 Interrupt Vector
    org INT_VEC6
    `@INTERRUPT_6`
    reti
	
;;INT_VEC7: equ  RELOC_INT_VECTORS +  1Ch                      ;GPIO Interrupt Vector
    org INT_VEC7
    `@INTERRUPT_7`
    reti

;;INT_VEC8: equ  RELOC_INT_VECTORS + 20h                      ;PSoC Block DBB00 Interrupt Vector
    org INT_VEC8
    `@INTERRUPT_8`
    reti

;;INT_VEC9: equ  RELOC_INT_VECTORS + 24h                      ;PSoC Block DBB01 Interrupt Vector
    org INT_VEC9
    `@INTERRUPT_9`
    reti

;;INT_VEC10: equ  RELOC_INT_VECTORS + 28h                      ;PSoC Block DCB02 Interrupt Vector
    org INT_VEC10
    `@INTERRUPT_10`
    reti

;;INT_VEC11: equ  RELOC_INT_VECTORS + 2Ch                      ;PSoC Block DCB03 Interrupt Vector
    org INT_VEC11
    `@INTERRUPT_11`
    reti

;;INT_VEC12: equ  RELOC_INT_VECTORS + 30h                      ;PSoC Block DBB10 Interrupt Vector
    org INT_VEC12
    `@INTERRUPT_12`
    reti

;;INT_VEC13: equ  RELOC_INT_VECTORS + 34h                      ;PSoC Block DBB11 Interrupt Vector
    org INT_VEC13
    `@INTERRUPT_13`
    reti

;;INT_VEC10: equ  RELOC_INT_VECTORS + 38h                      ;PSoC Block DCB12 Interrupt Vector
    org INT_VEC14
    `@INTERRUPT_14`
    reti

;;INT_VEC15: equ  RELOC_INT_VECTORS + 3Ch                      ;PSoC Block DCB13 Interrupt Vector
    org INT_VEC15
    `@INTERRUPT_15`
    reti


;;INT_VEC24: equ  RELOC_INT_VECTORS + 60h                      ;PSoC I2C Interrupt Vector
    org INT_VEC24
    ;`@INTERRUPT_24`
    ;reti

;;INT_VEC25: equ  RELOC_INT_VECTORS + 64h                      ;Sleep Timer Interrupt Vector
    org INT_VEC25
	`@INTERRUPT_25`
    reti

;;INT_VEC24: equ  I2C_ISR_Vector             ;PSoC I2C Interrupt Vector defined in i2cbootloader.inc
    org INT_VEC24
 GenericI2CINT_Vector::
_GenericI2CINT_Vector::
    `@INTERRUPT_24`		     	   ;DO NOT MOVE I2C JMP  
    reti				           ;
	                               ;Explanation for the future when this is confusing
								   ; The I2C vector is jumped to if the I2C processing part of the bootloader
								   ; figures out that I2C traffic has arrived that is not 'for' it.  For a ISR based
								   ; version, without leaving the ISR the bootloader code jumps to this location and
								   ; is redirected to a location that contains the generic I2C ISR.  This ISR may be upgraded
								   ; and moved around so the location that contains the variable jump address must be located
								   ; at a fixed spot so the bootload code (which never changes) can always jump to the same spot.
								   ; So- where the next jump is directed to doesn't matter as long as the location of this 
								   ; redirection is maintained.
								   ; it seems sort of logical to put this just at the top of this section at 900h
								   ; where the start vector would have gone if this were the main vector table.
		
;-----------------------------------------------------------------------------
;  Start of Execution.
;-----------------------------------------------------------------------------
;  The Supervisory ROM SWBootReset function has already completed the
;  calibrate1 process, loading trim values for 5 volt operation.
;
;;
;; Add fixed jumop vectors so that a bootloader and an application that are both built with these blocks in the
;; at the same location will be able to work together.
;;

GENERIC_VEC26: equ  (RELOC_INT_VECTORS + 68h)                      ;Generic Entry Vector
    org GENERIC_VEC26

ret

GENERIC_VEC27: equ  (RELOC_INT_VECTORS + 6ch)                      ;Generic Entry Vector
    org GENERIC_VEC27

ret
 
GENERIC_VEC28: equ  (RELOC_INT_VECTORS + 70h)                      ;Generic Entry Vector
    org GENERIC_VEC28
ret
GENERIC_VEC29:                      equ  (RELOC_INT_VECTORS + 74h)                      ;Generic Entry Vector
    org GENERIC_VEC29
ret
GENERIC_VEC30:                       equ  (RELOC_INT_VECTORS + 78h)                      ;Generic Entry Vector
    org GENERIC_VEC30
ret

GENERIC_VEC31: equ  (RELOC_INT_VECTORS + 7ch)                      ;Last Generic Entry in Block reserved for 
    org GENERIC_VEC31											   ;application __Start vector redirection
    export  GenericApplicationStart
	export _GenericApplicationStart
 GenericApplicationStart:
_GenericApplicationStart:
	ljmp __StartApp												   ;--a bootloader can always call this absolute address
															   ;  and get to the user app entry point 
																   ;  that was created with this vector table 
ret



;**********************************************;
;*** Block 4 to 223 0100h to 37FFh Writable ***;
;**********************************************;

   
IF	(TOOLCHAIN & HITECH)		
	AREA PD_startup(CODE, REL, CON)
__lit_start:	;this variable is used in bootloader.asm, so declare here if HITECH is used
	ljmp   __Start	
ELSE
    ;---------------------------------
    ; Order Critical RAM & ROM AREAs
	; See another set of area definitions at the bottom of this file
    ;---------------------------------
    ;  'TOP' is all that has been defined so far...

    ;  ROM AREAs for C CONST, static & global items
    ;
    ;;Area Lit always has to be first
    AREA lit               (ROM, REL, CON, LIT)   ; 'const' definitions 
__lit_start:    
    
    AREA Bootloader        (ROM, REL, CON)
	AREA UserApp		   (ROM, REL, CON)
foo::


    AREA idata             (ROM, REL, CON, LIT)   ; Constants for initializing RAM
__idata_start:

    AREA func_lit          (ROM, REL, CON, proclab)   ; Function Pointers
__func_lit_start:

IF ( SYSTEM_LARGE_MEMORY_MODEL )
    ; We use the func_lit area to store a pointer to extended initialized
    ; data (xidata) area that follows the text area. Func_lit isn't
    ; relocated by the code compressor, but the text area may shrink and
    ; that moves xidata around.
    ;
__pXIData:         word __text_end           ; ptr to extended idata
ENDIF

    AREA psoc_config       (ROM, REL, CON)   ; Configuration Load & Unload
    AREA UserModules       (ROM, REL, CON)   ; User Module APIs

    ; CODE segment for general use
    ;
    AREA Bootloader (ROM, REL, CON)
	nop		;these nops are for aligning BL_Jump_Table address 
	nop		;between ImageCraft and HI-Tech compiler
	nop
	
	AREA text (ROM, REL, CON)
__text_start:

ENDIF ; TOOLCHAIN

IF	(TOOLCHAIN & HITECH)						;<- ??? I rearrange the order of the areas to make them work better 
psect init                                                ;<- ??? (by default) for the bootloader (I still need to control 
ENDIF ;TOOLCHAIN

_START_USER_CODE::      
__StartApp:
lcall setPowerTrim
   

M8C_ClearWDTAndSleep
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Clear out all memory for consistancy
;;
;; This __Start function has to be re-entrant because of BootLoader and Watchdog
;; 
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;    
;
M8C_DisableGInt
M8C_SetBank0
;
; Disable and Clear all interrupts
;
mov reg[INT_MSK3], 0x00 ; Must set first because of SoftWare Interrupt capability
;This reg does not exist in this part
;mov reg[INT_MSK2], 0x00 ; Disables the hardware's ability to generate an interrupt
mov reg[INT_MSK1], 0x00 ;
mov reg[INT_MSK0], 0x00 ;
;
mov reg[INT_CLR3], 0x00 ; Clears any pending interrups
;This reg does not exist in this part
;mov reg[INT_CLR2], 0x00 ;
mov reg[INT_CLR1], 0x00 ;
mov reg[INT_CLR0], 0x00 ;
;
clear_memory_1_page_at_a_time:
    mov X, 0   					; Clear 1 thru 255 then clear 0 
	clear_memory_loop:
    	inc X
    	mov [X], 0
    jnz clear_memory_loop
	M8C_ClearWDTAndSleep
; Setup I2C pins for 1_5, 1_7
;(the config table may do it in an incorrect order)
	M8C_SetBank1
	or reg[PRT1DM1], a0h
	M8C_SetBank0
	or reg[PRT1DM2], a0h
	or reg[PRT1DR], a0h
	M8C_SetBank1
	or reg[PRT1DM0], a0h
	M8C_SetBank0
	and reg[I2C_CFG], ~40h


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Clear out all memory for consistancy
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;   

    ; initialize SMP values for voltage stabilization, if required,
    ; leaving power-on reset (POR) level at the default (low) level, at
    ; least for now. 
    ;
    M8C_SetBank1
    mov   reg[VLT_CR], SWITCH_MODE_PUMP_JUST | LVD_TBEN_JUST | TRIP_VOLTAGE_JUST
    M8C_SetBank0

IF ( WATCHDOG_ENABLE )             ; WDT selected in Global Params
    M8C_EnableWatchDog
ENDIF

IF ( SELECT_32K )
    or   reg[CPU_SCR1],  CPU_SCR1_ECO_ALLOWED  ; ECO will be used in this project
ELSE
    and  reg[CPU_SCR1], ~CPU_SCR1_ECO_ALLOWED  ; Prevent ECO from being enabled
ENDIF

IF	(TOOLCHAIN & HITECH) 
    ;---------------------------
    ; Set up the Temporary stack
    ;---------------------------
    ; A temporary stack is set up for the SSC instructions.
    ; The real stack start will be assigned later.
    ;
	global		__Lstackps
	mov     a,low __Lstackps
	swap    a,sp
ELSE
    ;------------------
    ; Set up the stack
    ;------------------
    mov   A, __ramareas_end        ; Set top of stack to end of used RAM
    swap  SP, A                    ; This is only temporary if going to LMM
ENDIF

;;    ;-----------------------------------------------
;;    ; Set Power-related Trim & the AGND Bypass bit.
;;    ;-----------------------------------------------
;;
;;IF ( SUPPLY_VOLTAGE )         ; 1 means 5.0V
;; IF ( AGND_BYPASS )
;;    ;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
;;    ; The 5V trim has already been set, but we need to update the AGNDBYP
;;    ; bit in the write-only BDG_TR register. Recalculate the register
;;    ; value using the proper trim values.
;;    ;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
;;    M8SSC_SetTableVoltageTrim 1, SSCTBL1_TRIM_BGR_5V, AGND_BYPASS_JUST
;; ENDIF
;;ELSE    ; 3.3 V Operation, not 5.0V
;;    M8SSC_SetTableTrims  1, SSCTBL1_TRIM_IMO_3V_24MHZ, SSCTBL1_TRIM_BGR_3V, AGND_BYPASS_JUST
;;ENDIF ;(SUPPLY_VOLTAGE)

    mov  [bSSC_KEY1],  0           ; Lock out Flash and Supervisiory operations
    mov  [bSSC_KEYSP], 0

    ;---------------------------------------
    ; Initialize Crystal Oscillator and PLL
    ;---------------------------------------

IF ( SELECT_32K & WAIT_FOR_32K )
    ; If the user has requested the External Crystal Oscillator (ECO) then turn it
    ; on and wait for it to stabilize and the system to switch over to it. The PLL
    ; is left off. Set the SleepTimer period is set to 1 sec to time the wait for
    ; the ECO to stabilize.
    ;
    M8C_SetBank1
    mov   reg[OSC_CR0], (SELECT_32K_JUST | OSC_CR0_SLEEP_1Hz | OSC_CR0_CPU_12MHz)
    M8C_SetBank0
    M8C_ClearWDTAndSleep                  ; Reset the sleep timer to get a full second
    or    reg[INT_MSK0], INT_MSK0_SLEEP   ; Enable latching of SleepTimer interrupt
    mov   reg[INT_VC],   0                ; Clear all pending interrupts
.WaitFor1s:
    tst   reg[INT_CLR0], INT_MSK0_SLEEP   ; Test the SleepTimer Interrupt Status
    jz   .WaitFor1s                       ; Interrupt will latch but will not dispatch
                                          ;   since interrupts are not globally enabled
ELSE ; !( SELECT_32K & WAIT_FOR_32K )
    ; Either no ECO, or waiting for stable clock is to be done in main
    M8C_SetBank1
    mov   reg[OSC_CR0], (SELECT_32K_JUST | PLL_MODE_JUST | SLEEP_TIMER_JUST | OSC_CR0_CPU_12MHz)
    M8C_SetBank0
    M8C_ClearWDTAndSleep           ; Reset the watch dog

ENDIF ;( SELECT_32K & WAIT_FOR_32K )

IF ( PLL_MODE )
    ; Crystal is now fully operational (assuming WAIT_FOR_32K was enabled).
    ; Now start up PLL if selected, and wait 16 msec for it to stabilize.
    ;
    M8C_SetBank1
    mov   reg[OSC_CR0], (SELECT_32K_JUST | PLL_MODE_JUST | OSC_CR0_SLEEP_64Hz | OSC_CR0_CPU_3MHz)
    M8C_SetBank0
    M8C_ClearWDTAndSleep                  ; Reset the sleep timer to get full period
    mov   reg[INT_VC], 0                  ; Clear all pending interrupts

.WaitFor16ms:
    tst   reg[INT_CLR0],INT_MSK0_SLEEP    ; Test the SleepTimer Interrupt Status
    jz   .WaitFor16ms
    M8C_SetBank1                          ; continue boot at CPU Speed of SYSCLK/2
    mov   reg[OSC_CR0], (SELECT_32K_JUST | PLL_MODE_JUST | OSC_CR0_SLEEP_64Hz | OSC_CR0_CPU_12MHz)
    M8C_SetBank0

IF      ( WAIT_FOR_32K )
ELSE ; !( WAIT_FOR_32K )
    ; Option settings (PLL-Yes, ECO-No) are incompatible - force a syntax error
    ERROR_PSoC Disabling WAIT_FOR_32K requires that the PLL_Lock must be enabled in user code.
ENDIF ;(WAIT_FOR_32K)
ENDIF ;(PLL_MODE)

	;-------------------------------------------------------
    ; Initialize Proper Drive Mode for External Clock Pin
    ;-------------------------------------------------------

    ; Change EXTCLK pin from Hi-Z Analog (110b) drive mode to Hi-Z (010b) drive mode
IF (SYSCLK_SOURCE)
    and reg[PRT1DM2],  ~0x10        ; Clear bit 4 of EXTCLK pin's DM2 register 
ENDIF
    ; EXTCLK pin is now in proper drive mode to input the external clock signal
	
    ;------------------------
    ; Close CT leakage path.
    ;------------------------
    mov   reg[ACB00CR0], 05h
    mov   reg[ACB01CR0], 05h
    mov   reg[ACB02CR0], 05h
    mov   reg[ACB03CR0], 05h

    ; intialize program temperature
    lcall BL_InitTemperature    
    
    ;-------------------------
    ; Load Base Configuration
    ;-------------------------
    ; Load global parameter settings and load the user modules in the
    ; base configuration. Exceptions: (1) Leave CPU Speed fast as possible
    ; to minimize start up time; (2) We may still need to play with the
    ; Sleep Timer.
    ;
    lcall LoadConfigInit

    ;-----------------------------------
    ; Initialize C Run-Time Environment
    ;-----------------------------------
IF ( C_LANGUAGE_SUPPORT )
    mov  A,0                           ; clear the 'bss' segment to zero
    mov  [__r0],<__bss_start
BssLoop:
    cmp  [__r0],<__bss_end
    jz   BssDone
    mvi  [__r0],A
    jmp  BssLoop
BssDone:
    mov  A,>__idata_start              ; copy idata to data segment
    mov  X,<__idata_start
    mov  [__r0],<__data_start
IDataLoop:
    cmp  [__r0],<__data_end
    jz   C_RTE_Done
    push A
    romx
    mvi  [__r0],A
    pop  A
    inc  X
    adc  A,0
    jmp  IDataLoop

C_RTE_Done:

ENDIF ; C_LANGUAGE_SUPPORT

    ;-------------------------------
    ; Voltage Stabilization for SMP
    ;-------------------------------

IF ( SUPPLY_VOLTAGE )                  ; 1 Means 5 Volts
IF ( SWITCH_MODE_PUMP ^ 1 )            ; SMP is operational
    ;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ; When using the SMP at 5V, we must wait for Vdd to slew from 3.1V to
    ; 5V before enabling the Precision Power-On Reset (PPOR).
    ;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    or   reg[INT_MSK0],INT_MSK0_SLEEP
    M8C_SetBank1
    and   reg[OSC_CR0], ~OSC_CR0_SLEEP
    or    reg[OSC_CR0],  OSC_CR0_SLEEP_512Hz
    M8C_SetBank0
    M8C_ClearWDTAndSleep                   ; Restart the sleep timer
    mov   reg[INT_VC], 0                   ; Clear all pending interrupts
.WaitFor2ms:
    tst   reg[INT_CLR0], INT_MSK0_SLEEP    ; Test the SleepTimer Interrupt Status
    jz   .WaitFor2ms                       ; Branch fails when 2 msec has passed
ENDIF ; ( SWITCH_MODE_PUMP ^ 1 )
ENDIF ; ( SUPPLY_VOLTAGE )

    ;-------------------------------
    ; Set Power-On Reset (POR) Level
    ;-------------------------------
    M8C_SetBank1

IF ( SUPPLY_VOLTAGE )                       ; 1 Means 5 Volts
 IF ( CPU_CLOCK_JUST ^ OSC_CR0_CPU_24MHz )  ;    Also 24MHz?
                                            ;       no, set 4.5V POR in user code, if desired
 ELSE ; 24HMz                               ;
    or    reg[VLT_CR],  VLT_CR_POR_HIGH     ;      yes, highest POR trip point required
 ENDIF ; OSC_CRO_CPU_24MHz
ENDIF ; 5V

    M8C_SetBank0

    ;----------------------------
    ; Wrap up and invoke "main"
    ;----------------------------

    ; Disable the Sleep interrupt that was used for timing above.  In fact,
    ; no interrupts should be enabled now, so may as well clear the register.
    ;
    mov  reg[INT_MSK0],0

    ; Everything has started OK. Now select requested CPU & sleep frequency.
    ;
    M8C_SetBank1
    mov  reg[OSC_CR0],(SELECT_32K_JUST | PLL_MODE_JUST | SLEEP_TIMER_JUST | CPU_CLOCK_JUST)
    M8C_SetBank0

    ; Global Interrupt are NOT enabled, this should be done in main().
    ; LVD is set but will not occur unless Global Interrupts are enabled.
    ; Global Interrupts should be enabled as soon as possible in main().
    ;
    mov  reg[INT_VC],0             ; Clear any pending interrupts which may
                                   ; have been set during the boot process.
IF	(TOOLCHAIN & HITECH)
	ljmp  startup                  ; Jump to C compiler startup code		   ;<-??? I'm confused what startup is and where it's defined
	                                                                           ;<-??? don't we have a label "main: 0r _main:" by default????
                															   ;<-??? additionally this is confusing because of the similarity to
																			   ;<-??? __Start:
ELSE
IF ENABLE_LJMP_TO_MAIN
    ljmp  _main                    ; goto main (no return)
ELSE
    lcall _main                    ; call main
.Exit:
    jmp  .Exit                     ; Wait here after return till power-off or reset
ENDIF
ENDIF ; TOOLCHAIN

    ;---------------------------------
    ; Library Access to Global Parms
    ;---------------------------------
    ;
AREA Bootloader        (ROM, REL, CON)
 bGetPowerSetting:
_bGetPowerSetting:
    ; Synthesize the "power setting" value used by chips with SlowIMO mode.
    ; Returns value of POWER_SETTING in the A register.
    ; No inputs. No Side Effects.
    ;
IF ( SUPPLY_VOLTAGE )            ; 1 means 5.0V
    mov   A, POWER_SET_5V0_24MHZ   ; Supply & Internal Main Oscillator speed
ELSE        
    mov   A, POWER_SET_3V3_24MHZ   ; Supply & Internal Main Oscillator speed
ENDIF
    ret

;---------------------------------
; Bootloader Jump Table
;---------------------------------

__Start:
    ljmp bootLoaderVerify
	

_BL_SetTemp::
 BL_SetTemp::
    ljmp JT_SetTemperature
	
 setPowerTrim:
_setPowerTrim:
    ;-----------------------------------------------
    ; Set Power-related Trim & the AGND Bypass bit.
    ;-----------------------------------------------

IF ( SUPPLY_VOLTAGE )         ; 1 means 5.0V
 IF ( AGND_BYPASS )
    ;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ; The 5V trim has already been set, but we need to update the AGNDBYP
    ; bit in the write-only BDG_TR register. Recalculate the register
    ; value using the proper trim values.
    ;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    M8SSC_SetTableVoltageTrim 1, SSCTBL1_TRIM_BGR_5V, AGND_BYPASS_JUST
 ENDIF
ELSE    ; 3.3 V Operation, not 5.0V
    M8SSC_SetTableTrims  1, SSCTBL1_TRIM_IMO_3V_24MHZ, SSCTBL1_TRIM_BGR_3V, AGND_BYPASS_JUST
ENDIF ;(SUPPLY_VOLTAGE)

IF ( WATCHDOG_ENABLE )             ; WDT selected in Global Params
    M8C_EnableWatchDog
ENDIF

    ; Everything has started OK. Now select requested CPU & sleep frequency.
    ;
    M8C_SetBank1
    mov  reg[OSC_CR0],(SELECT_32K_JUST | PLL_MODE_JUST | SLEEP_TIMER_JUST | CPU_CLOCK_JUST)
    M8C_SetBank0


ret    
    ;---------------------------------------------------------------------------------------
    ; Place BLChecksum here as 'default' last ROM area if no custom.lkp file is provided
    ;---------------------------------------------------------------------------------------
    ;
IF	(TOOLCHAIN & HITECH)
ELSE

AREA BLChecksum (ROM, REL, CON)


    ; RAM area usage
    ;
    AREA bootloaderRAM     (RAM, REL, CON)
    AREA data              (RAM, REL, CON)   ; initialized RAM
__data_start:

    AREA virtual_registers (RAM, REL, CON)   ; Temp vars of C compiler
    AREA InterruptRAM      (RAM, REL, CON)   ; Interrupts, on Page 0
    AREA bss               (RAM, REL, CON)   ; general use
__bss_start:
ENDIF ; TOOLCHAIN

; end of file boot.asm
