#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>

#define SIA_KEYMGR_CHAR_BIT 8u
#define SIA_KEYMGR_AES_BLOCK_BYTE_LEN 16u
uint8_t buf_0[] = {11,12,13,14,15,17,18,19,0xfe};
uint8_t buf_test[] = {1,2,3,4,5,7,20,1,0xfe,44,55,66,77,88,99,10,11,24,0xfe,1,2,3,4,5,7,20,1,2,0xfe,0xfe,43};
uint8_t buf_test_2[256] ;

uint8_t length_check_for_eeprom_2(uint8_t *buff);
void data_process(uint8_t *old_data, uint8_t old_data_size, uint8_t *old_al,uint8_t *new_data);

void Sia_Keymgr_u32_to_n(uint8_t *out, uint32_t in)
{
    unsigned int i;

    for (i = sizeof(in); i > 0u; --i)
    {
        out[i - 1u] = (uint8_t) in;
        in >>= SIA_KEYMGR_CHAR_BIT;
    }
}

int main(void) {
	
	printf("Begin \r\n");
	uint8_t m4lh_plain[SIA_KEYMGR_AES_BLOCK_BYTE_LEN];
	Sia_Keymgr_u32_to_n(m4lh_plain, (1u << 4) | 8u); /* set 32bit on the 128bit */
	for(int i = 0; i<SIA_KEYMGR_AES_BLOCK_BYTE_LEN; i++)
	{
		printf("current val = 0x%x,  \r\n",m4lh_plain[i]);
	}
	return 0;
}


uint8_t length_check_for_eeprom_2(uint8_t *buff)
{
	uint8_t length=0;
	bool valid_data = false;
	uint8_t out;
	
	for(int i = 0; i<256; i++)
	{
		if((*(buff + i)!=0xfe)||(*(buff + i + 1)!=0xfe))
		{
			//printf("current val = %d, next val = %d, length = %d \r\n",*(buff + i),*(buff + i + 1),length);
			length=length+1;
		}
//		else if((*(buff + i)==0xfe)&&(*(buff + i + 1)==0xfe))
//		{
//			length++;
//			valid_data = true;
//			break;
//		}
		else 
		{	length=length+1;
			valid_data = true;
			break;
		}
	}
	return (valid_data==true)? length+1 : 0;
}

//must decalre array new_data[] with correct size before call this function
void data_process(uint8_t *old_data, uint8_t old_data_size, uint8_t *old_al,uint8_t *new_data)
{
	if(old_data_size == 0)
	{
		memcpy(new_data,old_al,9);
		*(new_data+9) = 0xfe;
	}
	else
	{
		memcpy(new_data,old_data,old_data_size);
		memcpy(new_data+old_data_size-1,old_al,9);
		*(new_data+old_data_size+8) = 0xfe;
	}
}
