get_offset = 0x80

local ii_help_start = [[
-- WARNING: auto-generated by util/ii_lua_help.lua
-- DO NOT EDIT BY HAND

local Is = {}
Is.lu={}

function Is.new( name, address )
    local self = {}
    self.name = name
    if type(address)=='table' then
        self.help = function() ii.m_help(address[1]) end
    else
        self.help = function() ii.m_help(address) end
    end
    setmetatable( self, Is )
    if type(address)=='table' then
        for k,v in ipairs(address) do
            Is.lu[v] = {name,k}
        end
    else
        Is.lu[address] = name
    end
    return self
end

function Is.lookup( addr )
    local a=Is.lu[addr]
    if type(a)=='table' then
        return a[1],a[2] -- name & device index
    else
        return a
    end
end

function Is.openlib( self )
    local n = self.name
    if not rawget(ii, n) then -- confirm it hasnn't been loaded (handles pre-openlib aliases)
        collectgarbage()
        collectgarbage()
        ii[n] = dofile(string.format('build/ii_%s.lua',n))
        ii[n].help = self.help
    end
    return ii[n]
end

Is.__index = function( self, ix )
    return Is.openlib(self)[ix]
end

Is.__newindex = function( self, ix, val )
    Is.openlib(self)[ix] = val
end

]]

function ii_help_body( files )
    local h = ''
    for _,f in ipairs(files) do
        h = h .. 'Is.' ..  f.lua_name .. '=Is.new(\'' .. f.lua_name .. '\','
        if type(f.i2c_address) == 'table' then
            h = h .. '{'
            for k,v in ipairs(f.i2c_address) do
                h = h .. v .. ','
            end
            h = h .. '}'
        else
            h = h .. f.i2c_address
        end
        h = h .. ')\n'
    end
    return h
end

local ii_help_end = [[
setmetatable(Is, Is)

return Is
]]

function make_iihelp(files)
    return ii_help_start
        .. ii_help_body(files)
        .. ii_help_end
end

local in_file_dir = arg[1]
local out_file = arg[2]

do
    dir = io.popen('/bin/ls ' .. in_file_dir)
    files = {}
    for filename in dir:lines() do
        table.insert(files, dofile('lua/ii/' .. filename))
    end

    f = io.open( out_file, 'w' )
    f:write(make_iihelp(files))
    f:close()
end

-- example usage:
-- lua util/ii_lua_help.lua lua/ii/ build/ii_help.lua
