#! lua
-- rlua8

local pad in require "pad"

local dim, sys, $ in require "riscos"

-- load window win from template file tfile
-- return two buffers
local loadone = \ (tfile, win)
  local  name = dim (12)
  local  ok = sys (0x400d9, 0, tfile) -- Wimp_OpenTemplate
  assert (ok, "Cannot load template file")
  local r0, r1, r2, r3, r4, r5, r6
  local y = dim (0)
  $[name] = pad (win, 12, 0)
  r0, r1, r2, r3, r4, r5, r6 = sys (0x400db, 0, 0, y, y, -1, name, 0)
  if r6 == 0 then => nil, "Cannot find template" end -- if
  local buf = dim (r1)
  local indir = dim (r2)
  sys (0x400db, 0, buf, indir, indir + r2, -1, name, 0) -- Wimp_LoadTemplate
  sys (0x400da) -- Wimp_CloseTemplate
  => { data = buf, ind = (r2 > 0) and indir }
  end -- function

-- indir buffer for indirected data

-- return list of window names from template file t_file
-- matching pattern pat
local find = \ (t_file, pat)
    local pat = (pat or "*") .. "\r"
    local w = { }
    local ok = sys (0x400d9, 0, t_file) -- Wimp_OpenTemplate
    assert (ok, "Cannot load template file")
    local wild = dim (12)
    local work = dim (0)
    $[wild] = pat
    local r0, r1, r2, r3, r4, r5, r6 =
       sys (0x400db, 0, 0, work, work+1, -1, wild, 0)
    while r6 > 0  do
      w[1 + #w] = $ (r5)
      $[wild] = pat
      r0, r1, r2, r3, r4, r5, r6 =
      sys (0x400db, 0, 0, work, work+1, -1, wild, r6)
     end -- while
     sys (0x400da) -- Wimp_CloseTemplate
     => w
 end -- function

-- return a table, indexed by window names matching pattern pat,
-- of pairs of buffers from template file t_file
local load = \ (t_file, pat)
      local win_bufs = { }
      local wins = find (t_file, pat)
      for _, win in ipairs (wins) do
        win_bufs[win] = loadone (t_file, win)
      end -- for
      => win_bufs
      end -- function

=> { load = load }
