import random
import re


def generateWord(meaning, form, categories, settings, phonotactics,
                 formrules=None):
    '''Takes an English string, desired form, generation
    categories, settings, and optional form-specific rules.
    Returns a generated word.
    '''
    word = ""

    minS = settings["minS"]
    maxS = settings["maxS"]
    defaultrule = settings["rule"]

    if formrules is not None:
        if form in formrules:
            rule = formrules[form]
        else:
            rule = defaultrule
    else:
        rule = defaultrule

    for syllable in range(random.randint(minS, maxS)):
        word += generateSyllable(categories, rule)

    word = applyPhonotactics(word, phonotactics)

    return {'english': meaning, 'word': word, 'form': form}


def generateSyllable(categories, rule):
    '''Takes a category dictionary and a rule. Returns a
    generated syllable.
    '''
    syllable = ""
    for place in rule:
        if isinstance(place, str):
            syllable += random.choice(categories[place])
        else:
            x = random.choice(place)
            if x is not None:
                syllable += random.choice(categories[x])
    return syllable


def applyPhonotactics(word, phonotactics):
    '''Takes dictionary of phonotactics rules and a word. Returns
    word with all rules applied.'''
    for name, rule in phonotactics.items():
        r = rule.split("->")
        word = re.sub(r[0], r[1], word)
    return word

@@ -962,35 +962,183 @@
     
-if isinstance(place, str):%0A
+# Choose whether to include optional category%0A        if place%5B0%5D == %22%5B%22:%0A            if random.randint(1, 2) == 1:%0A                category = chooseRandomCategory(place)%0A    
     
@@ -1186,24 +1186,28 @@
 ies%5B
-place
+category
 %5D)%0A
+%0A
         
 else
@@ -1206,85 +1206,223 @@
     
-else:%0A            x = random.choice(place)%0A            if x is not None:%0A    
+# Include mandatory list%0A        elif place%5B0%5D == %22%7B%22:%0A            category = chooseRandomCategory(place)%0A            syllable += random.choice(categories%5Bcategory%5D)%0A%0A        # Include single category%0A        else:%0A
     
@@ -1470,12 +1470,17 @@
 ies%5B
-x
+place
 %5D)%0A
+%0A
     
@@ -1493,24 +1493,150 @@
  syllable%0A%0A%0A
+def chooseRandomCategory(rule):%0A    rule = rule%5B1:-1%5D%0A    categories = rule.split(%22/%22)%0A    return random.choice(categories)%0A%0A%0A
 def applyPho

Add optional categories and lists to word generation