-- character creation

--  CGS_MAIN = 0,
--  CGS_STARSIGN = 1,
--  CGS_SEX = 2,
--  CGS_RACE = 3,
--  CGS_PLAYER_CLASS = 4,
--  CGS_ATTRIBUTES_SELECTION = 5,
--  CGS_ATTRIBUTES_QUESTIONS = 6,
--  CGS_ATTRIBUTES_POINTS = 7,
--  CGS_BACKGROUND = 8,
--  CGS_TALENT = 9,
--  CGS_NAME = 10

local prec = nil

function initprec()
  if prec == nil then
    prec = {}
    prec.races = adom_nelib_get_all_races()
    prec.star_signs = adom_nelib_get_all_star_signs()
    prec.classes = adom_nelib_get_all_classes()
    prec.sextable = adom_nelib_get_all_sexes()
    end
  end

dofile("games/adom-intro.noe")

function openchargen(event)
  initprec()

  local i = event.screen
  if i == charactergenerationscreenids.CGS_STARSIGN then
    --openparallax()
    opencharacter("starsign", "Choose a starsign or \v#00AEFFmode", event)
  elseif i == charactergenerationscreenids.CGS_SEX then
    opencharacter("gender", "Choose a gender or \v#00AEFFmode", event)
  elseif i == charactergenerationscreenids.CGS_RACE then
    opencharacter("race", "Choose a race or \v#00AEFFmode", event)
  elseif i == charactergenerationscreenids.CGS_PLAYER_CLASS then
    opencharacter("profession", "Choose a profession or \v#00AEFFmode", event)
  elseif i == charactergenerationscreenids.CGS_ATTRIBUTES_SELECTION then
    opencharacter("attributes_selection", "Choose attributes by ... (or select \v#00AEFFmode\v#FFFFFF)", event)
  elseif i == charactergenerationscreenids.CGS_MAIN then
    opencharmain()
  elseif i == charactergenerationscreenids.CGS_ATTRIBUTES_POINTS then
    opencharstats(event)
  elseif i == charactergenerationscreenids.CGS_BACKGROUND then
    openbackground(event)
  else
    openscreen(nil)
    end
  end

function switchUI()
  print("switchUI called")
  do return end
  openscreen(nil)
  -- detectUI()
  if currentscreen and currentscreen.fullshow then 
    return currentscreen.fullshow() 
    end
  return false
  end

function openstarsign(ev)

  local t = getticks() + 2500
  local m = newmodalwindow("starsign")
  
  function m.fullshow()
--  if not string.find(getline(2), "You are born", 1, true) then
--    return switchUI()
--    end
    if not graphicalUI() then return false end
    
    drawtitleimage(m)

    local all_star_signs = prec.star_signs
    local misc_data = adom_nelib_get_tome_of_knowledge_pc_overview().misc_data
    local mysign = 1 + misc_data.star_sign_of_birth

    drawtile(Gfx, tileshade(0), 0, 0, xscreen.size.x, xscreen.size.y)
    local radius = math.min(xscreen.ctr.x, xscreen.ctr.y) - 35

    if t and getticks() < t then
      local u = (getticks() - t) / 1500
      u = u * u

      for k=1,12 do
        local sign_name = string.lower(all_star_signs[(k+mysign+5)%12+1].star_sign_name)
        drawnonscaled(tiles[nmain1.."starsigns/"..sign_name], 
          xscreen.ctr + V(-math.sin(k*math.pi/6 + u), math.cos(k*math.pi/6 + u)) * radius,
          align_center)
        end
      
      return true
      end
      
    local b = drawgenericbox(xscreen.ctr, V(-.5, -.5))
    
    for k=1,12 do
      local sign_name = string.lower(all_star_signs[(k+mysign+5)%12+1].star_sign_name)
      drawnonscaled(tiles[nmain1.."starsigns/"..sign_name], 
        xscreen.ctr + V(-math.sin(k*math.pi/6), math.cos(k*math.pi/6)) * 160,
        align_center,
        function(x) return tilecol(x, (k==6 and 0xFF000000 or 0xFFE0A000), recMult) end
        )
      end

    local ss = all_star_signs[mysign]
    local day = misc_data.day_of_birth
    local dob = misc_data.day_in_month_of_birth

    local text = 
      style_header.."\n\n\n"..ss.star_sign_name.."\n"..
      style_center.."You are born in the month of the "..ss.star_sign_name.." on day "..dob.." (day "..day.." of the year).\n"..
      style_boldcenter.."\nAspects: "..ss.star_sign_aspects.."\n"..
      style_header.."\nEffects\n"..
      style_center..ss.star_sign_effects.."\n"

    renderlongtext(AlegreyaRegular, 16, text, 0xFF000000, Gfx, b.content)
        
    return true
    end
  
  function m.handlemouse(ev)
    if not graphicalUI() then return false end
    if t and ev.type == evMouseUp then t = nil return true end
    return false
    end

  function m.handlekey(ev)
    if not graphicalUI() then return false end
    if t and ev.type == evKeyDown then t = nil return true end
    return false
    end

  openscreen(m)
  return m
  end

local config_y = xscreen and xscreen.bot.y or 0

function drawconfig()
  do return end
  local y = 0
  while y < 10 and not string.find(getline(24-y), "---") do y = y + 1 end
  if y == 10 then return end
  y = y + 1
  IMGL = renewscreen(IMGL, 80, y)
  scrcopy(S, 0, 25-y, IMGL, 0, 0, 80, y, tmap_shade)
  local zy = y
  if y > 2 and xscreen.bot.y <= 500 and not string.find(getline(2), "[f]ate decide", 1, true) then zy = 1 end
  config_y = xscreen.bot.y - zy * guifontsize.y
  V.drawscreen(Gfx, IMGL, V(xscreen.ctr.x - 40 * guifontsize.x, config_y), guifontsize)
  end

local function gethotkey(key)
  return "\n"..style_center.."\n\v#C06000hotkey: ["..key.."]\n"..style_normal
  end

    
function opencharacter(what, title, event)

  config_y = xscreen and xscreen.bot.y
  local m = newmodalwindow("char")

  local last_equipment_time = 0
  local last_equipment = nil
  local last_button = nil

  function m.fullshow()
    if not graphicalUI() then return false end
    
    drawtitleimage(m)
    drawconfig()
    
    local y = math.max(config_y/2, tiles[nmain1.."select_info"].size.y/2)
    
    local selctr = V(xscreen.ctr.x - 200, y)
    local infoctr = V(xscreen.ctr.x + 200, y)
    
    local btn = drawselectbuttons(selctr, V(-.5, -.5))
    
    local inf = drawselectinfobox(infoctr, V(-.5, -.5))

    local misc_data = adom_nelib_get_tome_of_knowledge_pc_overview().misc_data
      
    rendertext(GermaniaOne, 18, title, 0xFFFFFFFF, Gfx, btn.title, align_center)
    
    m.options = {}
    
    local function gettitle(t)
      return 
        style_header..t.."\n\n"..style_normal
      end

    local selected
    
    local function loaddata()
      PCData = {}
      
      local x = selected or {}

      PCData.starsign = x.starsign or (what ~= "starsign" and misc_data.star_sign_of_birth)
      PCData.sex = x.sex or (what ~= "sex" and misc_data.sex)
      PCData.race = x.race or (what ~= "race" and misc_data.race)
      PCData.class = x.class or (what ~= "profession" and misc_data.class)

      if PCData.class and PCData.race then
        if (getticks() > last_equipment_time + 500) then
          last_equipment = adom_nelib_get_starting_equipment(PCData.class, PCData.race).body_part
          last_equipment_time = getticks()
          end
        PCData.body_part = last_equipment
      else
        PCData.body_part = {}
        PCData.body_part[1 + bodypartids.LEFT_HAND] = {item_weapon_type = -1}
        PCData.body_part[1 + bodypartids.RIGHT_HAND] = {item_weapon_type = -1}
        PCData.body_part[1 + bodypartids.MISSILE_WEAPON] = {item_weapon_type = -1}
        PCData.body_part[1 + bodypartids.MISSILES] = {item_weapon_type = -1}
        PCData.body_part[1 + bodypartids.CLOAK] = {item = -1}
        end
      end
      
    local function drawpc()
      local tt
      
      if not PCData.race then
        tt = 
          (PCData.sex == 0) and tiles[nmain1.."ico_male_glow"] or 
          (PCData.sex == 1) and tiles[nmain1.."ico_female_glow"] or
          {t=0}
      
      else
        PCData.sex = PCData.sex or 0
        PCData.race = PCData.race or 0
        PCData.class = PCData.class or 0
        local obj = {direction = 0}    
        local img = getpctile(obj)
        tt = {t = img, size = obj.size}
        end

      drawnonscaled(tt, inf.char + V(0, -7), align_center)

      if PCData.starsign and PCData.starsign >= 0 and PCData.starsign < 12 then
        local sign_name = prec.star_signs[PCData.starsign+1].star_sign_name
        sign_name = string.lower(sign_name)
        drawnonscaled(tiles[nmain1.."starsigns/"..sign_name], inf.char + V(64,-10))
        end

      end
    
    local function addblueoption(text, icon, desc, key, x)
      local t = 
        {text = "\v#00AEFF"..text, icon = icon, desc = gettitle(text)..desc..gethotkey(key), key = key,
         y = 8, x = x}
      table.insert(m.options, t)
      end

    local function addoptionpc(text, x, desc, key)
      x.text = text
      x.desc = gettitle(text)..desc..gethotkey(key)
      x.key = key
      x.func = drawpc
      table.insert(m.options, x)
      end
    
    if what == "gender" then
      addoptionpc("Male", {sex=0, x=0.5, y=1}, "Male characters are slightly stronger.", "m")
      addoptionpc("Female", {sex=1, x=1.5, y=1}, "Female characters are more agile.", "f")

    elseif what == "race" then
      -- reset class descriptions, they depend on the race selection
      local r = prec.races
      for i=1,r.max_race do
        addoptionpc(r[i].race_name, {race=i-1}, (r[i].race_description_short or "?"), string.char(96+i))
        end

    elseif what == "starsign" then
      local r = prec.star_signs
      for i=1,r.max_star_sign do
        addoptionpc(r[i].star_sign_name or "?", {starsign=i-1}, (r[i].star_sign_aspects .. "\n\n" .. r[i].star_sign_effects), string.char(96+i))
        end
    
    elseif what == "profession" then
      local r = prec.classes
      for i=1,r.max_class do
        addoptionpc(r[i].class_name or "?", {class=i-1}, (r[i].class_description_short or "?"), string.char(96+i))
        end

    elseif what == "attributes_selection" then
      addoptionpc("Questions", {x=.5, y=1}, "You select the result by answering a series of questions.", "q")
      addoptionpc("Points", {x=1.5, y=1}, "You select the specific result based on a point-based system.", "p")
      end

      addblueoption("Fate", {t=0}, "The result of the step will be determined by Fate (randomly).", " ", 0)
      if event.is_first_phase == true then
        addblueoption("Chaotic", {t=0}, "Sometimes you can decide, sometimes Fate decides (randomly).", ",", 1)
        addblueoption("Spontaneous", {t=0}, "You get to choose the specific mode for the step each time.", ".", 2)
        end
    
    local txt = style_center.."\n\n\n\nPlease select one of the options."
    local icon = nil

    local buttonsize = tiles[nmain1.."btn_select_off"].size - V(0,8)
    
    local btnsel = use20 and (nmain.."charselect_frame") or nmain1.."btn_select"
    local btnsel1 = use20 and (nmain.."charselect_frame") or nmain1.."btn_select_off"

    tiles[btnsel].buttonsize = buttonsize
    tiles[btnsel].captionoffset = V(0,4)

    for k,v in pairs(m.options) do
      v.button = drawbutton(btnsel, 
        rectat(btn.content, V((v.x or (k-1)%3) / 3 + 1/6, math.floor((v.y or (k-1)/3)) / 10 + 1/20)), 
        align_center, use20
        )
      buttoncaption(v.button, GermaniaOne, 18, v.text)
      if v.button.over or v.button.down then
        txt = v.desc
        selected = v
        end
      if v.button.over then
        if (last_button ~= v.text) then
          last_button = v.text
          last_equipment_time = 0
          end
        end
      end
    
    loaddata()
    
    local coverat = inf.char + (PCData.starsign and V(33, -3) or V(1, -4))
    
    if PCData.starsign then
      drawnonscaled(tiles[nmain.."story_cover_bg"], coverat, align_center)
    else
      drawnonscaled(tiles[nmain.."charselect_bg"], coverat + V(-1,0), align_center)
      end
    
    drawpc()

    if (what ~= "sex" and what ~= "gender") or Global.is_deluxe then
      if what == "sex" or what == "gender" then
        m.back = drawshortbutton("Back", nil, 0, btn.bottombutton, V(-.5, -.3))
      else
        m.help = drawshortbutton("Help", nil, 0, btn.bottombutton, V(-1.1, -.3))
        m.back = drawshortbutton("Back", nil, 0, btn.bottombutton, V(0.1, -.3))
        end
      if m.back.over or m.back.down then
        txt = gettitle("Back").."Change one of the previous selections."..gethotkey("-")
        end
      if m.help and (m.help.over or m.help.down) then
        txt = gettitle("Help").."More information about the choices on this screen."..gethotkey("?")
        end
      end
    
    renderlongtext(AlegreyaRegular, 16,   
      txt, 
      0xFF59261E, Gfx, inf.content)
    
    -- rendertext(GermaniaOne, 18, "???", 0xFF000000, Gfx, inf.desc, align_center)

    if icon then
      drawnonscaled(icon, inf.char, align_center)
      end

    local dz = math.floor(getticks() / 100) % 8 + 1
    local dx = 0 -- math.random(-2, 2)
    local dy = 0 -- math.random(-2, 2)

    if not use20 then 
      drawnonscaled(tiles[nmain1.."flame/frame0"..dz], inf.char + V(49,-26), align_center)
      
      local function randomtrans(x) 
        local c = math.random(12,17) * 15 * 0x1000000 + 0xFFFFFF
        return tilecol(x, c, recMult)
        end
    
      drawnonscaled(tiles[nmain1.."flame/glow_floor"], inf.char + V(49+dx,25), align_center, randomtrans)
      drawnonscaled(tiles[nmain1.."flame/glow"], inf.char + V(49+dx,-26+dy), align_center, randomtrans)
      end

    if PCData.starsign then
      drawnonscaled(tiles[nmain.."story_cover"], coverat, align_center)
    else
      drawnonscaled(tiles[nmain.."charselect_cover"], coverat, align_center)
      end

    return true
    end
  
  function m.handlemouse(ev)
    if not graphicalUI() then return false end
    for k,v in pairs(m.options or {}) do
      if buttonclicked(ev, v.button) then 
        nsendtext(v.key)
        end
      end
    if buttonclicked(ev, m.back) then
      nsendtext("-")
      end
    if buttonclicked(ev, m.help) then
      nsendtext("?")
      end
    if ev.type == evMouseDown and ev.y >= config_y then
      nsendtext("!")
      end
    return true
    end

  openscreen(m)
  return m
  end

function opencharmain(what)

  config_y = xscreen and xscreen.bot.y
  local m = newmodalwindow("charmain")
  
  function m.fullshow()
    if not graphicalUI() then return false end
    
    drawtitleimage(m)
    drawconfig()
    
    local y = math.max(config_y/2, tiles[nmain1.."select_info"].size.y/2)
    
    local selctr = V(xscreen.ctr.x - 200, y)
    local infoctr = V(xscreen.ctr.x + 200, y)
    
    local btn = drawselectbuttons(selctr, V(-.5, -.5))
    local prevgame = drawgameinfobox(infoctr, V(-.5, -.5))
    
    local boxat = btn.content.top + V(5,5)
    local textat = boxat + V(60,18)
    local nrow = V(0,31)
    local secondbox = V(0,170)
    
    drawnonscaled(tiles[nmain.."game_setup_ui"], boxat)
    drawnonscaled(tiles[nmain.."game_setup_ui"], boxat + secondbox)

    local function colorcaption(text, index)
      if index and index > 0 then
        return "\v#FFD500"..(text:sub(1,index) or "").."\v#FFFFFF"..text:sub((index or 0)+1)
        end
      return text
      end

    local function gamesel_table(cgsel, previous)

      local function namesel(selmode, windex, wtable, wfield)
        local csm = criteriaselectionmodeids
        local wsel = windex and wtable and wtable[windex+1] and wtable[windex+1][wfield] or ""
        local wsel_par = (wsel and wsel ~= "" and previous and " ("..wsel..")") or ""
        if selmode == csm.CSM_SELECTED_SPONTANEOUSLY then return "Spontaneous"..wsel_par
        elseif selmode == csm.CSM_SELECTED_BY_FATE then return "Let Fate Decide"..wsel_par
        elseif selmode == csm.CSM_SELECTED_CHAOTICALLY then return "Chaotic"..wsel_par
        elseif selmode == csm.CSM_SELECTED_BY_PLAYER then return wsel
        elseif selmode == csm.CSM_SELECTED_BASED_ON_POINTS then return "Points"
        elseif selmode == csm.CSM_SELECTED_BASED_ON_STORY then return "Questions"
        end
        end
      
      -- print(printtableline(cgsel))
      local gco = cgsel.game_customization_options
      
      local btable = {}
      
      btable[0] = {"Starsign", namesel(cgsel.selection_mode_starsign, cgsel.starsign, prec.star_signs, "star_sign_name"), "s", "s", 1, "In Ancardia magic energies influence one's life depending on the time of birth. Each month is named after a particular star sign. It has notable effects on the characters' career, your character will also be slightly favored during the month named after his starsign."}
      btable[1] = {"Gender", namesel(cgsel.selection_mode_sex, cgsel.sex, prec.sextable, "sex_name"), "g", "g", 1, "Gender has a very minor influence on your characters abilities. Males of all races tend to be a bit stronger while females slightly more dexterous."}
      btable[2] = {"Race", namesel(cgsel.selection_mode_race, cgsel.race, prec.races, "race_name"), "r", "r", 1, "A wide variety of races can be chosen for your player character. Each has certain advantages and disadvantages and receives different equipment, attributes and starting skills."}
      btable[3] = {"Profession", namesel(cgsel.selection_mode_player_class, cgsel.player_class, prec.classes, "class_name"), "p", "p", 1, "Every character belongs to a certain profession which describes what he learned in his youth. It determines starting skills and gives a set of special powers acquired with experience."}
      btable[4] = {"Attributes", namesel(cgsel.selection_mode_attributes, nil, nil, nil), "a", "a", 1, "Every character is determined by nine attributes which represent his abilities by birthright. Attributes are rated from 1 to 99 (in theory). 10 is average, 8 slightly below, 17 exceptional and anything above 20 is considered epic."}
      btable[5] = {"Corruption", gco.corruption_active and "On" or "Off", "c", "c", 1, "Turns background corruption on or off."}
      btable[6] = {"Hunger", gco.hunger_active and "On" or "Off", "h", "h", 1, "Toggle the need for your character to nourish himself. Turning hunger off makes early game substantially easier."}
      local mnames = {"Wimpy", "Standard", "Tough"}
      local tnames = {"Few", "Standard", "Many"}
      btable[7] = {"Monsters", mnames [1+gco.monster_difficulty], "m", "m", 1, "How difficult are the monsters you encounter on your journey."}
      btable[8] = {"Death", gco.rpg_mode and "Reloadable games" or "Permanent", "d", "d", 1, "Permanent death means your savegame will be deleted when your character dies. Turning this off allows you to enjoy ADOM more like a regular RPG game - you can still restore your last save after death."}
      btable[9] = {"Treasures", tnames [1+gco.treasure_rate], "t", "t", 1, "The rate at which items are randomly generated."}

      return btable
      end

    local cgs = adom_nelib_current_game_selection()

    m.btable = gamesel_table(cgs)

    m.prevtable = gamesel_table(adom_nelib_previous_game_selection(), true)

    for y=0,9 do
      local coord = textat + nrow * (y % 5)
      if y >= 5 then coord = coord + secondbox end
      rendertext(GermaniaOne, 16, colorcaption(m.btable[y][1], m.btable[y][5]), 0xFFFFFFFF, Gfx, coord, align_center)
      rendertext(GermaniaOne, 16, m.btable[y][2], 0xFFFFFFFF, Gfx, coord + V(166,0), align_center)
      m.btable[y].main = drawbutton(nmain.."game_setup", coord + V(168,-1), V(-.5,-.5))
      end

    rendertext(GermaniaOne, 18, "Game Setup", 0xFFFFFFFF, Gfx, btn.title, align_center)
    
    m.geekcode = rendertext(GermaniaOne, 16, cgs.game_customization_options.geek_code or " ", 0xFFAAAAAA, Gfx, textat + secondbox*2 + V(-57, -15), align_lcenter)
    m.highscore = rendertext(GermaniaOne, 16, "Highscore: "..(cgs.game_customization_options.score_percentage or -1).."%", 0xFFAAAAAA, Gfx, textat + secondbox*2 + V(255,-15), align_rcenter)
    
    -- V.drawtile(D.output, tileshade(0x80800000), prevgame.downbuttons)

    m.back = drawshortbutton("Back", nil, 0, rectat(btn.content, V(0.25, .98)), V(-.5, -.5))
    m.play = drawshortbutton("Play!", nil, 0, rectat(btn.content, V(0.75, .98)), V(-.5, -.5))

    m.btnload = 
      drawsmallbutton(tiles[nmain.."btn_symbol_load"], prevgame.downbuttons.bot - V(15,25), V(-.5, -.5))
    m.btnsave = 
      drawsmallbutton(tiles[nmain.."btn_symbol_save"], prevgame.downbuttons.bot - V(46,25), V(-.5, -.5))
    m.btnplayprev = 
      drawsmallbutton(tiles[nmain.."btn_symbol_playprev"], prevgame.downbuttons.bot - V(77,25), V(-.5, -.5))
    m.btnplayprev2 = 
      drawsmallbutton(tiles[nmain.."btn_symbol_playprev2"], prevgame.downbuttons.bot - V(108,25), V(-.5, -.5))
    m.btnreset = 
      drawsmallbutton(tiles[nmain.."btn_symbol_reset"], prevgame.downbuttons.bot - V(139,25), V(-.5, -.5))

    -- render tooltip or previous game data
    local tooltip_title = nil
    local tooltip_text = nil

    for y=0,9 do
      local coord = textat + nrow * (y % 5)
      local button = m.btable[y].main
      local mouseregion = rectTB(button.top - V(144,0), button.bot)
      if button.over or button.down or (mousepos and inrect(mousepos, mouseregion)) then
        tooltip_title = m.btable[y][1]
        tooltip_text = m.btable[y][6]..gethotkey(m.btable[y][4])
        end
      end

    if m.back.over or m.back.down then
      tooltip_title = "Back"
      tooltip_text = "Change one of the previous selections."..gethotkey("-")
    elseif m.play.over or m.play.down then
      tooltip_title = "Play"
      tooltip_text = "Continue and play the game."..gethotkey(" ")
    elseif m.btnload.over or m.btnload.down then
      tooltip_title = "Load Game Mode Setup"
      tooltip_text = "Load current game mode setup from slot."..gethotkey("<")
    elseif m.btnsave.over or m.btnsave.down then
      tooltip_title = "Save Game Mode Setup"
      tooltip_text = "Save current game mode setup to slot."..gethotkey(">")
    elseif m.btnplayprev.over or m.btnplayprev.down then
      tooltip_title = "Play Last Mode"
      tooltip_text = "Use game rules settings from the last mode but current character generation settings."..gethotkey("l")
    elseif m.btnplayprev2.over or m.btnplayprev2.down then
      tooltip_title = "Play Last Selection"
      tooltip_text = "Play now using previous character generation and game settings."..gethotkey("L")
    elseif m.btnreset.over or m.btnreset.down then
      tooltip_title = "Reset Settings"
      tooltip_text = "Reset the game customization settings."..gethotkey("!")
    elseif mousepos and inrect(mousepos, m.geekcode) then
      tooltip_title = "Geek Code"
      tooltip_text = "Used to quickly describe your game settings:\n\nC stands for corruption, H means Hunger, M monsters, D death and T treasures. 0 is off, 1 is on, \"=\" means standard, \"+\" increased and \"-\" decreased.\n\nFor example C0 indicates corruption was turned off, M+ stands for Tough Monsters setting, etc."
    elseif mousepos and inrect(mousepos, m.highscore) then
      tooltip_title = "Highscore"
      tooltip_text = "The highscore percentage you receive for the current game customization."
      end

    if tooltip_title then
      rendertext(GermaniaOne, 18, tooltip_title, 0xFF603000, Gfx, prevgame.title, align_center)
      renderlongtext(AlegreyaRegular, 16, tooltip_text, 0xFF603000, Gfx, prevgame.content)
    else
      rendertext(GermaniaOne, 18, "Previous Game", 0xFF603000, Gfx, prevgame.title, align_center)

      for y=0,9 do
        local coord = prevgame.content.top + V(50,16) + V(0,23) * (y % 5)
        if y >= 5 then coord = coord + V(0, 140) end
        rendertext(AlegreyaBold, 16, m.prevtable[y][1], 0xFF603000, Gfx, coord, align_center)
        rendertext(AlegreyaRegular, 16, m.prevtable[y][2], 0xFF603000, Gfx, coord + V(160,0), align_center)
        end
      end

    return true
    end
  
  function m.handlemouse(ev)
    if not graphicalUI() then return false end
--  for k,v in pairs(m.options or {}) do
--    if buttonclicked(ev, v.button) then 
--      nsendtext(v.key)
--      end
--    end
    if buttonclicked(ev, m.back) then
      nsendtext("-")
      end
    if buttonclicked(ev, m.play) then
      nsendtext(" ")
      end
    if buttonclicked(ev, m.btnsave) then
      nsendtext(">")
      end
    if buttonclicked(ev, m.btnload) then
      nsendtext("<")
      end
    if buttonclicked(ev, m.btnplayprev) then
      nsendtext("l")
      end
    if buttonclicked(ev, m.btnplayprev2) then
      nsendtext("L")
      end
    if buttonclicked(ev, m.btnreset) then
      nsendtext("!")
      end
--  if ev.type == evMouseDown and ev.y >= config_y then
--    nsendtext("!")
--    end
    for y=0,9 do 
      if not m.btable then print("btable missing!")
      elseif buttonclicked(ev, m.btable[y].main) then nsendtext(m.btable[y][4]) end
      end
    return true
    end

  openscreen(m)
  return m
  end

function opencharstats(event)

  config_y = xscreen and xscreen.bot.y
  local m = newmodalwindow("charstats")

  local colnormal = 0xFF59261E
  local colmin = 0xFFE33A0C
  local colmax = 0xFF3FE413
  local colstarsign = 0xFFFFA614
  local colgender = 0xFF0063D2
  local colclass = 0xFFD737A8

  local tooltips = {}

  tooltips[1] = "Strength describes your ability to inflict damage in combat, determines your carrying capacity and influences your chance to hit opponents in melee combat. Initial hitpoints are also partially based upon strength."
  tooltips[2] = "Learning score describes how easily your character learns new things, how good the PC is at increasing skills and how easily magical spells are learned. Your ability to read and write (no, that's not automatic!) is also influenced by this score."
  tooltips[3] = "Your characters' strength of your will. The higher it is, the better your PC is able to resist attacks affecting his mind. Willpower influences your initial hit points and your initial magic points."
  tooltips[4] = "Rates your agility, nimbleness, speed and many other things. A high dexterity score allows you to better dodge enemy attacks and traps. PCs with low dexterity are clumsy and slow-moving... easy prey for your enemies. Dexterity is also very important when attacking."
  tooltips[5] = "Your characters' physical resistance, endurance, constitution and resistance to pain. Toughness is a major factor influencing the number of hit points of your character."
  tooltips[6] = "Describes the personality of your character. PCs with a high charisma are outgoing, friendly and easily make friends, while characters with low charisma are disliked by many people and have difficulties interacting on a friendly and easy-going basis."
  tooltips[7] = "Physical appearance and natural grace of your character. Each point above 10 makes the character more resistant to corruption by adding 1% more points required to transform the character. Each point below 10 decreases this value by the same amount."
  tooltips[8] = "Mana is a prime determinant for magical power, but also your characters' attunement and resistance to the forces of magic."
  tooltips[9] = "Determines how sharp your characters' senses are. A very important attribute since it determines how far you can see in dungeons, increases likelihood of finding traps, secret doors and hearing sounds. Last but not least it adds a small to-hit bonus in combat."

  function bonusvalue(value)
    if value > 0 then
      return "+"..value
      end
    return value
    end

  function showattributestable(startpos, overview, cap)

    local spx = 34

    local pos = startpos.top + V(20,70)
    rendertext(AlegreyaRegular, 14, "Min", colmin, Gfx, pos + V(spx,0), align_center)
    rendertext(AlegreyaRegular, 14, "Cur", colnormal, Gfx, pos + V(spx*2,0), align_center)
    rendertext(AlegreyaRegular, 14, "Max", colmax, Gfx, pos + V(spx*3,0), align_center)
    rendertext(AlegreyaRegular, 14, "Sn", colstarsign, Gfx, pos + V(spx*4,0), align_center)
    rendertext(AlegreyaRegular, 14, "Gn", colgender, Gfx, pos + V(spx*5,0), align_center)
    rendertext(AlegreyaRegular, 14, "Pr", colclass, Gfx, pos + V(spx*6,0), align_center)
    rendertext(AlegreyaRegular, 14, "Total", colnormal, Gfx, pos + V(spx*7,0), align_center)

    for attrid = 1,9 do
      local pos = startpos.top + V(20,70+21*attrid)
      local attr = cap.attributes[attrid] or {}
      local attrname = overview.attribute_data[attrid].attribute_name_short or ""

      rendertext(AlegreyaRegular, 14, string.upper(attrname), colnormal, Gfx, pos, align_center)
      rendertext(AlegreyaRegular, 14, attr.min_value or "", colmin, Gfx, pos + V(spx,0), align_center)
      rendertext(AlegreyaRegular, 14, attr.current_value or "", colnormal, Gfx, pos + V(spx*2,0), align_center)
      rendertext(AlegreyaRegular, 14, attr.max_value or "", colmax, Gfx, pos + V(spx*3,0), align_center)
      if attr.bonus_starsign and attr.bonus_starsign ~= 0 then
        rendertext(AlegreyaRegular, 14, bonusvalue(attr.bonus_starsign), colstarsign, Gfx, pos + V(spx*4,0), align_center)
        end
      if attr.bonus_sex and attr.bonus_sex ~= 0 then
        rendertext(AlegreyaRegular, 14, bonusvalue(attr.bonus_sex), colgender, Gfx, pos + V(spx*5,0), align_center)
        end
      if attr.bonus_class and attr.bonus_class ~= 0 then
        rendertext(AlegreyaRegular, 14, bonusvalue(attr.bonus_class), colclass, Gfx, pos + V(spx*6,0), align_center)
        end
      rendertext(AlegreyaRegular, 14, attr.total_value or "", colnormal, Gfx, pos + V(spx*7,0), align_center)

      end

    end

  function m.fullshow()
    if not graphicalUI() then return false end
    
    drawtitleimage(m)
    drawconfig()
    
    local statctr = xscreen.ctr
    
    local statscreen = drawstatscreen(statctr, V(-.5, -.5))
    
    local cap = adom_nelib_current_attribute_points()

    overview = adom_nelib_get_tome_of_knowledge_pc_overview()
    
    m.btnplus = {}
    m.btnminus = {}

    rendertext(GermaniaOne, 20, "Attributes", 0xFFFFFFFF, Gfx, rectat(statscreen, V(.5, 0)) + V(0,36), align_center)
    rendertext(GermaniaOne, 18, "Base Value", 0xFFFFFFFF, Gfx, statscreen.top + V(185,85), align_center)
    rendertext(GermaniaOne, 18, "Total", 0xFFFFFFFF, Gfx, statscreen.top + V(420,85), align_center)

    local title_txt = "Points Distribution"
    local tooltip_txt = "Point-based attribute distribution for a "

    if event.sex then
      local sex = event.sex or ""
      local race = event.race or ""
      local class = event.class or ""
      local starsign = event.starsign or ""

      tooltip_txt = tooltip_txt.."\v#0063D2"..sex.."\v#000000 "..race.."\v#D737A8 "..class.."\v#000000, \v#FFA614"..starsign.."\v#603000-born."
      end

    local hover = false

    for attrid = 1, 9 do 

      local pos = statscreen.top + V(35,83+31*attrid)
      
      local attrname = overview.attribute_data[attrid].attribute_name
      rendertext(GermaniaOne, 20, attrname, 0xFFFFFFFF, Gfx, pos, align_lcenter)
      
      local attrval = cap.attributes[attrid].current_value or ""
      local totalval = cap.attributes[attrid].total_value or ""
      local minval = cap.attributes[attrid].min_value or ""
      local maxval = cap.attributes[attrid].max_value or ""
      local costval = cap.attributes[attrid].cost_value or ""
      local bonusclass = cap.attributes[attrid].bonus_class or ""
      local bonussex = cap.attributes[attrid].bonus_sex or ""
      local bonusstarsign = cap.attributes[attrid].bonus_starsign or ""

      rendertext(GermaniaOne, 20, attrval, 0xFFFFFFFF, Gfx, pos + V(150,0), align_center)
      rendertext(GermaniaOne, 20, totalval, 0xFFFFFFFF, Gfx, pos + V(385,0), align_center)

      if attrval ~= maxval then
        m.btnplus[attrid] = drawtinybutton(tiles[nmain.."btn_symbol_add"], pos + V(178, -2), V(-.5, -.5))
        end

      if attrval ~= minval then
        m.btnminus[attrid] = drawtinybutton(tiles[nmain.."btn_symbol_substract"], pos + V(120, -2), V(-.5, -.5))
        end

      if (m.btnplus[attrid] and (m.btnplus[attrid].over or m.btnplus[attrid].down)) or
         (m.btnminus[attrid] and (m.btnminus[attrid].over or m.btnminus[attrid].down)) then
        hover = true
        title_txt = attrname
        tooltip_txt = tooltips[attrid].."\n\nMin: "..minval.."\nMax: "..maxval.."\nCost: "..costval
        if bonussex ~= 0 or bonusclass ~= 0 or bonusstarsign ~= 0 then
          tooltip_txt = tooltip_txt.."\n\nBonuses:"
          if bonussex ~= 0 then
            tooltip_txt = tooltip_txt.."\nGender: "..bonusvalue(bonussex)
            end
          if bonusclass ~= 0 then
            tooltip_txt = tooltip_txt.."\nProfession: "..bonusvalue(bonusclass)
            end
          if bonusstarsign ~= 0 then
            tooltip_txt = tooltip_txt.."\nStarsign: "..bonusvalue(bonusstarsign)
            end
          end
        end

      local gx = pos + V(207, -3)
      local count = totalval

      while count >= 2 do
        local b = drawnonscaled(tiles[nmain.."stat_full"], gx, align_lcenter)
        gx = gx + V(b.size.x, 0)
        count = count - 2
        end
      if count >= 1 then
        drawnonscaled(tiles[nmain.."stat_half"], gx, align_lcenter)
        end
      end

    local av_points_txt = "Available points: "..cap.attributes.available_points
    if (cap.attributes.available_points > 0) then
      av_points_txt = av_points_txt.." (use as many as possible)"
      end
    rendertext(GermaniaOne, 18, av_points_txt, 0xFFFFFFFF, Gfx, statscreen.top + V(35,400), align_lcenter)

    m.back = drawshortbutton("Back", nil, 0, rectat(statscreen, V(0.25, .89)), align_center)
    m.play = drawshortbutton("Play!", nil, 0, rectat(statscreen, V(0.75, .89)), align_center)

    if m.back.over or m.back.down then
      tooltip_txt = "Change one of the previous selections."..gethotkey("-")
      end
    if m.play and (m.play.over or m.play.down) then
      tooltip_txt = "Continue and play the game."..gethotkey(" ")
      end

    if hover == false then
      showattributestable(statscreen.content, overview, cap)
      end

    rendertext(GermaniaOne, 20, title_txt, 0xFF603000, Gfx, statscreen.title, align_center)

    renderlongtext(AlegreyaRegular, 14,
      tooltip_txt,
      0xFF603000, Gfx, statscreen.content)

    return true
    end
  
  function m.handlemouse(ev)
    if not graphicalUI() then return false end

    if buttonclicked(ev, m.back) then
      nsendtext("-")
      end
    if buttonclicked(ev, m.play) then
      nsendtext(" ")
      end
    
    for attrid=1,9 do 
      if m.btnplus and overview and buttonclicked(ev, m.btnplus[attrid]) then
        nsendtext(overview.attribute_data[attrid].attribute_name:sub(1,1):lower())
        end
      if m.btnminus and overview and buttonclicked(ev, m.btnminus[attrid]) then
        nsendtext(overview.attribute_data[attrid].attribute_name:sub(1,1))
        end
      end

    return true
    end

  openscreen(m)
  return m
  end

function openbackground(event)

  config_y = xscreen and xscreen.bot.y
  local m = newmodalwindow("charbackground")
  
  function m.fullshow()
    if not graphicalUI() then return false end

    local boxctr = V(xscreen.ctr.x, config_y/2)

    drawtitleimage(m)
    drawconfig()

    local box = drawbackgroundinfobox(boxctr, V(-.5, -.5))
--    local cover = V(box.content.ctr.x, box.top.y + 100)

--    drawnonscaled(tiles[nmain.."story_cover_bg"], cover, align_center)
--    drawnonscaled(tiles[nmain.."story_cover"], cover, align_center)

    local txt = event.background or ""

    txt = replace_adom_color_codes(txt, "#59261E")

    renderlongtext(AlegreyaRegular, 16,
      txt,
      0xFF59261E, Gfx, box.content)

    m.play = drawshortbutton("Play [ ]", nil, 0, box.bottombutton, V(-.5, -0.85))

    return true
    end
  
  function m.handlemouse(ev)
    if not graphicalUI() then return false end
    if buttonclicked(ev, m.play) then
      nsendtext(" ")
      end
    return true
    end

  openscreen(m)
  return m
  end
