#include "scb.h"
#include "bit_access.h"

enum AIRCR_Bits {
	PriorityGroup	= REG_BIT_DEFN(	 8,  10)
};

void SCB::SetPriorityGrouping(uint32_t priorityGroup)
{
	uint32_t reg_value;
	uint32_t priorityGroupTmp = (priorityGroup & 0x07);         // only values 0..7 are used

	reg_value  =  AIRCR;                                    // read old register configuration
	reg_value &= ~(SCB::VectorKeyMask| SCB::PriorityGroupMask);	// clear bits to change

	// Insert write key and priorty group
	reg_value  =  (reg_value | (0x5FA << 16) | (priorityGroupTmp << 8));

	AIRCR =  reg_value;
}

uint32_t SCB::GetPriorityGrouping(void)
{
	return bitRead(AIRCR,PriorityGroup);
}

void SCB::SetSystemHandlerPriority(SystemHandlerIRQn_Type IRQn, uint32_t priority)
{
	// Set Priority for Cortex-M  System Interrupts
	SHP[((uint32_t)(IRQn) & 0xF)-4] = ((priority << (8 - NVIC_PRIO_BITS)) & 0xff);
}

//    This function reads the priority for the specified interrupt. The interrupt
//    number can be positive to specify an external (device specific)
//    interrupt, or negative to specify an internal (core) interrupt.

uint32_t SCB::GetSystemHandlerPriority(SystemHandlerIRQn_Type IRQn)
{
	// Get priority for Cortex-M  system interrupts
	return((uint32_t)(SHP[((uint32_t)(IRQn) & 0xF)-4] >> (8 - NVIC_PRIO_BITS)));
}
