#include "am_init.h"

#include "c8051F120.h"                         // Device-specific SFR Definitions

//-----------------------------------------------------------------------------
// Initialization Routines
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// PORT_Init
//-----------------------------------------------------------------------------
//
// Configure the SPI, Interrupts, Crossbar and GPIO ports
//
void PORT_Init(void)
{
    char SFRPAGE_SAVE = SFRPAGE;

    SFRPAGE = CONFIG_PAGE;
    P0MDOUT |= 0x01;
    P1MDOUT |= 0x40;
//  P2MDOUT |= 0x00;
//  P3MDOUT |= 0x00;

    // all pins used by the external memory interface are in push-pull mode
    // including /WR (P4.7) and /RD (P4.6) but the reset (P4.5) is open-drain
    // You may want to set P4.3 (AB4_LED1) and P4.4 (AB4_LED2) to push-pull
    // You may want to set P4.1 (AB4_SW1)  and P4.2 (AM4_SW2)  to open-drain
    P4MDOUT =  0xD8;
    P4 = 0xC0;

    P5MDOUT =  0xFF;
    P6MDOUT =  0xFF;
    P7MDOUT =  0xFF;
    P5 = 0xFF;
    P6 = 0xFF;
    P7 = 0xFF;

    TCON &= ~0x01;

    XBR0 = 0x80;
    XBR1 = 0x04;
    XBR2 = 0x44;

    SFRPAGE = SFRPAGE_SAVE;
}

//-----------------------------------------------------------------------------
// SYSCLK_Init
//-----------------------------------------------------------------------------
//
// This routine initializes the system clock.
//
void SYSCLK_Init(void)
{
    int i;

    char SFRPAGE_SAVE = SFRPAGE;

    SFRPAGE = CONFIG_PAGE;

    OSCICN = 0x83;


    CLKSEL = 0x00;

    //Turn on the PLL and increase the system clock by a factor of M/N
    PLL0CN  = 0x00;
    SFRPAGE = LEGACY_PAGE;
    FLSCL   = 0x30;
    SFRPAGE = CONFIG_PAGE;

    PLL0CN |= 0x01;

    PLL0DIV = 0x01;
    PLL0MUL = 0x03;
    PLL0FLT = 0x01;


    for (i=0; i < 256; i++) ;
    PLL0CN  |= 0x02;
    while(!(PLL0CN & 0x10));
    // Select PLL as SYSCLK source
    CLKSEL  = 0x02;

    SFRPAGE = SFRPAGE_SAVE;
}