/*********************************************************************
 *                  Flowcode CAL EEPROM File
 *
 * File: PIC_CAL_EEPROM.c
 *
 * (c) 2011 Matrix Multimedia Ltd.
 * http://www.matrixmultimedia.com
 *
 * Software License Agreement
 *
 * The software supplied herewith by Matrix Multimedia Ltd (the
 * “Company”) for its Flowcode graphical programming language is
 * intended and supplied to you, the Company’s customer, for use
 * solely and exclusively on the Company's products. The software
 * is owned by the Company, and is protected under applicable
 * copyright laws. All rights are reserved. Any use in violation
 * of the foregoing restrictions may subject the user to criminal
 * sanctions under applicable laws, as well as to civil liability
 * for the breach of the terms and conditions of this licence.
 *
 * THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES,
 * WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
 * TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
 * IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
 * CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
 *
 * Changelog:
 *
 *  date  | by | description
 * -------+----+-----------------------------------------------------
 * 210911 | BR | Created
 * 010513 | LM | V6 EEPROM CAL standardised API to 16 bit data word size
 */



MX_UINT16 FC_CAL_EE_Read (MX_UINT16 Address)
{
	MX_UINT16 data = 0;

	#ifdef MX_EE

		EEADR = Address & 0xff;
		#if (MX_EE_SIZE > 256)
			EEADRH = (Address & 0xff00) >> 8;
		#endif
		#ifdef MX_EE_TYPE2
			cr_bit(EECON1, EEPGD);
		#endif
		#ifdef MX_EE_TYPE3
			cr_bit(EECON1, EEPGD);
			cr_bit(EECON1, CFGS);
		#endif
		st_bit(EECON1, RD);
		data = EEDATA;

	#else
		#error "Chip does not have EEPROM memory"
	#endif
	return (data);
}

void FC_CAL_EE_Write (MX_UINT16 Address, MX_UINT16 Data)
{
	#ifdef MX_EE

		char bInterruptsEnabled;
		//wait for previous EE writes to complete...
		while (ts_bit(EECON1, WR));
		EEADR = Address & 0xff;
		#if (MX_EE_SIZE > 256)
			EEADRH = (Address & 0xff00) >> 8;
		#endif
		EEDATA = Data;
		#ifdef MX_EE_TYPE2
			cr_bit(EECON1, EEPGD);
		#endif
		#ifdef MX_EE_TYPE3
			cr_bit(EECON1, EEPGD);
			cr_bit(EECON1, CFGS);
		#endif
		st_bit(EECON1, WREN);
		bInterruptsEnabled = ts_bit(INTCON, GIE);
		cr_bit(INTCON, GIE);			//Disable Interrupts
		EECON2 = 0x55;
		EECON2 = 0xAA;
		st_bit(EECON1, WR);
		while (ts_bit(EECON1, WR));	//wait for EE write to complete...
		if (bInterruptsEnabled)
			st_bit(INTCON, GIE);		//Re-enable Interrupts
		cr_bit(EECON1, WREN);

	#else
		#error "Chip does not have EEPROM memory"
	#endif
}

