/*====================================================================*
 *   
 *   signed ReadMAC2 (struct int6k *int6k);
 *   
 *   int6k2.h
 *   
 *   Read MAC Firmware image from a device using ihpapi_UpdateDevice
 *   api function call, and as many ihpapi_TxFrame and ihpapi_RxFrame
 *   as needed. Note: The image read is from SDRAM, which may no contain
 *   the MAC Firmware.
 *   
 *   See the HomePlugAV Firmware Technical Reference Manual for more 
 *   information;
 *   
 *   This software and documentation is the property of Atheros 
 *   Corporation, Ocala, Florida. It is provided 'as is' without 
 *   expressed or implied warranty of any kind to anyone for any 
 *   reason. Atheros assumes no responsibility or liability for 
 *   errors or omissions in the software or documentation and 
 *   reserves the right to make changes without notification. 
 *   
 *   Atheros customers may modify and distribute the software 
 *   without obligation to Atheros. Since use of this software 
 *   is optional, users shall bear sole responsibility and 
 *   liability for any consequences of it's use. 
 *   
 *.  Atheros Powerline Toolkit for HomePlug AV; 
 *:  Published 2007 by Intellon Corp. ALL RIGHTS RESERVED;
 *;  For demonstration; Not for production use;
 *
 *  Contributor(s):
 *      Charles Maier <charles.maier@atheros.com>
 *      Nathan Houghton <nathaniel.houghton@atheros.com>
 *      Alex Vasquez <alex.vasquez@atheros.com>
 *
 *--------------------------------------------------------------------*/

#ifndef READMAC2_SOURCE
#define READMAC2_SOURCE

#include <unistd.h>
#include <memory.h>

#include "../ihpapi/ihp.h"
#include "../ihpapi/ihpapi.h"
#include "../int6k/int6k.h"
#include "../tools/error.h"
#include "../nvm/nvm.h"

signed ReadMAC2 (struct int6k *int6k) 

{
	Request (int6k, "Reading MAC from Device");
	if (ihpapi_UpdateDevice (int6k->channel->host, int6k->channel->peer, IHPAPI_HAR_UPLOAD_FW) == -1) 
	{
		error ((int6k->flags & INT6K_BAILOUT), errno, "initialization error");
		return (-1);
	}
	do 
	{
		int6k->packetsize = (int)(ihpapi_TxFrame (sizeof (struct message), (uint8_t *)(int6k->message)));
		if (int6k->packetsize == 0) 
		{
			error ((int6k->flags & INT6K_BAILOUT), ECANCELED, "no more data");
			break;
		}
		if (SendMME (int6k) <= 0) 
		{
			error ((int6k->flags & INT6K_BAILOUT), ECANCELED, INT6K_CANTSEND);
			return (-1);
		}
		if (ReadMME2 (int6k) <= 0) 
		{
			error ((int6k->flags & INT6K_BAILOUT), ECANCELED, INT6K_CANTREAD);
			return (-1);
		}
		if (int6k->result->opStatus.status) 
		{
			Failure (int6k, INT6K_WONTDOIT);
			return (-1);
		}
		if (write (int6k->NVM.file, int6k->result->data.updateDev.buffer, (unsigned)(int6k->result->data.updateDev.bufferLen)) != int6k->result->data.updateDev.bufferLen) 
		{
			error ((int6k->flags & INT6K_BAILOUT), ECANCELED, "can't store buffer");
			return (-1);
		}
	}
	while (int6k->result->data.updateDev.eof == false);
	Confirm (int6k, "Read.");
	return (0);
}

#endif