Titular Title Generator
By Measter
Thanks to fivex for the assistance with scripting.

==Features==
 - Creates higher titular titles for every landed duchy and kingdom. The lower tier title is required to create the title (e.g. to create the Kingdom of Leinster, you would need the Duchy of Leinster as your primary title.)
 - Able to output to My Documents mod folder.
 - Lets you choose the name of the resulting mod.
 - Ability to use an existing mod as a base to create new titles, and creates an addon for it.
 - Can choose to only generate duchies, kingdoms, or empires.
 - Can output short names. For example: Leinsterian Kingdom instead of Kingdom of Leinster. English only.
 - Selectable culture restrictions:
    - None: No cultural restrictions. A character of any culture can create the title.
    - Culture: To create the Kingdom of Leinster, your character would need to be Irish.
	- Culture Group: To create the Kingdom of Leinster, your character would have to be Irish, Scottish, Welsh, or Breton to create it.
 - Selectable religion restrictions:
   - None: No religious restrictions. A character of any religion can create the title.
   - Religion: To create the Kingdom of Leinster, your character would have to be Catholic, or a heresy of Catholic to create it.
   - Religion Group: To create the Kingdom of Leinster, your character would have to be Christian to create it.
 - Selectable lower-tier-title requirements:
   - Duchies: To create a kingdom, you would need this number of duchy titles (minimum of 2).
   - Kingdoms: To create an empire, you would need this number of kingdom titles (minimum of 2).
 - Can make new titles de jure liege of currently held titles.
   - Replace De Jure Unchecked: You create the Kingdom of Leinster with the Duchies of Munster and Leinster, both remain de jure Kingdom of Ireland.
   - Replace De Jure Checked: You create the Kingdom of Leinster with the Duchies of Munster and Leinster, both are new de jure Kingdom of Leinster.
 - Can clear title history.
   - Counties: All county, duchy, kingdom, and empire histories are wiped.
   - Duchies: All duchy, kingdom, and empire histories are wiped.
   - Kingdoms: All kingdom and empire histories are wiped.
   - Empire: All empire history is wiped.
 - Added History Creation type selector.
   - Count: Will create a random character for every landed county.
   - Duke: Will create a random character for every landed duchy, and give 3-4 counties in that duchy to the character.
   - Kingdom: Will create a random character for every landed kingdom, and create random dukes for all but the first 2 duchies.
   - Empire: Will create a random character for every landed empire, and create random kings for all but the first 2 kingdoms.
   - Full Random: Will create a number of randomly place characters, and grow their territory until the land is filled.
 - Can generate random cultures.
 - Custom scripting for Allows and Gain Effects sections of generated titles. See Scripting Variables and Conditions.txt for a list of variables.

==Custom Adjacencies File==
I've included a customized adjacencies file for vanilla to make the Full History generation look a bit smoother.
I've connected up the islands to the mainland, so that realms can grow out to them, and you don't end up with the islands being independent counts.
To use it in history generation, just unzip the CustomAdj.zip to your mod directory, and select it in the generator.

You do not need to enable the Custom Adj mod when starting CKII, this is only for the generator.

==Information about the Full Random History Generation==
Before running this program, you must first run Crusader Kings II with the mod(s) you wish to use, if any. This is because
this program uses the logs generated by the game to determine which provinces are adjacent. If you do not do this it will either
result in an error message, or you may find that a realm is split over two or more areas.

The program will generate a random number of realms between the minimum and maximum realms you have specified. You can select between 2 and 2000.
If the number of realms is larger than the number of usable provinces, then the maximum will be reduced to one realm
per province. Provinces with no adjacencies (usually single province islands), or those that have a city as a capital will not be a 'home' province of the main cycle, though a realm may be expanded into it.

Realms will then be "grown" by giving all unowned provinces surrounding the character's realm to that character.

Characters will be given the Duke title of any duchy they hold more than 50% of. If the Create Kings option is on, then they may also be given a Kingdom. If they are given a Kingdom, then all duchies they hold will be made De Jure part of that Kingdom.

The King Chance box is the modifier chance (in percent) that a character will be made king. The base chance is decided as follows:

Take the average size of the De Jure Kingdoms.
Find the total number of provinces a character holds, and divide by the average Kingdom size.
A random number is then generate, and if it is less than the above, then the character will be a king if a free title is available.

If you have the Create Kingdoms option enabled, you will likely end up with more kingdoms, as it can also be one generated by their Duchy titles.

As many of the remaining empty provinces will be filled by the program, though if it cannot find a Dynasty of the same culture, then it will be left empty.

==Changelog==
Version 2.1.3
 - Includes a rule set for compatability with HIP.
 - Fixed issue causing settings to not restore.
 - Fixed infinite loop bug when using generated cultures.
 
Version 2.1.2
 - Cultures are now generated using the same growth algorithm as realms.
 - Cultures are now completely randomly generated, and not based on existing cultures.

Version 2.1.1
 - Generated cultures are now correctly added to rule set restrictions based on their parent culture.
 - Generated culture's colours are now based on the province they're based on.

Version 2.1.0
 - Added support for generating cultures for every county during history generation.

Version 2.0.19 
 - Now supports cultures, religions, and religion groups for followers of muslim laws in rule sets.
 - Changes the colour of generated titles.
 - Now handles provinces having invalid titles when filling empty provinces.
 - Handles invalid province culture or religion when creating duke vassals in full history.
 - All holy order and mercenary titles are ignored by history modification.
 - Can now specify whether existing character should be wiped in a Rule Set's misc section.
 - Can specify start ID for generated characters in a Rule Set's misc section.

Version 2.0.18
 - Fixed lexer error when encountering the ’ character.
 - Now checks that <mod>/common/landed_titles exists when creating history.

Version 2.0.17
 - Fixed parser error in dynasty parser.

Version 2.0.16
 - Better log output for created republics and ruleset characters.
 - Now handles provinces with non-existent cultures in feudal and republic character creation.

Version 2.0.15
 - Invalidate ProgressPopup on update.
 - Now saves previous seed.
 - Renamed KeepRepublicRuleSet to Keep1066Republics.
 - Added Keep867Republics.
 - Added characters to Keep1066Republics.
 - Added missing tooltips on County, Duchy, and Kingdom restrictions.
 - OptionGroup parser now handles dates with no day.
 - Can now specify the ID and Dynasty ID of a rule set character.
 
Version 2.0.14
 - Now attempts to find a settlement of the target type when changing province type, and swap them.

Version 2.0.13
 - No longer allows data load without a rule set.
 - Prevent program attempting to find CK2 in a blank path.
 - No longer throws error if mod directory doesn't exist.
 - Fixed default settings not having a ruleset checked.
 - Now outputs list of unchecked required rulesets.

Version 2.0.12
 - Now outputs data loader errors when selecting the CK2 directory.
 - Now using a custom settings file.
 
Version 2.0.11
 - Fixed infinite loop when generator has run out of dynasties.

Version 2.0.10
 - Province history is now correctly reset after Full History generation.
 - Fixed bug causing republic held provinces to not have cities if growth conditions aren't met.

Version 2.0.9
 - Fixed bug causing republic spouses to not be saved.
 - Add chance for republics to expand.
 - Add theocracy creation options like republics.
 - Add spouse chance to ruleset.
 - Handled collision when two republics are next to eachother and try to use the same duchy.

Version 2.0.8
 - Fixed issue with restoring values to min and max realms and republics.
 - Checkbox to change all theocracies to feudal.

Version 2.0.7
 - Now has a more descriptive error when setup.log doesn't exist.
 - Fixed error when a localisation doesn't exist.
 - Clears existing characters from game during history generation.

Version 2.0.6
 - Reimplemented gender rules usage when generated a character.
 - Added chance of ruler being female to Rule Set.

Version 2.0.5
 - Fixed crash when parsing CK2 data in cultures using a ',' for decimal points.

Version 2.0.4
 - Removed reference to counties in clear history combobox.
 - Now skips titles with null religions or cultures in history generation.
 - Now remembers last selected gains and allows script.
 - Colour values when parsing cultures and religions are now properly clamped.
 - No longer crashes when closing without loading data.
 
Version 2.0.3
 - Added more extensive logging in PopulateControls.
 - Fixed lexer error when encountering a tab in dynasty names.
 - Skips landless titles in history generation.
 - Implemented forgotten specified characters.
 - Log is now dumped after error loading data.

Version 2.0.2
 - Fixed null reference error when attempting to fetch a dynasty by culture.
 - Fetching of mods will now assign the error string.
 - Now outputs seed to log.
 - Renamed Full Logging checkbox to Output Log, and added tooltip.
 
Version 2.0.1
 - Now throws exception if script folders cannot be found.
 - Throws more descriptive error if data dictionaries are empty or null.
 - String entries in mod object are not String.Empty instead of null.
 - Fixed lexer errors in title, culture, and dynasty parsers.
 - Errors are now correctly passed on to the UI in LoadTask. 

Version 2.0
 - Added law generation to Full History generation.
 - Fixed bug causing mod history folder not being deleted.
 - New GUI.
 - CK2 data is now loaded separately before changing of settings.
 - Logging now has a limit of the last 100 lines of generator and data logging.
 - Full History now creates counts for titles outside of a realm's home duchies.
 - Moved included script files to subfolder.
 - Removed 50/50 chance of kingship.
 - Can now load multiple Rule Sets.
 - Independent count generation is back, along with kingdom and empire.
 - Can now specify seed to use for randomness in history generation.
 - Settings are new remembered when the program is closed.
 - Patricians are now created for republics.
 - Vanilla rule set selected by default.
 - Rule sets support required rule set files.
 - Supports converter's nation_table.csv.
 - Added logging when checking a selected directory.
 - Added error message when selected a directory that doesn't have a CK2 install.
 - There is now a 60% chance of a generate vassal being the same culture and religion as his liege. Set in rule sets.
 
Version 1.7.2b
 - Fixed lexical error when encountering a full stop in parser library.
 - Included a rule set that keeps republics in Full History generation.

Version 1.7.2
 - Added support for colour ranges of 0-255 in culture parser.

Version 1.7.1
 - Fixed titles generated from counties not having proper short names.

Version 1.7
 - Will correctly detect map modifications in mod selector.
 - Will now no longer output an incorrect number of realms if Min and Max are the same.
 - Can now provide a list of titles to ignore in history creation. Note: Character rules will override this.
 - Included a custom adjacencies file to allow realms to expand into islands.

Version 1.6.11
 - Now correctly copies over localisation strings that are not in quotes.
 - Fixed Open Gain Effects script assigning to Allows.

Version 1.6.10
 - Crusade weights, duchy_revokation, purple_born_heirs, creation_requires_capital, dignity, title, title_female, foa, and title_prefix data copied to generated titles.
 - Fix displayed error in mod selector when encountering empty folders.

Version 1.6.9
 - Fixed lexer error in title parser when encountering an ID starting with a single quote.
 - Coat of Arms definition now carried over to generated titles.

Version 1.6.8
 - Fixed lexar error when encountering a CoA in title definition.

Version 1.6.7
 - GetDynastyByCulture will now select a culture at random if a dynasty cannot be found in a culture group.

Version 1.6.6
 - Fixed errors in DefaultGains.txt.
 - Custom Duchies no longer made De Jure in Full History generation.
 - Scripting variables now need two underscores.
 - Added line to DefaultGains.txt script making laws be copied on from lower title on creation. 

Version 1.6.5
 - Generated duchies used in Full History now have a de jure liege.
 - Changed DefaultGains.txt to no longer change the de jure liege of counties when creating a duchy.
 - Liege of titles for ruleset characters is now blank.

Version 1.6.4
 - Fixed crash when trying to get an item from an empty list.

Version 1.6.3
 - Prevent crash during title check if a title's capital doesn't exist.
 - Prevent crash during character creation if a province's title is null.

Version 1.6.2
 - Generated kingdoms in Full History now have vassals for each Duchy held after the first two.
 - Generated titles now include the alternative localised names (e.g. Kingdom of York will be called Kingdom of Jorvik when held by a Norse character).
 - Changed calculation of the Mean kingdom size.
 - Generated realms will no longer be made kingdoms if the number of duchies is less than the set limit.
 - Removed King Chance selector, and replaced with Make Kingdoms checkbox.

Version 1.6.1
 - Now catches errors encountered while parsing .mod files.
 - Added label to list encountered errors in Mod Selector window.
 - Can now wipe history without generating titles.

Version 1.6
 - Renamed Min Chars and Max Chars to Min Realms and Max Realms.
 - Added Load Rule Set button to UI.
 - Added Rule Sets, to specify characters that must be created (e.g. the Pope), and restrict the genders of cultures and religions.
 - Added chance of generated characters having a spouse.

Version 1.5.6
 - Fixed lexical error in religion parser.
 - Changed FROM tag to AND tag in DefaultAllows.txt.
 - Fixed fencepost error when assigning titles to a character in Duke History.

Version 1.5.5
 - Fixed crash during history creation if a province definition doesn't have an associated title.

Version 1.5.4
 - Fixed crash when loading a province history that's already been loaded.
 - Fixed Options output label for Empire Effects and Kingdom Effects scripts.
 - Made the culture selection in ClearHistoryCreateDukes less error-prone.
 - Fixed fencepost error during dynasty selection in CreateNewRandomCharacters.
 - Fixed error when parsing religion files.
 - Fixed error when a title has null religion or culture.
 - Fixed error when setting provinces to feudal.
 - Added null culture and religion check when selecting a home province in Full History generation.
 - Fixed error when trying to open a title history in WriteProvinceOwners.
 - Fixed line feed detection in parser library.

Version 1.5.3
 - Removed Single Count creation. Same effect can be achieved with Full Random by setting high character count.
 - Removed checkbox in History Creation Options enabling and disabling King creation. Set to 0 for no kings.
 - Added republics to history generation.
 - Added tooltips.
 - Changed Duke creation to use the same character creation as Full History.
 - No longer generates titles from titles with the Landless option.

Version 1.5.2
 - Added log entries for gains and allows sections of title string creation.
 - Added checks for valid culture and religion when generating scripts for a title. If the check fails, the gain_effects will be empty, and allows will only have a titular check.
 - Attempted to fix not found bug when loading script files.

Version 1.5.1
 - Fixed crash when generating title string if cultures and religions aren't loaded.
 - Cultures and religions are now always loaded.
 
Version 1.5
 - Added support for float style numbers in title parser.
 - Added script support for Allows and Gain Effects.

Version 1.4.6
 - Fixed missing dynasties in Single Count creation dialog.
 
Version 1.4.5
 - Full random history options now added to log.
 - Seed for random number generator added to log.
 - Fixed bug while making dukes. They now must have more than 55% of a duchy to get the title, rather than less than 50%.
 - If the Create Duchies option is created, Full Random history will now also use those when creating a realm.

Version 1.4.4
 - Fixed crash if a localisation noun string is not found.
 - Now saves CK2 path between sessions.
 
Version 1.4.3
 - Fixed path issue on Linux.
 - Added missing dynasty check in Mod Select window when compiling list of mods.

Version 1.4.2
 - Fixed parse error when encountering the ’ character in a culture name.
 - Added Full Random history creation.
 - Added UI elements for control over the Full Random generation. 
 - The My Documents checkbox is now ticked by default.
 - Fixed crash if a province cannot be found while checking titles.
 - Fixed output of dependencies in .mod file.

Version 1.4.1
 - Added History options tab.
 - Moved Clear History options to History tab.
 - Added History Creation options.
 - Moved start date selector to main form.
 - Generated charcters will now have a random age between 16 and 35; this age will be subtracted from the start date.
 - Added Dukes history creation option.
 - Changed character ID for Count creation to 99,999,999. Duke IDs will also start from this value.

Version 1.4
 - Added option to output to My Documents.
 - Added option to name the output mod.
 - Rearranged the UI (again).
 - Fixed problem in County Selector if there are no suitable empires to populate the list with. The "All Titles" option will display every title in the category below it. So if you select this option in the Kingdoms list, ALL landed Duchies will be in the Duchy list.

Version 1.3.13
 - Fixed parser error with string options.
 - Fixed crash when no localisation string is found for a title.
 - Fixed missing log output when creating localisation strings for kingdoms.

Version 1.3.12
 - Fixed no error output in dynasty parser.
 - Fixed dynasty parser crashing on encountering a '?' in a name.

Version 1.3.11
 - Fixed bug with county selector window going under the main program window.
 - Fixed bug when creating title strings for empires from kingdoms.
 - Added title creation from counties.

Version 1.3.10
 - Fixed parser error when the last line is a comment.
 - Renamed County Selector window to Character Setup.
 - Rearranged Character Setup window.
 - Added birth year and gender selector on Character Setup dialog during history wipe.
 - Changed generated character ID to 999999999 to attempt to avoid conflicts.

Version 1.3.9
 - You can now select the starting county and dynasty.
 - Random character can now be female.
 - Supports reading mods from My Documents.

Version 1.3.8
 - Added list of skipped titles to the log.

Version 1.3.7
 - Fixed logic error in history creation causing duchy, kingdom, and empire settings to not run.

Version 1.3.6
 - Fixed exception when reading data style Coat of Arms definitions.

Version 1.3.5
 - Refactored history creation for less repetition.
 - Updated for CKUtils 1.8.
 - Fixed bug causing crash in culture parser when bastard prefix has more than two words.
 - Fixed bug in reading replaces in .mod files where they used a forward slash.
 - Fixed bug in parsers when encountering empty files.
 - Now outputs error log when the program encounters an error. The -log command line option now forces a dump of the log.
 - Added history clear selection to options log.

Version 1.3.4
 - Added history wipe options.
 - Fixed encoding selection on created files.

Version 1.3.3
 - Fixed crash if a title's culture/religion isn't defined, and the user selected the Culture/Religion Group restriction.

Version 1.3.2
 - Program no longer loads files with the same name.
 - Parsers now handle empty files.
 - Fixed crash in province parser handling comments.

Version 1.3.1
 - Added program version to log file.
 - Fixed crash when adding a sub title if another with the same ID already exists.

Version 1.3
 - Changed the UI layout to make more sense.
 - Fixed the Create Kingdoms and Create Empires checkboxes being enabled at start.
 - Added status of Create Kingdoms and Create Empires checkboxes to logging output.
 - Added support for generating from multiple mods.
 - Added support for mods that only change Religions, Cultures, Flags, Provinces, and Localisations.
 - Fixed the Generate button being enabled at start.
 - Short name checkboxes are now disabled at start.
 - Now doesn't load vanilla files if any selected mod replaces them.
 - Added logging when reading localisation.

Version 1.2.2
 - Fixed bug causing duplicate empires to be created.

Version 1.2.1
 - Fixed crash when a title is landless due to a conflicting title name being dealt with.

Version 1.2
 - Now supports CK2 1.06.
 - Option to generate only kingdoms or only empires.

Version 1.1.8
 - Removed copy feature in favour of dependant addon.
 - Fixed incorrect logging messages.
 - Fixed bug causing crash when the program is closed if logging isn't enabled.

Version 1.1.7
 - Fixed bug causing an ArgumentException when reading provinces.
 - Fixed bug where colour values were out of bounds.
 - Fixed bug when a from_dynasty_prefix in a culture is a blank string.
 - Fixed bug causing an error if a county title doesn't have a related province file.
 - Fixed bug preventing the log file being written if an exception is thrown.

Version 1.1.6
 - Added logging feature to assist with debugging.

Version 1.1.5
 - Fixed short names of empires generated from existing kingdoms being called kingdoms, not empires.

Version 1.1.4
 - Fixed missing '=' in generated titles.
 - Rewrote parsers to be better.
 - Added outputting of short names.

Version 1.1.3
 - Removed the culture and religion from the title definition, because it was limiting who could create the title.

Version 1.1.2
 - Fixed bug causing a crash if the Culture setting on the PC does not use a '.' as a decimal seperator.

Version 1.1.1
 - Generated titles can now be usurped without holding the capital.
 - Generated titles that have been destroyed will no longer add new de jure duchies when recreated.

Version 1.1
 - Fixed bug causing the program to crash if there are no mods installed in CK2.
 - Fixed bug causing tags in allow brackets to be read incorrectly as title stats.
 - Fixed bug in which the landed_titles.txt file wasn't replaced when run on vanilla.
 - Titles now become de jure vassals of new titles.

Version 1.0.1
 - Clamped colour values to the expected range.
 - Handled cases where there is a county level title without a matching province file.
 - Fixed bug where the program will fail if Copy was checked but Use Mod is not.
 - Fixed a bug in the file/directory selection code which caused files to be place/modified outside of the mod directory.