/*
 * milo/flash/makeflash.c
 *
 * Copyright (C) 2001 Compaq Computer Corporation
 *
 * bill.carr@compaq.com
 *
 * This program uses milo/flash/noname.c to generate a flash image file
 * suitable for burning into the UDB/Multia flash rom using the 
 * SRM "update" command.
 */

#include <stdio.h>
#include <string.h>
#include <stdarg.h>

extern char flash_image[];
extern unsigned int flash_image_size;

void *add_noname_flash_header(void *where, unsigned int rom_count);
int calc_rom_count(void);
unsigned char checksum(unsigned char *buf, unsigned int len);

int yes_no(char *string)
{
	return( fgetc( stdin ));
}

int printk(const char *fmt, ...)
{
	int count;
	va_list ap;
	char print_buf[4096];

	va_start(ap, fmt);

	if (fmt[0] == '<' && fmt[1] >= '0' && fmt[1] <= '9' && fmt[2] == '>') {

		/* skip annoying log-priority code: */
		fmt += 3;
	}

	count = vsprintf(print_buf, fmt, ap);

	fwrite (print_buf, count, 1, stdout);

	return( count );
}

int
main( int argc, char *argv[] )
{
#define FLASH_SIZE	(256 * 1024)

	FILE *fd;
	unsigned char buffer[FLASH_SIZE*3] = { 0 };
	void *where;
	int rom_count;
	int padded_size;
	unsigned char cs;

	if( 2 != argc ) {
		fprintf( stderr, "Usage: %s flash_image_name\n", argv[0] );
		return 1;
	}

	fd = fopen( argv[1], "wb" );
	if( NULL == fd ) {
		fprintf( stderr, "%s: Error opening %s for write.\n", argv[0], argv[1] );
	}

	/* Figure out how many flash units we will write. */
	rom_count = calc_rom_count();
	if (rom_count == -1) {
		return 1;
	}

	where = buffer;

	where = add_noname_flash_header(where, rom_count);

	memmove(where, flash_image, flash_image_size);

	cs = checksum(( unsigned char * )flash_image, flash_image_size );

	padded_size = ( FLASH_SIZE * rom_count );

	buffer[padded_size-1] = ( char )cs;

	fwrite( buffer, 1, padded_size, fd );

	fclose( fd );

	return 0;
}
