Module:Infobox chord

Revision as of 02:32, 12 August 2024 by Bcmills (talk | contribs)
Module documentation[view] [edit] [history] [purge]
Note: Do not invoke this module directly; use the corresponding template instead: Template:Infobox chord.

This module implements {{Infobox chord}} to generate an infobox providing information about a given chord.


local p = {}

local rat = require("Module:Rational")
local utils = require("Module:Utils")
local infobox = require("Module:Infobox")

function p.infobox_chord(frame)
	local debug_mode = frame.args["debug"]

	local page_name = frame:preprocess("{{PAGENAME}}")
	
	local infobox_data = {}
	local cats = ""
	local errors = ""

	if utils.value_provided(frame.args["Harmonics"]) then
		local harmonics = {}
		local i = 0
		for hs in string.gmatch(frame.args["Harmonics"], "[^:]+") do
			h = tonumber(hs)  -- TODO: support rational entries?
			if h == nil or h < 1 then
				errors = errors .. "<p>error: invalid harmonic " .. hs .. "</p>"
			else
				harmonics[i] = h
				i = i+1
			end
		end
		local root = harmonics[0]
		if root == nil and errors == "" then
			errors = errors .. "<p>error: no harmonics found</p>"
		end
		if errors ~= "" then
			return errors
		end

		local prime_limit = 1
		local odd_limit = 1

		for i, h in ipairs(harmonics) do
			for j, prime in ipairs(utils.prime_factorization_raw(h)) do
				if prime > prime_limit then
					prime_limit = prime
				end
			end

			local numer = h / utils.gcd(h, root)
			local odd = numer
			while odd % 2 == 0 do
				odd = odd / 2
			end
			if odd > odd_limit then
				odd_limit = odd
			end
		end

		cats = cats .. "[[Category:" .. prime_limit .. "-limit chords]]"
		cats = cats .. "[[Category:" .. odd_limit .. "-odd-limit chords]]"
	end

	local s = infobox.build("<u>Chord information</u>", infobox_data)
	if not debug_mode then
		s = s .. cats
	end
	return s
end

return p