Module:User:Santi2222/fax-pr

Hello, you have come here looking for the meaning of the word Module:User:Santi2222/fax-pr. In DICTIOUS you will not only get to know all the dictionary meanings for the word Module:User:Santi2222/fax-pr, but we will also tell you about its etymology, its characteristics and you will know how to say Module:User:Santi2222/fax-pr in singular and plural. Everything you need to know about the word Module:User:Santi2222/fax-pr you have here. The definition of the word Module:User:Santi2222/fax-pr will help you to be more precise and correct when speaking or writing your texts. Knowing the definition ofModule:User:Santi2222/fax-pr, as well as those of other words, enriches your vocabulary and provides you with more and better linguistic resources.


--[=[
This module implements the template {{mwl-pr}}.

Adapted from ] by ]
]=]

local export = {}

local m_IPA = require("Module:IPA")
local m_str_utils = require("Module:string utilities")
local m_table = require("Module:table")
local audio_module = "Module:audio"
local headword_data_module = "Module:headword/data"
local homophones_module = "Module:homophones"
local hyphenation_module = "Module:hyphenation"
local labels_module = "Module:labels"
local links_module = "Module:links"
local parameters_module = "Module:parameters"
local parse_utilities_module = "Module:parse utilities"
local pron_qualifier_module = "Module:pron qualifier"
local references_module = "Module:references"
local rhymes_module = "Module:rhymes"

local force_cat = false -- for testing

--[=[
FIXME:

]=]

--[=[
About styles, dialects and isoglosses:

In this module only two dialects are recognized, each corresponding to an isogloss. 

The recognized isoglosses/dialects are:
-- central
-- sendinese

A "style" here is a set of dialects (two at most) that pronounce a given word in a given fashion.

A "style spec" restricts the output to certain styles (e.g. {{mwl-pr|+<style:sendinese>}} in a Sendinese-only word)
]=]

local lang = require("Module:languages").getByCode("mwl")

local u = m_str_utils.char
local rfind = m_str_utils.find
local rsubn = m_str_utils.gsub
local rsplit = m_str_utils.split
local ulower = m_str_utils.lower
local ulen = m_str_utils.len
local unfd = mw.ustring.toNFD
local unfc = mw.ustring.toNFC

local AC = u(0x0301) -- acute =  ́
local GR = u(0x0300) -- grave =  ̀
local CFLEX = u(0x0302) -- circumflex =  ̂
local TILDE = u(0x0303) -- tilde =  ̃
local DIA = u(0x0308) -- diaeresis =  ̈
local CED = u(0x0327) --cedilla
local DENT = u(0x032A) --dental symbol
local NONSYL = u(0x032F) --non-syllabic vowel

local SYLDIV = u(0xFFF0) -- used to represent a user-specific syllable divider (.) so we won't change it
local vowel = "aeiouAEIOUɐãẽĩõũ" -- vowels
local V = "" -- vowel class
local accent = AC .. GR .. CFLEX
local accent_c = ""
local stress = AC .. CFLEX
local stress_c = ""
local ipa_stress = "ˈˌ"
local ipa_stress_c = ""
local sylsep = "%-." .. SYLDIV -- hyphen included for syllabifying from spelling
local sylsep_c = ""
local wordsep = "# "
local separator_not_wordsep = accent .. ipa_stress .. sylsep
local separator = separator_not_wordsep .. wordsep
local separator_c = ""
local C = "" -- consonant class
local T = "" -- obstruent or nasal

local unstressed_words = m_table.listToSet({
	--FIXME: add more unstressed words
	"a", "an", "en", "ne", "cun", "de", "des", "pra", "por", "sin", --prepositions
	"la", "las", --articles
})

-- version of rsubn() that discards all but the first return value
local function rsub(term, foo, bar)
	local retval = rsubn(term, foo, bar)
	return retval
end

-- version of rsubn() that returns a 2nd argument boolean indicating whether
-- a substitution was made.
local function rsubb(term, foo, bar)
	local retval, nsubs = rsubn(term, foo, bar)
	return retval, nsubs > 0
end

-- apply rsub() repeatedly until no change
local function rsub_repeatedly(term, foo, bar)
	while true do
		local new_term = rsub(term, foo, bar)
		if new_term == term then
			return term
		end
		term = new_term
	end
end

local function decompose(text)
	-- decompose everything but ũ, ç and ü
	text = unfd(text)
	text = rsub(text, ".", {
		 = "ũ",
		 = "Ũ",
		 = "ü",
		 = "Ü",
		 = "Ç",
		 = "ç"
	})
	return text
end

local function split_on_comma(term)
	if not term then
		return nil
	end
	if term:find(",%s") then
		return require(parse_utilities_module).split_on_comma(term)
	elseif term:find(",") then
		return rsplit(term, ",")
	else
		return {term}
	end
end

-- Remove any HTML from the formatted text and resolve links, since the extra characters don't contribute to the
-- displayed length.
local function convert_to_raw_text(text)
	text = rsub(text, "<.->", "")
	if text:find("%[%[") then
		text = require(links_module).remove_links(text)
	end
	return text
end

-- Return the approximate displayed length in characters.
local function textual_len(text)
	return ulen(convert_to_raw_text(text))
end

local function construct_default_differences(dialect)
	if dialect == "central" then
		return false
	end
	return nil
end

-- Main syllable-division algorithm. Can be called either directly on spelling (when hyphenating) or after
-- non-trivial processing of respelling in the direction of pronunciation (when generating pronunciation).
local function syllabify_from_spelling_or_pronun(text, is_spelling)

    -- Part 1: Divide before the last consonant in a cluster of consonants between vowels. 
    -- Then move the syllable division marker leftwards over clusters that
	-- can form onsets.
	text = rsub_repeatedly(text, "(" .. V .. accent_c .. "*)(" .. C .. V .. ")", "%1.%2")
	text = rsub_repeatedly(text, "(" .. V .. accent_c .. "*" .. C .. "+)(" .. C .. V .. ")", "%1.%2")

	-- NOTE: When run on pronun, we have already eliminated c and v, but not when run on spelling.
	-- When run on pronun, don't include r, which at this point represents the trill.
	local cluster_r = is_spelling and "rɾ" or "ɾ"
	-- Don't divide Cl or Cr where C is a stop or fricative, except for dl. --FIXME
	text = rsub(text, "()%.()", ".%1%2")
	text = text:gsub("d%.()", ".d%1")

	-- Part 2: Divide hiatuses.
	text = rsub_repeatedly(text, "(" .. accent_c .. "*)()", "%1.%2")
	text = rsub_repeatedly(text, "(" .. accent_c .. "*)()", "%1.%2")
	text = rsub(text, "ku%.En%.ta", "kuEn.ta") --but don't divide cin.quen.ta
	
	--Fix V.V -> V.V (note that we're using the symbols <jw> already)
	text = rsub_repeatedly(text, "(" .. V ..accent_c .. "*)%.()(" .. V .. ")", "%1%2.%3")
	return text
end

local function syllabify_from_spelling(text)
	text = decompose(text)
	-- start at FFF1 because FFF0 is used for SYLDIV
	-- Temporary replacements for characters we want treated as default consonants. The C and related consonant regexes
	-- treat all unknown characters as consonants.
	local TEMP_I = u(0xFFF1)
	local TEMP_U = u(0xFFF2)
	local TEMP_GH = u(0xFFF3)
	local TEMP_GH_CAPS = u(0xFFF4)
	local TEMP_NH = u(0x0400)
	local TEMP_NH_CAPS = u(0x0401)
	local TEMP_LH = u(0xFFFB)
	local TEMP_LH_CAPS = u(0xFFFC)	
	local TEMP_QU = u(0xFFF4)
	local TEMP_QU_CAPS = u(0xFFF5)
	local TEMP_GU = u(0xFFF6)
	local TEMP_GU_CAPS = u(0xFFF7)
	local TEMP_H = u(0xFFF8)

	-- Change user-specified . into SYLDIV so we don't shuffle it around when dividing into syllables.
	text = rsub(text, "gh", TEMP_GH)
	text = rsub(text, "Gh", TEMP_GH_CAPS)
	text = rsub(text, "nh", TEMP_NH)
	text = rsub(text, "Nh", TEMP_NH_CAPS)
	text = rsub(text, "lh", TEMP_LH)
	text = rsub(text, "Lh", TEMP_LH_CAPS)
	text = rsub(text, "qu(" .. V .. ")", TEMP_QU .. "%1")
	text = rsub(text, "Qu(" .. V .. ")", TEMP_QU_CAPS .. "%1")
	text = rsub(text, "gu(" .. V .. ")", TEMP_GU .. "%1")
	text = rsub(text, "Gu(" .. V .. ")", TEMP_GU_CAPS .. "%1")
	text = text:gsub("%.", SYLDIV)

	local vowel_to_glide = {  = TEMP_I,  = TEMP_U }
	text = rsub_repeatedly(text, "(.*" .. V .. accent_c .. "*)()(" .. V .. ")",
		function (v1, iu, v2) return v1 .. "." .. vowel_to_glide .. v2 end
	)

	text = syllabify_from_spelling_or_pronun(text, "is spelling")

	--restore everything back
	text = text:gsub(SYLDIV, ".")
	text = text:gsub("%." .. TEMP_I, TEMP_I .. ".")
	text = text:gsub("%." .. TEMP_U, TEMP_U .. ".")
	text = text:gsub(TEMP_I, "i")
	text = text:gsub(TEMP_U, "u")
	text = text:gsub(TEMP_GH, "gh")
	text = text:gsub(TEMP_GH_CAPS, "Gh")
	text = text:gsub(TEMP_NH, "nh")
	text = text:gsub(TEMP_NH_CAPS, "Nh")
	text = text:gsub(TEMP_LH, "lh")
	text = text:gsub(TEMP_LH_CAPS, "Lh")
	text = text:gsub(TEMP_QU, "qu")
	text = text:gsub(TEMP_QU_CAPS, "Qu")
	text = text:gsub(TEMP_GU, "gu")
	text = text:gsub(TEMP_GU_CAPS, "Gu")

	text = unfc(text)
	return text
end


-- Generate the IPA of a given respelling, where a respelling is the representation of the pronunciation of a given
-- Mirandese term using Mirandese spelling conventions.
function export.IPA(text, dialect, phonetic)
	local central = dialect == "central"
	local sendinese_different = false

	text = ulower(text or mw.title.getCurrentTitle().text)
	-- decompose everything but ũ, ç and ü
	text = decompose(text)
	-- convert commas and en/en dashes to IPA foot boundaries
	text = rsub(text, "%s*%s*", " | ")
	-- question mark or exclamation point in the middle of a sentence -> IPA foot boundary
	text = rsub(text, "()%s*%s*()", "%1 | %2")

	-- canonicalize multiple spaces and remove leading and trailing spaces
	local function canon_spaces(text)
		text = rsub(text, "%s+", " ")
		text = rsub(text, "^ ", "")
		text = rsub(text, " $", "")
		return text
	end

	text = canon_spaces(text)

	-- Make prefixes unstressed unless they have an explicit stress marker; also make certain
	-- monosyllabic words unstressed.
	local words = rsplit(text, " ")
	for i, word in ipairs(words) do
		if rfind(word, "%-$") and not rfind(word, accent_c) or unstressed_words then
			-- add GR to the last vowel not the first one
			words = rsub(word, "^(.*" .. V .. ")", "%1" .. GR)
		--words ending in -ie
		elseif rfind(word, "ie$") and not rfind(word, accent_c) then
			words = rsub(word, "ie$", "i" .. AC .. "e")
		end
	end
	text = table.concat(words, " ")
	-- Convert hyphens to spaces, to handle ], ], etc.
	text = rsub(text, "%-", " ")
	-- canonicalize multiple spaces again, which may have been introduced by hyphens
	text = canon_spaces(text)
	-- now eliminate punctuation
	text = rsub(text, "", "")
	-- put # at word beginning and end and double ## at text/foot boundary beginning/end
	text = rsub(text, " | ", "# | #")
	text = "##" .. rsub(text, " ", "# #") .. "##"
	
	-- handling of irregular spellings
	text = rsub(text, "cinquenta", "cincuenta")
	
	--handling of ũ (this is a rare character that appears when nasal u is in a hiatus)
	text = rsub(text, "ũ", "uñ")
	
	--handling of <e> and <o>
	text = rsub(text, "e" .. CFLEX, "e" .. AC)
	text = rsub(text, "o" .. CFLEX, "o" .. AC)

	--<y> is /j/ word-initially. We'll convert it to <i>, the script will convert it to <j> later
	text = rsub(text, "y", "i")
		
	--c, ç, s, z, ch. Internally we'll use S, Z, ć for s̺, z̺, t͡ʃ 
	text = rsub(text, "s", "S")
	text = rsub(text, "(" .. V .. ")S(" .. V .. ")", "%1Z%2")
	text = rsub(text, "SS", "S")
	text = rsub(text, "ç", "s")
	text = rsub(text, "c()", "s%1")
	text = rsub(text, "ch", "ć")
	
	--g, q
	text = rsub(text, "g()", "ʒ%1")
	text = rsub(text, "gu()", "g%1")
	text = rsub(text, "gü()", "gu%1") --it's actually /w/, but we will use <u> to keep the syllabification function simpler
	text = rsub(text, "qu()", "k%1")
	text = rsub(text, "qua", "kua")
	
	--do we need Sendinese?
	if rfind(text, "uo") or rfind(text, "ie") then
		sendinese_different = true
	end

	--digraphs
	text = rsub(text, "nh", "ɲ")
	text = rsubb(text, "lh", "ʎ")
	text = rsub(text, "#p()", "#%1")
	text = rsub(text, "x", "ʃ")
	text = rsub(text, "gh", "x") --used in some loanwords from Spanish
	
	text = rsub(text, "",
			{  = "k",  = "ʒ",  = "ɾ",  = "b",  = "j"})

	--treat the articles l/ls as a special case
	text = rsub(text, "#l(?)#", "#L%1#")
	
	-- trill or flap ɾ
	text = rsub(text, "ɾɾ", "r")
	text = rsub(text, "#ɾ", "#r")
	text = rsub(text, "(" .. C .. ")ɾ", "%1r")
	text = rsub(text, "()r", "%1ɾ")
	
	--other double consonants
	text = rsub(text, "(" .. C .. ")%1", "%1")

	--assimilation of sibilants
	-- θ, s, S before voiced consonants
	local voiced = "mnɲbdgʎl"
	local r = "ɾr"
	local tovoiced = {
		 = "Z",
		 = "z",
		 = "ʒ",
	}
	local function voice(sound, following)
		return tovoiced .. following
	end
	text = rsub(text, "()(" .. separator_c .. "*)", voice)

	-- convert i/u between vowels to glide
	local vowel_to_glide = {  = "j",  = "w" }
	text = rsub_repeatedly(text, "(.*" .. V .. accent_c .. "*)()(" .. V .. ")",
		function (v1, iu, v2) return v1 .. vowel_to_glide .. v2 end
	)

	--syllable division
	text = syllabify_from_spelling_or_pronun(text, false)

	--vowel reduction
	local function sendinese_vowels(syl, stressed)
		if stressed then
			if rfind(syl, "") then
				return true
			end
		else
			if rfind(syl, "e") then
				return true
			end
		end
		return false
	end
	
	local function reduce_vowels(syllables)
		for i = 1, #syllables do
			local is_syllable_stressed = rfind(syllables, "ˈ")
			if sendinese_vowels(syllables, is_syllable_stressed) then
				sendinese_different = true
			end
			--Changes that apply to all syllables
			syllables = rsub(syllables, "a()", "ɐ%1")
			--Changes that apply to unstressed syllables
			if not is_syllable_stressed then
				syllables = rsub(syllables, "ou", "û")
				syllables = rsub(syllables, "o", "u")
				
				if phonetic then
					syllables = rsub(syllables, "a", "ɐ")
					syllables = rsub(syllables, "ɐl", "al") --there's no reduction if followed by /l/ in the same syllable
					syllables = rsub(syllables, "ei", "ê")
					syllables = rsub(syllables, "e", "ɨ")
					syllables = central and rsub(syllables, "ɨ()", "ɐ%1") or syllables
				end
				syllables = rsub(syllables, "û", "ou")
				syllables = rsub(syllables, "ê", "ei")
			--Changes that apply to stressed syllables
			else
				if not central and phonetic then --FIXME: this should probably happen in the phonemic transcription too
					syllables = rsub(syllables, "()()", "%1ɨ%2")
				end
			end
		end
	end
	
	--diphthongs
	text = rsub(text, "i()", "j%1")
	text = rsub(text, "u()", "w%1") --e only in cinquenta

	-- add accents
	local accent_to_stress_mark = {  = "ˈ",  = ""}

	local function accent_word(word, syllables)
		-- Now stress the word. If any accent exists in the word (including ` indicating an unaccented word),
		-- put the stress mark(s) at the beginning of the indicated syllable(s). Otherwise, apply the default
		-- stress rule.
		if rfind(word, accent_c) then
			for i = 1, #syllables do
				syllables = rsub(syllables, "^(.*)(" .. accent_c .. ")(.*)$",
					function(pre, accent, post) return accent_to_stress_mark .. pre .. post end
				)
			end
		else
			-- Default stress rule. Words without vowels (e.g. IPA foot boundaries) don't get stress.
			-- Final-stressed words ending in -ç, -n, -l, -r, -i, -u, -is, -us don't need an explicit stress marker
			if #syllables > 1 and (rfind(word, "#*$") or rfind(word, "S#*$")) or #syllables == 1 and rfind(word, V) then
				syllables = "ˈ" .. syllables
			elseif #syllables > 1 then
				syllables = "ˈ" .. syllables
			end
		end
	end

	local words = rsplit(text, " ")
	for j, word in ipairs(words) do
		-- accentuation
		local syllables = rsplit(word, "%.")

		if rfind(word, "men%.te#") then
			local mente_syllables
			-- Words ends in -mente (converted above to ménti); add a stress to the preceding portion
			mente_syllables = {}
			mente_syllables = table.remove(syllables)
			mente_syllables = table.remove(syllables)
			accent_word(table.concat(syllables, "."), syllables)
			accent_word(table.concat(mente_syllables, "."), mente_syllables)
			table.insert(syllables, mente_syllables)
			table.insert(syllables, mente_syllables)
		else
			if rfind(word, "i" .. AC .. "e#") then
				local ie = central and "i" .. AC .. ".(e)#" or "je" .. AC .. "#"
				syllables = rsub(syllables, "i" .. AC .. "e#", ie)
			end
			accent_word(word, syllables)
		end
		reduce_vowels(syllables)

		-- Reconstruct the word and make all primary stresses but the last one be secondary
		words = table.concat(syllables, ".")
		words = rsub_repeatedly(words, "ˈ(.+)ˈ", "ˌ%1ˈ")
	end

	text = table.concat(words, " ")
	text = rsub(text, "%-", "")
	
	-- suppress syllable mark before IPA stress indicator
	text = rsub(text, "%.(" .. ipa_stress_c .. ")", "%1")
	
	-- apply dialectal variations
	if not central then
		text = rsub(text, "je", "i")
		text = rsub(text, "wo", "u")
	end
	
	--phonetic transcription
	if phonetic then
		--definite article
		text = rsub(text, "L", "(ɐ)l")
		
		-- velarization of syllable-final /l/
		text = rsub(text, "l()", "ɫ%1")
		
		-- fricative vs. stop allophones; first convert stops to fricatives, then back to stops
		-- after nasals and sometimes after l
		local stop_to_fricative = {  = "β",  = "ð",  = "ɣ" }
		local fricative_to_stop = {  = "b",  = "d",  = "g" }
		text = rsub(text, "", stop_to_fricative)
		text = rsub(text, "(" .. separator_c .. "*)()",
				function(nasal, fricative)
					return nasal .. fricative_to_stop
				end
		)
		text = rsub(text, "(" .. separator_c .. "*)()",
				function(nasal_l, fricative)
					return nasal_l .. fricative_to_stop
				end
		)
		text = rsub(text, "(##" .. ipa_stress_c .. "*)()",
				function(stress, fricative)
					return stress .. fricative_to_stop
				end
		)
		text = rsub(text, "", {  = "t̪",  = "d̪" })

		-- lateral assimilation before consonants
		text = rsub(text, "()(" .. separator_c .. "*)", "%1" .. DENT .. "%2")

		-- voiced fricatives are actually approximants
		text = rsub(text, "()", "%1̞")
		
		-- value of the dipthong <ei> = /ej/
		text = rsub(text, "ei", "ɐi")
		
		--palatalization of -ingo/a -ico/a in Sendinese
		if rfind(text, "ɨin%.g#") or rfind(text, "ɨi%.k#") then
			sendinese_different = true
		end
		if not central then
			text = rsub(text, "ɨin%.g()#", "ɨin.gʲ%1#")
			text = rsub(text, "ɨi%.k()#", "ɨi.kʲ%1#")
		end
	end
	
	--final conversions
	local final_conversions = {
		 = "",
		 = "t͡ʃ", 
		 = "ɡ",
		 = "s̻",
		 = "z̻",
		 = "s̺",
		 = "z̺",
	}
	text = rsub(text, "", final_conversions)
	
	--nasalization and semivowels
	text = rsub(text, "()i", "%1" .. TILDE .. "j" .. TILDE)
	text = rsub(text, "()u", "%1" .. TILDE .. "w" .. TILDE)
	text = rsub(text, "()", "%1" .. TILDE)
	text = rsub(text, "()i", "%1j") --"%1i" .. NONSYL) if we prefer the non-syllabic vowel notation
	text = rsub(text, "()u", "%1w") --"%1w" .. NONSYL)
	
	if rfind(text, "o" .. TILDE .. "#") then sendinese_different = true end
	if phonetic then
		text = rsub(text, TILDE .. "#", TILDE .. "ŋ#")
		text = rsub(text, "u%.ñ", "u" .. TILDE .. ".ŋ")
		if not central then --Sendinese final /õ/ is realized as 
			text = rsub(text, "o" .. TILDE .. "ŋ#", "ɐ" .. TILDE .. "w" .. TILDE .. "#")
		end
	else
		text = rsub(text, "L", "(a)l")
		text = rsub(text, "u%.ñ", "u" .. TILDE .. ".")
	end
	
	text = rsub(text, "#", "")
	text = unfc(text)
	
	-- mark /wo/ and /je/ explicitly (this is for the rhymes)
	text = rsub(text, "wo", "wO")
	text = rsub(text, "je", "jE")

	local differences = nil
	if dialect == "central" then
		differences = sendinese_different
	end
	local ret = {
		text = text,
		differences = differences,
	}
	return ret
end

-- Remove the special characters E and O
local function cleanup_pron(text)
	text = rsub(text, "E", "e")
	text = rsub(text, "O", "o")
	return text
end

-- For bot usage; {{#invoke:es-pronunc|IPA_string|SPELLING|style=STYLE|phonetic=PHONETIC}}
-- where
--
--   1. SPELLING is the word or respelling to generate pronunciation for;
--   2. required parameter style= indicates the pronunciation style to generate
--      (e.g. "distincion-yeismo" for distinción+yeísmo, as is common in Spain;
--      see the comment above export.IPA() above for the full list);
--   3. phonetic=1 specifies to generate the phonetic rather than phonemic pronunciation;
function export.IPA_string(frame)
	local iparams = {
		 = {},
		 = {required = true},
		 = {type = "boolean"},
	}
	local iargs = require(parameters_module).process(frame.args, iparams)
	local retval = export.IPA(iargs, iargs.style, iargs.phonetic)
	return retval.text
end


-- Generate all relevant dialect pronunciations and group into styles. See the comment above about dialects and styles.
-- A "pronunciation" here could be for example the IPA phonemic/phonetic representation of the term or the IPA form of
-- the rhyme that the term belongs to. If `style_spec` is nil, this generates all styles for all dialects, but
-- `style_spec` can also be a style spec such as "sendinese" or "central" (see comment above) to restrict the
-- output. `dodialect` is a function of two arguments, `ret` and `dialect`, where `ret` is the return-value table (see
-- below), and `dialect` is a string naming a particular dialect, such as "central" or "sendinese".
-- `dodialect` should side-effect the `ret` table by adding an entry to `ret.pronun` for the dialect in question.
--
-- The return value is a table of the form
--
-- {
--   pronun = {DIALECT = {PRONUN, PRONUN, ...}, DIALECT = {PRONUN, PRONUN, ...}, ...},
--   expressed_styles = {STYLE, STYLE, ...},
-- }
--
-- where:
-- 1. DIALECT is a string such as "central" naming a specific dialect.
-- 2. PRONUN is a table describing a particular pronunciation. If the dialect is "central", there should be
--    a field in this table named `differences`, but where other fields may vary depending on the type of pronunciation
--    (e.g. phonemic/phonetic or rhyme). See below for the form of the PRONUN table for phonemic/phonetic pronunciation
--    vs. rhyme and the form of the `differences` field.
-- 3. STYLE is a table of the form {tag = "TAG", pronun = {PRONUN, PRONUN, ...}}. The tag of the style group is the text 
--    displayed before the pronunciation, such as "Central" or "Sendinese". It can have the special value of `false` to indicate
--    that no tag text is to be displayed.
--
-- The PRONUN table has the following form for the full phonemic/phonetic pronunciation:
--
-- {
--   phonemic = "PHONEMIC",
--   phonetic = "PHONETIC",
--   differences = {FLAG = BOOLEAN, FLAG = BOOLEAN, ...},
-- }
--
-- Here, `phonemic` is the phonemic pronunciation (displayed as /.../) and `phonetic` is the phonetic pronunciation
-- (displayed as ).
--
-- The PRONUN table has the following form for the rhyme pronunciation:
--
-- {
--   rhyme = "RHYME_PRONUN",
--   num_syl = {NUM, NUM, ...},
--   qualifiers = nil or {QUALIFIER, QUALIFIER, ...},
--   differences = {FLAG = BOOLEAN, FLAG = BOOLEAN, ...},
-- }
--
-- Here, `rhyme` is a phonemic pronunciation such as "as̻" for ],
-- and `num_syl` is a list of the possible numbers of syllables for the term(s) that have this rhyme
-- (e.g. {3} for ]. `num_syl` is used to generate syllable-count categories such as
-- ] in addition to ]. `num_syl` may be nil to
-- suppress the generation of syllable-count categories; this is typically the case with multiword terms.
-- `qualifiers`, if non-nil, comes from the user using the syntax.
--
-- The value of the `differences` field in the PRONUN table (which, as noted above, only needs to be present for the
-- "central" dialect, and otherwise should be nil) is a table containing flags indicating whether and how
-- the per-dialect pronunciations differ. This is an optimization to avoid having to generate all six dialectal
-- pronunciations and compare them. It has the following form:
--
local function express_all_styles(style_spec, dodialect)
	local ret = {
		pronun = {},
		expressed_styles = {},
	}

	-- Add a style object that represents a particular style to `ret.expressed_styles`.
	-- `tag` is the tag text to be used.
	-- `dialect_name` is the dialect that this style represents, and whose pronunciation is stored in
	-- the style object.
	local function express_style(tag, dialect_name)
		-- If style specified, make sure it matches the requested style.
		local style_matches
		if not style_spec then
			style_matches = true
		else
			if dialect_name == style_spec then
				style_matches = true
			end
			if negate then
				style_matches = not style_matches
			end
		end
		if not style_matches then
			return
		end

		-- Fetch the representative dialect's pronunciation if not already present.
		if not ret.pronun then
			dodialect(ret, dialect_name)
		end
		-- Insert the new style.
		table.insert(ret.expressed_styles, {
			tag = tag,
			pronun = ret.pronun,
		})
	end

	-- For each type of difference, figure out if the difference exists in any of the given respellings. We do this by
	-- generating the pronunciation for the dialect "central", for each respelling. In the process of
	-- generating the pronunciation for a given respelling, it computes how the other dialects for that respelling
	-- differ. Then we take the union of these differences across the respellings.
	dodialect(ret, "central")
	local differences = false
	for _, pronun in ipairs(ret.pronun) do
		if pronun.differences == true then
			differences = true
		end
	end

	-- Now, based on the observed differences, figure out how to combine the individual dialects into styles and
	-- style groups.
	if not differences then
		express_style(false, "central")
	else
		express_style("Central", "central")
		express_style("Sendinese", "sendinese")
	end

	return ret
end


local function format_all_styles(expressed_styles, format_style)
	for i, style in ipairs(expressed_styles) do
		style.formatted = format_style(style.tag, style.pronun, i == 1)
	end

	local lines = {}

	for i, style in ipairs(expressed_styles) do
		table.insert(lines, style.formatted)
	end

	return table.concat(lines, "\n")
end


local function dodialect_pronun(args, ret, dialect)
	ret.pronun = {}
	for i, term in ipairs(args.terms) do
		local phonemic, phonetic, differences
		if term.raw then
			phonemic = term.raw_phonemic
			phonetic = term.raw_phonetic
			differences = construct_default_differences(dialect)
		else
			phonemic = export.IPA(term.term, dialect, false)
			phonetic = export.IPA(term.term, dialect, true)
			differences = phonemic.differences
			phonemic = phonemic.text
			phonetic = phonetic.text
		end

		ret.pronun = {
			raw = term.raw,
			phonemic = phonemic,
			phonetic = phonetic,
			refs = term.refs,
			q = term.q,
			qq = term.qq,
			a = term.a,
			aa = term.aa,
			differences = differences,
		}
	end
end

local function generate_pronun(args)
	local function this_dodialect_pronun(ret, dialect)
		dodialect_pronun(args, ret, dialect)
	end

	local ret = express_all_styles(args.style, this_dodialect_pronun)

	local function format_style(tag, pronuns, is_first)
		local pronunciations = {}
		local formatted_pronuns = {}

		local function ins(formatted_part)
			table.insert(formatted_pronuns, formatted_part)
		end

		-- Loop through each pronunciation. For each one, add the phonemic and phonetic versions to `pronunciations`,
		-- for formatting by ], and also create an approximation of the formatted version so that we can
		-- compute the appropriate width of the HTML switcher div box that holds the different per-dialect variants.
		-- NOTE: The code below constructs the formatted approximation out-of-order in some cases but that doesn't
		-- currently matter because we assume all characters have the same width. If we change the width computation
		-- in a way that requires the correct order, we need changes to the code below.
		for j, pronun in ipairs(pronuns) do
			-- Add tag to left qualifiers if first one
			-- FIXME: Consider using accent qualifier for the tag instead.
			local qs = pronun.q
			if j == 1 and tag then
				if qs then
					qs = m_table.deepCopy(qs)
					table.insert(qs, tag)
				else
					qs = {tag}
				end
			end

			local first_pronun = #pronunciations + 1

			if not pronun.phonemic and not pronun.phonetic then
				error("Internal error: Saw neither phonemic nor phonetic pronunciation")
			end

			if pronun.phonemic then -- missing if 'raw:' given
				-- don't display syllable division markers in phonemic
				local slash_pron = "/" .. cleanup_pron(pronun.phonemic:gsub("%.", "")) .. "/"
				table.insert(pronunciations, {
					pron = slash_pron,
				})
				ins(slash_pron)
			end

			if pronun.phonetic then -- missing if 'raw:/.../' given
				local bracket_pron = ""
				table.insert(pronunciations, {
					pron = bracket_pron,
				})
				ins(bracket_pron)
			end

			local last_pronun = #pronunciations

			if qs then
				pronunciations.q = qs
			end
			if pronun.a then
				pronunciations.a = pronun.a
			end
			if j > 1 then
				pronunciations.separator = ", "
				ins(", ")
			end
			if pronun.qq then
				pronunciations.qq = pronun.qq
			end
			if pronun.aa then
				pronunciations.aa = pronun.aa
			end
			if qs or pronun.qq or pronun.a or pronun.aa then
				-- Note: This inserts the actual formatted qualifier text, including HTML and such, but the later call
				-- to textual_len() removes all HTML and reduces links.
				ins(require(pron_qualifier_module).format_qualifiers {
					lang = lang,
					text = "",
					-- need to copy as formatting accent qualifiers destructively modifies the lists
					q = m_table.shallowCopy(qs),
					qq = m_table.shallowCopy(pronun.qq),
					a = m_table.shallowCopy(pronun.a),
					aa = m_table.shallowCopy(pronun.aa),
				})
			end

			if pronun.refs then
				pronunciations.refs = pronun.refs
				-- Approximate the reference using a footnote notation. This will be slightly inaccurate if there are
				-- more than nine references but that is rare.
				ins(string.rep("", #pronun.refs))
			end
			if first_pronun ~= last_pronun then
				pronunciations.separator = " "
				ins(" ")
			end
		end

		local bullet = string.rep("*", args.bullets) .. " "
		-- Here we construct the formatted line in `formatted`.
		local pre = is_first and args.pre and args.pre .. " " or ""
		local post = is_first and args.post and " " .. args.post or ""
		local formatted = bullet .. pre ..
			m_IPA.format_IPA_full { lang = lang, items = pronunciations, separator = "" } .. post
		return formatted
	end

	ret.text = format_all_styles(ret.expressed_styles, format_style)

	return ret
end


local function parse_respelling(respelling, pagename, parse_err)
	local raw_respelling = respelling:match("^raw:(.*)$")
	if raw_respelling then
		local raw_phonemic, raw_phonetic = raw_respelling:match("^/(.*)/ %$")
		if not raw_phonemic then
			raw_phonemic = raw_respelling:match("^/(.*)/$")
		end
		if not raw_phonemic then
			raw_phonetic = raw_respelling:match("^%$")
		end
		if not raw_phonemic and not raw_phonetic then
			parse_err(("Unable to parse raw respelling '%s', should be one of /.../,  or /.../ ")
				:format(raw_respelling))
		end
		return {
			raw = true,
			raw_phonemic = raw_phonemic,
			raw_phonetic = raw_phonetic,
		}
	end
	if respelling == "+" then
		respelling = pagename
	end
	return {term = respelling}
end

-- Return the number of syllables of a phonemic representation, which should have syllable dividers in it but no
-- hyphens.
local function get_num_syl_from_phonemic(phonemic)
	-- Maybe we should just count vowels instead of the below code.
	phonemic = rsub(phonemic, "|", " ") -- remove IPA foot boundaries
	local words = rsplit(phonemic, " +")
	for i, word in ipairs(words) do
		-- IPA stress marks are syllable divisions if between characters; otherwise just remove.
		word = rsub(word, "(.)(.)", "%1.%2")
		word = rsub(word, "", "")
		words = word
	end
	-- There should be a syllable boundary between words.
	phonemic = table.concat(words, ".")
	return ulen(rsub(phonemic, "", "")) + 1
end


-- Get the rhyme by truncating everything up through the last stress mark + any following consonants, and remove
-- syllable boundary markers.
local function convert_phonemic_to_rhyme(phonemic)
	-- NOTE: This works because the phonemic vowels are just  possibly with diacritics that are separate
	-- Unicode chars. If we want to handle things like ɛ or ɔ we need to add them to `vowel`.
	return rsub(rsub(phonemic, ".*", ""), "^*", ""):gsub("%.", ""):gsub("t͡ʃ", "tʃ")
end


local function split_syllabified_spelling(spelling)
	return rsplit(spelling, "%.")
end


-- "Align" syllabification to original spelling by matching character-by-character, allowing for extra syllable and
-- accent markers in the syllabification. If we encounter an extra syllable marker (.), we allow and keep it. If we
-- encounter an extra accent marker in the syllabification, we drop it. In any other case, we return nil indicating
-- the alignment failed.
local function align_syllabification_to_spelling(syllab, spelling)
	local result = {}
	local syll_chars = rsplit(decompose(syllab), "")
	local spelling_chars = rsplit(decompose(spelling), "")
	local i = 1
	local j = 1
	while i <= #syll_chars or j <= #spelling_chars do
		local ci = syll_chars
		local cj = spelling_chars
		if ci == cj then
			table.insert(result, ci)
			i = i + 1
			j = j + 1
		elseif ci == "." then
			table.insert(result, ci)
			i = i + 1
		elseif ci == AC or ci == GR or ci == CFLEX or ci == DIA then
			-- skip character
			i = i + 1
		else
			-- non-matching character
			return nil
		end
	end
	if i <= #syll_chars or j <= #spelling_chars then
		-- left-over characters on one side or the other
		return nil
	end
	return unfc(table.concat(result))
end


local function generate_hyph_obj(term)
	return {syllabification = term, hyph = split_syllabified_spelling(term)}
end


-- Word should already be decomposed.
local function word_has_vowels(word)
	if word == "l" or word == "ls" then
		return true
	end
	return rfind(word, V)
end


local function all_words_have_vowels(term)
	local words = rsplit(decompose(term), "")
	for i, word in ipairs(words) do
		-- Allow empty word; this occurs with prefixes and suffixes.
		if word ~= "" and not word_has_vowels(word) then
			return false
		end
	end
	return true
end


local function should_generate_rhyme_from_respelling(term)
	local words = rsplit(decompose(term), " +")
	return #words == 1 and -- no if multiple words
		not words:find(".%-.") and -- no if word is composed of hyphenated parts (e.g. ])
		not words:find("%-$") and -- no if word is a prefix
		not (words:find("^%-") and words:find(CFLEX)) and -- no if word is an unstressed suffix
		word_has_vowels(words) -- no if word has no vowels (e.g. a single letter)
end


local function should_generate_rhyme_from_ipa(ipa)
	return not ipa:find("%s") and word_has_vowels(decompose(ipa))
end


local function dodialect_specified_rhymes(rhymes, hyphs, parsed_respellings, rhyme_ret, dialect)
	rhyme_ret.pronun = {}
	for _, rhyme in ipairs(rhymes) do
		local num_syl = rhyme.num_syl
		local no_num_syl = false

		-- If user explicitly gave the rhyme but didn't explicitly specify the number of syllables, try to take it from
		-- the hyphenation.
		if not num_syl then
			num_syl = {}
			for _, hyph in ipairs(hyphs) do
				if should_generate_rhyme_from_respelling(hyph.syllabification) then
					local this_num_syl = 1 + ulen(rsub(hyph.syllabification, "", ""))
					m_table.insertIfNot(num_syl, this_num_syl)
				else
					no_num_syl = true
					break
				end
			end
			if no_num_syl or #num_syl == 0 then
				num_syl = nil
			end
		end

		-- If that fails and term is single-word, try to take it from the phonemic.
		if not no_num_syl and not num_syl then
			for _, parsed in ipairs(parsed_respellings) do
				for dialect, pronun in pairs(parsed.pronun.pronun) do
					-- Check that pronun.phonemic exists (it may not if raw phonetic-only pronun is given).
					if pronun.phonemic then
						if not should_generate_rhyme_from_ipa(pronun.phonemic) then
							no_num_syl = true
							break
						end
						-- Count number of syllables by looking at syllable boundaries (including stress marks).
						local this_num_syl = get_num_syl_from_phonemic(pronun.phonemic)
						m_table.insertIfNot(num_syl, this_num_syl)
					end
				end
				if no_num_syl then
					break
				end
			end
			if no_num_syl or #num_syl == 0 then
				num_syl = nil
			end
		end

		table.insert(rhyme_ret.pronun, {
			rhyme = rhyme.rhyme,
			num_syl = num_syl,
			qualifiers = rhyme.qualifiers,
			differences = construct_default_differences(dialect),
		})
	end
end


local q_qq_inline_modifier_spec = {
	store = "insert-flattened",
	type = "qualifier",
}
local a_aa_inline_modifier_spec = {
	store = "insert-flattened",
	type = "labels",
}
local ref_inline_modifier_spec = {
	store = "insert-flattened",
	item_dest = "refs",
	type = "references",
}

-- Parse a pronunciation modifier in `arg`, the argument portion in an inline modifier (after the prefix), which
-- specifies a pronunciation property such as rhyme, hyphenation/syllabification, homophones or audio. The argument
-- can itself have inline modifiers, e.g. <audio:Foo.ogg<a:Central>>. The allowed inline modifiers are specified
-- by `param_mods` (of the format expected by `parse_inline_modifiers()`); in addition to any modifiers specified
-- there, the modifiers <q:...>, <qq:...>, <a:...>, <aa:...> and <ref:...> are always accepted (and can be repeated).
-- `generate_obj` and `parse_err` are like in `parse_inline_modifiers()` and specify respectively a function to
-- generate the object into which modifier properties are stored given the non-modifier part of the argument, and
-- a function to generate an error message (given the message). Normally, a comma-separated list of pronunciation
-- properties is accepted and parsed, where each element in the list can have its own inline modifiers and where
-- no spaces are allowed next to the commas in order for them to be recognized as separators. If `no_split_on_comma`
-- is given, only a single pronunciation property is accepted. In all cases, however, the return value is a list
-- of property objects (when `no_split_on_comma` is given, the return value is a one-element list).
local function parse_pron_modifier(arg, parse_err, generate_obj, param_mods, no_split_on_comma)
	if arg:find("<") then
		param_mods.q = q_qq_inline_modifier_spec
		param_mods.qq = q_qq_inline_modifier_spec
		param_mods.a = a_aa_inline_modifier_spec
		param_mods.aa = a_aa_inline_modifier_spec
		param_mods.ref = ref_inline_modifier_spec
		local retval = require(parse_utilities_module).parse_inline_modifiers(arg, {
			param_mods = param_mods,
			generate_obj = generate_obj,
			parse_err = parse_err,
			splitchar = not no_split_on_comma and "," or nil,
		})
		if no_split_on_comma then
			retval = {retval}
		end
		return retval
	elseif no_split_on_comma then
		return {generate_obj(arg)}
	else
		local retval = {}
		for _, term in ipairs(split_on_comma(arg)) do
			table.insert(retval, generate_obj(term))
		end
		return retval
	end
end


local function parse_rhyme(arg, parse_err)
	local function generate_obj(term)
		return {rhyme = term}
	end
	local param_mods = {
		s = {
			item_dest = "num_syl",
			type = "number",
			sublist = true,
		},
	}

	return parse_pron_modifier(arg, parse_err, generate_obj, param_mods)
end


local function parse_hyph(arg, parse_err)
	-- None other than qualifiers
	local param_mods = {}

	return parse_pron_modifier(arg, parse_err, generate_hyph_obj, param_mods)
end


local function parse_homophone(arg, parse_err)
	local function generate_obj(term)
		return {term = term}
	end
	local param_mods = {
		t = {
			-- ] expects the gloss in "gloss".
			item_dest = "gloss",
		},
		gloss = {},
		-- No tr=, ts=, or sc=; doesn't make sense for Spanish.
		pos = {},
		alt = {},
		lit = {},
		id = {},
		g = {
			-- ] expects the genders in "genders".
			item_dest = "genders",
			sublist = true,
		},
	}

	return parse_pron_modifier(arg, parse_err, generate_obj, param_mods)
end


local function generate_audio_obj(arg)
	local file, caption = arg:match("^(.-)%s*#%s*(.*)$")
	file = file or arg
	return {file = file, caption = caption}
end


local function parse_audio(arg, parse_err)
	local param_mods = {
		IPA = {
			sublist = true,
		},
		text = {},
		t = {
			item_dest = "gloss",
		},
		-- No tr=, ts=, or sc=; doesn't make sense for Spanish.
		gloss = {},
		pos = {},
		-- No alt=; text= already goes in alt=.
		lit = {},
		-- No id=; text= already goes in alt= and isn't normally linked.
		g = {
			item_dest = "genders",
			sublist = true,
		},
		bad = {},
	}

	-- Don't split on comma because some filenames have embedded commas not followed by a space
	-- (typically followed by an underscore).
	local retvals = parse_pron_modifier(arg, parse_err, generate_audio_obj, param_mods, "no split on comma")
	local retval = retvals
	retval.lang = lang
	local textobj = require(audio_module).construct_audio_textobj(retval)
	retval.text = textobj
	retval.gloss = nil
	retval.pos = nil
	retval.lit = nil
	retval.genders = nil
	return retval
end


-- External entry point for {{es-pr}}.
function export.show_pr(frame)
	local params = {
		 = {list = true},
		 = {convert = parse_rhyme},
		 = {convert = parse_hyph},
		 = {convert = parse_homophone},
		 = {list = true},
		 = {},
	}
	local parargs = frame:getParent().args
	local args = require(parameters_module).process(parargs, params)
	local pagename = args.pagename or mw.loadData(headword_data_module).pagename

	-- Parse the arguments.
	local respellings = #args > 0 and args or {"+"}
	local parsed_respellings = {}
	local overall_rhyme = args.rhyme
	local overall_hyph = args.hyph
	local overall_hmp = args.hmp
	local overall_audio
	if args.audio then
		-- We can't specify parse_audio() as a `convert` function because it needs access to `pagename` (i.e. another
		-- parameter).
		overall_audio = {}
		for i, audio in ipairs(args.audio) do
			local function parse_err(msg)
				error(("%s: parameter audio%s=%s"):format(msg, i == 1 and "" or i, audio))
			end
			local parsed_audio = parse_audio(audio, parse_err, pagename)
			table.insert(overall_audio, parsed_audio)
		end
	end
	for i, respelling in ipairs(respellings) do
		if respelling:find("<") then
			local param_mods = {
				pre = { overall = true },
				post = { overall = true },
				style = { overall = true },
				bullets = {
					overall = true,
					type = "number",
				},
				rhyme = {
					overall = true,
					store = "insert-flattened",
					convert = parse_rhyme,
				},
				hyph = {
					overall = true,
					store = "insert-flattened",
					convert = parse_hyph,
				},
				hmp = {
					overall = true,
					store = "insert-flattened",
					convert = parse_homophone,
				},
				audio = {
					overall = true,
					store = "insert",
					convert = function(arg, parse_err)
						return parse_audio(arg, parse_err, pagename)
					end,
				},
				ref = ref_inline_modifier_spec,
				q = q_qq_inline_modifier_spec,
				qq = q_qq_inline_modifier_spec,
				a = a_aa_inline_modifier_spec,
				aa = a_aa_inline_modifier_spec,
			}

			local parsed = require(parse_utilities_module).parse_inline_modifiers(respelling, {
				paramname = i,
				param_mods = param_mods,
				generate_obj = function(term, parse_err)
					return parse_respelling(term, pagename, parse_err)
				end,
				splitchar = ",",
				outer_container = {
					audio = {}, rhyme = {}, hyph = {}, hmp = {}
				}
			})
			if not parsed.bullets then
				parsed.bullets = 1
			end
			table.insert(parsed_respellings, parsed)
		else
			local termobjs = {}
			local function parse_err(msg)
				error(msg .. ": " .. i .. "=" .. respelling)
			end
			for _, term in ipairs(split_on_comma(respelling)) do
				table.insert(termobjs, parse_respelling(term, pagename, parse_err))
			end
			table.insert(parsed_respellings, {
				terms = termobjs,
				audio = {},
				rhyme = {},
				hyph = {},
				hmp = {},
				bullets = 1,
			})
		end
	end

	if overall_hyph then
		local hyphs = {}
		for _, hyph in ipairs(overall_hyph) do
			if hyph.syllabification == "+" then
				hyph.syllabification = syllabify_from_spelling(pagename)
				hyph.hyph = split_syllabified_spelling(hyph.syllabification)
			elseif hyph.syllabification == "-" then
				overall_hyph = {}
				break
			end
		end
	end

	-- Loop over individual respellings, processing each.
	for _, parsed in ipairs(parsed_respellings) do
		parsed.pronun = generate_pronun(parsed)
		local no_auto_rhyme = false
		for _, term in ipairs(parsed.terms) do
			if term.raw then
				if not should_generate_rhyme_from_ipa(term.raw_phonemic or term.raw_phonetic) then
					no_auto_rhyme = true
					break
				end
			elseif not should_generate_rhyme_from_respelling(term.term) then
				no_auto_rhyme = true
				break
			end
		end

		if #parsed.hyph == 0 then
			if not overall_hyph and all_words_have_vowels(pagename) then
				for _, term in ipairs(parsed.terms) do
					if not term.raw then
						local syllabification = syllabify_from_spelling(term.term)
						local aligned_syll = align_syllabification_to_spelling(syllabification, pagename)
						if aligned_syll then
							m_table.insertIfNot(parsed.hyph, generate_hyph_obj(aligned_syll))
						end
					end
				end
			end
		else
			for _, hyph in ipairs(parsed.hyph) do
				if hyph.syllabification == "+" then
					hyph.syllabification = syllabify_from_spelling(pagename)
					hyph.hyph = split_syllabified_spelling(hyph.syllabification)
				elseif hyph.syllabification == "-" then
					parsed.hyph = {}
					break
				end
			end
		end

		-- Generate the rhymes.
		local function dodialect_rhymes_from_pronun(rhyme_ret, dialect)
			rhyme_ret.pronun = {}
			-- It's possible the pronunciation for a passed-in dialect was never generated.
			-- In this case we need to generate the missing overall pronunciation ourselves 
			-- since we need it to generate the dialect-specific rhyme pronunciation.
			if not parsed.pronun.pronun then
				dodialect_pronun(parsed, parsed.pronun, dialect)
			end
			for _, pronun in ipairs(parsed.pronun.pronun) do
				-- We should have already excluded multiword terms and terms without vowels from rhyme generation (see
				-- `no_auto_rhyme` below). But make sure to check that pronun.phonemic exists (it may not if raw
				-- phonetic-only pronun is given).
				if pronun.phonemic then
					-- Count number of syllables by looking at syllable boundaries (including stress marks).
					local num_syl = get_num_syl_from_phonemic(pronun.phonemic)
					-- Get the rhyme by truncating everything up through the last stress mark + any following
					-- consonants, and remove syllable boundary markers.
					local rhyme = convert_phonemic_to_rhyme(pronun.phonemic)
					local saw_already = false
					for _, existing in ipairs(rhyme_ret.pronun) do
						if existing.rhyme == rhyme then
							saw_already = true
							-- We already saw this rhyme but possibly with a different number of syllables.
							m_table.insertIfNot(existing.num_syl, num_syl)
							break
						end
					end
					if not saw_already then
						local rhyme_diffs = false
						if dialect == "central" then
							if rhyme:find("O") or rhyme:find("E") then
								rhyme_diffs = true
							end
						end
						table.insert(rhyme_ret.pronun, {
							rhyme = cleanup_pron(rhyme),
							num_syl = {num_syl},
							differences = rhyme_diffs,
						})
					end
				end
			end
		end

		if #parsed.rhyme == 0 then
			if overall_rhyme or no_auto_rhyme then
				parsed.rhyme = nil
			else
				parsed.rhyme = express_all_styles(parsed.style, dodialect_rhymes_from_pronun)
			end
		else
			local no_rhyme = false
			for _, rhyme in ipairs(parsed.rhyme) do
				if rhyme.rhyme == "-" then
					no_rhyme = true
					break
				end
			end
			if no_rhyme then
				parsed.rhyme = nil
			else
				local function this_dodialect(rhyme_ret, dialect)
					return dodialect_specified_rhymes(parsed.rhyme, parsed.hyph, {parsed}, rhyme_ret, dialect)
				end
				parsed.rhyme = express_all_styles(parsed.style, this_dodialect)
			end
		end
	end

	if overall_rhyme then
		local no_overall_rhyme = false
		for _, orhyme in ipairs(overall_rhyme) do
			if orhyme.rhyme == "-" then
				no_overall_rhyme = true
				break
			end
		end
		if no_overall_rhyme then
			overall_rhyme = nil
		else
			local all_hyphs
			if overall_hyph then
				all_hyphs = overall_hyph
			else
				all_hyphs = {}
				for _, parsed in ipairs(parsed_respellings) do
					for _, hyph in ipairs(parsed.hyph) do
						m_table.insertIfNot(all_hyphs, hyph)
					end
				end
			end
			local function dodialect_overall_rhyme(rhyme_ret, dialect)
				return dodialect_specified_rhymes(overall_rhyme, all_hyphs, parsed_respellings, rhyme_ret, dialect)
			end
			overall_rhyme = express_all_styles(parsed.style, dodialect_overall_rhyme)
		end
	end

	-- If all sets of pronunciations have the same rhymes, display them only once at the bottom.
	-- Otherwise, display rhymes beneath each set, indented.
	local first_rhyme_ret
	local all_rhyme_sets_eq = true
	for j, parsed in ipairs(parsed_respellings) do
		if j == 1 then
			first_rhyme_ret = parsed.rhyme
		elseif not m_table.deepEquals(first_rhyme_ret, parsed.rhyme) then
			all_rhyme_sets_eq = false
			break
		end
	end

	local function format_rhyme(rhyme_ret, num_bullets)
		local function format_rhyme_style(tag, pronuns, is_first)
			local pronunciations = {}
			local rhymes = {}
			for _, pronun in ipairs(pronuns) do
				table.insert(rhymes, pronun)
			end
			local data = {
				lang = lang,
				rhymes = rhymes,
				qualifiers = tag and {tag} or nil,
				force_cat = force_cat,
			}
			local bullet = string.rep("*", num_bullets) .. " "
			local formatted = bullet .. require(rhymes_module).format_rhymes(data)
			return formatted
		end

		return format_all_styles(rhyme_ret.expressed_styles, format_rhyme_style)
	end

	-- If all sets of pronunciations have the same hyphenations, display them only once at the bottom.
	-- Otherwise, display hyphenations beneath each set, indented.
	local first_hyphs
	local all_hyph_sets_eq = true
	for j, parsed in ipairs(parsed_respellings) do
		if j == 1 then
			first_hyphs = parsed.hyph
		elseif not m_table.deepEquals(first_hyphs, parsed.hyph) then
			all_hyph_sets_eq = false
			break
		end
	end

	local function format_hyphenations(hyphs, num_bullets)
		local hyphtext = require(hyphenation_module).format_hyphenations { lang = lang, hyphs = hyphs, caption = "Syllabification" }
		return string.rep("*", num_bullets) .. " " .. hyphtext
	end

	-- If all sets of pronunciations have the same homophones, display them only once at the bottom.
	-- Otherwise, display homophones beneath each set, indented.
	local first_hmps
	local all_hmp_sets_eq = true
	for j, parsed in ipairs(parsed_respellings) do
		if j == 1 then
			first_hmps = parsed.hmp
		elseif not m_table.deepEquals(first_hmps, parsed.hmp) then
			all_hmp_sets_eq = false
			break
		end
	end

	local function format_homophones(hmps, num_bullets)
		local hmptext = require(homophones_module).format_homophones { lang = lang, homophones = hmps }
		return string.rep("*", num_bullets) .. " " .. hmptext
	end

	local function format_audio(audios, num_bullets)
		local ret = {}
		for i, audio in ipairs(audios) do
			local text = require(audio_module).format_audio(audio)
			table.insert(ret, string.rep("*", num_bullets) .. " " .. text)
		end
		return table.concat(ret, "\n")
	end

	local textparts = {}
	local min_num_bullets = math.huge
	for j, parsed in ipairs(parsed_respellings) do
		if parsed.bullets < min_num_bullets then
			min_num_bullets = parsed.bullets
		end
		if j > 1 then
			table.insert(textparts, "\n")
		end
		table.insert(textparts, parsed.pronun.text)
		if #parsed.audio > 0 then
			table.insert(textparts, "\n")
			-- If only one pronunciation set, add the audio with the same number of bullets, otherwise
			-- indent audio by one more bullet.
			table.insert(textparts, format_audio(parsed.audio,
				#parsed_respellings == 1 and parsed.bullets or parsed.bullets + 1))
		end
		if not all_rhyme_sets_eq and parsed.rhyme then
			table.insert(textparts, "\n")
			table.insert(textparts, format_rhyme(parsed.rhyme, parsed.bullets + 1))
		end
		if not all_hyph_sets_eq and #parsed.hyph > 0 then
			table.insert(textparts, "\n")
			table.insert(textparts, format_hyphenations(parsed.hyph, parsed.bullets + 1))
		end
		if not all_hmp_sets_eq and #parsed.hmp > 0 then
			table.insert(textparts, "\n")
			table.insert(textparts, format_homophones(parsed.hmp, parsed.bullets + 1))
		end
	end
	if overall_audio and #overall_audio > 0 then
		table.insert(textparts, "\n")
		table.insert(textparts, format_audio(overall_audio, min_num_bullets))
	end
	if all_rhyme_sets_eq and first_rhyme_ret then
		table.insert(textparts, "\n")
		table.insert(textparts, format_rhyme(first_rhyme_ret, min_num_bullets))
	end
	if overall_rhyme then
		table.insert(textparts, "\n")
		table.insert(textparts, format_rhyme(overall_rhyme, min_num_bullets))
	end
	if all_hyph_sets_eq and #first_hyphs > 0 then
		table.insert(textparts, "\n")
		table.insert(textparts, format_hyphenations(first_hyphs, min_num_bullets))
	end
	if overall_hyph and #overall_hyph > 0 then
		table.insert(textparts, "\n")
		table.insert(textparts, format_hyphenations(overall_hyph, min_num_bullets))
	end
	if all_hmp_sets_eq and #first_hmps > 0 then
		table.insert(textparts, "\n")
		table.insert(textparts, format_homophones(first_hmps, min_num_bullets))
	end
	if overall_hmp and #overall_hmp > 0 then
		table.insert(textparts, "\n")
		table.insert(textparts, format_homophones(overall_hmp, min_num_bullets))
	end

	return table.concat(textparts)
end


return export