local p = {}

local function dump(t, ...)
    local args = {...}
    for _, s in ipairs(args) do
        table.insert(t, s)
    end
end

function p.demografia(frame)
    args = require('Modulo:Arguments').getArgs(frame)
    graph = {}
    dump(graph, 'Colors=\n id:lightgrey value:gray(0.9)\n id:darkgrey  value:gray(0.7)\n id:sfondo value:rgb(1,1,1)\n id:bar value:rgb(0.6,0.7,0.8)\n\n')
    dump(graph, 'ImageSize = width:', args.dimx or '455', ' height:', args.dmy or '373', '\n\n')
    dump(graph, 'PlotArea   = left:50 bottom:50 top:30 right:30\nDateFormat = x.y\n')
    dump(graph, 'Period = from:0 till:', args.popmax or '100000', '\n')
    dump(graph, 'TimeAxis   = orientation:vertical\nAlignBars  = justify')
    dump(graph, 'ScaleMajor = gridcolor:darkgrey increment:', args.passo1 or '10000', 'start:0\n' )
    dump(graph, 'ScaleMinor = gridcolor:lightgrey increment:', args.passo2 or '1000', 'start:0\n')
    dump(graph, 'BackgroundColors = canvas:sfondo\n')
    dump(graph, 'BarData=\n')
    for i =1,20 do
        local a = args['a' .. tostring(i)];
        if a then
            dump(graph, ' bar:', a, ' text:', a, '\n')
        end
    end
    dump(graph, 'PlotData=\n color:barra width:20 align:left\n\n')
    for i = 1,20 do
        local a = args['a' .. tostring(i)]
        local p = args['p' .. tostring(i)]
        if a then
            dump(graph, ' bar:', a, ' from:0 till: ', p or '0', '\n')
        end
    end
    lang = mw.language.new('it')
    dump(graph, 'PlotData=\n')
    for i = 1,20 do
        local a = args['a' .. tostring(i)]
        local p = args['p' .. tostring(i)]
        if a then
            p_formatted = '0'
            if p then
                p_formatted = lang.formatNum(math.floor(tonumber(p) + 0,5) )
            end
            dump(graph,  ' bar:', a, ' at: ', p or '0', ' fontsize:S text: ', p_formatted, ' shift:(-10,5)|n.d. shift:(-8,5)\n' )
        end
    end
    if args.fonte then
        dump(graph, 'TextData=\n fontsize:S pos:(20,20)\n text:fonte ', args.fonte, '\n')
    end
    local draw_graph
    if args.raw then
        draw_graph = table.concat(graph)
    else
        draw_graph = frame:extensionTag('timeline', table.concat(graph))
    end 
    local titolo = "''Abitanti censiti''\n"

    if args.titolo then
        args.titolo = "''" .. args.titolo .. "''\n"
    end
    return titolo .. draw_graph
end

return p