-- For functions in which the return value type depends on the input and a condition.

local function ReadFromIndex(inval,intbl)
	intbl = Select(NotNilToBool(intbl),intbl,_G)
	local outval = OpenTableLocation(intbl,inval)
	if NotNilToBool(outval) then return outval else return inval end
end

local function Execute(infunc,...)
	if IsFunctionToBool(infunc) then
--		printnote("\nExecute\t", "<" .. tostring(ReadFromIndex(infunc)) .. ">" .. "\nWith Args",...)
		local result = {infunc(...)}
--		printnote("Result For", "<" .. tostring(ReadFromIndex(infunc)) .. ">" .. "\nResult\t",TableUnpack(result))
		return TableUnpack(result)
	else
--		printnote("Execute","Nothing? ", "(" .. tostring(infunc) .. ")")
	end
end

local function ExecuteTable(intbl,...)
	if IsFunctionToBool(intbl[1]) then
--		printnote("ET     ExecuteTable " .. tostring(intbl[1]),"@",tostring(intbl))
		return Execute(TableUnpack(ConcatenateTables(intbl,{...})))
	else
--		printnote("ET     ExecuteTable : Nothing? " .. tostring(intbl))
	end
end

local function SequentialExecuteAndReturn(inval)
	while IsDataLogicToBool(inval) do
		printnote("Executing:",TableUnpack(inval))
		inval = ExecuteTable(inval)
	end
	return inval
end

function ExecSelect(conditiontbl,yestbl,notbl)
	return ExecuteTable(Select(ExecuteTable(conditiontbl),yestbl,notbl))
end

local function ExecuteFromLookupValue(inval)
        return ExecuteTable(_G[inval])
end

local function ExecuteFromTemplate(intbl,...)
--	printnote("EFT    ExecuteFromTemplate " .. tostring(intbl))
	intbl = RecursiveDuplicateTable(intbl)
	return ExecuteTable(ApplyTemplateToTable(EmptyTable(),FillTemplate(1,RecursiveDuplicateTable(intbl),TableUnpack(RecursiveDuplicateTable({...})))))
end

local function ExecuteTableOrFromTemplate(intbl,...)
	if IsFunctionToBool(intbl[1]) then
		return ExecuteTable(intbl,...)
	elseif IsTableToBool(intbl[1]) then	
		return ExecuteFromTemplate(TableUnpack(intbl),...)
	end
end