/*
Copyright (C) 2002 Pedro Zorzenon Neto <pzn@vztech.com.br>

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

Do not forget to visit Free Software Foundation site: http://fsf.org

$Id: txt2ihex.c,v 1.2 2003/06/30 17:20:25 pzn Exp $
*/
#include "common.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "intelhex.h"

int main (int argc, char *argv[]) {

  inteldata ihex;
  FILE *f;
  char l[780]; /* > (256*3)+5 */

  if ( argc == 2 ) {
    if ( (strcmp(argv[1],"--help")) ||
	 (strcmp(argv[1],"-h")) ||
	 (strcmp(argv[1],"-?")) ||
	 (strcmp(argv[1],"--usage")) ||
	 (strcmp(argv[1],"/?")) ) {
      fprintf(stderr,"txt2ihex is free software with ABSOLUTELY "
	      "NO WARRANTY. \nCopyright (c) 2002 - Pedro Zorzenon "
	      "Neto.\ntxt2ihex: converts simple text format to "
	      "Intelhex format\nUsage: txt2ihex inputfilename.txt "
	      "outputfilename.hex\nWarning: outputfilename.hex will "
	      "be overwritten.\n");
      return 1;
    }
  }

  if ( argc != 3 ) {
    fprintf(stderr,"Try: txt2ihex --help\n");
    return 1;
  }

  f=fopen(argv[1],"r");
  if (f==NULL) {
    perror("Error opening input file");
    abort();
  }
  intelhex_fileopen ( &ihex, argv[2], 0);

  fgets(l, 779, f);
  while ( feof(f)==0 ) {
    unsigned int offset;
    int i=0;
    char *s;

    s=strtok(l," ");
    offset=(unsigned int)strtol(s,NULL,16);
    ihex.offset=offset;

    s=strtok(NULL," ");
    while (s != NULL) {
      ihex.recdata[i]= 0xFF & strtol(s,NULL,16);
      i++;
      ihex.reclen=i;
      s=strtok(NULL," ");
    }
    intelhex_writeline (&ihex);
    fgets(l, 779, f);
  }

  fclose(f);
  intelhex_writeeof (&ihex);
  intelhex_fileclose (&ihex);

  return 0;
}
