--[[
Copyright (c) 2010 Peter "Corsix" Cawley

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. --]]

-- Create the data files
assert(loadfile((debug.getinfo(1, "S").source:match("@(.*[" .. package.config
:sub(1, 1) .. "])") or "") .. "mkfont.lua"))("bootstrap_font.bmp", 9, 12, 5)

-- Merge them into bootstrap.cpp
local lines = {}

local function merge(filename, globalname)
  lines[#lines + 1] = "/* Data from " .. filename .. " inserted by mkbootstrap.lua: */"
  lines[#lines + 1] = "const unsigned char " .. globalname .. "[] = {"
  local f = assert(io.open(filename, "rb"))
  while true do
    local s = f:read(13)
    if s == nil then
      break
    end
    lines[#lines + 1] = s:gsub(".", function(c) return ("0x%.02X, "):format(c:byte()) end)
  end
  lines[#lines] = lines[#lines]:sub(1, -3)
  f:close()
  lines[#lines + 1] = "};"
end

local f, s, l = assert(io.lines("../Src/bootstrap.cpp"))
repeat
  l = f(s, l)
  lines[#lines + 1] = l
until l == "/* Start autogenerated content */"
merge("bootstrap_font.tab", "g_aBootstrapFontTab")
merge("bootstrap_font.dat", "g_aBootstrapFontDat")
merge("bootstrap_font.pal", "g_aBootstrapFontPal")
while l ~= "/* End autogenerated content */" do
  l = f(s, l)
end
while l do
  lines[#lines + 1] = l
  l = f(s, l)
end

local linebreak = io.open("mkbootstrap.lua", "rb"):read(2000):match"[\r\n]+"
io.open("../Src/bootstrap.cpp", "wb"):write(table.concat(lines, linebreak))
