#include <main.h>
#include <hidef.h> /* for EnableInterrupts macro */
#include "derivative.h" /* include peripheral declarations */
#include "common.h"
#include "uart.h"

//run test should be defined in your module test case
extern void run_test();

void fb_clk_init(void);
void clkout_init(unsigned char clockout_select, unsigned char clkoutdiv);

/* Actual system clock frequency */
int core_clk_khz;
int core_clk_mhz;

void main(void) {
		int i;
		EnableInterrupts;
		
  	//Disable Watchdog Timer
		SIM_COPC = SIM_COPC_COPT(0);
		// Enable Clocks of all the modules
		SIM_SCGC1 = 0xFF;
		SIM_SCGC2 = 0xFF;
		SIM_SCGC3 = 0xFF;
		SIM_SCGC4 = 0xFF;
		SIM_SCGC5 = 0xFF;
		SIM_SCGC6 = 0xFF; 	
		clkout_init(MCG_OUT,0); // select CLKOUT source and division factor
//		fb_clk_init();
		// configure the Trim values for internal RC (slow) to get MCGOUT at 50MHz
		MCG_C3 = 0x11;
		// configure the DRS=1
		MCG_C4 = 0x30;	

		for(i=0;i<0x200;i++)
			asm("nop");		
		
		core_clk_mhz = 48;
		core_clk_khz = core_clk_mhz*1000;
		
		/* Enable the pins for the selected UART */
		if (TERM_PORT == UART0_BASE_PTR)
		{
			// Enable Port Muxing of Uart0, TXD on PTC6 and RXD on PTC7
			MXC_PTCPF1 = MXC_PTCPF1_C6(2)|MXC_PTCPF1_C7(2);
		}

		if (TERM_PORT == UART1_BASE_PTR)
		{
			// Enable Port Muxing of Uart1, TXD on PTA2 and RXD on PTA3
			MXC_PTAPF3 = MXC_PTAPF3_A2(2)| MXC_PTAPF3_A3(2);
		}

		uart_init (TERM_PORT, core_clk_khz, TERMINAL_BAUD);		
	
		print_str("Hello World !! \n");
		print_str("I'm Mini Micro Controller :-) \n");	  
   	    
       run_test();
       while(1);
 

}

/********************************************************************/
void fb_clk_init(void)
{
	/* Enable the clock to the FlexBus module */
        SIM_SCGC5 |= SIM_SCGC5_MFBUS_MASK;

 	/* Enable the FB_CLKOUT function on PTB1 (alt7 function) */
        MXC_PTBPF4 = MXC_PTBPF4_B1(7);
        PCTLB_DS |= 0x02;			// enable high drive strength to support high toggle rate	// enable high drive strength to support high toggle rate
}
/********************************************************************/
void clkout_init(unsigned char clockout_select, unsigned char clkoutdiv)
{
	/* Set the trace clock to the core clock frequency */
	// should add test of clkoutdiv to check it is is range 0 to 7
	SIM_CLKOUT = SIM_CLKOUT_CLKOUTDIV(clkoutdiv)|SIM_CLKOUT_CS(clockout_select);
        	
	//Enable CLKOUT on PTA5
	MXC_PTAPF2 = MXC_PTAPF2_A5(6);
	PCTLA_DS |= 0x20;			// enable high drive strength to support high toggle rate
}

