-- Purely for table returning functions.

local function ProcessTable(intbl) 
        return {ProcessList(TableUnpack(intbl))}
end

function RecursiveProcessTable(intbl)
--      printnote("RPT    Datalogic? " .. tostring(IsDataLogicToBool(intbl)))
--      printnote("RPT    Table? " .. tostring(IsTableToBool(intbl)))
        return {RecursiveProcessList(TableUnpack(intbl))}
end

local function RemoveTemplateEntry(intbl,...)
	local foldadjust = 0
	for i=1,TableLength(intbl) do
		-- Because we want to delete all offending entries, not just the first one we find
		-- We'll have to adjust i every time we fold an entry out of the table.
		-- Otherwise, we'll start reading one value forward from what we're trying to,
		--  for each deletion! This will go right past the end of the table.
		if TableLength(intbl[i - foldadjust]) > 2 then
			local locationadjust = 0
			for j=2,TableLength(intbl[i-foldadjust]) do
				if NumericTablePairMatchToBool({...},ValueToTable(intbl[i-foldadjust][j-locationadjust])) then
					intbl[i-foldadjust] = TableFold(intbl[i-foldadjust],j-locationadjust)
					locationadjust = Add(locationadjust,1)
				end
			end
		elseif NumericTablePairMatchToBool({...},ValueToTable(intbl[i-foldadjust][2])) then
			intbl = TableFold(intbl,i-foldadjust)
			-- Adjust i so that the newly folded table is properly read.
			foldadjust = Add(foldadjust,1)
		end
	end
	return intbl
end

-- Create a template entry, folding into an existing entry if there's an item match.
local function AddTemplateEntry(intbl,inval,...)
	intbl = RemoveTemplateEntry(intbl,...)
	for i=1, TableLength(intbl) do
		if inval == RecursiveOpenTableLocation(intbl,i,1) then
			intbl[i] = RecursiveTableAdd(intbl[i],...)
			return intbl
		end
	end
	return RecursiveTableAdd(intbl,{inval,...})
end

local function ConcatenateTemplates(intplt,intplt2)
	for i=1, TableLength(intplt2) do
		intplt = AddTemplateEntry(intplt,TableUnpack(intplt2[i]))
	end
	return intplt, intplt2
end

local function RecursiveConcatenateTemplates(intplt,...)
	local args = {...}
	for i=1, TableLength(args) do
		if IsTemplateToBool(intplt) and IsTemplateToBool(args[i]) then
			intplt = ConcatenateTemplates(intplt,args[i])
		else
		return intplt
		end
	end
end