--
-- Usage: require('thisfile');
--

local ihex_address = 0x0000;

function ihex_reset()
	ihex_address = 0x0000;
end

function ihex_set( value )
    ihex_address = value;
end

function table.byte(t,i)
    return( t[i] );
end

function table.len(t)
    return( #t );
end
--
-- Input : string or an array of byte-values and an optional length
-- If the first parameter is a table, then it gets 2 additional method-fields
-- that type 'string' already has by itself.
--
-- Outputs a ihex-format record containing 'len' bytes,
-- starting from byte 'start' (default: first)
-- and updates global ihex_address
--
--
function ihex_datarecord(buf,len,start)
    start = (start or 1) - 1;
    if( type(buf) == 'table' ) then -- Add 'string' methods that 'table' misses.
        buf.byte = table.byte; buf.len = table.len;
    end

	local ourLen = len or buf:len();
	local ourSum = ourLen;

	io.write( string.format(':%02X%04X00',ourLen,ihex_address) );

	for i=1,ourLen do
        local ourByte = buf:byte(i+start) ;
        ourSum = ourSum + ourByte;
        io.write( string.format('%02X', ourByte ) );
    end

	ourSum = ourSum + bit32.band(ihex_address,0xff);
	ourSum = ourSum + bit32.band( bit32.rshift(ihex_address,8),0xff);

	ourSum = bit32.bnot(ourSum) + 1;
	ourSum = bit32.band(ourSum,0xff);

	io.write( string.format('%02X', ourSum ) );
	io.write( '\n' );

	ihex_address = ihex_address + ourLen;
end

function ihex_endrecord()
	io.write(':00000001FF\n');
end

-- EOF --
