#include <stdint.h>
#include "stm32l476xx.h"

void System_Clock_Init(void);
void NVIC_SetPriority(int irq, int priority);

void SysTick_Handler(void) {

}


int main(void) {

	System_Clock_Init();

	return 0;

}



void System_Clock_Init(void) {

	/* Note, this code initializes the HSI 16MHz clock */

        /* Enable the HSI clock */
        RCC->CR |= RCC_CR_HSION;

	/* Wait until HSI is ready */
	while ( (RCC->CR & RCC_CR_HSIRDY) == 0 );

	/* Select HSI as system clock source  */
	RCC->CFGR &= ~RCC_CFGR_SW;
	RCC->CFGR |= RCC_CFGR_SW_HSI;  /* 01: HSI16 oscillator used as system clock */

	/* Wait till HSI is used as system clock source */
	while ((RCC->CFGR & RCC_CFGR_SWS) == 0 );

}


/* Note: no need to touch the code beyond this point */


void NVIC_SetPriority(int irq, int priority) {

	if (irq<0) {
		// for -1, 0xff -> f -> -4 = b (11)
		SCB->SHP[(((uint8_t)irq)&0xf)-4]=(priority<<4)&0xff;
	}
	else {
		NVIC->IP[irq]=(priority<<4)&0xff;
	}

	return;
}





static void nmi_handler(void) {
	for(;;);
}

static void hardfault_handler(void) {
	for(;;);
}

extern unsigned long _etext,_data,_edata,_bss_start,_bss_end;

	/* Copy DATA and BSS segments into RAM */
void Reset_Handler(void)	{

	unsigned long *src, *dst;

	/* Copy data segment */
	/* Using linker symbols */
	src = &_etext;
	dst = &_data;
	while(dst < &_edata) *(dst++) = *(src++);

	/* Zero out the BSS */
	src = &_bss_start;
	while(src < &_bss_end) *(src++) = 0;

	/* Call main() */
	main();

}

#define STACK_LOCATION (0x20000000+(96*1024))

/* Vector Table */
uint32_t *myvectors[128]
__attribute__ ((section(".isr_vector"))) = {
	(uint32_t *) STACK_LOCATION,	/*   0:0  = stack pointer      */
	(uint32_t *) Reset_Handler,	/* -15:4  = code entry point   */
	(uint32_t *) nmi_handler,	/* -14:8  = NMI handler        */
	(uint32_t *) hardfault_handler,	/* -13:12 = hard fault handler */
	(uint32_t *) nmi_handler,	/* -12:16 = MemManage        */
	(uint32_t *) nmi_handler,	/* -11:20 = BusFault        */
	(uint32_t *) nmi_handler,	/* -10:24 = UsageFault        */
	(uint32_t *) nmi_handler,	/*  -9:28 = Reserved        */
	(uint32_t *) nmi_handler,	/*  -8:32 = Reserved        */
	(uint32_t *) nmi_handler,	/*  -7:36 = Reserved        */
	(uint32_t *) nmi_handler,	/*  -6:40 = Reserved        */
	(uint32_t *) nmi_handler,	/*  -5:44 = SVC Handler        */
	(uint32_t *) nmi_handler,	/*  -4:48 = Debugmon        */
	(uint32_t *) nmi_handler,	/*  -3:52 = Reserved        */
	(uint32_t *) nmi_handler,	/*  -2:54 = PendSV        */
	(uint32_t *) SysTick_Handler,	/*  -1:58 = SysTick        */


};
