/*====================================================================*
 *
 *   int sdramfileA (int fd, const char * filename, flag_t flags);
 *
 *   sdram.h
 *
 *   open an SDRAM configuration file and validate it by checking the
 *   file length; unfortunately there are not many things to check;
 *
 *   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>
 *
 *--------------------------------------------------------------------*/

#ifndef SDRAMFILEA_SOURCE
#define SDRAMFILEA_SOURCE

#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

#include "../ram/sdram.h"
#include "../tools/memory.h"
#include "../tools/error.h"
#include "../tools/flags.h"

int sdramfileA (int fd, const char * filename, flag_t flags) 

{
	uint32_t checksum;
	struct config_ram config_ram = 
	{
		0 
	};
	if (lseek (fd, 0, SEEK_SET) == -1) 
	{
		if (_allclr (flags, SDRAM_SILENCE)) 
		{
			error (0, errno, "Can't rewind file: %s", filename);
		}
		return (-1);
	}
	if (read (fd, &config_ram, sizeof (config_ram)) < sizeof (config_ram)) 
	{
		if (_allclr (flags, SDRAM_SILENCE)) 
		{
			error (0, errno, "Wrong file size: %s", filename);
		}
		return (-1);
	}
	if (read (fd, &checksum, sizeof (checksum)) < sizeof (checksum)) 
	{
		if (_allclr (flags, SDRAM_SILENCE)) 
		{
			error (0, errno, "Can't read checksum: %s", filename);
		}
		return (-1);
	}
	if (checksum32 ((uint32_t *)(&config_ram), sizeof (config_ram) >> 2, checksum)) 
	{
		if (_allclr (flags, SDRAM_SILENCE)) 
		{
			alert ("Bad checksum: %s", filename);
		}
		return (-1);
	}
	if (_anyset (flags, SDRAM_VERBOSE)) 
	{
		if ((filename) && (*filename)) 
		{
			printf ("------- %s -------\n", filename);
		}
		sdrampeek (&config_ram);
	}
	if (lseek (fd, 0, SEEK_SET) == -1) 
	{
		if (_allclr (flags, SDRAM_SILENCE)) 
		{
			error (0, errno, "Can't rewind file: %s", filename);
		}
		return (-1);
	}
	return (0);
}

#endif