/* ------------------------------------------------------------------------

File   : hexline.c

Descr  : Create an INTEL-HEX formatted line, including the checksum;
         it requires an address (where it will be stored in EEPROM)
	 and a sequence of bytes.
         
--------------------------------------------------------------------------- */

#include <stdio.h>

#define LINE_MARKER     ':'
#define DATA_BLOCKTYPE  0

void usage();

/*---------------------------------------------------------------------------*/

int main( int argc, char *argv[] )
{
  int address, data[20], checksum=0, no_of_databytes=0, i;

  if( argc < 3 ) usage();

  /* The address */
  sscanf( argv[1], "%x", &address );
  if( address < 0 || address > 0xffff )
    {
      printf( "###Error in address (%x)\n", address );
      exit(1);
    }
  data[0] = (address & 0xff00) >> 8;
  data[1] = address & 0xff;
  printf( "address=%x\n", address );

  printf( "data=", address );
  for( i=2; i<argc; ++i )
    {
      sscanf( argv[i], "%x", &data[i] );
      if( data[i] < 0 || data[i] > 0xff )
	{
	  printf( "###Error in databyte (%x)\n", data[i] );
	  exit(1);
	}
      printf( "%x ", data[i] );
      ++no_of_databytes;
    }
  printf( "\n" );

  /* Calculate checksum */
  checksum = no_of_databytes;
  for( i=0; i<2+no_of_databytes; ++i ) checksum += data[i];
  checksum = ((~checksum) & 0xff) + 1;

  printf( "Resulting INTELHEX-data:\n" );
  if( no_of_databytes < 16 )
    {
      printf( ":0%1x", no_of_databytes );
    }
  else printf( ":%2x", no_of_databytes );
  for( i=0; i<2; ++i )
    {
      if( data[i] < 16 )
	{
	  printf( "0%1x", data[i] );
	}
      else printf( "%2x", data[i] );
    }
  printf( "00" );
  for( i=2; i<2+no_of_databytes; ++i )
    {
      if( data[i] < 16 )
	{
	  printf( "0%1x", data[i] );
	}
      else printf( "%2x", data[i] );
    }
  if( checksum < 16 )
    {
      printf( "0%1x", checksum );
    }
  else printf( "%2x", checksum );
  printf( "\n" );
  printf( ":00000001ff\n" );
}

/*---------------------------------------------------------------------------*/

void usage()
{
  printf("Usage: hexline <address> <databyte1> [<databyte2>....]\n");
  exit(1);
}

/*---------------------------------------------------------------------------*/

