--
--	Grail
--	Written by scott@mithrandir.com
--
--	Version History
--		001	Initial version.
--		002	Converted to using a hooked function to register completed quests.
--			Made it so quests that never appear in the quest log can be marked completed assuming the quest data is up to date.
--			Condensed the debug statements.
--			Changed the architecture so extra information can be returned for failure conditions.
--			Switched ProfessionExceeds to be able to use localized names of professions.
--		003	Made it so Darkmoon Faire NPCs return the location based on where the Darkmoon Faire currently is.
--			Removed the QUEST_AUTOCOMPLETE event handling since it seems to be unneeded.
--			Added specialZones which allow mapping of GetZoneText() to things we prefer.
--			Removed the check for IsDaily() and IsWeekly() from the Status routine since they are marked as non-complete when reset happens.
--			Added IsYearly() because there are holiday quests that can be completed only once.
--			Resettable quests (daily/weekly/yearly) are now recorded specially so quests can be queried as to whether they have ever been completed using HasQuestEverBeenCompleted().
--			Added a notification system for accepting and completing quests.
--			Added API to get quests that are available during an event (holiday).
--		004	Corrected a problem where resettable quests could not be saved for initial use.
--			Augmented level checking to maximum level is checked as well.
--			Added a targetLevel parameter to filtering quests.
--			Made it so "Near" NPCs can have a specific zone associated with them which makes their return location table entry have the zone name and the word "Near".
--			Removed the need for specialZones since GetRealZoneText() does what we need.  Switched the use of GetZoneText() to GetRealZoneText().
--			ProfessionExceeds() now returns success and skill level, where skill level can be Grail.NO_SKILL if the player does not have that skill at all.
--			LocationNPC() now has more parameters to refine the locations returned.
--			LocationQuest() now makes use of LocationNPC() changes and can return the NPC name as well.
--		005	Quest titles that do not match our internal database are recorded, which helpfully gives us localizations as well.
--			Made it so repeatable quests are also recorded in the resettable quests list.
--			Did a little optimization by declaring some LUA functions local.
--			Made some quest traversal routines take an optional argument to force garbage collection, which greatly increases the time to return the desired data, but brings the footprint back down.
--			Added a routine to get the riding skill level.
--			Made it so QueryQuestsCompleted() is called at startup because the earlier assumption did not take into account that there was still another add-on that did it.
--			Made it so we call QueryQuestsCompleted() if GetQuestResetTime() indicates that quests have been reset.  LIMITATION: The check that triggers this only happens upon accepting or completing a quest.
--			Corrected a problem in ProfessionExceeds() where the comparison was incorrect.  Also made sure the skill exists before API is called.  Changed the value of Grail.NO_SKILL.
--			IsNPCAvailable() now can work with heroic NPCs in their instances.
--		006	Corrected a problem where the questResetTime variable was misspelled.
--			Made it so the SpecialQuests are cleaned out of the GrailDatabase properly.
--			Switched City of Ironforge to Ironforge to match GetRealZoneText() return value.
--			Added a table that contains the quests per zone to allow QuestsInZone() to return the cached information immediately.
--			Made it so a callback can be registered for quest abandoning.
--		007	Corrected a problem where a mismatch in title would cause a LUA error when attempting to record bad quest data.
--			Made it so the GrailDatabase gets its NewQuests and NewNPCs cleaned out properly.
--			Added a QuestName function so the name can be gotten without need for internal data structure knowledge.
--			Added Quest and NPC localizations for French, German, Russian and Spanish.
--		008	Changed hooking quest completing to actually get the current script associated instead of the global name for the script.
--			Corrected some problems where LUA errors would occur if the internal database did not know about a quest.
--			Added support for a quest to have a prerequisite quest in the quest log and not complete.
--			Added support for automatic quests to indicate the NPC that needs to be killed to initiate quest acceptance.
--			Added support for automatic quests that are obtained from entering a zone.
--			Added a zoneMapping table that maps zone IDs returned by GetCurrentMapAreaID() to those used internally.
--			Made it so Status can ignore prerequisite requirements of a quest.
--			Made LocationQuest also return the NPC ID as well as the other information it returns.
--			Restructured the posting of the abandon notification to be about 0.75 seconds after the button click because it seems the quest log does not actually remove it immediately.
--			Added capability to handle indirect items where another NPC drops the one that starts the quest.  The NPC name returned is an NPC that drops the item followed by the item name in parentheses.
--		009	Added more mappings from GetCurrentMapAreaID().
--			Corrected a problem where some parameter names in Status() were not the same as in the implementation, thereby ignoring their values.
--			Added a QuestLevel() function.
--			MeetsRequirementLevel() now returns the levels used to determine success.
--			Added some quest interrogation routines IsEscort(), IsDungeon(), IsRaid(), IsPVP(), IsGroup() and IsHeroic().
--			Added a QuestsInMap() function that uses a map ID.
--			Added a convenience function SingleMapLocationQuest().
--		010	Added an NPCName() function.
--			Added an IsTooltipNPC() which indicates what type of NPC we are dealing with for those that modify tooltips.
--			Added an AvailableBreadcrumbs() which returns breadcrumb quests available to be gotten for the specified quest.
--		011	Corrected an issue where ensuring all prerequisite quests were confirmed could have been inaccurate.
--			Added AncestorStatus() and made Status() call it so prerequisite quests are checked to ensure they can be completed otherwise the Status will be false.  For example, this makes
--			an entire quest chain unavailable if the race does not permit the first quest to be accepted.
--			Debugging has now been turned off by default.
--			A new feature called tracking has been provided to keep a little history of basic quest activity, but is off by default.
--			Changed the posting of abandon notifications to be about 1.0 seconds after the button click since there were times when 0.75 seconds was not enough, and made it a variable.
--			Added some clearing out of BadQuestData that has been added to the database.
--			Made clearing out of NewQuest data more robust.
--			Changed to have NPC locations use map area IDs.
--			Removed the zoneMapping and zones tables as part of the move to using map area IDs for all locations.
--			Made the quest index per map area computed at runtime for the latest most accurate data.
--		012	Made it so marking a quest complete only does so if the quest is not already complete.  This is just a precaution to handle an edge case.
--			Added the "/grail backup" and "/grail compare" commands to help find quest IDs for quests that do not enter the quest log.
--			Made it so special quests that never appear in the quest log can be recorded as complete when there is more than one quest with the same name as long as the NPC ID is different.
--			Made it so NPC locations return the dungeon level and the alias map ID.
--			Added a lot of quest/NPC information for the Midsummer Fire Festival.
--		013	Updated quests and NPCs for Firelands.
--			Did a bunch of localization.
--		014	Corrected some localization issues.
--			Updates quests and NPCs for Mount Hyjal and Firelands.
--			Corrected quest prerequisite information to remove cycles to make a DAG.
--			Added AncestorQuests() which returns a complicated table structure of prerequisite quests.
--		015	Made low level comparisons use Blizzard's own routine so grey quests appear properly.
--			Added more quest level information.
--			Updates to quests/NPCs for Firelands, Alliance Grizzly Hills, and Kezan.
--			Added processing to have holiday quests stored in their own map areas (besides where the quest givers are) so they can be viewed as a group.
--			Added the ability to handle PH: prerequisites that require a quest to have been completed sometime in the past (used with dailies that are triggers).
--			Added the ability to handle Xc codes which exclude classes (basically the opposite of Cc codes).
--		016	Updates to quests/NPCs for Gilneas, and Durotar.
--			Corrected a problem in MultipleUniqueMapLocationQuest() where the accept or turn in parameter was not being passed along properly.
--		017	Updated quest and NPC data to minimize problems with stack overflows, etc.
--			Made it so questgiver locations with NearXXX codes are ignored like Near.
--			Made it so AncestorStatus is now passed the same ignore flags as Status so any subsequent calls to Status will get passed them as well.
--			Added tables for the five continents' dungeons.
--		018	Set up basic structures to start support for ptBR localization when Brazilian version comes on line.
--			Updated a large number of localizations for quest names.
--			Updates to some Firelands quest/NPC information, as well as Zul'Drak, Tirisfal Glades, Redridge Mountains, Duskwood and Northern Stranglethorn.
--			Implemented support for Sx quest codes which are the logical opposite of Rx codes.
--			Corrected the implementation of Xx codes.
--			Made it so a nil value we sometimes get will no longer crash, but output something helpful.
--		019	Added support for PC: quest codes.
--			Updated some Alliance quest information for Northern Stranglethorn, Cape of Stranglethorn, Dustwallow Marsh, Dun Morogh, Loch Modan, Wetlands, Arathi Highlands, The Hinterlands, Western Plaguelands, Badlands, Searing Gorge, Burning Steppes, Swamp of Sorrows, Darkshore, Teldrassil, Hillsbrad Foothills, Azuremyst, Bloodmyst Isle, Zul'Drak and the capital cities.
--			Updated some quest information for Mulgore, Tirisfal Glades and Silverpine Forest.
--			Made it so AvailableBreadcrumbs() will return breadcrumbs that have prerequisites that can be fulfilled as well as ones that are currently available.
--			K codes for cooking, fishing, and Brewfest quests have been changed to level 0 to indicate the actual level is the same as the player accepting the quest.
--			The zone-specific Self NPCs are now automatically generated for each zone.
--			Changed Status() to return a "Level" failure last of all the checks.
--			Corrected a probem where DEATHKNIGHT was not properly used as the class type.
--			Made it so there is a "map area" that contains all the daily quests.
--			Made "map areas" to contain each of the quests only available to specific classes.
--			Made "map areas" to contain each of the quests only available to specific professions.
--			Made "map areas" to contain each of the quests only available to those with specific reputations with factions.
--			Added support for OAC: quest codes.
--			Added a StatusCode() routine that returns a bitmask of quest status.
--		020	Updates some quest/NPC information for Durotar, Desolace, Southern Barrens, Ironforge, Stonetalon Mountains, Eversong Woods, Eastern Plaguelands, Badlands, Zul'Drak and Ashenvale.
--			Added more support for StatusCode() to support some more bit values plus values from prerequisites.
--			When using StatusCode() quest status values are cached to avoid recomputing values.  The cached values are invalidated as appropriate based on environment and the values of the status.
--			Made IsLowLevel() never consider quests whose level is 0 as low-level since those quests' levels change to match the player level.
--			Removed the Ahn'Qiraj War Effort from the list of world events.
--			Marked Status() as deprecated API which will be removed in the future.
--			Changed the method by which abandoned quests have their notifications posted so the variable abandonedQuestId no longer exists.
--			Added support for LoremasterMapArea() API which provides the map area of the Loremaster achievement for which the quest qualifies.  Also added Grail.loremasterQuests[mapAreaId] tables which list the quests that are used for each Loremaster achievement.
--		021	Updates some quest/NPC information for Feralas, Northern Stranglethorn, Un'Goro Crater, Stormwind City, Ghostlands, Silvermoon City and Cape of Stranglethorn.
--			Updates quest/NPC information for Hallow's End and Day of the Dead.
--			Created caching structure for accessing some quest information to help reduce runtime footprint and increase speed.
--			Added support for OCC:, PLT: and PCT: quest codes.
--			Made QuestsInMap() able to return only quests that qualify for Loremaster.
--			Removed a number of debug slash commands and the functions that were supporting them.
--			Added the CreateRaceNameLocalizedGenderized() routine so race names can be displayed nicely.
--			Removed AncestorStatus(), QuestsWithCode() and Status() and some support routines.
--		022	Updates some quest/NPC information for Mugore, Thunder Bluff, Silverpine Forest, Durotar, Bloodmyst Isle and Azshara.
--			Updates quest/NPC information for Pilgrim's Bounty.
--			Corrected the Gnomeregan reputation name to not include Exiles.
--			Started recording found defects in a new format.
--			Created a system to record when reputation changes do not match what the internal database has.
--			Added the achievement information where quests are associated with specific achievements.
--			Updated the TOC to support Interface 40300.
--		023	Corrects the detection of the Mr Popularity guild perks.
--			Updates some quest/NPC information for Darkmoon Faire, Azshara, Elwynn Forest, class-specific ones and the Bwemba's Spirit line.
--			Adds the missing reputation names to the non-English clients (whose lack was causing addons that use reputation to fail).
--			Updates a lot of Portuguese data.
--			Fixes a problem where unknown quests were not being recorded correctly, causing a LUA error.
--			Fixes a problem where event handlers were not installed properly because Blizzard events cannot arrive in a guaranteed order.
--			Fixes a problem where AZ codes were not being processed properly, thereby resulting in quests with those codes to appear in the current map area instead of their proper one.
--			Fixes a problem where the new Darkmoon Faire quests would not be available on Darkmoon Island unless the UI was reloaded.
--		024	Updates some quest/NPC information for Azshara, Ashenvale, Stonetalon Mountains, Southern Barrens, Dalaran, Shattrath City and some dungeons.
--			Updates some Portuguese localizations.
--			Updates the CleanDatabase() routine to do more cleaning.
--			Makes it so slash commands are not forced to lower case.
--			Changes the way StatusCode() works to not mark a quest complete if it does not meet race, class, gender and/or faction requirements.  This is to work around Blizzard behavior where the server marks quests complete that could not possibly be done by a player.
--			Changes the way StatusCode() works to not mark level problems or invalidation problems with quests that are marked complete.
--			Fixes a problem where CleanDatabase() could attempt to access data that does not exist.
--			Fixes an infinite loop that is sometimes encountered using Blizzard's GetFactionInfo(), found by ArcaneTourist.
--		025	Updates some quest/NPC information for Southern Barrens, Durotar, Northern Barrens, Desolace and Dustwallow Marsh.
--			Adds a Christmas Week holiday that handles the quests in Winter Veil that only start appearing on Christmas Day.
--			Adds a feature to record NPC names that do not match those in the database.
--			Updates some Portuguese localizations.
--			Updates some other localizations, for Winter Veil.
--
--	Known Issues
--
--			The use of GetQuestResetTime() is not adequate, nor is the API good enough to provide us accurate information for weeklies (and possibly yearlies depending on when they actually reset compared to dailies).
--				The check is only made when a quest is accepted or completed, and this means the reset could happen during play and the Blizzard-provided data would be out of date until a restart or one of our
--				monitored events occurs.  This is the price one pays for not using something like OnUpdate.
--
--			Update the "BadQuestData" data recording/cleaning to handle the rest of the failure possibilities.
--			Need to make it so special quests with the same name AND same NPC ID can be handled.  For the Consortium gem quests I believe we will have to check the levels of the Consortium rep to know how to distinguish.
--			Need to make sure quests with PL:, PC:, PCT: and PLT: codes are handled properly.  Basically the quests need to have their validity change based on presence in log, and completedness.  Note that when a PL: is turned in or abandoned anyone with that PL: code needs to be invalidated.  If a quest has a PL: code on it and that quest has been completed, then the quest with the PL: code can never be completed.  The same goes for a quest with PC: on it.
--			When the Blizzard server records multiple quests complete that are mutually exclusive, yet could have been obtained (like the Grateful Dead quests where one can get the race-specific one and the Dalaran one and even the Shattrath one), Grail will not know which one was actually completed.  The only way this seems to be doable, is if Grail records the specific quest -- for a holiday this could possibly use the technique for resettable ones, but in general this may need to be done in a different manner for others.
--			Quests that have a PL: requirement when complete, and the quest in the PL: is no longer in the log, will not show as green, but brown.  Logically they should show as green, but it seems Grail cannot handle this without knowing that the only reason for invalidation is the PL: which it would be nice to do.
--			Think about taking questStatusCache and moving it into quests if possible.  I have not tested to see which is more efficient, its own table or one that already exists.  Or perhaps only part of the structure should be present there.
--			The quests that are part of the OBC codes need to have a way to be marked as complete that will be permanent because server query will lose that data.  Basically there need to be a code associated with the special quests that triggers this since this can be associated with other codes besides OBC.  Is there any reason that this cannot be recorded in the repeatable quests structure?  I have created an actuallyCompletedQuests table which mimics the others that are ones the addon actually marks as complete for whatever reason.  The supporting infrastructure needs to look at this data to indicate when something with I codes should be green versus brown.
--
--	UTF-8 file
--

local Grail_File_Version = 025

if nil == Grail or Grail.versionNumber < Grail_File_Version then

	local tinsert, tContains = tinsert, tContains
	local strsplit, strfind, strformat, strsub = strsplit, string.find, string.format, string.sub
	local pairs = pairs

	--	Even though it is documented that UNIT_QUEST_LOG_CHANGED is preferable to QUEST_LOG_UPDATE, in practice UNIT_QUEST_LOG_CHANGED fails
	--	to do what it is supposed to do.  In fact, processing cannot properly happen using it and not QUEST_LOG_UPDATE, even with proper
	--	priming of the data structures.  Therefore, this addon makes use of QUEST_LOG_UPDATE instead.  Actually, this has proven to be a
	--	little unreliable as well, so a hooked function is now used instead.

	--	It would be really convenient to be able not to store the localized names of the quests and the NPCs.  However, the only real way
	--	to get any arbitrary one (that is not in the quest log) is to populate the tooltip with a hyperlink.  However, that will not normally
	--	return results immediately from a server query, so another attempt at tooltip population is needed.  In the case of quests, this
	--	works pretty well.  However, with NPCs the results are less than satisfactory.  In reality, we want the information to be readily
	--	available for when someone needs it, so polling the server is not convenient.  Therefore, we will continue to store the localized
	--	names of these objects so they are available immediately to the caller.  This means the size of the add-on in memory is going to
	--	be constant and not growing overtime if we were to attempt to populate the information in the background (which we would want to do
	--	to make the information available).

	--	Instead of trying to deal with the concept of having NPCs who have unique IDs to be associated with each other but only be available
	--	in specific "phases", the availability of an NPC should probably be checked through the use of determining whether a quest can be
	--	obtained.  Normally, the prerequisite structure of the quests will indicate specific quests cannot yet be obtained, and those are
	--	likely to be associated with the NPCs that will be in new "phases".  Therefore, nothing special needs be done in this library, but
	--	the onus can be put on the user of this library to ensure only quest givers for available quests are listed/shown.

	--
	--	Caching of the quest status.
	--
	--	If the status of a quest is requested, and that status already exists in the cache, then the cache results
	--	should be returned.  When the status of a quest is computed it is added to the quest status cache.  The
	--	cache of a quest status can be invalidated based on what happens in the environment and the status of the
	--	quest.  For example, if a quest was marked as being too high for the player to obtain, but the player gains
	--	a level, that quest status in the cache needs to be removed so it can be recomputed when needed.
	--

	--	For some quests Blizzard marks others complete when you complete one.  For example, Firelands dailies are in groups and when you
	--	finish one, the others are marked complete on the server.  This tends not to be a problem.  However, Blizzard also does this with
	--	quests the player would never be able to acquire, like the starting zone class-specific quests.  So, when a mage completes its
	--	class quest the server marks the class quests for hunter, warrior, etc. also complete.  This seems idiotic as Blizzard already has
	--	other mechanisms to limit a mage from getting a hunter quest, for example.  This causes a problem with the way Grail evaluates the
	--	status of a quest, since it is done "live" because quests have so many relationships.  In general, the quests that one could never
	--	aquire are evaluated such during play, and in the future when they are marked complete on the server they will be both marked
	--	complete since we must believe what the server reports, and will be marked unobtainable for whatever reasons are appropriate.
	--	This works well except for when we attempt to evaluate prerequisites because part of prerequisites is to see if the required quest
	--	is complete.  However, we also check to see whether the quest can be obtained.  The flaw that we currently have is that we are
	--	evaluating whether the quest can be obtained currently, which is technically incorrect because it should be can the quest be
	--	obtained at the time the quest is marked complete.  Of course we can only know this if we keep track of which specific quests are
	--	marked complete when any other is done.  This is yet another level of annoyance that Blizzard causes that it need not.  So, Grail
	--	is going to approximate this for the time being with evaluating the current ability to accept a quest that was complete.

	--	Database of stored information per character.
	GrailDatabase = { }
	--	The completedQuests is a table of 32-bit integers.  The index in the table indicates which set of 32 bits are being used and the value at that index
	--	is a bit representation of completed quests in that 32 quest range.  For example, quest 7 being the only one completed in the quests from 1 to 32
	--	would mean table entry 0 would have a value of 64.  Quest 33 being done would mean [1] = 1, while quests 33 and 35 would mean [1] = 5.  The user need
	--	not know any of this since the API to access this information takes care of the dirty work.
	--	The completedResettableQuests is just like completedQuests except it records only those quests that Blizzard resets like dailies and weeklies.  This
	--	is used for API that can determine if a quest has ever been completed (since a daily could have been completed in the past, but Blizzard's API would
	--	indicate that it is currently not completed (because it has been reset)).
	--	There are four possible tables of interest:  NewNPCs, NewQuests, SpecialQuests and BadQuestData.
	--	These tables could be used to provide feedback which can be used to update the internal database to provide more accurate quest information.

	Grail = {
		versionNumber = Grail_File_Version,
		questsVersionNumber = 0,
		npcsVersionNumber = 0,
		zonesVersionNumber = 0,
		zonesIndexedVersionNumber = 0,
		achievementsVersionNumber = 0,
		reputationsVersionNumber = 0,
		INFINITE_LEVEL = 100000,
		NO_SKILL = -1,
		NPC_TYPE_BY = 'BY',
		NPC_TYPE_DROP = 'DROP',
		NPC_TYPE_KILL = 'KILL',
		abandonPostNotificationDelay = 1.0,
		abandoningQuestIndex = nil,
		-- Bit mask system for quest status
		-- First bits are "good" bits
		bitMaskNothing = 0x0000,
		bitMaskCompleted = 0x0001,
		bitMaskRepeatable = 0x0002,
		bitMaskResettable = 0x0004,
		bitMaskEverCompleted = 0x0008,
		bitMaskInLog = 0x0010,
		bitMaskLevelTooLow = 0x0020,		-- the player's level is too low for the quest currently
		bitMaskLowLevel = 0x0040,			-- the quest is a low-level quest compared to the player's level
		-- These are really failure bits
		bitMaskClass = 0x0080,
		bitMaskRace = 0x0100,
		bitMaskGender = 0x0200,
		bitMaskFaction = 0x0400,
		bitMaskInvalidated = 0x0800,
		bitMaskProfession = 0x1000,
		bitMaskReputation = 0x2000,
		bitMaskHoliday = 0x4000,
		bitMaskLevelTooHigh = 0x8000,	-- the player's level is too high for the quest
		-- This next one indicates no prerequisites have been fulfilled
		bitMaskPrerequisites = 0x10000,
		-- These are failure bits for ancestor quests if bitMaskPrerequisites is set.  They are the same
		-- as the previous set of failure bits * 1024
		bitMaskAncestorClass = 0x20000,
		bitMaskAncestorRace = 0x40000,
		bitMaskAncestorGender = 0x80000,
		bitMaskAncestorFaction = 0x100000,
		bitMaskAncestorInvalidated = 0x200000,
		bitMaskAncestorProfession = 0x400000,
		bitMaskAncestorReputation = 0x800000,
		bitMaskAncestorHoliday = 0x1000000,
		bitMaskAncestorLevelTooHigh = 0x02000000,
		-- Informational bits
		bitMaskInLogComplete = 0x04000000,
		bitMaskInLogFailed = 0x08000000,
		-- These basically represent internal errors within the database
		bitMaskNonexistent = 0x40000000,
		bitMaskError = 0x80000000,
		-- Some convenience values precomputed
		bitMaskQuestFailure = 0xff80,	-- from bitMaskClass to bitMaskLevelTooHigh
		bitMaskQuestFailureWithAncestor = 0x03feff80,	-- bitMaskQuestFailure + (bitMaskAncestorClass to bitMaskAncestorLevelTooHigh)
		bitMaskAcceptableMask = 0xffffffb1,	-- all bits except bitMaskRepeatable, bitMaskResettable, bitMaskEverCompleted and bitMaskLowLevel
		-- End of Bit mask values
		-- Bit mask system for other quest information indicating who can get a quest
		-- Faction
		bitMaskFactionAlliance	=	0x00000001,
		bitMaskFactionHorde		=	0x00000002,
		-- Class
		bitMaskClassDeathKnight	=	0x00000004,
		bitMaskClassDruid		=	0x00000008,
		bitMaskClassHunter		=	0x00000010,
		bitMaskClassMage		=	0x00000020,
		bitMaskClassMonk		=	0x00000040,
		bitMaskClassPaladin		=	0x00000080,
		bitMaskClassPriest		=	0x00000100,
		bitMaskClassRogue		=	0x00000200,
		bitMaskClassShaman		=	0x00000400,
		bitMaskClassWarlock		=	0x00000800,
		bitMaskClassWarrior		=	0x00001000,
		-- Gender
		bitMaskGenderMale		=	0x00002000,
		bitMaskGenderFemale		=	0x00004000,
		-- Race
		bitMaskRaceHuman		=	0x00008000,
		bitMaskRaceDwarf		=	0x00010000,
		bitMaskRaceNightElf		=	0x00020000,
		bitMaskRaceGnome		=	0x00040000,
		bitMaskRaceDraenei		=	0x00080000,
		bitMaskRaceWorgen		=	0x00100000,
		bitMaskRaceOrc			=	0x00200000,
		bitMaskRaceScourge		=	0x00400000,
		bitMaskRaceTauren		=	0x00800000,
		bitMaskRaceTroll		=	0x01000000,
		bitMaskRaceBloodElf		=	0x02000000,
		bitMaskRaceGoblin		=	0x04000000,
		bitMaskRacePandaren		=	0x08000000,
		-- Some convenience values
		bitMaskFactionAll		=	0x00000003,
		bitMaskClassAll			=	0x00001ffc,
		bitMaskGenderAll		=	0x00006000,
		bitMaskRaceAll			=	0x0fff8000,
		-- End of bit mask values
		-- Bit mask system for information about type of quest and levels
		bitMaskQuestRepeatable	=	0x00000001,
		bitMaskQuestDaily		=	0x00000002,
		bitMaskQuestWeekly		=	0x00000004,
		bitMaskQuestMonthly		=	0x00000008,
		bitMaskQuestYearly		=	0x00000010,
		bitMaskQuestEscort		=	0x00000020,
		bitMaskQuestDungeon		=	0x00000040,
		bitMaskQuestRaid		=	0x00000080,
		bitMaskQuestPVP			=	0x00000100,
		bitMaskQuestGroup		=	0x00000200,
		bitMaskQuestHeroic		=	0x00000400,
		bitMaskQuestLevel		=	0xfe000000,	-- top 7 bits represent the actual quest level (0 - 127)
		bitMaskQuestMinLevel	=	0x01fc0000,	-- next 7 bits represent the minimum level to get the quest (0 - 127)
		bitMaskQuestMaxLevel	=	0x0003f800,	-- next 7 bits represent the maximum level allowed to get the quest (0 - 127)
		-- Some convenience values
		bitMaskQuestNonLevel	=	0x000007ff,
		bitMaskQuestLevelOffset = 0x02000000,
		bitMaskQuestMinLevelOffset = 0x00040000,
		bitMaskQuestMaxLevelOffset = 0x00000800,
		-- End of bit mask values
		-- Bit mask system for holidays
		bitMaskHolidayLove		=	0x00000001,
		bitMaskHolidayBrewfest	=	0x00000002,
		bitMaskHolidayChildren	=	0x00000004,
		bitMaskHolidayDead		=	0x00000008,
		bitMaskHolidayDarkmoon	=	0x00000010,
		bitMaskHolidayHarvest	=	0x00000020,
		bitMaskHolidayLunar		=	0x00000040,
		bitMaskHolidayMidsummer	=	0x00000080,
		bitMaskHolidayNoble		=	0x00000100,
		bitMaskHolidayPirate	=	0x00000200,
		bitMaskHolidayNewYear	=	0x00000400,
		bitMaskHolidayWinter	=	0x00000800,
		bitMaskHolidayHallow	=	0x00001000,
		bitMaskHolidayPilgrim	=	0x00002000,
		-- End of bit mask values
		classMapping = { ['K'] = 'DEATHKNIGHT', ['D'] = 'DRUID', ['H'] = 'HUNTER', ['M'] = 'MAGE', ['O'] = 'MONK', ['P'] = 'PALADIN', ['T'] = 'PRIEST', ['R'] = 'ROGUE', ['S'] = 'SHAMAN', ['L'] = 'WARLOCK', ['W'] = 'WARRIOR', },
		classToBitMapping = { ['K'] = 0x00000004, ['D'] = 0x00000008, ['H'] = 0x00000010, ['M'] = 0x00000020, ['O'] = 0x00000040, ['P'] = 0x00000080, ['T'] = 0x00000100, ['R'] = 0x00000200, ['S'] = 0x00000400, ['L'] = 0x00000800, ['W'] = 0x00001000, },
		classToMapAreaMapping = { ['CK'] = 200011, ['CD'] = 200004, ['CH'] = 200008, ['CM'] = 200013, ['CO'] = 200015, ['CP'] = 200016, ['CT'] = 200020, ['CR'] = 200018, ['CS'] = 200019, ['CL'] = 200012, ['CW'] = 200023, },
		completingQuest = nil,
		completingQuestTitle = nil,
		continents = {},
		currentlyProcessingStatus = {},
		currentlyVerifying = false,
		currentMortalIssues = {},
		currentQuestIndex = nil,
		debug = false,
		emergencyOutlet = 0,
		eventDispatch = {			-- table of functions whose keys are the events
			['CHAT_MSG_COMBAT_FACTION_CHANGE'] = function(self, frame, message)
				if nil ~= self.questStatusCache then
					self:StatusCodeInvalidate(self.questStatusCache["R"])
					self.questStatusCache["R"] = {}
				end
				self:RecordReputation(message)
			end,
			['CHAT_MSG_SKILL'] = function(self, frame)
				if nil ~= self.questStatusCache then
					self:StatusCodeInvalidate(self.questStatusCache["P"])
					self.questStatusCache["P"] = {}
				end
			end,
			['PLAYER_LEVEL_UP'] = function(self, frame, newLevel)
				self.levelingLevel = tonumber(newLevel)
				if nil ~= self.questStatusCache then
					self:StatusCodeInvalidate(self.questStatusCache["L"])
					self.questStatusCache["L"] = {}
					self:StatusCodeInvalidate(self.questStatusCache["V"])
					self.questStatusCache["V"] = {}
				end
			end,
			['PLAYER_LOGIN'] = function(self, frame)
				if self.receivedVariablesLoaded then self:PlayerLogin(frame) end
				self.receivedPlayerLogin = true
			end,
			['QUEST_ACCEPTED'] = function(self, frame, questIndex)
				local questTitle, level, questTag, suggestedGroup, isHeader, isCollapsed, isComplete, isDaily, questId = GetQuestLogTitle(questIndex)
				local npcId = nil
				local version = self.versionNumber.."/"..self.questsVersionNumber.."/"..self.npcsVersionNumber.."/"..self.zonesVersionNumber

				-- Get the target information to ensure the target exists in the database of NPCs
				local targetName, npcId, coordinates = self:TargetInformation()
				self:UpdateTargetDatabase(targetName, npcId, coordinates, version)

				--	If this quest is not in our internal database attempt to record some information about it so we have a chance the
				--	user can provide this to us to update the database.
				if not isHeader then
					self:UpdateQuestDatabase(questId, questTitle, npcId, isDaily, 'A', version)
				end

				--	If we think we should not have been able to accept this quest we should record some information that may help us update our faulty database.
				local statusCode = self:StatusCode(questId)
				local errorString = 'G' .. self.versionNumber .. '|' .. questId .. '|' .. statusCode
				if not self:CanAcceptQuest(questId, false, false, true) then
					-- look at the reason and record the reason and contrary information for that reason
					if bit.band(statusCode, self.bitMaskLevelTooLow + self.bitMaskLevelTooHigh) > 0 then errorString = errorString .. "|L:" .. UnitLevel('player') end
					if bit.band(statusCode, self.bitMaskClass) > 0 then errorString = errorString .. "|C:" .. self.playerClass end
-- TODO: Correct the fact that |R results in the loss of the R because it is a code used in their strings
					if bit.band(statusCode, self.bitMaskRace) > 0 then errorString = errorString .. "|R:" .. self.playerRace end
					if bit.band(statusCode, self.bitMaskGender) > 0 then errorString = errorString .. "|G:" .. self.playerGender end
					if bit.band(statusCode, self.bitMaskFaction) > 0 then errorString = errorString .. "|F:" .. self.playerFaction end
					if bit.band(statusCode, self.bitMaskInvalidated) > 0 then

					end
					if bit.band(statusCode, self.bitMaskProfession) > 0 then
-- TODO: Need to look at all the professions associated with the quest and record the actual profession values the user currently has for them

					end
					if bit.band(statusCode, self.bitMaskReputation) > 0 then
-- TODO: Same as professions, but with reputations instead

					end
					if bit.band(statusCode, self.bitMaskHoliday) > 0 then
-- TODO: Determine if we actually need to mark which holiday caused the problem because when CleanDatabase comes across this without the specific one, it can only remove this if there is NO holiday associated with the quest.
						errorString = errorString .. "HOL"
					end
					if bit.band(statusCode, self.bitMaskPrerequisites) > 0 then

					end
					self:RecordBadQuestData(errorString)
				end

				--	If the questTitle is different from what we have recorded, note that as BadQuestData (even though it could just be a localization issue)
				if self:DoesQuestExist(questId) and questTitle ~= self:QuestName(questId) then
					errorString = errorString .. "|Title:" .. questTitle .. "|Locale:" .. self.playerLocale
					self:RecordBadQuestData(errorString)
				end

				--	If the level as reported by Blizzard API does not match our internal database we should note that fact
				if self:DoesQuestExist(questId) then
					local internalQuestLevel = self:QuestLevel(questId)
					if 0 ~= internalQuestLevel and (internalQuestLevel or 1) ~= level then
						errorString = errorString .. "|Level:" .. level
						self:RecordBadQuestData(errorString)
					end
				end

				self:PostNotification("Accept", questId)

				-- If there is an OAC: code associated with the quest we need to complete all the quests listed there.
				local oacCodes = self:QuestOnAcceptCompletes(questId)
				if nil ~= oacCodes then
					for i = 1, #oacCodes do
						self:MarkQuestComplete(oacCodes[i], true, true)
					end
				end

				if self.debug then
					local debugMessage = "Grail Debug: Accepted quest: ".. questTitle .. " (" .. questId .. ") from "
					if nil ~= targetName then debugMessage = debugMessage .. targetName .. " (" .. npcId .. ") " .. coordinates else debugMessage = debugMessage .. "no target" end
					if not self:CanAcceptQuest(questId, false, false, true) then debugMessage = debugMessage .. " but should not accept because of: " .. errorString else debugMessage = debugMessage .. " without problems" end
					DEFAULT_CHAT_FRAME:AddMessage(debugMessage)
				end
				self:UpdateQuestResetTime()
			end,
			['QUEST_COMPLETE'] = function(self, frame)
				local titleText = GetTitleText()
				self.completingQuest = self:QuestInQuestLogMatchingTitle(titleText)
				self.completingQuestTitle = titleText
				if nil == self.completingQuest then	-- if we still do not have it, mark it in the saved variables for possible future inclusion
					if nil == GrailDatabase["SpecialQuests"] then GrailDatabase["SpecialQuests"] = { } end
					if nil == GrailDatabase["SpecialQuests"][titleText] then GrailDatabase["SpecialQuests"][titleText] = true end
				end
				self:UpdateQuestResetTime()
			end,
			['UNIT_QUEST_LOG_CHANGED'] = function(self, frame, arg1)
				if arg1 == "player" then
					-- Get all the quests in the Blizzard quest log and invalidate their status cache values if they have changed with regard to completed/failed
					local questsInLog = {}
					local i = 1
					local bitsToCheckAgainst = self.bitMaskInLog + self.bitMaskInLogComplete + self.bitMaskInLogFailed
					while GetQuestLogTitle(i) do
						local _, _, _, _, isHeader, _, completionStatus, _, questId = GetQuestLogTitle(i)
						if (not isHeader) then
--							local cachedStatus = self.questStatusCache["quests"][questId]
							local cachedStatus = self.quests[questId][7]
							if nil ~= cachedStatus then
								local soughtBitMask = self.bitMaskInLog
								local foundComplete = false
								if completionStatus then
									if completionStatus > 0 then soughtBitMask = soughtBitMask + self.bitMaskInLogComplete foundComplete = true end
									if completionStatus < 0 then soughtBitMask = soughtBitMask + self.bitMaskInLogFailed end
								end
								if bit.band(cachedStatus, bitsToCheckAgainst) ~= soughtBitMask then
									tinsert(questsInLog, questId)
									if foundComplete then
										local occCodes = self.quests[questId]['OCC']
										if nil ~= occCodes then
											for j = 1, #occCodes do
												self:MarkQuestComplete(occCodes[j], true, true)
												tinsert(questsInLog, occCodes[j])
											end
										end
									end
								end
							end
						end
						i = i + 1
					end
					self:StatusCodeInvalidate(questsInLog)
				end
			end,
			['QUEST_QUERY_COMPLETE'] = function(self, frame, arg1)
				DEFAULT_CHAT_FRAME:AddMessage("Grail starting to process completed query results")
				--	First make a temporary backup of what we think is completed
				local temporaryBackupQuests = {}
				for i, v in pairs(GrailDatabase[self.playerRealm][self.playerName]["completedQuests"]) do
					temporaryBackupQuests[i] = v
				end
				--	Now process the completed quests from the server query results
				local completedQuests = { }
				local db = GrailDatabase[self.playerRealm][self.playerName]
				GetQuestsCompleted(completedQuests)
				local hour, minute = GetGameTime()
				local weekday, month, day, year = CalendarGetDate()
				db["serverUpdated"] = strformat("%4d-%02d-%02d %02d:%02d", year, month, day, hour, minute)
				db["completedQuests"] = { }
				for v,_ in pairs(completedQuests) do
					self:MarkQuestComplete(v)
				end
				--	Now invalidate any quests whose completed status from the backup does not match the server
				local questsToInvalidate = {}
				local backup, current, diff, base
				for index, value in pairs(db["completedQuests"]) do
					if value ~= nil then
						if db["completedQuests"][index] ~= temporaryBackupQuests[index] then
							backup = temporaryBackupQuests[index] or 0
							current = db["completedQuests"][index] or 0
							if current ~= backup then
								if current > backup then
									diff = current - backup
								else
									diff = backup - current
								end
								base = index * 32
								for i = 0, 31 do
									if bit.band(diff, 2^i) > 0 then
										tinsert(questsToInvalidate, base + i + 1)
									end
								end
							end
						end
					end
				end
				if 0 < #questsToInvalidate then self:StatusCodeInvalidate(questsToInvalidate) end
				--	Remove the temporary backup
				wipe(temporaryBackupQuests)
				DEFAULT_CHAT_FRAME:AddMessage("Grail finished processing completed query results")
			end,
			['VARIABLES_LOADED'] = function(self, frame)

				-- We have loaded GrailDatabase at this point, but we need to ensure the structure is set up for first-time players as we rely on at least an empty structure existing
				if nil == GrailDatabase[self.playerRealm] then GrailDatabase[self.playerRealm] = { } end
				if nil == GrailDatabase[self.playerRealm][self.playerName] then GrailDatabase[self.playerRealm][self.playerName] = { } end
				if nil == GrailDatabase[self.playerRealm][self.playerName]["completedQuests"] then GrailDatabase[self.playerRealm][self.playerName]["completedQuests"] = { } end
				if nil == GrailDatabase[self.playerRealm][self.playerName]["completedResettableQuests"] then GrailDatabase[self.playerRealm][self.playerName]["completedResettableQuests"] = { } end
				if nil == GrailDatabase[self.playerRealm][self.playerName]["actuallyCompletedQuests"] then GrailDatabase[self.playerRealm][self.playerName]["actuallyCompletedQuests"] = { } end

				--	Ensure the tooltip is not messed up
				if not com_mithrandir_grailTooltip:IsOwned(UIParent) then
					com_mithrandir_grailTooltip:SetOwner(UIParent, "ANCHOR_NONE")
				end

				self:RegisterSlashOption("debug", "|cFF00FF00debug|r => toggles debug on and off, printing new value", function()
					self.debug = not self.debug
					print(format("Grail Debug now %s", self.debug and "ON" or "OFF"))
				end)
				self:RegisterSlashOption("target", "|cFF00FF00target|r => gets target information (NPC ID and your current location)", function()
					local targetName, npcId, coordinates = self:TargetInformation()
					if targetName == nil then targetName = 'nil target' end
					if npcId == nil then npcId = -1 end
					if coordinates == nil then coordinates = 'no coords' end
					local message = format("%s (%d) %s", targetName, npcId, coordinates)
					print(message)
					self:AddTrackingMessage(message)
				end)
				self:RegisterSlashOption("c ", "|cFF00FF00c|r |cFFFF8C00msg|r => adds the |cFFFF8C00msg|r to the tracking data", function(msg)
					self:AddTrackingMessage(strsub(msg, 3))
				end)
				self:RegisterSlashOption("comment ", "|cFF00FF00comment|r |cFFFF8C00msg|r => adds the |cFFFF8C00msg|r to the tracking data", function(msg)
					self:AddTrackingMessage(strsub(msg, 9))
				end)
				self:RegisterSlashOption("tracking", "|cFF00FF00tracking|r => toggles tracking on and off, printing new value", function()
					self.tracking = not self.tracking
					print(format("Grail Tracking now %s", self.tracking and "ON" or "OFF"))
					if self.tracking then
						self:RegisterObserverQuestAbandon(Grail.AddTrackingCallback)
						self:RegisterObserverQuestAccept(Grail.AddTrackingCallback)
						self:RegisterObserverQuestComplete(Grail.AddTrackingCallback)
					else
						self:UnregisterObserverQuestAbandon(Grail.AddTrackingCallback)
						self:UnregisterObserverQuestAccept(Grail.AddTrackingCallback)
						self:UnregisterObserverQuestComplete(Grail.AddTrackingCallback)
					end
				end)
				self:RegisterSlashOption("help", "|cFF00FF00help|r => print out this list of commands", function()
					print("|cFFFF0000Grail|r slash commands:")
					for option, value in pairs(self.slashCommandOptions) do
						print("|cFFFF0000/grail|r",value['help'])
					end
					print("|cFFFF0000/grail|r => initiates a database query to get completed quests [this happens at startup normally]")
				end)
				self:RegisterSlashOption("backup", "|cFF00FF00backup|r => creates a backup copy of the completed quests used for comparison", function()
					GrailDatabase[self.playerRealm][self.playerName]["backupCompletedQuests"] = {}
					for i, v in pairs(GrailDatabase[self.playerRealm][self.playerName]["completedQuests"]) do
						GrailDatabase[self.playerRealm][self.playerName]["backupCompletedQuests"][i] = v
					end
					print("|cFFFF0000Grail|r: A backup of the completed quests has been made")
				end)
				self:RegisterSlashOption("compare", "|cFF00FF00compare|r => compares the current completed quest list to the backup copy", function()
					local db = GrailDatabase[self.playerRealm][self.playerName]
					if nil == db["backupCompletedQuests"] then print("Please do |cFF00FF00/grail backup|r first") return
					else print("Starting quest comparison between completed quests and backup") end
					for index, value in pairs(db["completedQuests"]) do
						if value ~= nil then
							if db["completedQuests"][index] ~= db["backupCompletedQuests"][index] then
								local backup = db["backupCompletedQuests"][index] or 0
								local current = db["completedQuests"][index] or 0
								if current > backup then
									local diff = current - backup
									-- index 0 covers 1 - 32
									-- index 1 covers 33 - 64
									-- index 2 covers 65 - 96
									local base = index * 32

									for i = 0, 31 do
										if bit.band(diff, 2^i) > 0 then
											local message = strformat("New quest completed %d", base + i + 1)
											print(message)
											self:AddTrackingMessage(message)
										end
									end
								else
									print("Index", index, "has a backup bigger than the current, which is not expected")
									local diff = backup - current
									-- index 0 covers 1 - 32
									-- index 1 covers 33 - 64
									-- index 2 covers 65 - 96
									local base = index * 32

									for i = 0, 31 do
										if bit.band(diff, 2^i) > 0 then
											local message = strformat("New quest LOST %d", base + i + 1)
											print(message)
											self:AddTrackingMessage(message)
										end
									end
								end
							end
						end
					end
					print("End quest comparison")
				end)

				-- Here we deal with the fact that VARIABLES_LOADED may happen after PLAYER_LOGIN which is not how
				-- we want things to process.
				if self.receivedPlayerLogin then self:PlayerLogin(frame) end
				self.receivedVariablesLoaded = true
			end,
			},
		factionMapping = { ['A'] = 'Alliance', ['H'] = 'Horde', },
		genderMapping = { ['M'] = 2, ['F'] = 3, },
		holidayMapping = { ['A'] = 'Love is in the Air', ['B'] = 'Brewfest', ['C'] = "Children's Week", ['D'] = 'Day of the Dead', ['F'] = 'Darkmoon Faire',
				['H'] = 'Harvest Festival', ['L'] = 'Lunar Festival', ['M'] = 'Midsummer Fire Festival', ['N'] = 'Noblegarden', ['P'] = "Pirates' Day",
				['U'] = 'New Year', ['V'] = 'Feast of Winter Veil', ['W'] = "Hallow's End", ['Y'] = "Pilgrim's Bounty", ['Z'] = "Christmas Week", },
		holidayToBitMapping = { ['A'] = 0x00000001, ['B'] = 0x00000002, ['C'] = 0x00000004, ['D'] = 0x00000008, ['F'] = 0x00000010,
				['H'] = 0x00000020, ['L'] = 0x00000040, ['M'] = 0x00000080, ['N'] = 0x00000100, ['P'] = 0x00000200,
				['U'] = 0x00000400, ['V'] = 0x00000800, ['W'] = 0x00001000, ['Y'] = 0x00002000, ['Z'] = 0x00004000, },
		holidayToMapAreaMapping = { ['HA'] = 100001, ['HB'] = 100002, ['HC'] = 100003, ['HD'] = 100004, ['HF'] = 100006, ['HH'] = 100008, ['HL'] = 100012, ['HM'] = 100013,
				['HN'] = 100014, ['HP'] = 100016, ['HQ'] = 100017, ['HU'] = 100021, ['HV'] = 100022, ['HW'] = 100023, ['HY'] = 100025, ['HZ'] = 100026, },
		indexedQuests = {},
		indexedQuestsExtra = {},
		levelingLevel = nil,	-- this is set during the PLAYER_LEVEL_UP event because UnitLevel() does not work during it
		mapAreaBaseAchievement = 500000,
		mapAreaBaseClass = 200000,
		mapAreaBaseDaily = 400000,
		mapAreaBaseHoliday = 100000,
		mapAreaBaseProfession = 300000,
		mapAreaBaseReputation = 400000,	-- note that 400000 is used for Daily
		mapAreaBaseReputationChange = 600000,
		mapAreaMapping = {},
		mapAreaMaximumAchievement = 599999,
		mapAreaMaximumClass = 299999,
		mapAreaMaximumDaily = 400000,	-- not used since Daily really is only every one area
		mapAreaMaximumHoliday = 199999,
		mapAreaMaximumProfession = 399999,
		mapAreaMaximumReputation = 499999,
		mapAreaMaximumReputationChange = 599999,
		observers = { },
		origAbandonQuestFunction,
		origConfirmAbandonQuestFunction,
		origHookFunction,
		playerClass,
		playerFaction,
		playerGender,
		playerLocale,
		playerName,
		playerRace,
		playerRealm,
		professionMapping = { ['A'] = 'Alchemy', ['B'] = 'Blacksmithing', ['C'] = 'Cooking', ['E'] = 'Enchanting', ['F'] = 'Fishing', ['H'] = 'Herbalism',
				['I'] = 'Inscription', ['J'] = 'Jewelcrafting', ['L'] = 'Leatherworking', ['M'] = 'Mining', ['N'] = 'Engineering', ['P'] = 'Lockpicking',
				['R'] = 'Riding', ['S'] = 'Skinning', ['T'] = 'Tailoring', ['U'] = 'Runeforging', ['X'] = 'Archaeology', ['+'] = 'First Aid', },
		-- might be able to make use of the following global strings that have the values associated PROFESSIONS_ARCHAEOLOGY PROFESSIONS_COOKING PROFESSIONS_FIRST_AID PROFESSIONS_FISHING
		professionToMapAreaMapping = { ['PA'] = 300001, ['PB'] = 300002, ['PC'] = 300003, ['PE'] = 300005, ['PF'] = 300006, ['PH'] = 300008, ['PI'] = 300009, ['PJ'] = 300010, ['PL'] = 300012, ['PM'] = 300013, ['PN'] = 300014, ['PP'] = 300016, ['PR'] = 300018, ['PS'] = 300019, ['PT'] = 300020, ['PU'] = 300021, ['PX'] = 300024, ['P+'] = 300043, },
		questNPCId = nil,
		questResetTime = 0,
		raceMapping = { ['H'] = 'Human', ['F'] = 'Dwarf', ['E'] = 'NightElf', ['N'] = 'Gnome', ['D'] = 'Draenei', ['W'] = 'Worgen', ['O'] = 'Orc', ['U'] = 'Scourge', ['T'] = 'Tauren', ['L'] = 'Troll', ['B'] = 'BloodElf', ['G'] = 'Goblin', ['A'] = 'Pandaren', },
		raceNameFemaleMapping = { ['H'] = 'Human', ['F'] = 'Dwarf', ['E'] = 'Night Elf', ['N'] = 'Gnome', ['D'] = 'Draenei', ['W'] = 'Worgen', ['O'] = 'Orc', ['U'] = 'Undead', ['T'] = 'Tauren', ['L'] = 'Troll', ['B'] = 'Blood Elf', ['G'] = 'Goblin', ['A'] = 'Pandaren', },
		raceNameMapping = { ['H'] = 'Human', ['F'] = 'Dwarf', ['E'] = 'Night Elf', ['N'] = 'Gnome', ['D'] = 'Draenei', ['W'] = 'Worgen', ['O'] = 'Orc', ['U'] = 'Undead', ['T'] = 'Tauren', ['L'] = 'Troll', ['B'] = 'Blood Elf', ['G'] = 'Goblin', ['A'] = 'Pandaren', },
		raceToBitMapping = { ['H'] = 0x00008000, ['F'] = 0x00010000, ['E'] = 0x00020000, ['N'] = 0x00040000, ['D'] = 0x00080000, ['W'] = 0x00100000, ['O'] = 0x00200000, ['U'] = 0x00400000, ['T'] = 0x00800000, ['L'] = 0x01000000, ['B'] = 0x02000000, ['G'] = 0x04000000, ['A'] = 0x08000000, },
		reputationClassicMapping = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, },
		reputationBurningCrusadeMapping = { 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 59, 60, },
		reputationWrathMapping = { 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, },
		reputationCataclysmMapping = { 56, 81, 57, 58, 80, 83, 84, 85, 86, },
		reputationMapping = {
			[01] = 'Darnassus', [02] = 'Gnomeregan', [03] = 'Ironforge', [04] = 'Stormwind', [05] = 'Exodar', [06] = 'Gilneas', [07] = 'Darkspear Trolls', [08] = 'Orgrimmar',
			[09] = 'Thunder Bluff', [10] = 'Undercity', [11] = 'Silvermoon City', [12] = 'Bilgewater Cartel', [13] = 'The League of Arathor', [14] = 'Silverwing Sentinels', [15] = 'Stormpike Guard', [16] = 'The Defilers',
			[17] = 'Frostwolf Clan', [18] = 'Warsong Outriders', [19] = 'Booty Bay', [20] = 'Everlook', [21] = 'Gadgetzan', [22] = 'Ratchet', [23] = 'Cenarion Expedition', [24] = 'Honor Hold',
			[25] = 'Kurenai', [26] = "The Mag'har", [27] = "Ogri'la", [28] = 'Netherwing', [29] = 'Sporeggar', [30] = 'The Consortium', [31] = 'Thrallmar', [32] = 'Lower City',
			[33] = "Sha'tari Skyguard", [34] = 'Shattered Sun Offensive', [35] = 'The Aldor', [36] = 'The Scryers', [37] = "The Sha'tar", [38] = 'Alliance Vanguard', [39] = 'Argent Crusade', [40] = "Explorers' League",
			[41] = 'Frenzyheart Tribe', [42] = 'The Frostborn', [43] = 'The Hand of Vengeance', [44] = 'Horde Expedition', [45] = "The Kalu'ak", [46] = 'Knights of the Ebon Blade', [47] = 'The Oracles', [48] = 'The Sons of Hodir',
			[49] = 'The Taunka', [50] = 'Valiance Expedition', [51] = 'Warsong Offensive', [52] = 'The Wyrmrest Accord', [53] = 'Kirin Tor', [54] = 'The Silver Covenant', [55] = 'The Sunreavers', [56] = 'Guardians of Hyjal',
			[57] = 'The Earthen Ring', [58] = 'Therazane', [59] = 'The Ashen Verdict', [60] = 'Ashtongue Deathsworn', [61] = 'Brood of Nozdormu', [62] = 'Cenarion Circle', [63] = 'Hydraxian Waterlords', [64] = 'The Scale of the Sands',
			[65] = 'Zandalar Tribe', [66] = 'Argent Dawn', [67] = 'Bloodsail Buccaneers', [68] = 'Darkmoon Faire', [69] = 'Gelkis Clan Centaur', [70] = 'Keepers of Time', [71] = 'Magram Clan Centaur', [72] = 'Ravenholdt',
			[73] = "Shen'dralar", [74] = 'Syndicate', [75] = 'Thorium Brotherhood', [76] = 'Timbermaw Hold', [77] = 'Tranquillien', [78] = 'The Violet Eye', [79] = 'Wintersaber Trainers', [80] = 'Wildhammer Clan',
			[81] = 'Ramkahen', [82] = 'Guild', [83] = "Hellscream's Reach", [84] = "Dragonmaw Clan", [85] = "Baradin's Wardens", [86] = "Avengers of Hyjal",
			},
		slashCommandOptions = {},
		specialQuests = { },
		statusMapping = { ['C'] = "Completed", ['F'] = 'Faction', ['G'] = 'Gender', ['H'] = 'Holiday', ['I'] = 'Invalidated', ['L'] = "InLog",
			['P'] = 'Profession', ['Q'] = 'Prerequisites', ['R'] = 'Race', ['S'] = 'Class', ['T'] = 'Reputation', ['V'] = "Level", },
		timeSinceLastUpdate = 0,
		tooltip = nil,
		tracking = false,
		trackingStarted = false,
		useAncestor = true,
		verifyTable = {},
		verifyTableCount = 0,
		zoneNameMapping = {},	-- maps zone names into map IDs

		---
		--	Internal Use.
		AddQuestToMapArea = function(self, questId, mapAreaId, title)
			if nil ~= questId and nil ~= mapAreaId then
				if nil == self.indexedQuests[mapAreaId] then self.indexedQuests[mapAreaId] = {} end
				if not tContains(self.indexedQuests[mapAreaId], questId) then tinsert(self.indexedQuests[mapAreaId], questId) end
				if nil == self.mapAreaMapping[mapAreaId] then self.mapAreaMapping[mapAreaId] = title end
			end
		end,

		---
		--	Internal Use.
		--	This routine is registered to be called when any of the notifications this addon can post are posted.
		--	It formats a message that is stored in the tracking system.
		--	@param callbackType The string representing the type of callback as posted by the notification system.
		--	@param questId The standard questId posted by the notification system.
		AddTrackingCallback = function(callbackType, questId)
			local message = strformat("%s %s(%d)", callbackType, Grail:QuestName(questId) or "NO NAME", questId)
			if "Accept" == callbackType or "Complete" == callbackType then
				local targetName, npcId, coordinates = Grail:TargetInformation()
				if nil ~= targetName then
					if nil == npcId then npcId = -123 end
					if nil == coordinates then coordinates = "NO COORDS" end
					message = strformat("%s %s %s(%d) %s", message, ("Accept" == callbackType) and "from" or "to", targetName, npcId, coordinates)
				end
			end
			Grail:AddTrackingMessage(message)
		end,

		---
		--	Internal Use.
		--	This adds the provided message to the tracking system.  The first time this is called, a timestamp with some player
		--	information is logged into the tracking system as well.
		--	@param msg The string that will be added to the tracking system.
		AddTrackingMessage = function(self, msg)
			if nil == GrailDatabase["Tracking"] then GrailDatabase["Tracking"] = {} end
			if not self.trackingStarted then
				local hour, minute = GetGameTime()
				local weekday, month, day, year = CalendarGetDate()
				tinsert(GrailDatabase["Tracking"], strformat("%4d-%02d-%02d %02d:%02d %s/%s/%s/%s/%s/%s", year, month, day, hour, minute, self.playerRealm, self.playerName, self.playerFaction, self.playerClass, self.playerRace, self.playerGender))
				self.trackingStarted = true
			end
			tinsert(GrailDatabase["Tracking"], msg)
		end,

		AliasQuestId = function(self, questId)	return self:QuestGenericAccess(questId, 'Y')	end,

-- TODO: Work on this code and the following to be able to replace AncestorStatusCode properly
		AncestorStatusCodeHelper = function(self, quests, masterQuestId, baseStatusCode)
			if nil ~= quests then
				local anyFailure = nil
				for _, questId in pairs(quests) do
					if nil == self.questStatusCache["Q"][questId] then sef.questStatusCache["Q"][questId] = {} end
					if not tContains(self.questStatusCache["Q"][questId], masterQuestId) then tinsert(self.questStatusCache["Q"][questId], masterQuestId) end
					if nil == anyFailure then
						local subCode = self:StatusCode(questId)
						local failureBits = bit.band(subCode, self.bitMaskQuestFailure)
						if failureBits > 0 then
							-- this means this specific quest has bits in it that would cause failure (need not check prerequisites for it at all since it fails by itself)
							-- and that means since this is part of an AND clause (which could be a sole quest technically), the AND clause fails
							anyFailure = failureBits
						elseif bit.band(subCode, self.bitMaskPrerequisites) > 0 then
							-- this means the quest itself does not immediately fail, but it fails because of prerequisites, so that reason needs to be checked in
							-- case it is one of the hard reasons for failure
							failureBits = bit.band(subCode, self.bitMaskQuestFailureWithAncestor)
							if failureBits > 0 then
								-- this means the quest has a prerequisite quest that fails in one of the hard ways
								anyFailure = failureBits / 1024
							end
						end
					end
				end
				-- TODO: Continue working on this
				
			end
			return baseStatusCode
		end,

		NEWAncestorStatusCode = function(self, questId, baseStatusCode)
			local prerequisites = self:QuestPrerequisites(questId)
			if nil ~= prerequisites then
				local valueToUse
				for key, value in pairs(prerequisites) do
					valueToUse = ("table" == type(value)) and value or {value}
					XXX = self:AncestorStatusCodeHelper(valueToUse, questId, baseStatusCode)
				end
			end
			return baseStatusCode
		end,

-- TODO:	Transform this code to use the new code that has all the P type codes available to it.
		AncestorStatusCode = function(self, questId, baseStatusCode)
			-- First, gather all the quests that can possibly make up the prerequisite list
			local allCodes = ""
			allCodes = self:AppendQuestCodes(questId, "P:", allCodes)
			allCodes = self:AppendQuestCodes(questId, "PL:", allCodes)
			allCodes = self:AppendQuestCodes(questId, "PH:", allCodes)
			allCodes = self:AppendQuestCodes(questId, "PC:", allCodes)
			allCodes = self:AppendQuestCodes(questId, "PLT:", allCodes)
			allCodes = self:AppendQuestCodes(questId, "PCT:", allCodes)

			-- Now process the list by splitting it apart by the OR clauses symbolized by commas, and within the AND clauses symbolized by pluses
			local questArray = { strsplit(",", allCodes) }
			if nil ~= questArray then
				local possibleFailure = nil
				local foundSuccess = false
				for i = 1, #questArray do
					-- each of these elements is considered part of an OR clause, so any that match would qualify as a success
					local eachQuest = { strsplit("+", questArray[i]) }
					local anyFailure = nil
					for j = 1, #eachQuest do
						-- each of these elements is considered part of an AND clause, so all must match to be true
						local currentQuestId = tonumber(eachQuest[j])
						if nil == self.questStatusCache["Q"][currentQuestId] then self.questStatusCache["Q"][currentQuestId] = {} end
						if not tContains(self.questStatusCache["Q"][currentQuestId], questId) then tinsert(self.questStatusCache["Q"][currentQuestId], questId) end
						if nil == anyFailure then
							local subCode = self:StatusCode(currentQuestId)
							local failureBits = bit.band(subCode, self.bitMaskQuestFailure)
							if failureBits > 0 then
								-- this means this specific quest has bits in it that would cause failure (need not check prerequisites for it at all since it fails by itself)
								-- and that means since this is part of an AND clause (which could be a sole quest technically), the AND clause fails
								anyFailure = failureBits
							elseif bit.band(subCode, self.bitMaskPrerequisites) > 0 then
								-- this means the quest itself does not immediately fail, but it fails because of prerequisites, so that reason needs to be checked in
								-- case it is one of the hard reasons for failure
								failureBits = bit.band(subCode, self.bitMaskQuestFailureWithAncestor)
								if failureBits > 0 then
									-- this means the quest has a prerequisite quest that fails in one of the hard ways
									anyFailure = failureBits / 1024
								end
							end
						end
					end
					if nil ~= anyFailure and nil == possibleFailure then
						possibleFailure = anyFailure
					end
					if nil == anyFailure then	-- normally we would break out of the loop here, but we need to register all the quests to be able to invalidate properly
						foundSuccess = true
					end
				end
				if not foundSuccess and nil ~= possibleFailure then
					baseStatusCode = baseStatusCode + (1024 * possibleFailure)
				end
			end
		return baseStatusCode
		end,

		---
		--	Internal Use.
		--	This looks at each of the quests in the quests table, and makes the appropriate checks to see
		--	whether they have been completed, are in the log, etc. based on the parameters used.  If all
		--	of the quests pass muster true is returned, otherwise false.
		AllEvaluateTrue = function(self, quests, masterQuestId, dangerous, checkLog, checkEver, checkStatusComplete, shouldCheckTurnin)
			local stillGood = true
			if nil ~= quests then
				local questCompleted, questInLog, questStatus, questEverCompleted, canAcceptQuest
				local checkTurnin = (nil ~= shouldCheckTurnin) and shouldCheckTurnin or true
				for _, questId in pairs(quests) do
					questCompleted = self:IsQuestCompleted(questId)
					questInLog, questStatus = self:IsQuestInQuestLog(questId)
					questEverCompleted = self:HasQuestEverBeenCompleted(questId)
					canAcceptQuest = true
					if (checkTurnin and questCompleted) or (checkEver and questEverCompleted) then
						if dangerous then
							if nil == self.currentMortalIssues[questId] then self.currentMortalIssues[questId] = {} end
							if not tContains(self.currentMortalIssues[questId], masterQuestId) then tinsert(self.currentMortalIssues[questId], masterQuestId) end
						else
							canAcceptQuest = self:CanAcceptQuest(questId, true)
						end
					end
					stillGood = stillGood and (
						(checkTurnin and questCompleted and canAcceptQuest) or		-- PLT, P, PH, PCT
						(checkLog and questInLog) or								-- PL
						(checkEver and questEverCompleted and canAcceptQuest) or	-- PH
						(checkStatusComplete and questInLog and questStatus ~= nil and questStatus > 0)	-- PC
						)
				end
			end
			return stillGood
		end,

		---
		--	Internal Use.
		--	This looks at the code with appropriate prefix from the specified log and analyzes it to determine if any of the quests
		--	the code contains have been completed, or if checkLog is true, are in the quest log.  The format for the code is a comma
		--	separated list of single questIds that match or if more than one is required to match, they are separated by a plus.  So:
		--	<br>123,456,789+1122,3344<br>means and of the following quests would match:<br>123<br>456<br>789 and 1122<br>3344<br>
		--	@param questId The standard numeric questId representing a quest.
		--	@param codePrefix An prefix used to determine which type of internal code to process.
		--	@param checkLog If true, quests in the quest log are also checked, otherwise they are not.
		--	@param checkEver If true, quests that have ever been completed are checked, otherwise they are not.
		--	@return True if any of the codes quests are completed (or appropriately in the quest log), false otherwise.
		--	@return True is there actually is a code that needed checking, false otherwise.
		--	@return A table of failures, or nil if there are none.
		AnyEvaluateTrue = function(self, questId, codePrefix, checkLog, checkEver, checkStatusComplete, shouldCheckTurnin)
			questId = tonumber(questId)
			if nil == questId or nil == self.quests[questId] then return false end
			local anyEvaluateTrue = false
			local requirementPresent = false
			local codeValues = self.quests[questId][codePrefix]
			local dangerous = (codePrefix == 'I')
			if nil ~= codeValues then
				local valueToUse
				requirementPresent = true
				for key, value in pairs(codeValues) do
					valueToUse = ("table" == type(value)) and value or {value}
					anyEvaluateTrue = self:AllEvaluateTrue(valueToUse, questId, dangerous, checkLog, checkEver, checkStatusComplete, shouldCheckTurnin)
					if anyEvaluateTrue then break end
				end

			end
			return anyEvaluateTrue, requirementPresent
		end,

-- TODO:	Remove this once the routine that uses it is weaned from it
		AppendQuestCodes = function(self, questId, code, allCodes)
			allCodes = allCodes or ""
			local codes = self:CodesWithPrefixQuest(questId, code)
			if nil ~= codes then
				for i = 1, #codes do
					local colonPosition = (strfind(codes[i], ':') or 0) + 1
					if strlen(allCodes) > 0 then allCodes = allCodes .. "," end
					allCodes = allCodes .. strsub(codes[i], colonPosition)
				end
			end
			return allCodes
		end,

		---
		--	Returns a table of questIds that are available breadcrumb quests for the specified quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@return A table of questIds for available breadcrumb quests for this quest, or nil if there are none.
		AvailableBreadcrumbs = function(self, questId)
			local retval = {}
			local possible = self:QuestBreadcrumbs(questId)
			if nil ~= possible then
				for _, qid in pairs(possible) do
					if self:CanAcceptQuest(qid, false, true) then
						tinsert(retval, qid)
					end
				end
			end
			if 0 == #retval then retval = nil end
			return retval
		end,

		CanAcceptQuest = function(self, questId, ignoreCompleted, ignorePrerequisites, ignoreInLog, ignoreLevelTooLow)
			local bitValue = self.bitMaskAcceptableMask
			if ignoreCompleted then bitValue = bitValue - self.bitMaskCompleted end
			if ignorePrerequisites then bitValue = bitValue - self.bitMaskPrerequisites end
			if ignoreInLog then bitValue = bitValue - self.bitMaskInLog - self.bitMaskInLogComplete end
			if ignoreLevelTooLow then bitValue = bitValue - self.bitMaskLevelTooLow end
			return (0 == bit.band(self:StatusCode(questId), bitValue))
		end,

		---
		--	Determines whether the soughtHolidayName is currently being celebrated.
		--	@param soughtHolidayName The localized name of a holiday, like Brewfest or Darkmoon Faire.
		--	@return true if the holiday is being celebrated currently, or false otherwise
		CelebratingHoliday = function(self, soughtHolidayName)
			local retval = false
			local weekday, month, day, year = CalendarGetDate()
			local i = 1
			local needsChristmasOrLater = false
			if self.holidayMapping['Z'] == soughtHolidayName then
				needsChristmasOrLater = true
				soughtHolidayName = self.holidayMapping['V']
			end
			while CalendarGetDayEvent(0, day, i) do
				local title, hour, minute, calendarType, sequenceType, eventType, texture, modStatus, inviteStatus, invitedBy, difficulty, inviteType = CalendarGetDayEvent(0, day, i)
				if eventType == 0 and calendarType == 'HOLIDAY' then
					if title == soughtHolidayName then
						retval = true
					end
				end
				i = i + 1
			end
			if retval and needsChristmasOrLater then
				if 12 == month and 25 > day then
					retval = false
				end
			end
			if self.holidayMapping['U'] == soughtHolidayName then
				if (12 == month and 31 == day) then
					retval = true
				end
			end
			return retval
		end,

		---
		--	Internal Use.
		--	This routine attempts to remove items from the special tables that are stored in the GrailDatabase table
		--	when they have been added to the internal database.  These special tables are populated when Grail discovers
		--	something lacking in its internal database as game play proceeds.  This routine is called upon startup.
		CleanDatabase = function(self)

			-- Remove quests from SpecialQuests that have been marked as special in our internal database.
			if nil ~= GrailDatabase["SpecialQuests"] then
				for questName, _ in pairs(GrailDatabase["SpecialQuests"]) do
					local questId = self:QuestWithName(questName)
					if self.quests[questId] and  self.quests[questId]['SP'] then
						GrailDatabase["SpecialQuests"][questName] = nil
					end
				end
			end

			-- Remove quests from NewQuests that have been added to our internal database.
			-- If the name matches and all the codes are in our internal datbase we remove.
			if nil ~= GrailDatabase["NewQuests"] then
				for questId, q in pairs(GrailDatabase["NewQuests"]) do
					if self:DoesQuestExist(questId) then
						if q[self.playerLocale] == self:QuestName(questId) or q[self.playerLocale] == "No Title Stored" then
							local allCodesGood = true
							if nil ~= q[1] then
								local codeArray = { strsplit(" ", q[1]) }
								for _, code in pairs(codeArray) do
									if code ~= "" then
										if "A:" == strsub(code, 1, 2) then
											local npcId = tonumber(strsub(code, 3))
											if 0 == npcId then
												local foundAny = false
												if nil ~= self.quests[questId]['A'] then
													for _, n in pairs(self.quests[questId]['A']) do
														if n <= 0 then foundAny = true end
													end
												end
												if not foundAny then allCodesGood = false end
											elseif nil == self.quests[questId]['A'] or not tContains(self.quests[questId]['A'], npcId) then
												allCodesGood = false
											end
										elseif "T:" == strsub(code, 1, 2) then
											local npcId = tonumber(strsub(code, 3))
											if 0 == npcId then
												local foundAny = false
												if nil ~= self.quests[questId]['T'] then
													for _, n in pairs(self.quests[questId]['T']) do
														if n <= 0 then foundAny = true end
													end
												end
												if not foundAny then allCodesGood = false end
											elseif nil == self.quests[questId]['T'] or not tContains(self.quests[questId]['T'], npcId) then
												allCodesGood = false
											end
										else
											print("|rffff0000Grail|c found NewQuests quest ID", questId, "with unknown code", code)
										end
									end
								end
							end
							if allCodesGood then GrailDatabase["NewQuests"][questId] = nil end
						end
					end
				end
			end

			-- Remove NPCs from NewNPCs that have been added to our internal database
			-- Basically, if the name matches and we have a location in our internal database we remove
			if nil ~= GrailDatabase["NewNPCs"] then
				for npcId, n in pairs(GrailDatabase["NewNPCs"]) do
					local locations, npcName = self:LocationNPC(npcId)
					if nil ~= npcName and n[self.playerLocale] == npcName and nil ~= locations then
						GrailDatabase["NewNPCs"][npcId] = nil
					end
				end
			end

			-- BadNPCData is processed like BadQuestData (which follows)
			if nil ~= GrailDatabase["BadNPCData"] then
				local newBadNPCData = {}
				for k, v in pairs(GrailDatabase["BadNPCData"]) do
					local startPos, endPos, grailVersion, npcId, restOfString = strfind(v, "G(%d+)|(%d+)(.*)")
					local writables = {}
					if nil ~= startPos then
						npcId = tonumber(npcId)
						if nil ~= restOfString then
							local codes = { strsplit('|', restOfString) }
							if nil ~= codes then
								local nameValue = nil	-- used in conjunction with localeValue
								local localeValue = nil	-- used in conjunction with nameValue
								for _, v in pairs(codes) do
									if nil == v or "" == v then
										-- skip it
									elseif "Locale:" == strsub(v, 1, 7) then
										localeValue = strsub(v, 8)
										if nil ~= nameValue then
											if localeValue ~= self.playerLocale or nameValue ~= self:NPCName(npcId) then
												tinsert(writables, "Name:" .. nameValue)
												tinsert(writables, "Locale:" .. localeValue)
											end
										end
									elseif "Name:" == strsub(v, 1, 5) then
										nameValue = strsub(v, 6)
										if nil ~= localeValue then
											if localeValue ~= self.playerLocale or nameValue ~= self:NPCName(npcId) then
												tinsert(writables, "Name:" .. nameValue)
												tinsert(writables, "Locale:" .. localeValue)
											end
										end
									else
										tinsert(writables, v)
									end
								end
							end
						end
					end
					if 0 < #writables then
						local whatToWrite = 'G' .. grailVersion .. '|' .. npcId
						for _, w in pairs(writables) do
							whatToWrite = whatToWrite .. '|' .. w
						end
						tinsert(newBadNPCData, whatToWrite)
					end
				end
				GrailDatabase["BadNPCData"] = newBadNPCData
			end

			-- The BadQuestData will be analyzed against the current database and things that have been fixed
			-- in the current database will be removed from BadQuestData.  This is done by creating a new table
			-- and only putting things that are not fixed into it.
			if nil ~= GrailDatabase["BadQuestData"] then
				local newBadQuestData = {}
				for k, v in pairs(GrailDatabase["BadQuestData"]) do
					if "table" ~= type(v) then
						local startPos, endPos, grailVersion, questId, statusCode, restOfString = strfind(v, "G(%d+)|(%d+)|(%d+)(.*)")
						local writables = {}

						if nil ~= startPos then
							questId = tonumber(questId)
							statusCode = tonumber(statusCode)
							if nil ~= restOfString then
								local codes = { strsplit('|', restOfString) }
								if nil ~= codes then
									local titleValue = nil	-- used in conjunction with localeValue
									local localeValue = nil	-- used in conjunction with titleValue
									for _, v in pairs(codes) do
										if nil == v or "" == v then
											-- skip it
										elseif "Rep:" == strsub(v, 1, 4) and 4 < strlen(v) then
											if nil == self.quests[questId] or nil == self.quests[questId][6] or not tContains(self.quests[questId][6], strsub(v, 5)) then
												tinsert(writables, v)
											end
										elseif "UnknownRep:" == strsub(v, 1, 11) then
											local startPos2, endPos2, reputationName, changeAmount = strfind(strsub(v, 12), "(.*) (-?%d+)")
											local shouldWrite = true
											local whatToWrite = v
											if nil ~= startPos2 then
												local reputationIndex = self.reverseReputationMapping[reputationName]
												if nil ~= reputationIndex then
													if 82 == reputationIndex then	-- remove the Guild reputation indexes that beta testers may have since we do not want them
														shouldWrite = false
													else
														local repChangeString = strformat("%02d%d", reputationIndex, changeAmount)
														if nil ~= self.quests[questId][6] and tContains(self.quests[questId][6], repChangeString) then
															shouldWrite = false
														else
															whatToWrite = strformat("Rep:%s", repChangeString)
														end
													end
												end
											end
											if shouldWrite then tinsert(writables, whatToWrite) end
										elseif "C:" == strsub(v, 1, 2) then
											if not self:MeetsRequirementClass(questId, strsub(v, 3)) then tinsert(writables, v) end
										elseif "F:" == strsub(v, 1, 2) then
											if not self:MeetsRequirementFaction(questId, strsub(v, 3)) then tinsert(writables, v) end
										elseif "G:" == strsub(v, 1, 2) then
											if not self:MeetsRequirementGender(questId, strsub(v, 3)) then tinsert(writables, v) end
										elseif "L:" == strsub(v, 1, 2) then
											if not self:MeetsRequirementLevel(questId, tonumber(strsub(v, 3))) then tinsert(writables, v) end
										elseif "R:" == strsub(v, 1, 2) then
											if not self:MeetsRequirementRace(questId, strsub(v, 3)) then tinsert(writables, v) end
										elseif "Level:" == strsub(v, 1, 6) then
											local internalLevel = self:QuestLevel(questId)
											local actualLevel = tonumber(strsub(v, 7))
											if 0 ~= internalLevel and (internalLevel or 1) ~= actualLevel then
												tinsert(writables, v)
											end
										elseif "Locale:" == strsub(v, 1, 7) then
											localeValue = strsub(v, 8)
											if nil ~= titleValue then
												if localeValue ~= self.playerLocale or titleValue ~= self:QuestName(questId) then
													tinsert(writables, "Title:" .. titleValue)
													tinsert(writables, "Locale:" .. localeValue)
												end
											end
										elseif "Title:" == strsub(v, 1, 6) then
											titleValue = strsub(v, 7)
											if nil ~= localeValue then
												if localeValue ~= self.playerLocale or titleValue ~= self:QuestName(questId) then
													tinsert(writables, "Title:" .. titleValue)
													tinsert(writables, "Locale:" .. localeValue)
												end
											end
										else
											tinsert(writables, v)
										end
									end
								end
							end
						end
						if 0 < #writables then
							local whatToWrite = 'G' .. grailVersion .. '|' .. questId .. '|' .. statusCode
							for _, w in pairs(writables) do
								whatToWrite = whatToWrite .. '|' .. w
							end
							tinsert(newBadQuestData, whatToWrite)
						end
					end
				end
				GrailDatabase["BadQuestData"] = newBadQuestData
			end
		end,

		CoalesceDelayedNotification = function(self, notificationName, delay)
			local needToPost = true
			if nil ~= self.delayedNotifications then
				for i = 1, #(self.delayedNotifications) do
					if notificationName == self.delayedNotifications[i]["n"] then
						needToPost = false
					end
				end
			end
			if needToPost then
				self:PostDelayedNotification(notificationName, nil, delay)
			end
		end,

		---
		--	Internal use.
		--	Populates the internal caches for all the fixed codes that are derived from quest data.
		--	@param questId The standard numeric questId representing a quest.
		CodeAllFixed = function(self, questId)
			questId = tonumber(questId)

			if nil ~= questId then

				--	We just need to use one of the caches as the signal to compute them since they are all done together
				if nil ~= self.quests[questId] and nil == self.quests[questId][2] then
					local typeValue = 0
					local holidayValue = 0
					local obtainersValue = 0

					local codeString = self.quests[questId][1] or nil
					if nil ~= codeString then
						local codeArray = { strsplit(" ", codeString) }
						local c
						local code
						local codeValue
						local bitValue
						local foundTFaction = false
						local foundAFaction = false
						for i = 1, #codeArray do
							c = codeArray[i]
							code = strsub(c, 1, 1)
							codeValue = strsub(c, 2, 2)

							if 'C' == code then
								bitValue = self.classToBitMapping[codeValue]
								if nil ~= bitValue then
									obtainersValue = obtainersValue + bitValue
								else
									print("|cFFFF0000Grail Error|r: Quest",questId,"has unknown code:",c)
								end

							elseif 'X' == code then
								--	The inherent nature of an X code makes is such that only one has meaning, and C codes should not be combined
								bitValue = self.classToBitMapping[codeValue]
								if nil ~= bitValue then
									obtainersValue = bit.band(obtainersValue, bit.bnot(self.bitMaskClassAll))
									obtainersValue = obtainersValue + self.bitMaskClassAll - bitValue
								else
									print("|cFFFF0000Grail Error|r: Quest",questId,"has unknown code:",c)
								end

							elseif 'F' == code then
								if 'A' == codeValue then
									obtainersValue = obtainersValue + self.bitMaskFactionAlliance
								elseif 'H' == codeValue then
									obtainersValue = obtainersValue + self.bitMaskFactionHorde
								else
									print("|cFFFF0000Grail Error|r: Quest",questId,"has unknown code:",c)
								end

							elseif 'G' == code then
								if 'M' == codeValue then
									obtainersValue = obtainersValue + self.bitMaskGenderMale
								elseif 'F' == codeValue then
									obtainersValue = obtainersValue + self.bitMaskGenderFemale
								else
									print("|cFFFF0000Grail Error|r: Quest",questId,"has unknown code:",c)
								end

							elseif 'R' == code then
								bitValue = self.raceToBitMapping[codeValue]
								if nil ~= bitValue then
									obtainersValue = obtainersValue + bitValue
								else
									print("|cFFFF0000Grail Error|r: Quest",questId,"has unknown code:",c)
								end

							elseif 'S' == code then
								if 'P' ~= codeValue then
									--	The inherent nature of an S code makes is such that only one has meaning, and R codes should not be combined
									bitValue = self.raceToBitMapping[codeValue]
									if nil ~= bitValue then
										obtainersValue = bit.band(obtainersValue, bit.bnot(self.bitMaskRaceAll))
										obtainersValue = obtainersValue + self.bitMaskRaceAll - bitValue
									else
										print("|cFFFF0000Grail Error|r: Quest",questId,"has unknown code:",c)
									end
								else
									self.quests[questId]['SP'] = true
								end

							elseif 'K' == code then
								typeValue = typeValue + (tonumber(strsub(c, 2, 4)) * self.bitMaskQuestLevelOffset)
								if strlen(c) > 4 then
									local kValue = tonumber(strsub(c, 5))
									if kValue > 0 then	-- we only do this check because we still use + codes
										-- clear the proper bits from self.bitMaskQuestNonLevel
										typeValue = bit.band(typeValue, bit.bnot(self.bitMaskQuestNonLevel))
										-- add in the bits set in the K code
										typeValue = typeValue + kValue
									end
								end

							elseif 'L' == code then
								typeValue = typeValue + ((tonumber(strsub(c, 2)) or 1) * self.bitMaskQuestMinLevelOffset)

							elseif 'M' == code then
								typeValue = typeValue + ((tonumber(strsub(c, 2)) or 127) * self.bitMaskQuestMaxLevelOffset)

							elseif 'H' == code then
								bitValue = self.holidayToBitMapping[codeValue]
								if nil ~= bitValue then
									holidayValue = holidayValue + bitValue
								else
									print("|cFFFF0000Grail Error|r: Quest",questId,"has unknown code:",c)
								end

							elseif '+' == code then
								if '+' == codeValue then
									typeValue = typeValue + self.bitMaskQuestRepeatable
								elseif 'D' == codeValue then
									typeValue = typeValue + self.bitMaskQuestDaily
								elseif 'W' == codeValue then
									typeValue = typeValue + self.bitMaskQuestWeekly
								elseif 'M' == codeValue then
									typeValue = typeValue + self.bitMaskQuestMonthly
								elseif 'Y' == codeValue then
									typeValue = typeValue + self.bitMaskQuestYearly
								else
									print("|cFFFF0000Grail Error|r: Quest",questId,"has unknown code:",c)
								end

							elseif 'V' == code or 'W' == code then
								local reputationIndex = tonumber(strsub(c, 2, 3))
								local reputationValue = tonumber(strsub(c, 4, 8))
								if nil == self.quests[questId]['rep'] then self.quests[questId]['rep'] = {} end
								if nil == self.quests[questId]['rep'][reputationIndex] then self.quests[questId]['rep'][reputationIndex] = {} end
								self.quests[questId]['rep'][reputationIndex][('V' == code) and 'min' or 'max'] = reputationValue

							elseif 'O' == code then
								if ':' == codeValue then
									self.quests[questId]['O'] = self:FromPattern(strsub(c, 3))
								elseif 'A' == codeValue and strlen(c) > 4 and 'OAC:' == strsub(c, 1, 4) then
									self.quests[questId]['OAC'] = self:FromList(strsub(c, 5))
								elseif 'B' == codeValue and strlen(c) > 4 and 'OBC:' == strsub(c, 1, 4) then
									self.quests[questId]['OBC'] = self:FromList(strsub(c, 5))
								elseif 'C' == codeValue and strlen(c) > 4 and 'OCC:' == strsub(c, 1, 4) then
									self.quests[questId]['OCC'] = self:FromList(strsub(c, 5))
								elseif 'T' == codeValue and strlen(c) > 4 and 'OTC:' == strsub(c, 1, 4) then
									self.quests[questId]['OTC'] = self:FromPattern(strsub(c, 5))
								else
									print("|cFFFF0000Grail Error|r: Quest",questId,"has unknown code:",c)
								end

							elseif 'Y' == code then
								if ':' == codeValue then
									self.quests[questId]['Y'] = tonumber(strsub(c, 3))
								else
									print("|cFFFF0000Grail Error|r: Quest",questId,"has unknown code:",c)
								end

							elseif 'T' == code then
								if ':' == codeValue then
									if not foundTFaction then self.quests[questId]['T'] = self:FromList(strsub(c, 3)) end
								elseif 'A' == codeValue or 'H' == codeValue then
									if (('Horde' == self.playerFaction) and 'H' or 'A') == codeValue then
										self.quests[questId]['T'] = self:FromList(strsub(c, 4))
										foundTFaction = true
									end
								else
									print("|cFFFF0000Grail Error|r: Quest",questId,"has unknown code:",c)
								end

							elseif 'I' == code then
								if ':' == codeValue then
									self.quests[questId]['I'] = self:FromPattern(strsub(c, 3))
								else
									print("|cFFFF0000Grail Error|r: Quest",questId,"has unknown code:",c)
								end

							elseif 'A' == code then
								if ':' == codeValue then
									if not foundAFaction then self.quests[questId]['A'] = self:FromList(strsub(c, 3)) end
								elseif 'A' == codeValue or 'H' == codeValue then
									if (('Horde' == self.playerFaction) and 'H' or 'A') == codeValue then
										self.quests[questId]['A'] = self:FromList(strsub(c, 4))
										foundAFaction = true
									end
								elseif 'K' == codeValue then
									self.quests[questId]['AK'] = self:FromList(strsub(c, 4))
								elseif 'Z' == codeValue then
									self.quests[questId]['AZ'] = tonumber(strsub(c, 4))
								else
									print("|cFFFF0000Grail Error|r: Quest",questId,"has unknown code:",c)
								end

							elseif 'B' == code then
								self.quests[questId]['B'] = tonumber(strsub(c, 2))

							elseif 'P' == code then
								local colonCheck = strsub(c, 3, 3) 
								if ':' == codeValue then
									self.quests[questId]['P'] = self:FromPattern(strsub(c, 3))
								elseif 'L' == codeValue and ':' == colonCheck then
									self.quests[questId]['PL'] = self:FromPattern(strsub(c, 4))
								elseif 'L' == codeValue and 'T' == colonCheck and ':' == strsub(c, 4, 4) then
									self.quests[questId]['PLT'] = self:FromPattern(strsub(c, 5))
								elseif 'H' == codeValue and ':' == colonCheck then
									self.quests[questId]['PH'] = self:FromPattern(strsub(c, 4))
								elseif 'C' == codeValue and ':' == colonCheck then
									self.quests[questId]['PC'] = self:FromPattern(strsub(c, 4))
								elseif 'C' == codeValue and 'T' == colonCheck and ':' == strsub(c, 4, 4) then
									self.quests[questId]['PCT'] = self:FromPattern(strsub(c, 5))
								elseif nil ~= self.professionMapping[codeValue] then
									if nil == self.quests[questId]['prof'] then self.quests[questId]['prof'] = {} end
									self.quests[questId]['prof'][codeValue] = tonumber(strsub(c, 3))
								else
									print("|cFFFF0000Grail Error|r: Quest",questId,"has unknown code:",c)
								end
							end

						end

						--	Since the assumption is if there is a lack of code present to limit those permitted to
						--	obtain quests, checks must be done to see whether any limitations are present, and if
						--	none, the values need to be altered to permit all of those subset.
						if 0 == bit.band(obtainersValue, self.bitMaskFactionAll) then obtainersValue = obtainersValue + self.bitMaskFactionAll end
						if 0 == bit.band(obtainersValue, self.bitMaskClassAll) then obtainersValue = obtainersValue + self.bitMaskClassAll end
						if 0 == bit.band(obtainersValue, self.bitMaskGenderAll) then obtainersValue = obtainersValue + self.bitMaskGenderAll end
						if 0 == bit.band(obtainersValue, self.bitMaskRaceAll) then obtainersValue = obtainersValue + self.bitMaskRaceAll end

						--	And the levels are assumed to have minimum and maximum values that are reasonable if none present
						if 0 == bit.band(typeValue, self.bitMaskQuestMinLevel) then typeValue = typeValue + self.bitMaskQuestMinLevelOffset end
						if 0 == bit.band(typeValue, self.bitMaskQuestMaxLevel) then typeValue = typeValue + self.bitMaskQuestMaxLevel end

					end

					if nil ~= self.quests[questId] and nil ~= self.quests[questId][6] and 0 < #(self.quests[questId][6]) then
						local index, mapId
						for _, v in pairs(self.quests[questId][6]) do
							index = tonumber(strsub(v, 1, 2))
							mapId = index  + self.mapAreaBaseReputationChange
							self:AddQuestToMapArea(questId, mapId, COMBAT_TEXT_SHOW_REPUTATION_TEXT .. " - " ..self.reputationMapping[index])
						end
					end

					self.quests[questId][2] = typeValue
					self.quests[questId][3] = holidayValue
					self.quests[questId][4] = obtainersValue

				end

			end

		end,

		---
		--	Returns a bit mask indicating the type of the holidays that limit who can get the quest.
		--	@return An integer that should be interpreted as a bit mask containing information about what holiday .
		CodeHoliday = function(self, questId)
			questId = tonumber(questId)
			self:CodeAllFixed(questId)
			return nil ~= questId and self.quests[questId][3] or 0
		end,

		---
		--	Returns a bit mask indicating the type of the obtainers who can get the quest.
		--	@return An integer that should be interpreted as a bit mask containing information about who can get the quest.
		CodeObtainers = function(self, questId)
			questId = tonumber(questId)
			self:CodeAllFixed(questId)
			return nil ~= questId and self.quests[questId][4] or 0
		end,

		---
		--	Internal Use.
		--	Returns a table of codes from the victim string that match the sought prefix.
		--	@param victim The string that contains codes separated by spaces.
		--	@param soughtPrefix The prefix of the desired matching codes.
		--	@return A table of the matching codes or nil if there are none.
		CodesWithPrefix = function(self, victim, soughtPrefix)
			local retval = { }
			local codeArray = { strsplit(" ", victim) }
			if nil ~= codeArray then
				for i = 1, #(codeArray), 1 do
					if 1 == strfind(codeArray[i], soughtPrefix) then
						tinsert(retval, codeArray[i])
					end
				end
			end
			-- return nil if there is nothing in the table of matching codes
			if 0 == #(retval) then
				retval = nil
			end
			return retval
		end,

		---
		--	Internal Use.
		--	Returns a table of codes from the NPC that match the sought prefix.
		--	@param npcId The standard numeric npcId representing an NPC.
		--	@param soughtPrefix The prefix of the desired matching codes.
		--	@return A table of the matching codes or nil if there are none.
		CodesWithPrefixNPC = function(self, npcId, soughtPrefix)
			local retval = nil
			if nil == npcId or not tonumber(npcId) then return nil end
			npcId = tonumber(npcId)
			if nil ~= self.npcs[npcId] then
				retval = self:CodesWithPrefix(self.npcs[npcId][1], soughtPrefix)
			end
			return retval
		end,

-- TODO: Get rid of this routine by changing all that call it to use more modern data structures
		---
		--	Internal Use.
		--	Returns a table of codes from the quest that match the sought prefix.
		--	@param questId The standard numeric questId representing a quest.
		--	@param soughtPrefix The prefix of the desired matching codes.
		--	@return A table of the matching codes or nil if there are none.
		CodesWithPrefixQuest = function(self, questId, soughtPrefix)
			if nil == self.quests[questId] then return nil end
			return self:CodesWithPrefix(self.quests[questId][1], soughtPrefix)
		end,

		---
		--	Returns a bit mask indicating the type of the quest including its level information.
		--	@return An integer that should be interpreted as a bit mask containing information about the type of quest and its level information.
		CodeType = function(self, questId)
			questId = tonumber(questId)
			self:CodeAllFixed(questId)
			return nil ~= questId and self.quests[questId][2] or 0
		end,

		---
		--	Returns the localized and gender specific name of the player's class.
		--	@param englishName The Blizzard internal name of the class.  If nil, the player's class will be used.
		--	@param desiredGender The numeric value for the desired gender (2 is male and 3 is female).  If nil, the player's gender will be used.
		--	@return A string whose value is the localized name of the class using the appropriate gender where applicable.
		CreateClassNameLocalizedGenderized = function(self, englishName, desiredGender)
			local nameToUse = englishName or self.playerClass
			local genderToUse = desiredGender or self.playerGender
			return (genderToUse == 3) and LOCALIZED_CLASS_NAMES_FEMALE[nameToUse] or LOCALIZED_CLASS_NAMES_MALE[nameToUse]
		end,

		---
		--	Internal Use.
		--	Populates internal quest lists based on location of NPCs that can start
		--	the quests.  In normal mode, the API will use this indexed list instead
		--	of accessing the NPC information, thereby speeding up queries.
		CreateIndexedQuestList = function(self)
			if self.debug then debugprofilestart() end
			self.indexedQuests = {}
			self.indexedQuestsExtra = {}
			self.loremasterQuests = {}
			self.specialQuests = {}

			local locations
			local mapId
			local bitMask
			local questName

			for questId in pairs(self.quests) do

				self:CodeAllFixed(questId)

				--	Add the quests to the map areas based on the locations of the starting NPCs
				locations = self:LocationQuestInMap(questId, 'A')
				if nil ~= locations then
					for i = 1, #locations do
						mapId = tonumber(locations[i][1])
						if nil ~= mapId then
							if 4 == #(locations[i]) then
								if nil == self.indexedQuestsExtra[mapId] then self.indexedQuestsExtra[mapId] = {} end
								if not tContains(self.indexedQuestsExtra[mapId], questId) then tinsert(self.indexedQuestsExtra[mapId], questId) end
							else
								if nil == self.indexedQuests[mapId] then self.indexedQuests[mapId] = {} end
								if not tContains(self.indexedQuests[mapId], questId) then tinsert(self.indexedQuests[mapId], questId) end
							end
						else
							if self.debug then print("Quest ", questId, " has nil mapId for location ", i, "/", #locations) end
						end
					end
				end

				-- Add this quest to its achievements
				if nil ~= self.quests[questId][5] then
					for _, achievementId in pairs(self.quests[questId][5]) do
						if achievementId < self.mapAreaBaseAchievement and achievementId > 0 then
							if nil == self.loremasterQuests[achievementId] then self.loremasterQuests[achievementId] = {} end
							if not tContains(self.loremasterQuests[achievementId], questId) then tinsert(self.loremasterQuests[achievementId], questId) end
						else
							self:AddQuestToMapArea(questId, achievementId, select(2, GetAchievementInfo(achievementId - Grail.mapAreaBaseAchievement)))
						end
					end
				end

				--	Add this quest to holiday quests
				bitMask = self.quests[questId][3]
				if 0 ~= bitMask then
					for bitValue,code in pairs(self.holidayBitToCodeMapping) do
						if bit.band(bitMask, bitValue) > 0 then
							self:AddQuestToMapArea(questId, tonumber(self.holidayToMapAreaMapping['H'..code]), self.holidayMapping[code])
						end
					end
				end

				--	Add this quest to class quests
				bitMask = bit.band(self.quests[questId][4], self.bitMaskClassAll)
				if bitMask ~= self.bitMaskClassAll then
					for bitValue,code in pairs(self.classBitToCodeMapping) do
						if bit.band(bitMask, bitValue) > 0 then
							self:AddQuestToMapArea(questId, tonumber(self.classToMapAreaMapping['C'..code]), self:CreateClassNameLocalizedGenderized(self.classMapping[code]))
						end
					end
				end
				
				--	Add this quest to profession quests
				if nil ~= self.quests[questId]['prof'] then
					for code in pairs(self.quests[questId]['prof']) do
						self:AddQuestToMapArea(questId, tonumber(self.professionToMapAreaMapping['P'..code]), self.professionMapping[code])
					end
				end
				
				--	Add this quest to daily quests
				if bit.band(self.quests[questId][2], self.bitMaskQuestDaily) > 0 then
					self:AddQuestToMapArea(questId, self.mapAreaBaseDaily, DAILY)
				end
				
				--	Add this quest to reputation quests
				if nil ~= self.quests[questId]['rep'] then
					for reputationIndex in pairs(self.quests[questId]['rep']) do
						self:AddQuestToMapArea(questId, self.mapAreaBaseReputation + reputationIndex, REPUTATION .. " - " .. self.reputationMapping[reputationIndex])
					end
				end
				
				--	Deal with SPecial and repeatable quests to allow them to be accepted even when they do not appear in the quest log
				if nil ~= self.quests[questId]['SP'] or bit.band(self.quests[questId][2], self.bitMaskQuestRepeatable) > 0 then
					questName = self:QuestName(questId)
					if nil == self.specialQuests[questName] then self.specialQuests[questName] = {} end
					-- Now we go through and get the NPCs that give this quest and add them to the name table matching this quest
					local npcs = self:TableAppendCodes(nil, self.quests[questId], { 'A', 'AK' })
					if nil ~= npcs then
						for _, questGiverId in pairs(npcs) do
							tinsert(self.specialQuests[questName], { questGiverId, questId })
						end
					end
				end

			end
			if self.debug then print("Done creating indexed quest list with elapsed milliseconds: "..debugprofilestop()) end
		end,

		CreateRaceNameLocalizedGenderized = function(self, englishName, desiredGender)
			local retval = nil
			local nameToUse = englishName or self.playerClass
			local genderToUse = desiredGender or self.playerGender
			local codeToUse = nil
			for code,raceName in pairs(self.raceMapping) do
				if raceName == nameToUse then
					codeToUse = code
				end
			end
			if nil ~= codeToUse then
				retval = (genderToUse == 3) and self.raceNameFemaleMapping[codeToUse] or self.raceNameMapping[codeToUse]
			end
			return retval
		end,

		---
		--	Determines whether the internal database contains the NPC specified by npcId.
		--	@param npcId The standard numeric npcId representing an NPC.
		--	@return true if the NPC is known to the internal database, false otherwise
		DoesNPCExist = function(self, npcId)
			npcId = tonumber(npcId)
			return nil ~= npcId and nil ~= self.npcs[npcId] and true or false
		end,

		---
		--	Determines whether the internal database contains the quest specified by questId.
		--	@param questId The standard numeric questId representing a quest.
		--	@return true if the quest is known to the internal database, false otherwise
		DoesQuestExist = function(self, questId)
			questId = tonumber(questId)
			return nil ~= questId and nil ~= self.quests[questId] and true or false
		end,

		FromList = function(self, list, splitter)
			local retval = {}
			local splitterToUse = splitter or ','
			local items = { strsplit(splitterToUse, list) }
			for i = 1, #items do
				tinsert(retval, tonumber(items[i]))
			end
			return retval
		end,

		FromPattern = function(self, pattern, orSplitter, andSplitter)
			local retval = {}
			local orSplitterToUse = orSplitter or ','
			local andSplitterToUse = andSplitter or '+'
			local items = { strsplit(orSplitterToUse, pattern) }
			local andItems
			for i = 1, #items do
				andItems = self:FromList(items[i], andSplitterToUse)
				if 1 == #andItems then
					tinsert(retval, andItems[1])
				else
					tinsert(retval, andItems)
				end
			end
			return retval
		end,

		GetNPCId = function(self, useTargetFirst, useMouseoverOnly)
			local used
			local targetName = nil
			local npcId = nil
--			if useMouseoverOnly then
--				used = "mouseover"
--				targetName = UnitName(used)
--			else
--				if useTargetFirst then
--					used = "target"
--					targetName = UnitName(used)
--				end
--				if nil == targetName then used = "npc" targetName = UnitName(used) end
--				if nil == targetName then used = "questnpc" targetName = UnitName(used) end
--			end
			local searchTable = {}
			if useMouseoverOnly then
				tinsert(searchTable, "mouseover")
			else
				if useTargetFirst then tinsert(searchTable, "target") end
				tinsert(searchTable, "npc")
				tinsert(searchTable, "questnpc")
			end
			for k, v in pairs(searchTable) do
				used = v
				targetName = UnitName(used)
				if nil ~= targetName then break end
			end
			if nil ~= targetName then
				local gid = UnitGUID(used)
				if nil ~= gid then
					local targetType = tonumber(gid:sub(5,5), 16) % 8
					npcId = tonumber(gid:sub(7,10), 16)
					if 1 == targetType then npcId = npcId + 1000000 end		-- our representation of a world object
				end
			end
			return npcId, targetName
		end,

		GetOTCQuest = function(self, questId, npcId)
			questId = tonumber(questId)
			npcId = tonumber(npcId)
			local retval = questId
			if nil ~= questId and nil ~= self.quests[questId] and nil ~= self.quests[questId]['OTC'] then
				local sets = self.quests[questId]['OTC']
				for i = 1, #sets do
					if npcId == sets[i][1] then retval = sets[i][2] end
				end
			end
			return retval
		end,

		---
		--	Indicates whether the character has ever completed the specified quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@return true if the quest has been marked complete, or if the quest has been completed and is one that Blizzard resets daily/weekly/yearly, otherwise false
		HasQuestEverBeenCompleted = function(self, questId)	return self:IsQuestCompleted(questId) or self:IsResettableQuestCompleted(questId)	end,

		---
		--	Indicates whether the character is in a heroic instance with the specified NPC.
		--	@param npcId The standard numeric npcId representing an NPC.
		--	@return true if the character is in a heroic instance where the NPC is located, otherwise false
		InWithHeroicNPC = function(self, npcId)
			local retval = false
			local isHeroic, instanceName = self:IsInHeroicInstance()
			if isHeroic then
				local locations = self:LocationNPCInMap(npcId, false, false, true)	-- only return things that match the current zone
				if nil ~= locations and 0 < #(locations) then
					retval = true
				end
			end
			return retval
		end,

		---
		--	Indicates whether the quest is a daily quest as indicated by the internal database.
		--	@param questId The standard numeric questId representing a quest.
		--	@return true if the quest is a daily quest, otherwise false
		IsDaily = function(self, questId)	return (bit.band(self:CodeType(questId), self.bitMaskQuestDaily) > 0)	end,

		---
		--	Indicates whether the quest is a dungeon quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@return true if the quest is a dungeon quest, otherwise false
		IsDungeon = function(self, questId)	return (bit.band(self:CodeType(questId), self.bitMaskQuestDungeon) > 0)	end,

		---
		--	Indicates whether the quest is an escort quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@return true if the quest is an escort quest, otherwise false
		IsEscort = function(self, questId)	return (bit.band(self:CodeType(questId), self.bitMaskQuestEscort) > 0)	end,

		---
		--	Indicates whether the quest is a group quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@return true if the quest is a group quest, otherwise false
		IsGroup = function(self, questId)	return (bit.band(self:CodeType(questId), self.bitMaskQuestGroup) > 0)	end,

		---
		--	Indicates whether the quest is a heroic quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@return true if the quest is a heroic quest, otherwise false
		IsHeroic = function(self, questId)	return (bit.band(self:CodeType(questId), self.bitMaskQuestHeroic) > 0)	end,

		---
		--	Indicates whether the NPC is only to be found in heroic instances.
		--	@param npcId The standard numeric npcId representing an NPC.
		--	@return True if the NPC is only found in heroic instances, false otherwise.
		IsHeroicNPC = function(self, npcId)
			retval = false
			local codes = self:CodesWithPrefixNPC(npcId, 'X')
			if nil ~= codes and 0 < #(codes) then
				retval = true
			end
			return retval
		end,

		---
		--	Indicates whether the character is in a heroic instance.
		--	@return true if the character is in a heroic instance, otherwise false
		--	@return the name of the instance the character is in
		--	@usage isHeroic, instanceName = Grail:IsInHeroicInstance()
		IsInHeroicInstance = function(self)
			local retval = false
			local name, type, difficultyIndex, difficultyName, maxPlayers, dynamicDifficulty, isDynamic = GetInstanceInfo()
			if "none" ~= type then
				if 3 == difficultyIndex or 4 == difficultyIndex or (2 == difficultyIndex and "raid" ~= type) then
					retval = true
				end
			end
			return retval, name
		end,

		---
		--	Indicates whether the quest is invalidated (meaning it cannot be accepted based on other completed quests or those in the quest log).
		--	@param questId The standard numeric questId representing a quest.
		--	@return True if the quest cannot be accepted because of a quest in the log or one already completed, false otherwise.
		--	@return A table of failure reasons, or nil if there are none.
		IsInvalidated = function(self, questId)
			local retval = false
			local any, present, failures = self:AnyEvaluateTrue(questId, "I", true, false, false, true)
			if present then
				retval = any
			end
-- TODO:	Fix this to work properly.
--		The issue is the quest will be invalid if all of its prerequisites are PL: or PC: and they have all been turned in.
--		If there are other prerequisites (which in practice we have not seen), then they could still allow the quest to be
--		obtainable.  Should we just assume that if there are PL: or PC: there will not be any other type of prerequisite?
--			--	We need to check to see whether this quest has any PL: or PC: prerequisites
--			--	because if it does and they are all turned in
--			if not retval then
--				local questsToCheck = self.quests[questId]['PL']
--				if nil ~= questsToCheck then
--					for i = 1, #questsToCheck do
--						if self:IsQuestCompleted(questsToCheck[i]) then
--							retval = true
--						end
--					end
--				end
--				local questsToCheck = self.quests[questId]['PC']
--				if nil ~= questsToCheck then
--					for i = 1, #questsToCheck do
--						if self:IsQuestCompleted(questsToCheck[i]) then
--							retval = true
--						end
--					end
--				end
--			end
			return retval, failures
		end,

		---
		--	Returns whether the quest is a low level quest in comparison to the specified level
		--	or that of the player if none specified.
		--	@param questId The standard numeric questId representing a quest.
		--	@param comparisonLevel The level used to make a comparison against the quest level.
		--	@return True if the comparisonLevel (or player level) is more than the quest's level plus Blizzard's green range comparison
		IsLowLevel = function(self, questId, comparisonLevel)
			local retval = false
			comparisonLevel = tonumber(comparisonLevel) or UnitLevel("player")
			local questLevel = self:QuestLevel(questId) or 1
			if 0 ~= questLevel then		-- 0 is the special marker indicating the quest is actually the same level as the player
				retval = (comparisonLevel > (questLevel + (GetQuestGreenRange() or 8)))	-- 8 is the return value from GetQuestGreenRange() for anyone level 60 or higher (at least)
			end
			return retval
		end,

		IsMonthly = function(self, questId)	return (bit.band(self:CodeType(questId), self.bitMaskQuestMonthly) > 0)	end,

		---
		--	Returns whether the NPC should be available to the character.
		--	@param npcId The standard numeric npcId representing an NPC.
		--	@return True if the NPC is available based on holidays currently celebrated and presence in a heroic instance, false otherwise.
		IsNPCAvailable = function(self, npcId)
			if nil == npcId or not tonumber(npcId) then return false end
			npcId = tonumber(npcId)
			local retval = true
			local codes = self:CodesWithPrefixNPC(npcId, 'H')
			if nil ~= codes then
				local holidayGood = true
				for i = 1, #(codes), 1 do
					if holidayGood then
						holidayGood = self:CelebratingHoliday(self.holidayMapping[strsub(codes[i], 2, 2)])
					end
				end
				retval = holidayGood
			end
			if retval and self:IsHeroicNPC(npcId) then
				retval = self:InWithHeroicNPC(npcId)
			end
			return retval
		end,

		---
		--	Indicates whether the quest is a PVP quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@return true if the quest is a PVP quest, otherwise false
		IsPVP = function(self, questId)	return (bit.band(self:CodeType(questId), self.bitMaskQuestPVP) > 0)	end,

		---
		--	Returns whether the quest is considered completed.
		--	Note that certain types of quests can be reset (e.g., dailies) and when they are, this routine will return false.  These types of
		--	quests can be completed and this routine will return true until they are once again reset.
		--	@param questId The standard numeric questId representing a quest.
		--	@return True if the quest is completed, false otherwise.
		--	@see HasQuestEverBeenCompleted
		--	@see IsResettableQuestCompleted
		IsQuestCompleted = function(self, questId)
			questId = tonumber(questId)
			if nil == questId then return false end
			local retval = false
			local index = math.floor((questId - 1) / 32)
			local offset = questId - (index * 32) - 1
			local db = GrailDatabase[self.playerRealm][self.playerName]["completedQuests"]
			if (nil ~= db[index]) then
				if bit.band(db[index], 2^offset) > 0 then
					retval = true
				end
			end
			return retval
		end,

		---
		--	Returns whether the quest is in the quest log.
		--	@param questId The standard numeric questId representing a quest.
		--	@return True if the quest is in the quest log, false otherwise.
		--	@return True if the quest is marked as complete in the quest log, false otherwise.
		--	@use inLog, isComplete = Grail:IsQuestInQuestLog(11)
		IsQuestInQuestLog = function(self, questId)
			questId = tonumber(questId)
			if nil == questId then return false end
			local retval = false
			local retvalComplete = false
			local i = 1
			while GetQuestLogTitle(i) and false == retval do
				local questTitle, level, questTag, suggestedGroup, isHeader, isCollapsed, isComplete, isDaily, questID = GetQuestLogTitle(i)
				if (not isHeader) then
					if questID == questId then
						retval = true
						retvalComplete = isComplete
					end
				end
				i = i + 1
			end
			return retval, retvalComplete
		end,

		---
		--	Indicates whether the quest is a raid quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@return true if the quest is a raid quest, otherwise false
		IsRaid = function(self, questId)	return (bit.band(self:CodeType(questId), self.bitMaskQuestRaid) > 0)	end,

		---
		--	Returns whether the quest is a repeatable quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@return True if the quest is a repeatable quest, false otherwise.
		IsRepeatable = function(self, questId)	return (bit.band(self:CodeType(questId), self.bitMaskQuestRepeatable) > 0)	end,

		---
		--	Returns whether the quest is a resettable quest and has been completed in the past.
		--	This routine can return true and IsQuestCompleted() can return false as the quest can be reset.
		--	@param questId The standard numeric questId representing a quest.
		--	@return True if the quest is resettable and has ever been completed, false otherwise.
		--	@see HasQuestEverBeenCompleted
		--	@see IsQuestCompleted
		IsResettableQuestCompleted = function(self, questId)
			questId = tonumber(questId)
			if nil == questId then return false end
			local retval = false
			local index = math.floor((questId - 1) / 32)
			local offset = questId - (index * 32) - 1
			local db = GrailDatabase[self.playerRealm][self.playerName]["completedResettableQuests"]
			if (nil ~= db[index]) then
				if bit.band(db[index], 2^offset) > 0 then
					retval = true
				end
			end
			return retval
		end,

		---
		--	Returns whether this is a special type of NPC that has information useful for tooltips and a table of that information
		--	where each item in the table is a table with the type of NPC and the associated NPC/quest/item ID.
		--	@param npcId The standard numeric npcId representing an NPC.
		--	@return True if there is any table data being returned, false otherwise
		--	@return Table data containing tables of NPC type and associated ID.
		IsTooltipNPC = function(self, npcId)
			local retval = {}
			local dropCodes = self:CodesWithPrefixNPC(npcId, 'D:')
			if nil ~= dropCodes then
				for i = 1, #(dropCodes), 1 do
					local npcs = { strsplit(",", strsub(dropCodes[i], 3)) }
					if nil ~= npcs then
						for j = 1, #(npcs), 1 do
							tinsert(retval, { self.NPC_TYPE_BY, npcs[j] } )
						end
					end
				end
			end
			local killCodes = self:CodesWithPrefixNPC(npcId, 'K:')
			if nil ~= killCodes then
				for i = 1, #(killCodes), 1 do
					local quests = { strsplit(",", strsub(killCodes[i], 3)) }
					if nil ~= quests then
						for j = 1, #(quests), 1 do
							tinsert(retval, { self.NPC_TYPE_KILL, quests[j] } )
						end
					end
				end
			end
			local hasCodes = self:CodesWithPrefixNPC(npcId, 'H:')
			if nil ~= hasCodes then
				for i = 1, #(hasCodes), 1 do
					local items = { strsplit(",", strsub(hasCodes[i], 3)) }
					if nil ~= items then
						for j = 1, #(items), 1 do
							tinsert(retval, { self.NPC_TYPE_DROP, items[j] } )
						end
					end
				end
			end
			return (0 < #(retval)), retval
		end,

		---
		--	Returns whether the quest is a weekly quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@return True if the quest is a weekly quest, false otherwise.
		IsWeekly = function(self, questId)	return (bit.band(self:CodeType(questId), self.bitMaskQuestWeekly) > 0)	end,

		---
		--	Returns whether the quest is a yearly quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@return True if the quest is a yearly quest, false otherwise.
		IsYearly = function(self, questId)	return (bit.band(self:CodeType(questId), self.bitMaskQuestYearly) > 0)	end,

-- TODO: This is not currently called by anyone, investigate why.
		---
		--	Returns a table of locations for the NPC and its name.
		--	Each table element is itself a table with one or two entries.  Those with two entries will have as their first entry the localized
		--	name of the zone.  The second entry will either be the x,y pair of coordinates in the zone or the special word Near which represents
		--	something that should be near the character (from a recent summoning for example) or the special word Self which represents automatic
		--	acceptance of the quest.  Those with one entry are special and can have either the localized name of the zone in which an object is
		--	found or one of the special keywords:<br>
		--	Preowned (the character must already own the object since it has been removed from the game)<br>
		--	Created (this item can be created)<br>
		--	Mailbox (this item will be mailed by Blizzard)<br>
		--	Self (this will be used by quests that are automatically accepted or have no NPC)<br>
		--	Near (the NPC should be nearby (from a recent summons for example))<br>
		--	@param npcId The standard numeric npcId representing an NPC.
		--	@param requiresNPCAvailable If true, the NPC must be available.
		--	@param onlySingleReturn If true, only one location will be in the returned table, otherwise all matching locations will be there.
		--	@param onlyZoneReturn If true, only locations matching the appropriate zone will be returned.
		--	@param preferredZoneName The localized name of the zone to use, and if nil the character's current zone is used.
		--	@return A table of locations where the NPC can be found or nil if there are none.
		--	@return The localized name of the NPC.
		--	@see IsNPCAvailable
		LocationNPC = function(self, npcId, requiresNPCAvailable, onlySingleReturn, onlyZoneReturn, preferredZoneName)
			local preferredMapId = nil
			if nil ~= preferredZoneName then
				preferredMapId = self.zoneNameMapping[preferredZoneName]
				if nil == preferredMapId and self.debug then print("Grail:LocationNPC could not find zone name ", preferredZoneName, " so is using current zone.") end
			end
			local retval, retvalName = self:LocationNPCInMap(npcId, requiresNPCAvailable, onlySingleReturn, onlyZoneReturn, preferredMapId)
			if nil ~= retval then
				for i = 1, #retval do
					if 2 == #(retval[i]) or (1 == #(retval[i]) and tonumber(retval[i][1])) then retval[i][1] = self.mapAreaMapping[tonumber(retval[i][1])] end
				end
			end
			return retval, retvalName
		end,

		---
		--	Returns a table of locations for the NPC and its name.
		--	Each table element is itself a table with one or two entries.  Those with two entries will have as their first entry the map area ID.
		--	The second entry will either be the x,y pair of coordinates in the zone or the special word Near which represents something that
		--	should be near the character (from a recent summoning for example) or the special word Self which represents automatic acceptance of
		--	the quest.  Those with one entry are special and can have either the map area ID in which an object is found or one of the special keywords:<br>
		--	Preowned (the character must already own the object since it has been removed from the game)<br>
		--	Created (this item can be created)<br>
		--	Mailbox (this item will be mailed by Blizzard)<br>
		--	Self (this will be used by quests that are automatically accepted or have no NPC)<br>
		--	Near (the NPC should be nearby (from a recent summons for example))<br>
		--	@param npcId The standard numeric npcId representing an NPC.
		--	@param requiresNPCAvailable If true, the NPC must be available.
		--	@param onlySingleReturn If true, only one location will be in the returned table, otherwise all matching locations will be there.
		--	@param onlyMapAreaReturn If true, only locations matching the appropriate map area will be returned.
		--	@param preferredMapId The map area to use, and if nil the character's current zone is used.
		--	@return A table of locations where the NPC can be found or nil if there are none.
		--	@return The localized name of the NPC.
		--	@see IsNPCAvailable
		LocationNPCInMap = function(self, npcId, requiresNPCAvailable, onlySingleReturn, onlyMapAreaReturn, preferredMapId)
			if nil == npcId or not tonumber(npcId) then return nil, nil end
			npcId = tonumber(npcId)
			if nil == self.npcs[npcId] then return nil, nil end
			local retval = {}
			local retvalName = self:NPCName(npcId)
			local codes = self.npcs[npcId][1]
			local npcIsDarkmoonFaire = false
			local mapIdToUse = tonumber(preferredMapId) or GetCurrentMapAreaID()
			if nil ~= codes and (not requiresNPCAvailable or self:IsNPCAvailable(npcId)) then
				local codeArray = { strsplit(" ", codes) }

				-- First we check for the Darkmoon Faire code to see if we must limit the returned locations to the current Darkmoon Faire location
				for i = 1, #codeArray do
					if codeArray[i] == 'HF' then
						npcIsDarkmoonFaire = true
					end
				end

				for i = 1, #(codeArray), 1 do
					local controlCode = strsub(codeArray[i], 1, 1)
					local mapAreaId
					if 'Z' == controlCode then
						mapAreaId = tonumber(strsub(codeArray[i], 2))
						if not onlyMapAreaReturn or (onlyMapAreaReturn and mapIdToUse == mapAreaId) then
							tinsert(retval, { mapAreaId })
						end
					elseif 'H' == controlCode then
						-- ignore this because it indicates the NPC is only present during a holiday, or if H: has the specified item that starts a quest
					elseif 'K' == controlCode then
						-- ignore this because it indicates the NPC is killed to start the specified quest
					elseif 'A' == controlCode then
						-- ignore this because it is an alias marker indicating the real NPC id
					elseif 'X' == controlCode then
						-- ignore this because it indicates the NPC is only present in heroic mode
					elseif 'P' == controlCode
					    or 'C' == controlCode
					    or 'M' == controlCode
					    or 'S' == controlCode then
						tinsert(retval, { codeArray[i] })	-- Preowned, Created, Mailbox, Self
					elseif 'N' == controlCode then
						if strlen(codeArray[i]) > 4 then	--	NearXXXX where XXXX is the only map area where this Near can appear
							mapAreaId = tonumber(strsub(codeArray[i], 5))
							if not onlyMapAreaReturn or (onlyMapAreaReturn and mapIdToUse == mapAreaId) then
								tinsert(retval, { mapAreaId, "Near" })
							end
						else
							tinsert(retval, { codeArray[i] })	-- Near
						end
					elseif 'D' == controlCode then
						-- these are NPCs that can drop the item that we are processing, therefore add the location for each NPC to the table
						local modifiedName = false
						if strlen(codeArray[i]) > 2 and ':' == strsub(codeArray[i], 2, 2) then
							local realNPCs = { strsplit(',', strsub(codeArray[i], 3)) }
							for j = 1, #realNPCs do
								local subnpclocations, subnpcname = self:LocationNPCInMap(realNPCs[j], requiresNPCAvailable, onlySingleReturn, onlyMapAreaReturn, preferredMapId)
								if nil ~= subnpclocations then
									for k = 1, #subnpclocations do
										tinsert(retval, subnpclocations[k])
									end
								end
								if subnpcname and not modifiedName then
									retvalName = subnpcname .. " (" .. retvalName .. ")" -- an NPC that drops the item needed for the quest in parentheses
									modifiedName = true
								end
							end
						end
					else	-- a real coordinate
						local mapId, rest = strsplit(":", codeArray[i])
						local mapLevel = 0
						local mapLevelString
						mapId, mapLevelString = strsplit("[", mapId)
						mapId = tonumber(mapId)
						if nil ~= mapLevelString then
							mapLevel = tonumber(strsub(mapLevelString, 1, strlen(mapLevelString) - 1))
						end
						local coord, realArea = nil, nil
						if nil ~= rest then
							coord, realArea = strsplit(">", rest)
						end
						if not onlyMapAreaReturn or (onlyMapAreaReturn and mapIdToUse == mapId) then
							if nil ~= realArea then
								tinsert(retval, { mapId, coord, mapLevel, tonumber(realArea) })
							else
								tinsert(retval, { mapId, coord, mapLevel })
							end
						end
					end
				end
			end
			if onlySingleReturn and 1 < #retval then
				retval = { retval[1] }		-- pick the first item for no better algorithm to use to decide
			end
			if 0 == #retval then
				retval = nil
			end
			return retval, retvalName
		end,

-- TODO: This is not currently being called by anyone
		---
		--	Returns a table of locations for the quest's NPC for accepting the quest or turning it in and the NPC name.
		--	@param questId The standard numeric questId representing a quest.
		--	@param acceptOrTurnin 'A' for the NPC from which the quest is accepted or 'T' for the NPC to which one turns in the quest.  If nil, 'A' is used.
		--	@param requiresNPCAvailable If true, the NPC must be available.
		--	@param onlySingleReturn If true, only one location will be in the returned table, otherwise all matching locations will be there.
		--	@param onlyZoneReturn If true, only locations matching the appropriate zone will be returned.
		--	@param preferredZoneName The localized name of the zone to use, and if nil the character's current zone is used.
		--	@return A table of locations where the NPC can be found or nil if there are none.
		--	@return The localized name of the NPC.
		--	@return Whether the NPC must be killed.
		--	@see LocationNPC
		LocationQuest = function(self, questId, acceptOrTurnin, requiresNPCAvailable, onlySingleReturn, onlyZoneReturn, preferredZoneName)
			local preferredMapId = nil
			if nil ~= preferredZoneName then
				preferredMapId = self.zoneNameMapping[preferredZoneName]
				if nil == preferredMapId and self.debug then print("Grail:LocationNPC could not find zone name ", preferredZoneName, " so is using current zone.") end
			end
			local retval, npcNameRetval, npcIdRetval, npcMustDie = self:LocationQuestInMap(questId, acceptOrTurnin, requiresNPCAvailable, onlySingleReturn, onlyZoneReturn, preferredMapId)
-- TODO: Determine whether we need to change map IDs to zone names like we did for LocationNPC
			return retval, npcNameRetval, npcIdRetval, npcMustDie
		end,

		---
		--	Returns a table of locations for the quest's NPC for accepting the quest or turning it in and the NPC name, NPC ID and whether the NPC needs to
		--	be killed to satisfy the quest.  Note that the two parameters onlySingleReturn and acceptsMultipleUniques can be used to get specific location
		--	information as follows.  E.g., an NPC may wander and therefore have more than one location.  To get only one of those locations (instead of all
		--	of them) specify true for onlySingleReturn.  However, if there is more than one NPC that provides a quest (like the Hero Boards in Stormwind)
		--	and you are specifying true for onlySingleReturn, you need to specify true for acceptsMultipleUniques to get both boards, otherwise only one of
		--	them will appear in the results.
		--	@param questId The standard numeric questId representing a quest.
		--	@param acceptOrTurnin 'A' for the NPC from which the quest is accepted or 'T' for the NPC to which one turns in the quest.  If nil, 'A' is used.
		--	@param requiresNPCAvailable If true, the NPC must be available.
		--	@param onlySingleReturn If true, only one location will be in the returned table, otherwise all matching locations will be there.
		--	@param onlyMapAreaReturn If true, only locations matching the appropriate map area will be returned.
		--	@param preferredMapId The map area to use, and if nil the character's current zone is used.
		--	@param acceptsMultipleUniques If true, returns locations for multiple NPCs that satisfy the many criteria.
		--	@return A table of locations where the NPC can be found or nil if there are none.
		--	@return The localized name of the NPC.
		--	@return Whether the NPC must be killed.
		--	@see LocationNPCInMap
		LocationQuestInMap = function(self, questId, acceptOrTurnin, requiresNPCAvailable, onlySingleReturn, onlyMapAreaReturn, preferredMapId, acceptsMultipleUniques)
			local retval, npcMustDie = self:LocationQuestInMapRaw(questId, acceptOrTurnin, requiresNPCAvailable, onlySingleReturn, onlyMapAreaReturn, preferredMapId, acceptsMultipleUniques)
			local newRetval, npcNameRetval, npcIdRetval = {}, nil, nil

			if 0 == #retval then
				retval = nil
			else
				for i = 1, #retval do
					tinsert(newRetval, retval[i][1])
					if nil == npcNameRetval then npcNameRetval = retval[i][2] end
					if nil == npcIdRetval then npcIdRetval = retval[i][3] end
				end
				retval = newRetval
			end

			return retval, npcNameRetval, npcIdRetval, npcMustDie
		end,


		---
		--	Returns a table of locations for the quest's NPC for accepting the quest or turning it in and whether the NPC needs to be killed to satisfy the quest.
		--	The returned table has location, name, and ID.  Note that the two parameters onlySingleReturn and acceptsMultipleUniques can be used to get specific location
		--	information as follows.  E.g., an NPC may wander and therefore have more than one location.  To get only one of those locations (instead of all
		--	of them) specify true for onlySingleReturn.  However, if there is more than one NPC that provides a quest (like the Hero Boards in Stormwind)
		--	and you are specifying true for onlySingleReturn, you need to specify true for acceptsMultipleUniques to get both boards, otherwise only one of
		--	them will appear in the results.
		--	@param questId The standard numeric questId representing a quest.
		--	@param acceptOrTurnin 'A' for the NPC from which the quest is accepted or 'T' for the NPC to which one turns in the quest.  If nil, 'A' is used.
		--	@param requiresNPCAvailable If true, the NPC must be available.
		--	@param onlySingleReturn If true, only one location will be in the returned table, otherwise all matching locations will be there.
		--	@param onlyMapAreaReturn If true, only locations matching the appropriate map area will be returned.
		--	@param preferredMapId The map area to use, and if nil the character's current zone is used.
		--	@param acceptsMultipleUniques If true, returns locations for multiple NPCs that satisfy the many criteria.
		--	@return A table of locations where the NPC can be found or nil if there are none.
		--	@return The localized name of the NPC.
		--	@return Whether the NPC must be killed.
		--	@see LocationNPCInMap
		LocationQuestInMapRaw = function(self, questId, acceptOrTurnin, requiresNPCAvailable, onlySingleReturn, onlyMapAreaReturn, preferredMapId, acceptsMultipleUniques)
			questId = tonumber(questId)
			if nil == questId or nil == self.quests[questId] then return nil, nil end
			local retval, npcMustDie = {}, false
			local npcCodes = self.quests[questId][acceptOrTurnin]
			if nil == npcCodes then
				npcCodes = self.quests[questId][acceptOrTurnin..'K']
				if nil ~= npcCodes then npcMustDie = true end
			end
			if nil ~= npcCodes then
				for _, npcId in pairs(npcCodes) do
					local npcLocations, npcName = self:LocationNPCInMap(npcId, requiresNPCAvailable, onlySingleReturn, onlyMapAreaReturn, preferredMapId)
					if nil ~= npcLocations then
						for _, value in pairs(npcLocations) do
							tinsert(retval, { value, npcName, npcId })
						end
					end
				end
			else
				local zoneId = self.quests[questId][acceptOrTurnin..'Z']
				if nil ~= zoneId then
					local mapId = tonumber(preferredMapId) or GetCurrentMapAreaID()
					if not onlyMapAreaReturn or (onlyMapAreaReturn and zoneId == mapId) then
						tinsert(retval, { {zoneId}, self:NPCName(0), 0 })
					end
				end
			end
			-- Since the return values from LocationNPCMapInfo will process things like onlySingleReturn properly, that means the retval should only have one location value per unique NPC
			-- and that means we can make use of acceptsMultipleUniques to ignore the onlySingleReturn value at this point.
			if onlySingleReturn and not acceptsMultipleUniques and 1 < #retval then retval = { retval[1] } end		-- pick the first item for no better algorithm to use to decide

			return retval, npcMustDie
		end,

		---
		--	This returns the map area to which the specified quest belongs for Loremaster purposes.  If the quest does not
		--	belong to any Loremaster nil is returned.
		--	@param questId The standard numeric questId representing a quest.
		--	@return The map area for Loremaster or nil if not a Loremaster quest.
		LoremasterMapArea = function(self, questId)
			local retval = nil
			questId = tonumber(questId)
			if nil ~= questId and nil ~= self.quests[questId] and nil ~= self.quests[questId][5] then
				for _, achievementId in pairs(self.quests[questId][5]) do
					if achievementId < self.mapAreaBaseAchievement then
						retval = achievementId
					end
				end
			end
			return retval
		end,

		---
		--	Internal Use.
		--	This marks the specified quest as complete in the internal database.  Optionally it will attempt to update the NewNPCs and NewQuests.
		--	@param questId The standard numeric questId representing a quest.
		--	@param updateDatabase If true the NewNPCs and NewQuests will be updated as well as posting the Complete notification.
		MarkQuestComplete = function(self, questId, updateDatabase, updateActual)
			local v = tonumber(questId)
			local index = math.floor((v - 1) / 32)
			local offset = v - (index * 32) - 1
			local db = GrailDatabase[self.playerRealm][self.playerName]["completedQuests"]
			local db2 = GrailDatabase[self.playerRealm][self.playerName]["actuallyCompletedQuests"]
			if (nil == db[index]) then
				db[index] = 0
			end
			if bit.band(db[index], 2^offset) == 0 then
				db[index] = db[index] + (2^offset)
			else
				if self.debug then print(format("Quest %d is already marked completed", v)) end
			end

--	Do not enable this until the system by which only those quests that have I codes (and maybe a few others) trigger this to happen instead of all completed.
--	This also means clearing out of the others in an I grouping when one is completed.  And it means when the server query is processed this needs to be checked
--	to have its values included (or the code that checks completedQuests checks here as well).
--			if updateActual then
--				if nil == db2[index] then db2[index] = 0 end
--				if bit.band(db2[index], 2^offset) == 0 then
--					db2[index] = db2[index] + (2^offset)
--				else
--					if self.debug then print(format("Quest %d is already marked actually completed", v)) end
--				end
--			end

			if updateDatabase then

-- TODO: Change this over to actually use the bits instead of all the separate calls because I believe the bits to be more efficient
				if not self:IsResettableQuestCompleted(questId) and (self:IsDaily(questId) or self:IsWeekly(questId) or self:IsYearly(questId) or self:IsRepeatable(questId)) then
					local rdb = GrailDatabase[self.playerRealm][self.playerName]["completedResettableQuests"]
					if (nil == rdb[index]) then
						rdb[index] = 0
					end
					rdb[index] = rdb[index] + (2^offset)
				end

				-- Get the target information to ensure the target exists in the database of NPCs
				local version = self.versionNumber.."/"..self.questsVersionNumber.."/"..self.npcsVersionNumber.."/"..self.zonesVersionNumber
				local targetName, npcId, coordinates = self:TargetInformation()
				self:UpdateTargetDatabase(targetName, npcId, coordinates, version)
				if self.debug then
					if nil ~= targetName then
						DEFAULT_CHAT_FRAME:AddMessage("Grail Debug: Marked questId "..questId.." complete, turned in to: "..targetName.."("..npcId..") "..coordinates)
					else
						DEFAULT_CHAT_FRAME:AddMessage("Grail Debug: Turned in quest "..questId.." with no target")
					end
				end
				self:UpdateQuestDatabase(questId, 'No Title Stored', npcId, false, 'T', version)
				self:PostNotification("Complete", questId)
			end

		end,

		---
		--	Returns whether the character meets prerequisites for the specified quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@return True if the character meets the prerequisites for the specified quest or false otherwise.
		--	@return A table of failures if any, nil otherwise.
		MeetsPrerequisites = function(self, questId)
			local retval = true
			local any, present, failures = self:AnyEvaluateTrue(questId, "P", false, false, false, true)
			if present then
				retval = any
			else
				any, present, failures = self:AnyEvaluateTrue(questId, "PL", true, false, false, false)
				if present then
					retval = any
				else
					any, present, failures = self:AnyEvaluateTrue(questId, "PH", false, true, false, true)
					if present then
						retval = any
					else
						any, present, failures = self:AnyEvaluateTrue(questId, "PC", false, false, true, false)
						if present then
							retval = any
						else
							any, present, failures = self:AnyEvaluateTrue(questId, "PLT", true, false, false, true)
							if present then
								retval = any
							else
								any, present, failures = self:AnyEvaluateTrue(questId, "PCT", false, false, true, true)
								if present then
									retval = any
								end
							end
						end
					end
				end
			end
			return retval, failures
		end,

		MeetsRequirement = function(self, questId, requirementCode, soughtParameter)
			if nil == questId or not tonumber(questId) then return false end
			local retval = true
			questId = tonumber(questId)
			self:CodeAllFixed(questId)
			local bitMaskToUse
			if 'G' == requirementCode then
				if nil == soughtParameter then
					bitMaskToUse = self.playerGenderBitMask
				elseif 3 == tonumber(soughtParameter) then
					bitMaskToUse = self.bitMaskGenderFemale
				else
					bitMaskToUse = self.bitMaskGenderMale
				end
				retval = (bit.band(self.quests[questId][4], bitMaskToUse) > 0)
			elseif 'F' == requirementCode then
				if nil == soughtParameter then
					bitMaskToUse = self.playerFactionBitMask
				elseif 'Horde' == soughtParameter then
					bitMaskToUse = self.bitMaskFactionHorde
				else
					bitMaskToUse = self.bitMaskFactionAlliance
				end
				retval = (bit.band(self.quests[questId][4], bitMaskToUse) > 0)
			elseif 'C' == requirementCode or 'X' == requirementCode then
				bitMaskToUse = (nil == soughtParameter) and self.playerClassBitMask or self.classNameToBitMapping[soughtParameter]
				retval = (bit.band(self.quests[questId][4], bitMaskToUse) > 0)
			elseif 'H' == requirementCode then
				if 0 ~= self.quests[questId][3] then
					local found = false
					local comparisonValue = self.quests[questId][3]
					for bitMask,code in pairs(self.holidayBitToCodeMapping) do
						if bit.band(comparisonValue, bitMask) > 0 then		-- this bitValue is one that is required by the quest
							if self:CelebratingHoliday(self.holidayMapping[code]) then
								found = true
							end
						end
					end
					retval = found
				end
			elseif 'R' == requirementCode or 'S' == requirementCode then
				bitMaskToUse = (nil == soughtParameter) and self.playerRaceBitMask or self.raceNameToBitMapping[soughtParameter]
				retval = (bit.band(self.quests[questId][4], bitMaskToUse) > 0)
-- TODO: Should convert these over to the new way of doing things
			elseif 'V' == requirementCode or 'W' == requirementCode or 'P' == requirementCode then
				local codeArray = { strsplit(" ", self.quests[questId][1]) }
				local controlCode
				local controlValue
				for i = 1, #codeArray do
					controlCode = strsub(codeArray[i], 1, 1)
					controlValue = strsub(codeArray[i], 2, 2)
					if controlCode == requirementCode then
						if 'V' == requirementCode or 'W' == requirementCode then
							local repIndex = tonumber(strsub(codeArray[i], 2, 3))
							local repValue = tonumber(strsub(codeArray[i], 4, 8))
							local exceeds, earnedValue = self:ReputationExceeds(self.reputationMapping[repIndex], repValue)
							local success = exceeds
							if ('V' == requirementCode) then success = not success end
							if success then
								retval = false
--								if nil ~= earnedValue then
--									tinsert(failures, codeArray[i].." actual: "..earnedValue)
--								end
							end
						elseif 'P' == requirementCode then
							local colonCheck = strsub(codeArray[i], 3, 3)
							if ':' == controlValue or
							('L' == controlValue and ':' == colonCheck) or
							('H' == controlValue and ':' == colonCheck) or
							('C' == controlValue and ':' == colonCheck) or
							('C' == controlValue and 'T' == colonCheck and ':' == strsub(codeArray[i], 4, 4)) or
							('L' == controlValue and 'T' == colonCheck and ':' == strsub(codeArray[i], 4, 4))
							then
								-- we ignore these because they are not profession requirements.
							else
								local profValue = tonumber(strsub(codeArray[i], 3, 5))
								local exceeds, skillLevel = self:ProfessionExceeds(controlValue, profValue)
								if not exceeds then
									retval = false
--									tinsert(failures, codeArray[i].." actual: "..skillLevel)
								end
							end

						end
					end
				end
			end
			return retval
		end,

		---
		--	Returns whether the character meets class requirements for the specified quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@soughtClass The desired class to be matched, or if nil the player's class will be used
		--	@return True if the character meets the class requirements for the specified quest or false otherwise.
		--	@return A table of failures if any, nil otherwise.
		MeetsRequirementClass = function(self, questId, soughtClass)	return self:MeetsRequirement(questId, 'C', soughtClass)	end,

		---
		--	Returns whether the character meets faction requirements for the specified quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@soughtFaction The desired faction to be matched, or if nil the player's faction will be used
		--	@return True if the character meets the faction requirements for the specified quest or false otherwise.
		--	@return A table of failures if any, nil otherwise.
		MeetsRequirementFaction = function(self, questId, soughtFaction)	return self:MeetsRequirement(questId, 'F', soughtFaction)	end,

		---
		--	Returns whether the character meets gender requirements for the specified quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@param soughtGender The desired gender to be matched, or if nil the player's gender will be used
		--	@return True if the character meets the gender requirements for the specified quest or false otherwise.
		--	@return A table of failures if any, nil otherwise.
		MeetsRequirementGender = function(self, questId, soughtGender)	return self:MeetsRequirement(questId, 'G', soughtGender)	end,

		---
		--	Returns whether the character meets holiday requirements for the specified quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@return True if the character meets the holiday requirements for the specified quest or false otherwise.
		--	@return A table of failures if any, nil otherwise.
		MeetsRequirementHoliday = function(self, questId)	return self:MeetsRequirement(questId, 'H')	end,

		---
		--	Returns whether the level requirements are met for the specified quest.  This handles both minimum and maximum level requirements.
		--	@param questId The standard numeric questId representing a quest.
		--	@param optionalComparisonLevel A comparison level to use.  If nil the character's level is used.
		--	@return True if the level requirements for the specified quest are met or false otherwise.
		--	@return The level used in making comparisons to the requirements of the quest.
		--	@return The minimum level required for the quest.
		--	@return The maximum level permitted for the quest or Grail.INFINITE_LEVEL if there is none.
		MeetsRequirementLevel = function(self, questId, optionalComparisonLevel)
			questId = tonumber(questId)
			if nil == questId then return false end
			local bitMask = self:CodeType(questId)
			local retval = true
			local levelToCompare = optionalComparisonLevel or UnitLevel('player')
			local levelRequired = bit.band(bitMask, self.bitMaskQuestMinLevel) / self.bitMaskQuestMinLevelOffset
			local levelNotToExceed = bit.band(bitMask, self.bitMaskQuestMaxLevel) / self.bitMaskQuestMaxLevelOffset
			if levelToCompare < levelRequired or levelToCompare > levelNotToExceed then
				retval = false
			end
			return retval, levelToCompare, levelRequired, levelNotToExceed
		end,

		---
		--	Returns whether the character meets profession requirements for the specified quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@return True if the character meets the profession requirements for the specified quest or false otherwise.
		--	@return A table of failures if any, nil otherwise.
		MeetsRequirementProfession = function(self, questId)	return self:MeetsRequirement(questId, 'P')	end,

		---
		--	Returns whether the character meets race requirements for the specified quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@soughtRace The desired race to be matched, or if nil the player's race will be used
		--	@return True if the character meets the race requirements for the specified quest or false otherwise.
		--	@return A table of failures if any, nil otherwise.
		MeetsRequirementRace = function(self, questId, soughtRace)	return self:MeetsRequirement(questId, 'R', soughtRace)	end,

		---
		--	Returns whether the character meets reputation requirements for the specified quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@return True if the character meets the reputation requirements for the specified quest or false otherwise.
		--	@return A table of failures if any, nil otherwise.
		MeetsRequirementReputation = function(self, questId)
			local first, failures = self:MeetsRequirement(questId, 'V')
			local second, failures2 = self:MeetsRequirement(questId, 'W')
			local retval = first and second
			if nil == failures then
				failures = failures2
			else
				failures = self:TableAppend(failures, failures2)
			end
			return retval, failures
		end,

		---
		--	Returns a table of NPC information, and whether the NPC must be killed.  Each element in the table is a table with the x-coordinate,
		--	y-coordinate, NPC name, and NPC ID in it.
		--	@param questId The standard numeric questId representing a quest.
		--	@param acceptOrTurnin Either "A" or "T" depending on which type of NPC is sought, one that gives the quest, or one to whom the quest is turned in.
		--	@param mapId The desired map area where the NPC should appear.
		--	@return A table of NPC information
		--	@return	Whether the NPC must be killed.
		MultipleUniqueMapLocationQuest = function(self, questId, acceptOrTurnin, mapId, dungeonLevel, allowAnyMap)
			local retval = {}
			local onlyInSpecifiedMap = true
			if allowAnyMap then onlyInSpecifiedMap = false end
			local locations, mustKill = self:LocationQuestInMapRaw(questId, acceptOrTurnin, false, true, onlyInSpecifiedMap, mapId, true)
			if nil ~= locations then
				for i = 1, #locations do	-- each location should be { { mapId, coords, dungeonLevel [,realArea] }, NPCname, NPCID }
					if locations[i][2] ~= self:NPCName(0) and nil == strfind(locations[i][2], 'Near') and 2 <= #(locations[i][1]) then
						if nil == locations[i][1][2] then
							print("Grail error: Not expecting nil for coords from Quest", questId, acceptOrTurnin, i)
						else
							local coords = { strsplit(',', locations[i][1][2]) }
							if 2 >= #coords and (nil == dungeonLevel or dungeonLevel == locations[i][1][3]) then
								tinsert(retval, { tonumber(coords[1]), tonumber(coords[2]), locations[i][2], locations[i][3], locations[i][1][1], locations[i][1][3], locations[i][1][4] } )
							end
						end
					end
				end
			end
			if 0 == #retval then retval = nil end
			return retval, mustKill
		end,	

		---
		--	Returns the localized name of the NPC represented by the specified NPC ID.
		--	@param npcId The standard numeric npcId representing an NPC.
		--	@return The localized string for the specific NPC, or nil if the NPC is not found in the database.
		NPCName = function(self, npcId)	npcId = tonumber(npcId)	return nil ~= npcId and nil ~= self.npcs[npcId] and self.npcs[npcId][0] or nil	end,

		PlayerLogin = function(self, frame)
			frame:RegisterEvent("CHAT_MSG_COMBAT_FACTION_CHANGE")	-- needed for quest status caching
			frame:RegisterEvent("CHAT_MSG_SKILL")	-- needed for quest status caching
			frame:RegisterEvent("PLAYER_LEVEL_UP")	-- needed for quest status caching
			frame:RegisterEvent("QUEST_ACCEPTED")
			frame:RegisterEvent("QUEST_COMPLETE")
			frame:RegisterEvent("UNIT_QUEST_LOG_CHANGED")	-- so we can know when a quest is complete or failed
			frame:RegisterEvent("QUEST_QUERY_COMPLETE")
			self:CleanDatabase()
			self:UpdateQuestResetTime()
		end,

		---
		--	Internal Use.
		--	Routine used to put notifications into the system that will be posted in a routine called by OnUpdate after
		--	the spcified delay.  If there were no notifications in the queue prior to this call the notificationFrame
		--	will have an OnUpdate script set.
		--	@param notificationName The name of the notification that will eventually be posted.  E.g., Abandon, Accept, etc.
		--	@param questId The questId associated with the notification.
		--	@param delay The delay time in seconds which will probably be a floating point number less than one.
		PostDelayedNotification = function(self, notificationName, questId, delay)
			if nil == self.delayedNotifications then self.delayedNotifications = {} end
			if 0 == #(self.delayedNotifications) then	-- the assumption is when the table has 0 notifications we pull the handler off
				self.notificationFrame:SetScript("OnUpdate", function(myself, elapsed) self:ProcessDelayedNotifications(elapsed) end)
			end
			tinsert(self.delayedNotifications, { ["n"] = notificationName, ["q"] = questId, ["f"] = GetTime() + delay })
		end,

		---
		--	Internal Use.
		--	This routine is used to post notifications to observers.
		--	@param eventName The name of the notification.
		--	@param questId The questId associated with the notification.
		PostNotification = function(self, eventName, questId)
			if nil ~= self.observers[eventName] then
				for _,f in pairs(self.observers[eventName]) do
					f(eventName, questId)
				end
			end
		end,

		---
		--	Internal Use.
		--	Routine used by the OnUpdate system to process notifications that have been put into a queue for delayed
		--	processing.  When the last notification is removed from the queue, the notificationFrame will have its
		--	OnUpdate script removed.
		ProcessDelayedNotifications = function(self, ignoredElapsed)
			local now = GetTime()	-- if now > "fire trigger" we post the associated notification
			local newNotificationTable = {}
			for _, t in pairs(self.delayedNotifications) do
				if now > t["f"] then
					self:PostNotification(t["n"], t["q"])
				else
					tinsert(newNotificationTable, t)
				end
			end
			self.delayedNotifications = newNotificationTable
			if 0 == #(self.delayedNotifications) then
				self.notificationFrame:SetScript("OnUpdate", nil)
			end
		end,

		---
		--	Internal Use.
		--	Returns whether the character has the profession specified by the code exceeding the specified level.
		--	@param professionCode The code representing the profession as used in Grail.professionMapping
		--	@param professionValue The skill level to use in comparison.
		--	@return True when the character possesses the skill in excess of the indicated value, false otherwise.
		--	@return The actual skill level the character posseses or Grail.NO_SKILL if the character does not have the specified skill.
		--	@use hasSkill, skillLevel = Grail:ProfessionExceeds('+', 125)
		ProfessionExceeds = function(self, professionCode, professionValue)
			local retval = false
			local skillLevel = self.NO_SKILL
			local skillName = nil
			local prof1, prof2, archaeology, fishing, cooking, firstAid = GetProfessions();

			if "X" == professionCode and nil ~= archaeology then
				_, _, skillLevel = GetProfessionInfo(archaeology)
			elseif "F" == professionCode and nil ~= fishing then
				_, _, skillLevel = GetProfessionInfo(fishing)
			elseif "C" == professionCode and nil ~= cooking then
				_, _, skillLevel = GetProfessionInfo(cooking)
			elseif "+" == professionCode and nil ~= firstAid then
				_, _, skillLevel = GetProfessionInfo(firstAid)
			elseif "R" == professionCode then
				skillLevel = self:RidingSkillLevel()
			else
				professionName = self.professionMapping[professionCode]
				if nil ~= prof1 then
					skillName, _, skillLevel = GetProfessionInfo(prof1)
				end
				if skillName ~= professionName then
					if nil ~= prof2 then
						skillName, _, skillLevel = GetProfessionInfo(prof2)
					end
					if skillName ~= professionName then
						skillLevel = self.NO_SKILL
					end
				end
			end
			if skillLevel >= professionValue then
				retval = true
			end
			return retval, skillLevel
		end,

		---
		--	Internal Use.
		--	Routine used to hook the function for abandoning a quest.  This is needed because the events that Blizzard issues
		--	are not adequate for our desired tasks.  One of three needed for abandoning.
		QuestAbandonStart = function(self)
			self.abandoningQuestIndex = GetQuestLogSelection()
			self.origAbandonQuestFunction()
		end,

		---
		--	Internal Use.
		--	Routine used to hook the function for abandoning a quest.  This is needed because the events that Blizzard issues
		--	are not adequate for our desired tasks.  One of three needed for abandoning.
		QuestAbandonStop = function(self)
			local questTitle, level, questTag, suggestedGroup, isHeader, isCollapsed, isComplete, isDaily, questId = GetQuestLogTitle(self.abandoningQuestIndex)
			self.origConfirmAbandonQuestFunction()
			if nil ~= self.quests[questId] and nil ~= self.quests[questId]['OBC'] then
-- TODO: The fact that these quests are completed will be lost when the server is queried.  Therefore, they need to be recorded as completed in some special way that is permanent.  And when server query is performed, the special way needs to be accessed to update after server query so we always believe they are complete.
				local questsToInvalidate = {}
				for _,clearQuestId in pairs(self.quests[questId]['OBC']) do
					self:MarkQuestComplete(clearQuestId, true, true)
					tinsert(questsToInvalidate, clearQuestId)
				end
				self:StatusCodeInvalidate(questsToInvalidate)
			end
			self:PostDelayedNotification("Abandon", questId, self.abandonPostNotificationDelay)
		end,

		---
		--	Returns a table of questIds that are possible breadcrumbs for the specified quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@return A table of questIds for possible breadcrumb quests for this quest, or nil if there are none.
		QuestBreadcrumbs = function(self, questId)	return self:QuestGenericAccess(questId, 'O')	end,

		QuestGenericAccess = function(self, questId, internalCode)	questId = tonumber(questId)	return nil ~= questId and nil ~= self.quests[questId] and self.quests[questId][internalCode] or nil	end,

		---
		--	Returns the questId of the quest in the quest log with the sought title.
		--	@param soughtTitle The localized name of the quest sought in the quest log.
		--	@return The questId of the quest in the quest log matching the sought name or nil if none match.
		QuestInQuestLogMatchingTitle = function(self, soughtTitle)
			local retval = nil
			local i = 1
			local cleanedTitle = strtrim(soughtTitle)
			while GetQuestLogTitle(i) and nil == retval do
				local questTitle, level, questTag, suggestedGroup, isHeader, isCollapsed, isComplete, isDaily, questId = GetQuestLogTitle(i)
				if not isHeader and questTitle == cleanedTitle then
					retval = questId
				end
				i = i + 1
			end
			return retval
		end,

		---
		--	Returns a table of questIds that invalidate the specified quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@return A table of questIds that invalidate this quest, or nil if there are none.
		QuestInvalidates = function(self, questId)	return self:QuestGenericAccess(questId, 'I')	end,

		---
		--	Returns the level of the quest with the specified questId.
		--	@param questId The standard numeric questId representing a quest.
		--	@return The level of the quest matching the questId or nil if none found.
		QuestLevel = function(self, questId)	return bit.band(self:CodeType(questId), self.bitMaskQuestLevel) / self.bitMaskQuestLevelOffset	end,

		---
		--	Returns the name of the quest with the specified questId.
		--	@param questId The standard numeric questId representing a quest.
		--	@return The localized name of the quest matching the questId or nil if none found.
		QuestName = function(self, questId)	questId = tonumber(questId)	return nil ~= questId and nil ~= self.quests[questId] and self.quests[questId][0] or nil	end,

		QuestNPCAccepts = function(self, questId)	return self:QuestGenericAccess(questId, 'A')	end,

		QuestNPCKills = function(self, questId)	return self:QuestGenericAccess(questId, 'AK')	end,

		QuestNPCTurnins = function(self, questId)	return self:QuestGenericAccess(questId, 'T')	end,

		QuestOnAcceptCompletes = function(self, questId)	return self:QuestGenericAccess(questId, 'OAC')	end,

		QuestOnCompletionCompletes = function(self, questId)	return self:QuestGenericAccess(questId, 'OCC')	end,

		QuestOnTurninCompletes = function(self, questId)	return self:QuestGenericAccess(questId, 'OTC')	end,

		---
		--	Returns a table of questIds of quests that can be a prerequisite of the specified quest.  The
		--	list is a combination of all the types of prerequisite quests possible.
		--	@param questId The standard numeric questId representing a quest.
		--	@return A table of questIds of prerequisite quests for this quest, or nil if there are none.
		QuestPrerequisites = function(self, questId)
			questId = tonumber(questId)
			if nil == questId or nil == self.quests[questId] then return nil end
			local retval = self:TableAppendCodes(nil, self.quests[questId], { 'P', 'PH', 'PL', 'PLT', 'PC', 'PCT' })
--			local retval = {}
--			retval = self:TableAppend(retval, self:QuestPrerequisitesSimple(questId))
--			retval = self:TableAppend(retval, self:QuestPrerequisitesEver(questId))
--			retval = self:TableAppend(retval, self:QuestPrerequisitesLog(questId))
--			retval = self:TableAppend(retval, self:QuestPrerequisitesLogTurnin(questId))
--			retval = self:TableAppend(retval, self:QuestPrerequisitesComplete(questId))
--			retval = self:TableAppend(retval, self:QuestPrerequisitesCompleteTurnin(questId))
			if 0 == #retval then retval = nil end
			return retval
		end,

		QuestPrerequisitesComplete = function(self, questId)	return self:QuestGenericAccess(questId, 'PC')	end,

		QuestPrerequisitesCompleteTurnin = function(self, questId)	return self:QuestGenericAccess(questId, 'PCT')	end,

		---
		--	Returns a table of questIds that are prerequisites ever completed for the specified quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@return A table of questIds that are prerequisites ever completed for this quest, or nil if there are none.
		QuestPrerequisitesEver = function(self, questId)	return self:QuestGenericAccess(questId, 'PH')	end,

		QuestPrerequisitesLog = function(self, questId)	return self:QuestGenericAccess(questId, 'PL')	end,

		QuestPrerequisitesLogTurnin = function(self, questId)	return self:QuestGenericAccess(questId, 'PLT')	end,

		---
		--	Returns a table of questIds that are simple prerequisites for the specified quest.
		--	@param questId The standard numeric questId representing a quest.
		--	@return A table of questIds that are simple prerequisites for this quest, or nil if there are none.
		QuestPrerequisitesSimple = function(self, questId)	return self:QuestGenericAccess(questId, 'P')	end,

		---
		--	Internal Use.
		--	Routine used to hook the function for completing a quest.  This is needed because the events that Blizzard issues
		--	are not adequate for our desired tasks.
		QuestRewardCompleteButton_OnClick = function(self)
			self.questNPCId = self:GetNPCId(false)
			if nil == self.completingQuest then
				local questGivers = self.specialQuests[self.completingQuestTitle]
				if nil ~= questGivers then
					for i = 1, #questGivers do
						if tonumber(questGivers[i][1]) == self.questNPCId then
							self.completingQuest = questGivers[i][2]
						end
					end
				end
			end

			if self.completingQuest then
				self.completingQuest = self:GetOTCQuest(self.completingQuest, self.questNPCId)
				self.reputationCompletingQuest = self.completingQuest
				self:MarkQuestComplete(self.completingQuest, true, true)
				self.completingQuest = nil
			end
			self.origHookFunction()
		end,

		---
		--	Returns a table of quest IDs for quests that take place during the specified holiday.
		--	@param eventName The localized name of the holiday.
		--	@return A table of questIds for quests taking place in the specified holiday or nil if there are none.
		--	@see QuestsDuringEventCode
		QuestsDuringEvent = function(self, eventName)
			local retval = nil
			local desiredEventCode = nil
			for holidayCode, holidayName in pairs(self.holidayMapping) do
				if eventName == holidayName then desiredEventCode = holidayCode end
			end
			if nil ~= desiredEventCode then retval = self:QuestsDuringEventCode(desiredEventCode) end
			return retval
		end,

		---
		--	Returns a table of quest IDs for quests that take place during the holiday specified by the code.
		--	@param eventNameCode The code representing the holiday taken from Grail.holidayMapping.  This is not a localized code.
		--	@return A table of questIds for quests taking place in the specified holiday or nil if there are none.
		--	@see QuestsDuringEvent
		QuestsDuringEventCode = function(self, eventNameCode)	return self.indexedQuests[self.holidayToMapAreaMapping['H'..eventNameCode]]	end,

-- TODO: Determine if this should live since no one is calling it
		---
		--	Returns the table of questIds filtered by character's specifics.
		--	@param questTable The master table of questIds to be filtered.
		--	@param faction If true, the character's faction must match that of the quest.
		--	@param class If true, the character's class must match that of the quest.
		--	@param race If true, the character's race must match that of the quest.
		--	@param gender If true, the character's gender must match that of the quest.
		--	@param targetLevel If present, the quest must be acceptable for a character of this level.
		--	@return A table of filtered quests or nil if there are none.
		QuestsFiltered = function(self, questTable, faction, class, race, gender, targetLevel)
			local retval = { }
			local stillGood
			if nil ~= questTable then
				for _, questId in pairs(questTable) do
					stillGood = true
					if faction and not self:MeetsRequirementFaction(questId) then stillGood = false end
					if class and not self:MeetsRequirementClass(questId) then stillGood = false end
					if race and not self:MeetsRequirementRace(questId) then stillGood = false end
					if gender and not self:MeetsRequirementGender(questId) then stillGood = false end
					if targetLevel and not self:MeetsRequirementLevel(questId, targetLevel) then stillGood = false end
					if stillGood then tinsert(retval, questId) end
				end
			end
			if 0 == #(retval) then retval = nil end
			return retval
		end,

-- TODO: Remove the forceSearch and most likely the forceGarbageCollection parameters and code that uses them
		---
		--	Returns a table of quest IDs for quests that can start in the specified map area.
		--	@param mapId The map area to use, or if nil, the map area the character is currently in will be used.
		--	@param forceGarbageCollection If true, garbage collection is performed after searching the internal database.
		--	@param forceSearch If true, a search is performed using starting NPCs instead of using the cached indexed, resulting in slower and more memory intensive use.
		--	@return A table of questIds for quests that start in the map area or nil if none.
		QuestsInMap = function(self, mapId, forceGarbageCollection, forceSearch, useDungeonAlso, useLoremasterOnly)
			local retval = {}
			local mapIdToUse = mapId or GetCurrentMapAreaID()

			if nil ~= mapIdToUse and not forceSearch then	-- take the easy way out and use the precomputed list of quests in the map area
				if useLoremasterOnly then
					retval = self.loremasterQuests[mapIdToUse]
				elseif useDungeonAlso then
					if nil == self.indexedQuestsExtra[mapIdToUse] then
						retval = self.indexedQuests[mapIdToUse]
					elseif nil == self.indexedQuests[mapIdToUse] then
						retval = self.indexedQuestsExtra[mapIdToUse]
					else
						for k,v in pairs(self.indexedQuests[mapIdToUse]) do
							tinsert(retval, v)
						end
						for k, v in pairs(self.indexedQuestsExtra[mapIdToUse]) do
							if not tContains(retval, v) then
								tinsert(retval, v)
							end
						end
					end
				else
					retval = self.indexedQuests[mapIdToUse]
				end
			else	-- do a manual search through all the quests to find where their A NPCs are, and whether they match the mapIdToUse
				local locations
				local shouldAdd
				for questId, _ in pairs(self.quests) do
					locations = self:LocationQuestInMap(questId, 'A')
					shouldAdd = false
					if nil ~= locations then
						for i = 1, #locations do
							if tonumber(locations[i][1]) == mapIdToUse then shouldAdd = true end
						end
					end
					if shouldAdd then tinsert(retval, questId) end
				end
			end

			if forceGarbageCollection then collectgarbage() end

			if nil ~= retval and 0 == #retval then retval = nil end
			return retval
		end,

		---
		--	Returns a table of quest IDs for the quests in the character's quest log.
		--	@return A table of questIds of quests in the character's quest log or an empty table if there are none.
		QuestsInQuestLog = function(self)
			local retval = { }
			local i = 1
			while GetQuestLogTitle(i) do
				local questTitle, level, questTag, suggestedGroup, isHeader, isCollapsed, isComplete, isDaily, questId = GetQuestLogTitle(i)
				if not isHeader then
					tinsert(retval, questId)
				end
				i = i + 1
			end
			return retval
		end,

-- TODO: Continue analyzing from here down...
		---
		--	Returns a table of quest IDs for quests that can start in the specified zone.
		--	@param zoneText The localized zone name, or if nil is used the zone the character is currently in.
		--	@param forceGarbageCollection If true, garbage collection is performed after searching the internal database.
		--	@param forceSearch If true, a search is performed using starting NPCs instead of using the cached indexed, resulting in slower and more memory intensive use.
		--	@return A table of questIds for quests that start in the zone or nil if none.
		QuestsInZone = function(self, zoneText, forceGarbageCollection, forceSearch)
			local mapIdToUse = nil
			if nil ~= zoneText then
				mapIdToUse = self.zoneNameMapping[zoneText]
				if nil == mapIdToUse and self.debug then print("Grail:QuestsInZone could not find zone name ", zoneText, " so is using current zone.") end
			end
			return self:QuestsInMap(mapIdToUse, forceGarbageCollection, forceSearch)
		end,

		---
		--	Returns the questId for the quest with the specified name.
		--	@param soughtName The localized name of the quest.  If nil this will raise.
		--	@return The questId of the quest or nil if no quest with that name found.
		QuestWithName = function(self, soughtName)
			assert((nil ~= soughtName), "Grail Error: sought name cannot be nil")
			local retval = nil
			for questId, _ in pairs(self.quests) do
				if self:QuestName(questId) == soughtName then
					retval = questId
				end
			end
			return retval
		end,

		RecordBadData = function(self, whichData, errorString)
			if nil == GrailDatabase[whichData] then GrailDatabase[whichData] = {} end
			tinsert(GrailDatabase[whichData], errorString)
		end,

		RecordBadNPCData = function(self, errorString)
			self:RecordBadData("BadNPCData", errorString)
		end,

		RecordBadQuestData = function(self, errorString)
			self:RecordBadData("BadQuestData", errorString)
		end,

		RecordReputation = function(self, message)
			local startPos, endPos, reputationName, changeAmount = strfind(message, self.increasedPattern)
			local direction = 1
			if nil == startPos then
				startPos, endPos, reputationName, changeAmount = strfind(message, self.decreasedPattern)
				direction = -1
			end
			if nil ~= startPos then

				-- Figure out the modifications to reputation
				local bonus = 0
				local playerGuildLevel = GetGuildLevel()
				if playerGuildLevel >= 12 then
					bonus = bonus + 0.10
				elseif playerGuildLevel >= 4 then
					bonus = bonus + 0.05
				end
				if "Human" == self.playerRace then
					bonus = bonus + 0.10
				end
				
				if 0 ~= bonus then
					changeAmount = floor((changeAmount / (1.00 + bonus)) + 0.5)
				end

				changeAmount = changeAmount * direction
				local questId = self.reputationCompletingQuest
				local reputationIndex = self.reverseReputationMapping[reputationName]
				local repChangeString = nil
				local message = nil
				if nil ~= reputationIndex then
					if 82 ~= reputationIndex then
						repChangeString = strformat("%02d%d", reputationIndex, changeAmount)
					end
				else
					message = strformat("UnknownRep:%s %d", reputationName, changeAmount)
				end
				if nil ~= repChangeString and nil ~= questId and nil ~= self.quests[questId] and (nil == self.quests[questId][6] or not tContains(self.quests[questId][6], repChangeString)) then
					message = strformat("Rep:%s", repChangeString)
				end
				if nil ~= message and nil ~= questId then
					self:RecordBadQuestData('G' .. self.versionNumber .. '|' .. questId .. "|0|" .. message)
				end
			end
			
		end,

		---
		--	Internal Use.
		--	Adds the callback to the observer queue for eventName.  Should not be called directly, but through the use of convenience API.
		--	@see RegisterObserverQuestAbandon
		--	@see RegisterObserverQuestAccept
		--	@see RegisterObserverQuestComplete
		--	@param eventName The name of the event to which the callback should be added.
		--	@param callback The callback that is to be added.
		RegisterObserver = function(self, eventName, callback)
			assert((nil ~= callback), "Grail Error: cannot register a nil callback")
			if nil == self.observers[eventName] then self.observers[eventName] = { } end
			tinsert(self.observers[eventName], callback)
		end,

		---
		--	Add the callback to receive quest Abandon notifications.
		--	When the notification is posted the callback will be called with two parameters, "Abandon" and the questId.
		--	@param callback The callback that is to be added.
		RegisterObserverQuestAbandon = function(self, callback)
			self:RegisterObserver("Abandon", callback)
		end,

		---
		--	Add the callback to receive quest Accept notifications.
		--	When the notification is posted the callback will be called with two parameters, "Accept" and the questId.
		--	@param callback The callback that is to be added.
		RegisterObserverQuestAccept = function(self, callback)
			self:RegisterObserver("Accept", callback)
		end,

		---
		--	Add the callback to receive quest Completion notifications.
		--	When the notification is posted the callback will be called with two parameters, "Complete" and the questId.
		--	@param callback The callback that is to be added.
		RegisterObserverQuestComplete = function(self, callback)
			self:RegisterObserver("Complete", callback)
		end,

		RegisterSlashOption = function(self, option, helpDescription, theFunction)
			self.slashCommandOptions[option] = { ['help'] = helpDescription, ['func'] = theFunction }
		end,

		---
		--	Internal Use.
		--	Returns whether the character has a reputation that exceeds the value specified for the reputation specified.
		--	@param reputationName The localized name of the sought reputation.
		--	@param reputationValue The reputation value that needs to be exceeded.  Note that internally all reputation values are the earned reputation value + 42000.
		--	@return True if the character has more reputation than was sought, or false otherwise.
		--	@return The reputation value the character actually has (earned value + 42000).
		--	@usage doesExceed, reputationValue = Grail:ReputationExceeds("Lower City", 41999)
		ReputationExceeds = function(self, reputationName, reputationValue)
			local retval = false
			local actualEarnedValue = nil
			local factionIndex = 1
			reputationValue = tonumber(reputationValue)
			local lastFactionName = nil
			repeat
				local name, description, standingId, bottomValue, topValue, earnedValue, atWarWith, canToggleAtWar, isHeader, isCollapsed, hasRep, isWatched, isChild = GetFactionInfo(factionIndex)
				if name == lastFactionName then break end
				lastFactionName = name
				if not isHeader then
					if name == reputationName then
						earnedValue = earnedValue + 42000	-- the reputationValue is stored with 42000 added to it so we do not have to deal with negative numbers, so we normalize here
						retval = (earnedValue > reputationValue)
						actualEarnedValue = earnedValue
						break
					end
				end
				factionIndex = factionIndex + 1
			until factionIndex > 200
			return retval, actualEarnedValue
		end,

		---
		--	Returns the riding skill level of the character.
		--	@return The riding skill level of the character or Grail.NO_SKILL if no skill exists.
		RidingSkillLevel = function(self)
			-- Need to search the spell book for the Riding skill
			local retval = self.NO_SKILL
			local spellIdMapping = { [33388] = 75, [33391] = 150, [34090] = 225, [34091] = 300, [90265] = 375 }
			local _, _, _, numberSpells = GetSpellTabInfo(1)
			for i = 1, numberSpells, 1 do
				local name = GetSpellBookItemName(i, BOOKTYPE_SPELL)
				local link = GetSpellLink(name)
				if link then
					local spellId = tonumber(link:match("^|c%x+|H(.+)|h%[.+%]"):match("(%d+)"))
					if spellId then
						local newLevel = spellIdMapping[spellId]
						if newLevel and newLevel > retval then
							retval = newLevel
						end
					end
				end
			end
			return retval
		end,

		---
		--	Returns a single x-coordinate, y-coordinate, NPC name, NPC ID, and whether the NPC must be killed for the specified information.
		--	@param questId The standard numeric questId representing a quest.
		--	@param acceptOrTurnin Either "A" or "T" depending on which type of NPC is sought, one that gives the quest, or one to whom the quest is turned in.
		--	@param mapId The desired map area where the NPC should appear.
		--	@return The x-coordinate of the NPC.
		--	@return The y-coordinate of the NPC.
		--	@return The localized name of the NPC.
		--	@return The ID of the NPC.
		--	@return	Whether the NPC must be killed.
		SingleMapLocationQuest = function(self, questId, acceptOrTurnin, mapId)
			local locations, npcName, npcId, mustKill = self:LocationQuestInMap(questId, 'A', false, true, true, mapId)
			if nil ~= locations and 0 < #(locations) and 2 == #(locations[1]) and locations[1][2] ~= self:NPCName(0) and nil == strfind(locations[1][2], 'Near') then
				local coords = { strsplit(',', locations[1][2]) }
				return tonumber(coords[1]), tonumber(coords[2]), npcName, npcId, mustKill
			else
				return nil
			end
		end,

		---
		--	Internal Use.
		--	The routine called when the /grail slash command is used.  For the most part the currently implemented commands are for testing only.
		--	@param frame The tooltip frame.
		--	@param msg The rest of the command line used with the /grail slash command.
		SlashCommand = function(self, frame, msg)
			local executed = false
--			msg = strlower(msg)
			for option, value in pairs(self.slashCommandOptions) do
				if option == strsub(msg, 1, strlen(option)) then
					value['func'](msg, frame)
					executed = true
				end
			end
			if not executed then
				print("|cFFFF0000Grail|r initiating server database query")
				QueryQuestsCompleted()
			end			
		end,

		---
		--	Returns a bit mask indicating the status of the quest.
		--	@param questId The standard numeric questId representing the quest.
		--	@return An integer that should be interpreted as a bit mask containing information why the quest cannot be accepted (or 0 (or 2) if it can).
		StatusCode = function(self, questId)
			local retval = 0
			questId = tonumber(questId)

			if questId ~= nil and self.quests[questId] ~= nil then
--				if nil == self.questStatusCache["quests"][questId] then
				if nil == self.quests[questId][7] then
					tinsert(self.currentlyProcessingStatus, questId)
					if self:DoesQuestExist(questId) then
						if not self:MeetsRequirementClass(questId) then retval = retval + self.bitMaskClass end
						if not self:MeetsRequirementRace(questId) then retval = retval + self.bitMaskRace end
						if not self:MeetsRequirementGender(questId) then retval = retval + self.bitMaskGender end
						if not self:MeetsRequirementFaction(questId) then retval = retval + self.bitMaskFaction end
						-- Only set the completed if it actually could have been done based on class, race, gender and faction
						if 0 == retval and self:IsQuestCompleted(questId) then retval = retval + self.bitMaskCompleted end
						if self:IsRepeatable(questId) then retval = retval + self.bitMaskRepeatable end
						if self:IsDaily(questId) or self:IsWeekly(questId) or self:IsMonthly(questId) or self:IsYearly(questId) then retval = retval + self.bitMaskResettable end
						if self:HasQuestEverBeenCompleted(questId) then retval = retval + self.bitMaskEverCompleted end
						if self:IsLowLevel(questId) then retval = retval + self.bitMaskLowLevel else tinsert(self.questStatusCache["V"], questId) end
						local inLog, inLogStatus = self:IsQuestInQuestLog(questId)
						if inLog and 0 == bit.band(retval, self.bitMaskCompleted) then retval = retval + self.bitMaskInLog end
						if inLogStatus then
							if inLogStatus > 0 then retval = retval + self.bitMaskInLogComplete end
							if inLogStatus < 0 then retval = retval + self.bitMaskInLogFailed end
						end
						if not self:MeetsPrerequisites(questId) then
							retval = retval + self.bitMaskPrerequisites
							retval = self:AncestorStatusCode(questId, retval)
						end
						-- Only set an invalidation if the quest is not already completed
						if 0 == bit.band(retval, self.bitMaskCompleted) and self:IsInvalidated(questId) then retval = retval + self.bitMaskInvalidated end
						if not self:MeetsRequirementProfession(questId) then retval = retval + self.bitMaskProfession tinsert(self.questStatusCache["P"], questId) end
						if not self:MeetsRequirementReputation(questId) then retval = retval + self.bitMaskReputation tinsert(self.questStatusCache["R"], questId) end
						if not self:MeetsRequirementHoliday(questId) then retval = retval + self.bitMaskHoliday end
						local success, levelToCompare, levelRequired, levelNotToExceed = self:MeetsRequirementLevel(questId, self.levelingLevel)
						-- Only set a level problem if the quest is not already completed
						if not success and 0 == bit.band(retval, self.bitMaskCompleted) then
							if levelToCompare < levelRequired then retval = retval + self.bitMaskLevelTooLow tinsert(self.questStatusCache["L"], questId) end
							if levelToCompare > levelNotToExceed then retval = retval + self.bitMaskLevelTooHigh end
						end
-- TODO: Think about moving this code out of here and to CodeAllFixed because this need not be reevaluated each time the quest is
						local iQuests = self.quests[questId]['I']
						if nil ~= iQuests then
							for _, iQuestId in pairs(iQuests) do
								if nil == self.questStatusCache["I"][iQuestId] then self.questStatusCache["I"][iQuestId] = {} end
								if not tContains(self.questStatusCache["I"][iQuestId], questId) then tinsert(self.questStatusCache["I"][iQuestId], questId) end
							end
						end

					else
						retval = self.bitMaskNonexistent + self.bitMaskError
					end
--					self.questStatusCache["quests"][questId] = retval
					self.quests[questId][7] = retval

					-- First we invalidate the cache for all the quests whose status is suspect
					if nil ~= self.currentMortalIssues[questId] then
						for victimQuestId in pairs(self.currentMortalIssues[questId]) do
--							self.questStatusCache["quests"][victimQuestId] = nil
							self.quests[victimQuestId][7] = nil
						end
						self.currentMortalIssues[questId] = nil
					end
					-- Now we remove ourselves from the stack of processing
					tremove(self.currentlyProcessingStatus)

				else
--					retval = self.questStatusCache["quests"][questId]
					retval = self.quests[questId][7]
				end
			else
				retval = self.bitMaskError
			end
			return retval
		end,

		StatusCodeCallback = function(callbackType, questId)
			if nil ~= questId and tonumber(questId) then
				questId = tonumber(questId)
				if nil ~= Grail.questStatusCache then
--					Grail.questStatusCache["quests"][questId] = nil
					Grail.quests[questId][7] = nil
					Grail:CoalesceDelayedNotification("Status", 0)
					Grail:StatusCodeInvalidate(Grail.questStatusCache["I"][questId])
					Grail:StatusCodeInvalidate(Grail.questStatusCache["Q"][questId])
					Grail.questStatusCache["Q"][questId] = {}	-- the list we nuked should be regenerated when descendants get their new StatusCode values
				end
			end
		end,

		---
		--	
		StatusCodeInvalidate = function(self, tableOfQuestIds)
--			if nil ~= tableOfQuestIds and nil ~= self.questStatusCache then
			if nil ~= tableOfQuestIds then
				for _, questId in pairs(tableOfQuestIds) do
--					if nil ~= self.questStatusCache["quests"][questId] then
					if nil ~= self.quests[questId] and nil ~= self.quests[questId][7] then
--						self.questStatusCache["quests"][questId] = nil
						self.quests[questId][7] = nil
						self.StatusCodeCallback("bogus", questId)	-- we want to invalidate the cache for descendants
						self:CoalesceDelayedNotification("Status", 0)
					end
				end
			end
		end,

		TableAppend = function(self, t1, t2)
			if nil ~= t1 and nil ~= t2 then
				for _, value in pairs(t2) do
					tinsert(t1, value)
				end
			end
			return t1
		end,

		TableAppendCodes = function(self, t, master, codes)
			local tableToUse = t or {}
			if nil ~= codes and nil ~= master then
				for _, code in pairs(codes) do
					tableToUse = self:TableAppend(tableToUse, master[code])
				end
			end
			return tableToUse
		end,

		---
		--	Returns information about the currently selected target.
		--	@return The localized name of the target or nil if no target.
		--	@return The npcId of the target unless the target is a world object in which one million is added to its value.
		--	@return The coordinates of the player (since the target coordinates cannot be determined) in the format mapId*:xx.xx,yy.yy, where * is nothing or the dungeon level in []
		--	@usage targetName, npcId, coordinates = Grail:TargetInformation()
		TargetInformation = function(self)
			local coordinates = nil
			local npcId, targetName = self:GetNPCId(true)
			if nil ~= npcId then
				local x, y = GetPlayerMapPosition("player")	-- cannot get target x,y since Blizzard disabled that and returns 0,0 all the time for it
				local dungeonLevel = GetCurrentMapDungeonLevel()
				local dungeonIndicator = (dungeonLevel > 0) and "["..dungeonLevel.."]" or ""
				coordinates = strformat("%d%s:%.2f,%.2f", GetCurrentMapAreaID(), dungeonIndicator, x*100, y*100)
			end
			return targetName, npcId, coordinates
		end,

		---
		--	Internal Use.
		--	The routine called for event processing associated with the hidden tooltip.
		--	@param frame The tooltip frame.
		--	@param event The name of the event.
		--	@param ... Various parameters depending on the event.
		Tooltip_OnEvent = function(self, frame, event, ...)
			if self.eventDispatch[event] then
				self.eventDispatch[event](self, frame, ...)
			end
		end,

		---
		--	Internal Use.
		--	The routine called by the hidden tooltip used to receive events when it is loaded into the system.
		--	It is used to set up information about the player, register the /grail slash command, hook the routines
		--	for handling accepting and abandoning quests, updating database values, and registering for the
		--	VARIABLES_LOADED event.
		--	@param frame The tooltip frame.
		Tooltip_OnLoad = function(self, frame)
			self.playerRealm = GetRealmName()
			self.playerName = UnitName('player')
			_, self.playerClass = UnitClass('player')
			_, self.playerRace = UnitRace('player')
			self.playerFaction = UnitFactionGroup('player')
			self.playerGender = UnitSex('player')
			self.playerLocale = GetLocale()
			self.levelingLevel = UnitLevel('player')
			SlashCmdList["GRAIL"] = function(msg)
				self:SlashCommand(frame, msg)
			end
			SLASH_GRAIL1 = "/grail"

			if not frame:IsOwned(UIParent) then
				frame:SetOwner(UIParent, "ANCHOR_NONE")
			end

			-- Now to hook the QuestRewardCompleteButton_OnClick function
			self.origHookFunction = QuestFrameCompleteQuestButton:GetScript("OnClick")
			QuestFrameCompleteQuestButton:SetScript("OnClick", function() self:QuestRewardCompleteButton_OnClick() end);

			self.origAbandonQuestFunction = SetAbandonQuest
			SetAbandonQuest = function() self:QuestAbandonStart() end

			self.origConfirmAbandonQuestFunction = AbandonQuest
			AbandonQuest = function() self:QuestAbandonStop() end

			-- We set up the basic structure to cache quest status information
			if nil == self.questStatusCache then
				-- quests is a table whose indexes are questIds and values are the actual bit mask status
				-- L is a table of questIds who fail because of bitMaskLevelTooLow
				-- P is a table of questIds who fail because of bitMaskProfession
				-- R is a table of questIds who fail because of bitMaskReputation
				-- I is a table whose indexes are questIds and values are tables of questIds that suffer bitMaskInvalidated from the quest that is the index
				-- Q is a table whose indexes are questIds and values are tables of questIds that suffer bitMaskPrerequisites from the quest that is the index
				-- V is a table of questIds for quests that are NOT marked bitMaskLowLevel because gaining levels can change that value
--				self.questStatusCache = { ["quests"] = {}, ["L"] = {}, ["P"] = {}, ["R"] = {}, ["I"] = {}, ["Q"] = {}, ["V"] = {}, }
				self.questStatusCache = { ["L"] = {}, ["P"] = {}, ["R"] = {}, ["I"] = {}, ["Q"] = {}, ["V"] = {}, }
			end

			-- Create some convenience tables
			self.raceNameToBitMapping = {}
			for code,raceName in pairs(self.raceMapping) do
				self.raceNameToBitMapping[raceName] = self.raceToBitMapping[code]
			end
			self.classNameToBitMapping = {}
			self.classBitToCodeMapping = {}
			for code,className in pairs(self.classMapping) do
				self.classNameToBitMapping[className] = self.classToBitMapping[code]
				self.classBitToCodeMapping[self.classToBitMapping[code]] = code
			end
			self.holidayBitToCodeMapping = {}
			for code,bitValue in pairs(self.holidayToBitMapping) do
				self.holidayBitToCodeMapping[bitValue] = code
			end

			-- Set up some reputation processing code
			self.reverseReputationMapping = {}
			for index, repName in pairs(self.reputationMapping) do
				self.reverseReputationMapping[repName] = index
			end
			self.increasedPattern = string.gsub(string.gsub(FACTION_STANDING_INCREASED, "%%s", "(.*)"), "%%d", "(%%d+)")
			self.decreasedPattern = string.gsub(string.gsub(FACTION_STANDING_DECREASED, "%%s", "(.*)"), "%%d", "(%%d+)")

			-- Load Continent and Zone information
			local continentNames = { GetMapContinents() }
			local L
			for i = 1, #(continentNames), 1 do
				L = {}
				L["name"] = continentNames[i]
				L["zones"] = {}
				local zoneNames = { GetMapZones(i) }
				for j = 1, #(zoneNames), 1 do
					L["zones"][j] = {}
					L["zones"][j]["name"] = zoneNames[j]
					SetMapZoom(i, j)
					L["zones"][j]["mapID"] = GetCurrentMapAreaID()
					self.zoneNameMapping[zoneNames[j]] = L["zones"][j]["mapID"]
				end
				self.continents[i] = L
			end

			local selfName = self:NPCName(0)
			-- Now we need to make a reverse mapping table that maps map area IDs into localized zone names.
			for zoneName, mapId in pairs(self.zoneNameMapping) do
				if nil == self.mapAreaMapping[mapId] then self.mapAreaMapping[mapId] = zoneName end
				-- Also create the "self" NPCs that are specific to each zone
				self.npcs[0 - mapId]={[0]=selfName,[1]=format("Z%d",mapId)}
			end

			-- Create the indexed quest list up front so future requests are much faster
			self:CreateIndexedQuestList()

			-- Precompute the bit masks associated with things that cannot change so future access will be faster
			self.playerClassBitMask = self.classNameToBitMapping[self.playerClass]
			self.playerRaceBitMask = self.raceNameToBitMapping[self.playerRace]
			self.playerFactionBitMask = ('Horde' == self.playerFaction) and self.bitMaskFactionHorde or self.bitMaskFactionAlliance
-- TODO: Determine what we do with a Pandaren Monk that has no faction until it graduates
			self.playerGenderBitMask = (3 == self.playerGender) and self.bitMaskGenderFemale or self.bitMaskGenderMale

			-- We need to be notified when any of these happen so we can update the quest status caches properly
			self:RegisterObserverQuestAbandon(Grail.StatusCodeCallback)
			self:RegisterObserverQuestAccept(Grail.StatusCodeCallback)
			self:RegisterObserverQuestComplete(Grail.StatusCodeCallback)

			self.tooltip = frame

			self.notificationFrame = CreateFrame("Frame")
			self.notificationFrame:SetScript("OnEvent", function(frame, event, ...) self:Tooltip_OnEvent(frame, event, ...) end)
			self.notificationFrame:RegisterEvent("VARIABLES_LOADED")
			self.notificationFrame:RegisterEvent("PLAYER_LOGIN")
		end,

		---
		--	Internal Use.
		--	Removes the callback from the observer queue for eventName.  Should not be called directly, but through the use of convenience API.
		--	@see UnregisterObserverQuestAbandon
		--	@see UnregisterObserverQuestAccept
		--	@see UnregisterObserverQuestComplete
		--	@param eventName The name of the event from which the callback should be removed.
		--	@param callback The callback that is to be removed.
		UnregisterObserver = function(self, eventName, callback)
			if nil ~= callback and nil ~= self.observers[eventName] then
				for i = 1, #(self.observers[eventName]), 1 do
					if callback == self.observers[eventName][i] then
						tremove(self.observers[eventName], i)
						break
					end
				end
			end
		end,

		---
		--	Remove the callback from receiving quest Abandon notifications.
		--	@param callback The callback that is to be removed.
		UnregisterObserverQuestAbandon = function(self, callback)
			self:UnregisterObserver("Abandon", callback)
		end,

		---
		--	Remove the callback from receiving quest Accept notifications.
		--	@param callback The callback that is to be removed.
		UnregisterObserverQuestAccept = function(self, callback)
			self:UnregisterObserver("Accept", callback)
		end,

		---
		--	Remove the callback from receiving quest Completion notifications.
		--	@param callback The callback that is to be removed.
		UnregisterObserverQuestComplete = function(self, callback)
			self:UnregisterObserver("Complete", callback)
		end,

		---
		--	Internal Use.
		--	Updates the NewQuests with data if the quest does not already exist in the internal database or adds the npcCode to the NewQuests data if it does not already exist.
		--	@param questId The standard numeric questId representing a quest.
		--	@param questTitle The localized name of the quest.
		--	@param npcId The standard numeric npcId representing an NPC.
		--	@param isDaily Indicates whether the quest is a daily quest.
		--	@param npcCode A string value 'A:' or 'T:' indicating whether the NPC is for accepting a quest or turning one in.
		--	@param version A version string based on the current internal database versions.
		UpdateQuestDatabase = function(self, questId, questTitle, npcId, isDaily, npcCode, version)
			questId = tonumber(questId)
			if nil == questId then return end
			if not self:DoesQuestExist(questId) or nil == self.quests[questId][npcCode] then
				if nil == GrailDatabase["NewQuests"] then GrailDatabase["NewQuests"] = { } end
				if nil == GrailDatabase["NewQuests"][questId] then
					GrailDatabase["NewQuests"][questId] = { }
					GrailDatabase["NewQuests"][questId][self.playerLocale] = questTitle
					local codes = nil
					if isDaily then codes = "+D" end
					if nil ~= npcId then
						if nil == codes then codes = npcCode..':'..npcId else codes = codes.." "..npcCode..':'..npcId end
					end
					if nil ~= codes then GrailDatabase["NewQuests"][questId][1] = codes end
					GrailDatabase["NewQuests"][questId][2] = version
				else
					local codes = GrailDatabase["NewQuests"][questId][1] or ''
					if nil == self:CodesWithPrefix(codes, npcCode) then
						if nil ~= npcId then
							if nil == codes then codes = npcCode..':'..npcId else codes = codes.." "..npcCode..':'..npcId end
						end
						if nil ~= codes then GrailDatabase["NewQuests"][questId][1] = codes end
					end
				end
				if nil == self.quests[questId] then
					self.quests[questId] = { [0] = questTitle, [1] = '' }
				end
			end
		end,

		---
		--	Internal Use.
		--	Updates the time until quests reset based on the GetQuestResetTime() API.  A side-effect is that if the reset time is past QueryQuestsCompleted() will be called.
		UpdateQuestResetTime = function(self)
			local seconds = GetQuestResetTime()
			if seconds > self.questResetTime then
				QueryQuestsCompleted()
			end
			self.questResetTime = seconds
		end,

		---
		--	Internal Use.
		--	Updates the NewNPCs with data if the NPC does not already exist in the internal database.
		--	@param targetName The localized name of the NPC.
		--	@param npcId The standard numeric npcId representing an NPC.
		--	@param coordinates The zone coordinates of the player.
		--	@param version A version string based on the current internal database versions.
		UpdateTargetDatabase = function(self, targetName, npcId, coordinates, version)
			if nil ~= npcId then
				if nil == self.npcs[npcId] then
					if nil == GrailDatabase["NewNPCs"] then	GrailDatabase["NewNPCs"] = { } end
					if nil == GrailDatabase["NewNPCs"][npcId] then GrailDatabase["NewNPCs"][npcId] = { } end
					GrailDatabase["NewNPCs"][npcId][self.playerLocale] = targetName
					GrailDatabase["NewNPCs"][npcId][1] = coordinates
					GrailDatabase["NewNPCs"][npcId][2] = version
				elseif 0 ~= npcId and nil ~= targetName and targetName ~= self:NPCName(npcId) then
					self:RecordBadNPCData('G' .. self.versionNumber .. '|' .. npcId .. "|Name:" .. targetName .. "|Locale:" .. self.playerLocale)
				end
			end
		end,

		}

end
