#include "igloo.h"

int main()
{
	// HRI_NVMCTRL_SET_CTRLA_RWS_bf
	// osc32kctrl_init
	// oscctrl_init
	// mclk_init
	// if GCLK_INIT_1ST
	// gclk_init_generators_by_freq FIRST
	// endif
	// oscctrl_init_referenced_generators
	// gclk_init_generators_by_fref LAST
	//
	// if dmac enable
	// hri_mclk_set_AHBMASK_DMAC_bit
	// dma init
	// endif


	// if CONF_PORT_EVCTRL_PORT_0 | CONF_PORT_EVCTRL_PORT_1 | 2 | 3
	// port event init
	// endif

	// if CONF_CMCC_ENABLE
	// cache init
	// endif



	// Run with 12mhz external crystal on XOSC0

	// Automatic Loop Control
	// 0 - disable
	// 1 - enable
	OSCCTRL->XOSCCTRL[0].bit.ENALC = 1;
	// Current Multiplier
	// 6 - >24MHz to 48MHz
	// 5 - >16MHz to 24MHz
	// 4 - >8MHz to 16MHz
	// 3 - 8MHz
	OSCCTRL->XOSCCTRL[0].bit.IMULT = 4;
	// 3 - >24MHz to 48MHz
	// 3 - >16MHz to 24MHz
	// 3 - >8MHz to 16MHz
	// 2 - 8MHz
	OSCCTRL->XOSCCTRL[0].bit.IPTAT = 3;
	OSCCTRL->XOSCCTRL[0].bit.ONDEMAND = 0;
	OSCCTRL->XOSCCTRL[0].bit.XTALEN = 1;
	OSCCTRL->XOSCCTRL[0].bit.ENABLE = 1;

	while(0 == OSCCTRL->STATUS.bit.XOSCRDY0);

	OSCCTRL->Dpll[0].DPLLRATIO.bit.LDRFRAC = 0;
	OSCCTRL->Dpll[0].DPLLRATIO.bit.LDR = 119;
	OSCCTRL->Dpll[0].DPLLCTRLB.bit.DIV = 5;
	// 0 - GCLK
	// 1 - XOSC32
	// 2 - XOSC0
	// 3 - XOSC1
	OSCCTRL->Dpll[0].DPLLCTRLB.bit.REFCLK = 2;
	OSCCTRL->Dpll[0].DPLLCTRLA.bit.ONDEMAND = 0;
	OSCCTRL->Dpll[0].DPLLCTRLA.bit.ENABLE = 1;

	// wait for pll to be locked and ready
	while(0 == OSCCTRL->Dpll[0].DPLLSTATUS.bit.LOCK
		  || 0 == OSCCTRL->Dpll[0].DPLLSTATUS.bit.CLKRDY);


	// Connect DPLL0 to clock generator 0 (120mhz) - frequency used by CPU, AHB, APBA, APBB
	GCLK->GENCTRL[0].reg = GCLK_GENCTRL_SRC_DPLL0 | GCLK_GENCTRL_DIV(1) | GCLK_GENCTRL_GENEN;
	while(1 == GCLK->SYNCBUSY.bit.GENCTRL0);



	asm volatile("nop");
	for(;;)
	{

	}
	return 0;
}
