#!/usr/bin/env lua

local shift = '^'   -- prefix of blanks to remove

if arg[1] and arg[1]:find '^%-%d+$' then
  shift = '^' .. string.rep(' ', -tonumber(arg[1]))
  table.remove(arg, 1)
end

local outputs = { } -- map filename to list of lines
setmetatable(outputs, { __index = function(t, k) local u = {}; t[k] = u; return u end })

local function add_modified_line(lines, l)
  if l:find '%{ fact_name%s+='
    or l:find '^%s*%-%- See Note '
  then
    return
  end
  l = l:gsub('%s*%-%- Note %[.*$', '')
  l = l:gsub('%s*%-%- I do not understand.*$', '')
  l = l:gsub('^(%s*),( fact_bot)', '%1{%2')
--  l = l:gsub('^(%s*, fact_join = .*)$', '%1 }')
  l = l:gsub('%s*%-%-%s%^.*$', '')
  l = l:gsub('CheckpointMonad', 'CkpointMonad')
  return table.insert(lines, l)
end


local function shift_left(l, n)
  l = l:gsub('^' .. string.rep(' ', n), '')
  return l
end

for _, file in ipairs(arg) do
  local outfile, distance
  for l in io.lines(file) do
    local action, filename, n = l:match '^%s*%-%-%s%@%s+(%w+)%s+(%S+)%s+%-(%d+)%s*$'
    if not n then
      action, filename = l:match '^%s*%-%-%s%@%s+(%w+)%s+(%S+)%s*$'
      n = action and 0
    end
    if action == 'start' then
      assert(outfile == nil and distance == nil)
      outfile, distance = filename, n
    elseif action == 'stop' or action == 'end' then
      assert(outfile, '@stop without @start: ' .. l)
      assert(outfile == filename, l .. 'does not match @start ' .. outfile)
      outfile, distance = nil, nil
    elseif action ~= nil then
      error("Unknown action '" .. action .. "' in line " .. l)
    else
      if outfile then
        add_modified_line(outputs[outfile], shift_left(l, distance))
      end
    end
  end
end

for file, lines in pairs(outputs) do
  local f = assert(io.open(file, 'w'))
  local do_shift = true
  for _, l in ipairs(lines) do
    if not l:find(shift) then
      do_shift = false
      break
    end
  end
  for _, l in ipairs(lines) do
    f:write(do_shift and l:gsub(shift, '') or l, '\n')
  end
  f:close()
end

      
      