local getArgs = require('Moduł:Arguments').getArgs
local p = {} -- module's table

local am = {}  -- Elements with wiki links
am.H="[[w:Wodór|H]]";am.He="[[w:Hel (pierwiastek)|He]]";
am.Li="[[w:Lit (pierwiastek)|Li]]";am.Be="[[w:Beryl (pierwiastek)|Be]]";am.B="[[w:Bor|B]]";am.C="[[w:Węgiel (pierwiastek)|C]]";am.N="[[w:Azot|N]]";am.O="[[w:Tlen|O]]";am.F="[[w:Fluor|F]]";am.Ne="[[w:Neon (pierwiastek)|Ne]]";
am.Na="[[w:Sód|Na]]";am.Mg="[[w:Magnez|Mg]]";am.Al="[[w:Glin|Al]]";am.Si="[[w:Krzem|Si]]";am.P="[[w:Fosfor|P]]";am.S="[[w:Siarka|S]]";am.Cl="[[w:Chlor|Cl]]";am.Ar="[[w:Argon|Ar]]";
am.K="[[w:Potas|K]]";am.Ca="[[w:Wapń|Ca]]";am.Sc="[[w:Skand|Sc]]";am.Ti="[[w:Tytan (pierwiastek)|Ti]]";am.V="[[w:Wanad|V]]";am.Cr="[[w:Chrom|Cr]]";am.Mn="[[w:Mangan|Mn]]";am.Fe="[[w:Żelazo|Fe]]";am.Co="[[w:Kobalt|Co]]";am.Ni="[[w:Nikiel|Ni]]";am.Cu="[[w:Miedź|Cu]]";am.Zn="[[w:Cynk|Zn]]";am.Ga="[[w:Gal|Ga]]";am.Ge="[[w:German|Ge]]";am.As="[[w:Arsen|As]]";am.Se="[[w:Selenium|Se]]";am.Br="[[w:Brom|Br]]";am.Kr="[[w:Krypton|Kr]]";am.Rb="[[w:Rubid|Rb]]";
am.Sr="[[w:Stront|Sr]]";am.Y="[[w:Itr|Y]]";am.Zr="[[w:Cyrkon (pierwiastek)|Zr]]";am.Nb="[[w:Niob|Nb]]";am.Mo="[[w:Molibden|Mo]]";am.Tc="[[w:Technet|Tc]]";am.Ru="[[w:Ruten|Ru]]";am.Rh="[[w:Rod (pierwiastek)|Rh]]";am.Pd="[[w:Pallad|Pd]]";am.Ag="[[w:Srebro|Ag]]";am.Cd="[[w:Kadm|Cd]]";am.In="[[w:Ind|In]]";am.Sn="[[w:Cyna]]";am.Sb="[[w:Antymon|Sb]]";am.Te="[[w:Tellur|Te]]";am.I="[[w:Jod|I]]";am.Xe="[[w:Ksenon|Xe]]";
am.Cs="[[w:Cez|Cs]]";am.Ba="[[w:Bar (pierwiastek)|Ba]]";am.La="[[w:Lantan|La]]";am.Ce="[[w:Cer|Ce]]";am.Pr="[[w:Prazeodym|Pr]]";am.Nd="[[w:Neodym|Nd]]";am.Pm="[[w:Promet|Pm]]";am.Sm="[[w:Samar|Sm]]";am.Eu="[[w:Europ|Eu]]";am.Gd="[[w:Gadolin|Gd]]";am.Tb="[[w:Terb|Tb]]";am.Dy="[[w:Dysproz|Dy]]";am.Ho="[[w:Holm (pierwiastek)|Ho]]";am.Er="[[w:Erb|Er]]";am.Tm="[[w:Tul|Tm]]";am.Yb="[[w:Iterb|Yb]]";am.Lu="[[w:Lutet|Lu]]";am.Hf="[[w:Hafn|Hf]]";am.Ta="[[w:Tantal (pierwiastek)|Ta]]";am.W="[[w:Wolfram|W]]";am.Re="[[w:Ren (pierwiastek)|Re]]";am.Os="[[w:Osm|Os]]";am.Ir="[[w:Iryd|Ir]]";am.Pt="[[w:Platyna|Pt]]";am.Au="[[w:Złoto|Au]]";am.Hg="[[w:Rtęć|Hg]]";am.Tl="[[w:Tal|Tl]]";am.Pb="[[w:Ołów|Pb]]";am.Bi="[[w:Bizmut|Bi]]";am.Po="[[w:Polon|Po]]";am.At="[[w:Astat|At]]";am.Rn="[[w:Radon|Rn]]";
am.Fr="[[w:Frans|Fr]]";am.Ra="[[w:Rad (pierwiastek)|Ra]]";am.Ac="[[w:Aktyn|Ac]]";am.Th="[[w:Tor (pierwiastek)|Th]]";am.Pa="[[w:Protaktyn|Pa]]";am.U="[[w:Uran (pierwiastek)|U]]";am.Np="[[w:Neptun (pierwiastek)|Np]]";am.Pu="[[w:Pluton (pierwiastek)|Pu]]";am.Am="[[w:Ameryk|Am]]";am.Cm="[[w:Kiur (pierwiastek)|Cm]]";am.Bk="[[w:Berkel|Bk]]";am.Cf="[[w:Kaliforn|Cf]]";am.Es="[[w:Einstein (pierwiastek)|Es]]";am.Fm="[[w:Ferm|Fm]]";am.Md="[[w:Mendelew|Md]]";am.No="[[w:Nobel (pierwiastek)|No]]";am.Lr="[[w:Lorens|Lr]]";am.Rf="[[w:Rutherford (pierwiastek)|Rf]]";am.Db="[[w:Dubn|Db]]";am.Sg="[[w:Seaborg|Sg]]";am.Bh="[[w:Bohr (pierwiastek)|Bh]]";am.Hs="[[w:Has|Hs]]";am.Mt="[[w:Meitner|Mt]]";am.Ds="[[w:Darmsztadt|Ds]]";am.Rg="[[w:Roentgen (pierwiastek)|Rg]]";am.Cp="[[w:Kopernik (pierwiastek)|Cp]]";am.Uut="[[w:Ununtrium|Uut]]";am.Fl="[[w:Flerow|Fl]]";am.Uup="[[w:Ununpentium|Uup]]";am.Lv="[[w:Livermor|Lv]]";am.Uus="[[w:Ununseptium|Uus]]";am.Uuo="[[w:Ununoctium|Uuo]]";

local T_ELEM = 0         -- token types
local T_NUM = 1          -- number
local T_OPEN = 2         -- open '('
local T_CLOSE = 3        -- close ')'
local T_PM_CHARGE = 4    -- + or −
local T_WATER = 6        -- .xH2O x number
local T_CRYSTAL = 9      -- .x
local T_CHARGE = 8       -- charge (x+), (x-)
local T_SUF_CHARGE = 10  -- suffix and charge e.g. 2+ from H2+
local T_SUF_CHARGERP = 11 -- suffix and (charge plus + radical)
local T_SUF_CHARGE2 = 12 -- suffix and (charge) e.g. 2(2+) from He2(2+)
local T_SUF_CHARGERM = 13 -- suffix and (charge minus + radical)
local T_SPECIAL = 14     -- starting with \ e.g. \d for double bond (=)
local T_ARROWS = 15      -- match: \xx+
local T_SPECIAL2 = 16    -- starting with \y{x} e.g. \i{12} for isotope with mass number 12
local T_ARROW_R = 17     -- match: ->
local T_ARROW_EQ = 18    -- match: <->
local T_UNDERSCORE = 19  -- _{ ... }
local T_CARET = 20       -- ^{ ... }
local T_SUF_RADICAL = 21 -- suffix and (radical)
local T_NOCHANGE = 30        -- Anything else like ☃

function su(up, down) -- like template:su
  if (down == "") then 
    return "<span style=\"display:inline-block; margin-bottom:-0.3em; vertical-align:0.7em; line-height:1.0em; font-size:80%; text-align:left;\">" .. up .. "<br /></span>";
  else
    return "<span style=\"display:inline-block; margin-bottom:-0.3em; vertical-align:-0.3em; line-height:1.0em; font-size:80%; text-align:left;\">" .. up .. "<br />" .. down .. "</span>";
  end
end

function DotIt()
  return '<span style="font-weight:bold;">&middot;</span>'
end


function item(f) -- (iterator) returns one token (type, value) at a time from the formula 'f'
   local i = 1
   local first = "true";

   return function ()
	local t, x = nil, nil

        if (first == "true" and f:match('^[0-9]', i)) then 
                 x = f:match('^[%d.]+', i); t = T_NOCHANGE; i = i + x:len();   -- matching coefficient (need a space first)
        elseif i <= f:len() then
                              x = f:match('^%s+[%d.]+', i); t = T_NOCHANGE;  -- matching coefficient (need a space first)
		if not x then x = f:match('^%s[+]', i); t = T_NOCHANGE; end       -- matching + (H2O + H2O)
		if not x then x = f:match('^%,%d', i); t = T_NOCHANGE; end       -- fraction
		if not x then x = f:match('^%&%#[%w%d]+%;', i); t = T_NOCHANGE; end       -- &#...;
		if not x then x = f:match('^%<%-%>', i); t = T_ARROW_EQ; end       -- matching <->
		if not x then x = f:match('^%-%>', i); t = T_ARROW_R; end       -- matching ->
		if not x then x = f:match('^[\\].[%l]+', i); t = T_ARROWS; end  -- matching \xx+
		if not x then x = f:match('^%u%l*', i); t = T_ELEM; end        -- matching symbols like Aaaaa
		if not x then x = f:match('^%d+%([\\][r]%)', i); t = T_SUF_RADICAL; end -- matching x(\r)
		if not x then x = f:match('^%d+%([\\][r]%-%)', i); t = T_SUF_CHARGERM; end -- matching x(\r-)
		if not x then x = f:match('^%d+%([\\][r]%+%)', i); t = T_SUF_CHARGERP; end -- matching x(\r+)
		if not x then x = f:match('^%d+[+-]', i); t = T_SUF_CHARGE; end        -- matching x+, x-
		if not x then x = f:match('^%d+%(%d*[+-]%)', i); t = T_SUF_CHARGE2; end        -- matching x(y+/-), x(+/-)
		if not x then x = f:match('^%(%d*[+-]%)', i); t = T_CHARGE; end        -- matching (x+) (xx+), (x-) (xx-)
		if not x then x = f:match('^[%d.]+', i); t = T_NUM; end        -- matching number
		if not x then x = f:match('^[(|{|%[]', i); t = T_OPEN; end     -- matching ({[
		if not x then x = f:match('^[)|}|%]]', i); t = T_CLOSE; end           -- matching )}]
		if not x then x = f:match('^[+-]', i); t = T_PM_CHARGE; end        -- matching + or -
		if not x then x = f:match('^%*[%d.]*H2O', i); t = T_WATER; end -- Crystal water
		if not x then x = f:match('^%*[%d.]*', i); t = T_CRYSTAL; end -- Crystal
		if not x then x = f:match('^[\\].{%d+}', i); t = T_SPECIAL2; end -- \y{x}
		if not x then x = f:match('^[\\].', i); t = T_SPECIAL; end -- \x
		if not x then x = f:match('^_{[^}]*}', i); t = T_UNDERSCORE; end -- _{...}
		if not x then x = f:match('^\^{[^}]*}', i); t = T_CARET; end -- ^{...}
		if not x then x = f:match('^.', i); t = T_NOCHANGE; end  --the rest - one by one
		if x then i = i + x:len(); else i = i + 999; error("Invalid character in formula!!!!!!! : "..f) end
	end
        first = "false"
	return t, x
	end
   end

function p._chem(args)
   
local f = args[1] or ''

   f = string.gsub(f, "–", "-")  -- replace – with -
   f = string.gsub(f, "−", "-")  -- replace − with -

   local sumO = 0
   local formula = ''
   local t, x

   local link = args['link'] or ""
   local auto = args['auto'] or ""

   if not (link == '') then formula = formula .. "[[" .. link .. "|"; end   -- wiki link start [[link|
 
   for t, x in item(f) do 
      if     t == T_ELEM then if (auto == '') then formula = formula .. x elseif am[x] then formula = formula .. am[x]; am[x] = x else formula = formula .. x end 
      elseif t == T_COEFFICIENT then formula = formula .. x
      elseif t == T_NUM   then formula = formula .. su("", x);
      elseif t == T_OPEN  then formula = formula .. x; sumO = sumO + 1;        -- ( {
      elseif t == T_CLOSE then formula = formula .. x; sumO = sumO -1;         -- ) }
      elseif t == T_SUF_RADICAL then 
          formula = formula .. su("•", string.match(x, "%d+"))      	
      elseif t == T_SUF_CHARGERM then 
          formula = formula .. su("•−", string.match(x, "%d+"))
      elseif t == T_SUF_CHARGERP then 
          formula = formula .. su("•+", string.match(x, "%d+"))
      elseif t == T_PM_CHARGE    then formula = formula .. su(string.gsub(x, "-", "−"), "");
      elseif t == T_SUF_CHARGE then 
           formula = formula .. su(string.gsub(string.match(x, "[+-]"), "-", "−"), string.match(x, "%d+"), "");
      elseif t == T_SUF_CHARGE2 then 
          formula = formula .. su(string.sub(string.gsub(string.match(x, "%(%d*[+-]"), "-", "−"), 2, -1), string.match(x, "%d+"))
      elseif t == T_CHARGE then formula = formula .. "<span style=\"display:inline-block; margin-bottom:-0.3em; vertical-align:0.7em; line-height:1.0em; font-size:80%; text-align:left;\">"; if string.match(x, "%d+") then formula = formula .. string.match(x, "%d+"); end formula = formula .. string.gsub(string.match(x, "[%+-]"), "-", "−") .. "</br></span>";  -- can not concatenat a nil value from string.match(x, "%d+");

      elseif t == T_CRYSTAL then formula = formula .. DotIt() .. string.gsub( x, "*", '', 1 );

      elseif t == T_ARROWS then
  		  parameter = string.sub(x, 2)
  		  if	   parameter == "arrow"   then formula = formula .. "<abbr class=\"abbr\" title=\"Przebieg reakcji w prawo\" style=\"text-decoration:none !important\">→</abbr>"   -- rightwards arrow
  		  	elseif parameter == "reaguje"  then formula = formula .. "<abbr class=\"abbr\" title=\"Przebieg reakcji w prawo\" style=\"text-decoration:none !important\">→</abbr>"
  		  	elseif parameter == "larrow"  then formula = formula .. "<abbr class=\"abbr\" title=\"Przebieg reakcji w lewo\" style=\"text-decoration:none !important\">←</abbr>"   -- leftwards arrow
			elseif parameter == "darrow"  then formula = formula .. "<abbr class=\"abbr\" title=\"Reakcja odwracalna\" style=\"text-decoration:none !important\">⇄</abbr>"   -- double arrow (rightwards arrow over leftwards arrow)
			elseif parameter == "dlarrow" then formula = formula .. "<abbr class=\"abbr\" title=\"Reakcja odwracalna\" style=\"text-decoration:none !important\">⇆</abbr>"   -- double arrow (leftwards arrow over rightwards arrow)
			elseif parameter == "equil"   then formula = formula .. "<abbr class=\"abbr\" title=\"Reakcja równowagowa\" style=\"text-decoration:none !important\">⇌</abbr>"   -- double arrow (chemical equilibrium)
			elseif parameter == "redox"   then formula = formula .. "<abbr class=\"abbr\" title=\"Reakcja połówkowa redoks\" style=\"text-decoration:none !important\">=</abbr>"   -- equals sign (redox reaction)				
			elseif parameter == "meso"    then formula = formula .. "<abbr class=\"abbr\" title=\"Rezonans chemiczny\" style=\"text-decoration:none !important\">↔</abbr>"   -- left right arrow (mesomerizm)
			elseif parameter == "up"      then formula = formula .. "<abbr class=\"abbr\" title=\"Reagent opuszcza środowisko reakcji\" style=\"text-decoration:none !important\">↑</abbr>"   -- upwards arrow
			elseif parameter == "opuszcza"      then formula = formula .. "<abbr class=\"abbr\" title=\"Reagent opuszcza środowisko reakcji\" style=\"text-decoration:none !important\">↑</abbr>"   -- upwards arrow
			elseif parameter == "down"    then formula = formula .. "<abbr class=\"abbr\" title=\"Reagent tworzy nierozpuszczalny osad\" style=\"text-decoration:none !important\">↓</abbr>"   -- downwards arrow
			elseif parameter == "osad"    then formula = formula .. "<abbr class=\"abbr\" title=\"Reagent tworzy nierozpuszczalny osad\" style=\"text-decoration:none !important\">↓</abbr>"   -- downwards arrow
			elseif parameter == "prim"    then formula = formula .. "<abbr class=\"abbr\" title=\"Prim\" style=\"text-decoration:none !important\">′</abbr>"   -- prim
			elseif parameter == "bis"     then formula = formula .. "<abbr class=\"abbr\" title=\"Bis\" style=\"text-decoration:none !important\">″</abbr>"   -- bis
			elseif parameter == "tris"    then formula = formula .. "<abbr class=\"abbr\" title=\"Ter\" style=\"text-decoration:none !important\">‴</abbr>"   -- tris
			elseif parameter == "quat"    then formula = formula .. "<abbr class=\"abbr\" title=\"Kwater\" style=\"text-decoration:none !important\">⁗</abbr>"   -- quater
			elseif parameter == "ds"      then formula = formula .. "<abbr class=\"abbr\" title=\"Dwa wiązania pojedyncze\" style=\"text-decoration:none !important\">></abbr>"   -- two single bonds
			elseif parameter == "dr"      then formula = formula .. "<abbr class=\"abbr\" title=\"Wolna para elektronowa\" style=\"text-decoration:none !important; font-weight:bold\">&#58;</abbr>"   -- diradical
			elseif parameter == "hbond"	  then formula = formula .. "<abbr class=\"abbr\" title=\"Wiązanie wodorowe\" style=\"text-decoration:none !important\">⋯</abbr>"   --  hydrogen bond
            elseif parameter == "wforce"  then formula = formula .. "<abbr class=\"abbr\" title=\"Słabe oddziaływanie międzycząsteczkowe\" style=\"text-decoration:none !important\">⋯</abbr>"   --  weak intermolecular force
            elseif parameter == "minus"   then formula = formula .. "−"   --  minus

		  end
      elseif t == T_SPECIAL then
          parameter = string.sub(x, 2, 2) -- x fra \x  
          if       parameter == "s" then formula = formula .. "<abbr class=\"abbr\" title=\"Wiązanie pojedyncze\" style=\"text-decoration:none !important\">−</abbr>"   -- single bond
            elseif parameter == "d" then formula = formula .. "<abbr class=\"abbr\" title=\"Wiązanie podwójne\" style=\"text-decoration:none !important\">=</abbr>"   -- double bond
            elseif parameter == "t" then formula = formula .. "<abbr class=\"abbr\" title=\"Wiązanie potrójne\" style=\"text-decoration:none !important\">≡</abbr>"   -- tripple bond
            elseif parameter == "q" then formula = formula .. "<abbr class=\"abbr\" title=\"Wiązanie poczwórne\" style=\"text-decoration:none !important\">≣</abbr>"   -- quadruple bond
            elseif parameter == "p" then formula = formula .. "<abbr class=\"abbr\" title=\"Wiązanie połówkowe, niepełne\" style=\"text-decoration:none !important\">⋯</abbr>"   --  partial bond
            elseif parameter == "r" then formula = formula .. su("<abbr class=\"abbr\" title=\"Niesparowany elektron\" style=\"text-decoration:none !important\">•</abbr>","") -- radical
            elseif parameter == "h" then formula = formula .. "η"   -- η, hapticity
            elseif parameter == "m" then formula = formula .. "μ"   -- μ, bridging ligand
            elseif parameter == "-" then formula = formula .. "-"   -- -
            elseif parameter == "\\" then formula = formula .. "\\"   -- \
            elseif parameter == "\'" then formula = formula .. "′"   -- prime
          end
      elseif t == T_SPECIAL2 then  -- \y{x}
         parameter = string.sub(x, 2, 2) -- y fra \y{x} 
          if parameter  == "h" then --[[Ligandy]]
             if (auto == '') then formula = formula .. "η<sup>" .. string.match(x, '%d+') .. "</sup>-" 
               else
             formula = formula .. "[[Ligandy|η<sup>" .. string.match(x, '%d+') .. "</sup>]]-" 
             end
--          elseif parameter == "i" then formula = formula .. su(string.match(x, '%d+'), "") -- isotope
          elseif parameter == "m" then formula = formula .. "μ<sup>" .. string.match(x, '%d+') .. "</sup>-"   -- mu (bridging ligand)
          elseif parameter == "n" then formula = formula .. string.sub(x, 4, -2) -- rzadkie przypadki, gdy coś ma pozostać bez zmian, a moduł coś knoci

          end
      elseif t == T_WATER then 
        if string.match(x, "^%*[%d.]") then 
            formula = formula .. DotIt() .. string.match(x, "%f[%.%d]%d*%.?%d*%f[^%.%d%]]") .. "H<span style=\"display:inline-block; margin-bottom:-0.3em; vertical-align:-0.3em; line-height:1.0em; font-size:80%; text-align:left;\"><br />2</span>O";
        else
          formula = formula .. DotIt() .. "H<span style=\"display:inline-block; margin-bottom:-0.3em; vertical-align:-0.3em; line-height:1.0em; font-size:80%; text-align:left;\"><br />2</span>O";
        end  
 
-- not (auto == nil or auto == '') then formula = formula .. DotIt .. 
-- "[[Water of crystallization|H<sub>2</sub>O]]";
--            else
--              formula = formula .. 
-- DotIt .. "H<sub>2</sub>O";
---- xxx brug af sub til tal
--            end

      elseif t == T_UNDERSCORE  then formula = formula .. su("", string.sub(string.gsub(x,"-","−"),3,-2)) -- x contains _{string}
      elseif t == T_CARET then formula = formula .. su(string.sub(x,3,-2), "") -- x contains ^{string}

      elseif t == T_ARROW_R then formula = formula .. " → "
      elseif t == T_ARROW_EQ then formula = formula .. " ⇄ "

      elseif t == T_NOCHANGE  then formula = formula .. x;  -- resten, som ikke blev fanget af diverse regular expresions
     
      else error('unreachable - ???') end -- in fact, unreachable

end

-- usunięte: wyświetla problemy przy linkowaniu
--   if      sumO > 0 then formula = formula .. "'<span style=\"display:none;font-size:100%\" class=\"error citation-comment\">   Too many (</span>'\";"
--    elseif sumO < 0 then formula = formula .. "'<span style=\"display:none;font-size:100%\" class=\"error citation-comment\">   Too many )</span>'\";"
--   end

   if not (link == nil or link == '') then formula = formula .. "]]"; end   -- wikilink closing ]]

   return formula
end

function p.chem(frame)
	local args = getArgs(frame)
	return p._chem(args)
end

return p