/*******************************************************************************
 *  flash_replace16.c - Flash memory copy routines.
 *
 *  Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.com/ 
 *  ALL RIGHTS RESERVED 
 * 
*/

#include <signal.h>
#include <inttypes.h>
#if defined(__MSP430__)
#include <msp430.h>
#endif
#include "emeter-toolkit.h"

#if defined(__MSP430__)
#define FSEG_A 0x01080      // Flash Segment A start address
#define FSEG_B 0x01000      // Flash Segment B start address

// ***********************************************************************
//  This routine makes the flash looks like EEPROM. It will erase and
//  replace just one word
//  This routine copies will erase SEGA and then image SEGB to SEGA
//  It will then erase SEGB and copy from SEGA back to SEGB all 128 bytes
//  except the one to be replaced.
// ***********************************************************************
void flash_replace16(int16_t *ptr, int16_t word)
{
    int *read_ptr;
    int *write_ptr;
    int w;
  
    //Optimise the case where the new and old values are the same
    if (*ptr == word)
        return;
    flash_clr((int *) FSEG_A);

    _DINT();
    //Set to write mode to prepare for copy
    FCTL3 = FWKEY;          /* Lock = 0 */
    FCTL1 = FWKEY | WRT;

    //Copy block B to A
    read_ptr = (int *) FSEG_B;
    write_ptr = (int *) FSEG_A;
    for (w = 0;  w < 64;  w++)
        *write_ptr++ = *read_ptr++;
    flash_clr((int *) FSEG_B);

    //Set to write mode to prepare for copy
    FCTL3 = FWKEY;          /* Lock = 0 */
    FCTL1 = FWKEY | WRT;

    //Copy block A to B, slipping in the new value at the right location
    read_ptr = (int *) FSEG_A;
    write_ptr = (int *) FSEG_B;
    for (w = 0;  w < 64;  w++, read_ptr++, write_ptr++)
    {
        if (write_ptr == ptr)
            *write_ptr = word;
        else
            *write_ptr = *read_ptr;
    }
    flash_secure();
    _EINT();
}
#endif
