PROGRAM INT2ELEK;

PROCEDURE ERROR (STR : STRING);

BEGIN
  WRITELN; WRITELN ('Error in input-file');
  WRITELN (STR);

  HALT(1);
END;


FUNCTION HEXNIBBLE (CAR: CHAR):BYTE;
VAR
  TMP : BYTE;
BEGIN
  IF (CAR>='0') AND (CAR <= '9') THEN TMP:=ORD(CAR)-ORD('0');
  IF (CAR>='A') AND (CAR <='F') THEN TMP:=(ORD(CAR)-ORD('A'))+10;
  HEXNIBBLE:=(TMP AND $0F);
END;

FUNCTION HEXBYTE (STRNG:STRING):BYTE;
VAR
  TMP : BYTE;
BEGIN
  TMP:=HEXNIBBLE(STRNG[2])+(16*HEXNIBBLE(STRNG[1]));;
  HEXBYTE:=TMP;
END;

FUNCTION WORDHEX (INP : WORD): STRING;
VAR T,X:BYTE;STR:STRING;
BEGIN
  STR:='';
  FOR X:=1 TO 4 DO
  BEGIN
    T:=INP AND $0F;
    IF T>9 THEN
      STR:=CHR(T-10+ORD('A'))+STR
    ELSE
      STR:=CHR(T+ORD('0'))+STR;
    INP:=INP DIV 16;
  END;
  WORDHEX:=STR;
END;

FUNCTION HEXWORD (STRNG:STRING):WORD;
VAR
  TMP : WORD;
BEGIN
  TMP:=HEXBYTE(COPY(STRNG,3,2));
  TMP:=TMP+(256*HEXBYTE(COPY(STRNG,1,2)));
  HEXWORD:=TMP;
END;


FUNCTION CONVERT (INSTR: STRING) : STRING;
VAR
  TSTR,STR : STRING;
  LEN,X : WORD;
  CRC : WORD;
BEGIN
  TSTR:=INSTR;STR:='';
  IF INSTR[1]<>':' THEN ERROR (TSTR);
  STR:=COPY (INSTR,2,2)+' '+COPY (INSTR,4,4)+':';
  LEN:=HEXBYTE (COPY(INSTR,2,2));
  CRC:=0;
  FOR X:=2 TO LEN+1 DO
  BEGIN
    STR:=STR+COPY(INSTR,(6+(X*2)),2)+' ';
    CRC:=CRC+HEXBYTE (COPY(INSTR,(6+(X*2)),2));
  END;
  STR:=STR+WORDHEX (CRC);
  IF (HEXBYTE (COPY(INSTR,8,2))=1) THEN STR:='';
  WRITELN (STR);
  CONVERT:=STR;
END;


VAR
  INFILE,OUTFILE : TEXT;
  INFILENAME,OUTFILENAME : STRING;
  LINEIN,LINEOUT: STRING;
  TEST : BYTE;
BEGIN

  WRITELN ('INT2ELEK');
  WRITELN ('(c) 2000 Elektor');
  IF PARAMCOUNT=0 THEN
  BEGIN
    Writeln ('Error!'); Writeln ('Usage : INT2ELEK infile [outfile]');
    Writeln ('If no outfile is given, then ELEKTOR.HEX is used as outfile');
    Halt (1);
  END;
  INFILENAME:=PARAMSTR(1);
  IF PARAMCOUNT>1 THEN OUTFILENAME:=PARAMSTR(2) ELSE OUTFILENAME:='ELEKTOR.HEX';
  Writeln ('Infile :',INFILENAME); Writeln ('Outfile :',OUTFILENAME);
  ASSIGN (INFILE,INFILENAME);
  ASSIGN (OUTFILE,OUTFILENAME);
  {$I-}
  REWRITE (OUTFILE);
  RESET (OUTFILE);
  CLOSE (OUTFILE);
  {$I+}
  IF (IORESULT<>0) THEN
  BEGIN
    WRITELN ('Error creating outfile ',OUTFILENAME);
    Halt(1);
  END;
  {$I-}
  RESET (INFILE);
  CLOSE (INFILE);
  {$I+}
  IF (IORESULT<>0) THEN
  BEGIN
    WRITELN ('Error opening infile ',INFILENAME);
    Halt(1);
  END;
  RESET (INFILE);
  REWRITE (OUTFILE);
  LINEOUT:=' ';
  WHILE (NOT EOF(INFILE)) AND (LINEOUT<>'') DO
  BEGIN
    READLN (INFILE,LINEIN);
    LINEOUT:=CONVERT (LINEIN);
    IF (LINEOUT<>'') THEN WRITELN (OUTFILE,LINEOUT);
  END;
  CLOSE (INFILE);
  CLOSE (OUTFILE);
END.