# lgenerator.py
# Some interesting string handling experiments can be
# found here.
#     http://www.skymind.com/~ocrow/python_string/
# Malcolm Kesson 
# 10 Jan 2012
import random
  
def write_lstring(database):
    generations = database['generations']
    outstr = database['axiom']
    rules = database['rules']
    # Loop over the generations
    for n in range(generations):
        is_last_gen = False
        if n == (generations - 1):
            is_last_gen = True
        temp = []
        # Loop over each character in the string
        for char in outstr:
            # Assume we do not have a rule for the character
            sub = char
            if rules.has_key(char):
                mode = rules[char][0]
                if mode == 'normal':
                    sub = rules[char][1]
                else:
                    if mode == 'random':
                        multi_subst = rules[char][1:]
                        max_index = len(multi_subst)
                        index = int(random.uniform(0, max_index))
                        sub = multi_subst[index]
                    elif mode == 'last_gen_only':
                        if is_last_gen == True:
                            last_item = len(rules[char]) - 1
                            sub = rules[char][last_item]
                        elif len(rules[char]) > 2:
                            sub = rules[char][1]
                    elif mode == 'ignore_last_gen':
                        if is_last_gen == False:
                            sub = rules[char][1]
                #print('%s    %s' % (char, sub))
            temp.append(sub)
        # Replace the old string with the new one.
        outstr = ''.join(temp)
    return outstr
  
# Breaks a string into lines of text so that no more than 
# "count" characters appear on a line.
def format(instr, count):
    buff = []
    maxchars = count
    for c in instr:
        buff.append(c)
        if len(buff) >= maxchars:
            buff.append('\n')
            maxchars += (count + 1)        
    return ''.join(buff)