#include "CDD_Usart.h"
#include "Mcu.h"
#include "Port.h"

#include "Fls.h"

#include "Mcu_RcmReg.h"

/**************************************************************************
                      LOCAL FUNCTION
**************************************************************************/
void SysDelay(volatile int cnt)
{
    while(cnt--);
}

void Fls_JobEndNotification( void )
{

}

void Fls_JobErrorNotification( void )
{

}

/**************************************************************************
                      GLOBAL FUNCTION
**************************************************************************/
int main(void)
{
    Mcu_Init(&g_mcuConfig);
    Mcu_InitClock(McuClockSettingConfig_0);
    Port_Init(&g_portConfig);
    Usart_Init(g_usartConfg);  //TX PIN:PA9

    Fls_Init(&g_flsConfig);

    /* Erase flash
       Start Address: 0x08040000U
       Length: 64 sector(all dflash area)
    */
    Fls_Erase(0x40000U, PAGE_SIZE * 64U);
    Fls_MainFunction();
    SysDelay(100000);

    /* clear iwdt interrupt flag */
    if(0U != REG_BIT_GET32(RCM_CSTS_REG_ADDR, RCM_CSTS_IWDTRSTFLG_MASK))
    {
        REG_BIT_SET32(RCM_CSTS_REG_ADDR, RCM_CSTS_RSTFLGCLR_MASK);
    }
    else
    {
        /* do nothing */
    }

    printf("\r\nECC erase task completed!\r\n");

    while(1);
}

#if defined (__CC_ARM) || defined (__ICCARM__) || (defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050))

/*!
* @brief       Redirect C Library function printf to serial port.
*              After Redirection, you can use printf function.
*
* @param       ch:  The characters that need to be send.
*
* @param       *f:  pointer to a FILE that can recording all information
*              needed to control a stream
*
* @retval      The characters that need to be send.
*
* @note
*/
int fputc(int ch, FILE* f)
{
    int reVal = 0;
    reVal = Usart_PutRedefinition(USART1_ID,&ch);
    
    return reVal;
}

/* If configuring the full library using versions after IAR 9.30,
   it is necessary to implement the _write function for printf redirection.*/
size_t __write(int handle,const unsigned char *buf,size_t bufSize)
{
    int32 tempCh = 0;
    for(int i=0; i<bufSize; i++)
    {
        Usart_PutRedefinition(USART1_ID,&tempCh);
    }
    return bufSize;
}

#elif defined (__GNUC__)

/* For Arm Cross GCC: Eclipse */
int _write(int fd,const unsigned char *buf,int len)
{
    int32 tempCh = 0;
    for(int i=0; i<len; i++)
    {
        int32 tempCh = (int32)buf[i];
        Usart_PutRedefinition(USART1_ID,&tempCh);
    }
    return len;
}

#endif
