#!BPY

"""
Name: 'Import Floretions'
Blender: 248
Group: 'Misc'
Tooltip: 'Generate quaternion and floretion curves in 2-D and 3-D space.'
"""

__author__ = "Creighton Dement"
__url__ = ("Cranborg Home Page, http://www.fumba.eu", "http://wiki.blender.org/index.php/Extensions:Py/Scripts/Manual/Misc/Import_Floretions")
__version__ = "1.2 21 July, 2008"
__email__ = ["Author's personal e-mail, mail*fumba.eu"]
__bpydoc__ = """\
This is a Python script for Blender which uses short (quaternion-based, floretion-based) algorithms to draw curves in space. <br>
<br>
The user can create new shapes and curves by setting a variety of parameters.  
The options "cyc" and "sig" (and several others) cannot be set via the GUI at the moment. They can, however,
be set internally. Ex. Y = u.dtl(Ydict, {'cyc': True, 'sig': False})
"""


####################################################
#Copyright (C) 2008: Creighton Dement <mail_*_fumba.eu>
####################################################
#-------------GPL LICENSE BLOCK-------------
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hopes that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of 
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
####################################################






import Blender
from Blender import *
import math
from math import sqrt
 
from Blender.Draw import *
from Blender.BGL import *
from Blender.Window import *

from Blender import NMesh,Object
from Blender.NMesh import Col




#if Window.EditMode(): Window.EditMode(0)

class Floretify(object):

    __vlist = ["ee", "ei", "ej", "ek", "ie", "je", "ke", "ii", "jj", "kk", "ij", "ik", "ji", "jk", "ki", "kj"]


    
    

    def floretadd(self, x,y):
      
        
        if len(x) and len(y) != 16:
            print 'x ', x
            print 'y ', y
        
            print 'lenx ', len(x)
            
            print 'Incorrect format'
            return
        z = [0]*16  # the result will go here
       
        

        for r in range(0,16):
            
            z[r] = x[r] + y[r]

        return z

    def floretsub(self, x,y):
        if len(x) and len(y) != 16:
            print 'x ', x
            print 'y ', y
        
          #  print 'lenx ', len(x)
            
            print 'Incorrect format'
            return
        z = [0]*16  # the result will go here

        for r in range(0,16):
            z[r] = x[r] - y[r]

        return z
    
        
    def floretproduct(self, x,y):
        if len(x) and len(y) != 16:
            print 'x ', x
            print 'y ', y
        
            print 'lenx ', len(x)
            
            print 'Incorrect format'
            return
        z = [0]*16  # the products will go here



    ## 'i,  'j,  'k,   i',  j',  k',  'ii',  'jj',  'kk',  'ij',  'ik',  'ji',  'jk',  'ki',  'kj',  1  x
    ##  0    1    2    3    4    5      6      7      8      9     10     11     12     13     14   15  x
    ##
    ## 'i,  'j,  'k,   i',  j',  k',  'ii',  'jj',  'kk',  'ij',  'ik',  'ji',  'jk',  'ki',  'kj',  1  y
    ##  0    1    2    3    4    5      6      7      8      9     10     11     12     13     14   15  y

        
    ##    Deterimine coefficient of e (the unit basis vector) in the product 
            
        z[15] = -x[0]*y[0] - x[1]*y[1]  - x[2]*y[2]   - x[3]*y[3]  -  x[4]*y[4]  - x[5]*y[5] \
                + x[6]*y[6]  + x[7]*y[7]  + x[8]*y[8]  + x[9]*y[9]  +  x[10]*y[10] + x[11]*y[11] \
                + x[12]*y[12] + x[13]*y[13] + x[14]*y[14] + x[15]*y[15]  



    ##    Deterimine coefficient of 'i in the product
        
        z[0] =  x[0]*y[15] + x[1]*y[2]   - x[2]*y[1]   - x[3]*y[6] \
               -  x[4]*y[9]  - x[5]*y[10] -x[6]*y[3]  - x[7]*y[14]  + x[8]*y[12] \
               - x[9]*y[4]  -  x[10]*y[5] - x[11]*y[13] \
               -x[12]*y[8] + x[13]*y[11] + x[14]*y[7] + x[15]*y[0] 

    ##    Deterimine coefficient of 'j in the product  
        z[1] = -x[0]*y[2]  + x[1]*y[15]  + x[2]*y[0] - x[3]*y[11] \
               -  x[4]*y[7]  - x[5]*y[12] +x[6]*y[13] - x[7]*y[4] \
               - x[8]*y[10]  + x[9]*y[14] +  x[10]*y[8]  - x[11]*y[3] \
               -x[12]*y[5] - x[13]*y[6] - x[14]*y[9] + x[15]*y[1]
     
           
    ##    Deterimine coefficient of 'k in the product  
        z[2] = x[0]*y[1]  - x[1]*y[0] + x[2]*y[15] - x[3]*y[13] \
               -  x[4]*y[14]  - x[5]*y[8] -x[6]*y[11] + x[7]*y[9] \
               - x[8]*y[5]  - x[9]*y[7] -  x[10]*y[12]  + x[11]*y[6] \
               + x[12]*y[10] - x[13]*y[3] - x[14]*y[4] + x[15]*y[2] 
         

     

    ##    Deterimine coefficient of i' in the product
        z[3] =-x[0]*y[6]  - x[1]*y[11]  - x[2]*y[13]  + x[3]*y[15] \
               +  x[4]*y[5]  - x[5]*y[4] -x[6]*y[0]  - x[7]*y[12] \
               + x[8]*y[14]  - x[9]*y[10]  +  x[10]*y[9] - x[11]*y[1] \
               + x[12]*y[7] - x[13]*y[2]  - x[14]*y[8]  + x[15]*y[3]

                   
          
                  
    ##    Deterimine coefficient of j' in the product
        z[4] = -x[0]*y[9]   - x[1]*y[7]  - x[2]*y[14]  - x[3]*y[5]  \
                +  x[4]*y[15]  + x[5]*y[3] + x[6]*y[10]  - x[7]*y[1] \
                - x[8]*y[13]  - x[9]*y[0]  -  x[10]*y[6]  + x[11]*y[12] \
                -x[12]*y[11] + x[13]*y[8] - x[14]*y[2]  + x[15]*y[4]
            
           
    ##    Deterimine coefficient of k' in the product
        z[5] = -x[0]*y[10]  - x[1]*y[12] - x[2]*y[8] + x[3]*y[4] \
               -x[4]*y[3] + x[5]*y[15] -x[6]*y[9] + x[7]*y[11] \
               - x[8]*y[2]  + x[9]*y[6] -  x[10]*y[0]  - x[11]*y[7] \
               -x[12]*y[1] - x[13]*y[14] + x[14]*y[13] + x[15]*y[5] 
         

            
    ##    Deterimine coefficient of 'ii' in the product
        z[6] = x[0]*y[3]  + x[1]*y[13]  - x[2]*y[11]  + x[3]*y[0] \
               +  x[4]*y[10]  - x[5]*y[9] + x[6]*y[15]  + x[7]*y[8] \
               + x[8]*y[7]  + x[9]*y[5]  -  x[10]*y[4] + x[11]*y[2] \
               -x[12]*y[14] - x[13]*y[1]  - x[14]*y[12]  + x[15]*y[6]    
           
                                          
    ##    Deterimine coefficient of 'jj' in the product
        z[7] = -x[0]*y[14]   + x[1]*y[4]  + x[2]*y[9]  - x[3]*y[12] \
               +  x[4]*y[1]  + x[5]*y[11] + x[6]*y[8]  + x[7]*y[15] \
               + x[8]*y[6]  - x[9]*y[2]  -  x[10]*y[13]  - x[11]*y[5] \
               + x[12]*y[3] - x[13]*y[10] + x[14]*y[0]  + x[15]*y[7]
      
           
    ##    Deterimine coefficient of 'kk' in the product
        z[8] = x[0]*y[12]  - x[1]*y[10] + x[2]*y[5] + x[3]*y[14] \
               -  x[4]*y[13] + x[5]*y[2] + x[6]*y[7] + x[7]*y[6] \
               + x[8]*y[15]  - x[9]*y[11] + x[10]*y[1]  - x[11]*y[9] \
               - x[12]*y[0] + x[13]*y[4] - x[14]*y[3] + x[15]*y[8] 
          
            
    ##    Deterimine coefficient of 'ij' in the product
        z[9] = x[0]*y[4]  + x[1]*y[14]  - x[2]*y[7]  - x[3]*y[10] \
               +  x[4]*y[0]  + x[5]*y[6] - x[6]*y[5]  + x[7]*y[2] \
               - x[8]*y[11]  + x[9]*y[15]  +  x[10]*y[3] - x[11]*y[8] \
               + x[12]*y[13] + x[13]*y[12]  - x[14]*y[1]  + x[15]*y[9]     
            
                                          
    ##    Deterimine coefficient of 'ik' in the product
        z[10] = x[0]*y[5]   + x[1]*y[8]  - x[2]*y[12]  + x[3]*y[9] \
                -x[4]*y[6]  + x[5]*y[0]  + x[6]*y[4]  - x[7]*y[13]  \
                - x[8]*y[1]  - x[9]*y[3]  +  x[10]*y[15]  + x[11]*y[14] \
                + x[12]*y[2] - x[13]*y[7] + x[14]*y[11]  + x[15]*y[10] 
     
    ##    Deterimine coefficient of 'ji' in the product
        z[11] =  -x[0]*y[13]  + x[1]*y[3]  + x[2]*y[6]  + x[3]*y[1] \
                +  x[4]*y[12]  - x[5]*y[7] - x[6]*y[2]  + x[7]*y[5] \
                - x[8]*y[9]  - x[9]*y[8]  +  x[10]*y[14] + x[11]*y[15] \
                -x[12]*y[4] + x[13]*y[0]  + x[14]*y[10]  + x[15]*y[11]    
          
                  
                                                
    ##    Deterimine coefficient of 'jk' in the product
        z[12] = -x[0]*y[8]   + x[1]*y[5]  + x[2]*y[10]  + x[3]*y[7] \
                -  x[4]*y[11]  + x[5]*y[1] - x[6]*y[14]  - x[7]*y[3] \
                + x[8]*y[0]   + x[9]*y[13]  -  x[10]*y[2]  + x[11]*y[4] \
                + x[12]*y[15]  + x[13]*y[9] - x[14]*y[6]  + x[15]*y[12] 
         


    ##    Deterimine coefficient of 'ki' in the product
        z[13] = x[0]*y[11]  - x[1]*y[6]  + x[2]*y[3]  + x[3]*y[2] \
                +  x[4]*y[8]  - x[5]*y[14] + x[6]*y[1]  - x[7]*y[10]\
                - x[8]*y[4]  + x[9]*y[12]  -  x[10]*y[7] - x[11]*y[0] \
                + x[12]*y[9] + x[13]*y[15]  + x[14]*y[5]  + x[15]*y[13]    
            
                                          
                                                          
                                          
    ##    Deterimine coefficient of 'kj' in the product
        z[14] = x[0]*y[7]  - x[1]*y[9]  + x[2]*y[4]  - x[3]*y[8]\
                +  x[4]*y[2]  + x[5]*y[13] -x[6]*y[12]  - x[7]*y[0] \
                + x[8]*y[3]  + x[9]*y[1]  +  x[10]*y[11]  + x[11]*y[10] \
                -x[12]*y[6] - x[13]*y[5] + x[14]*y[15]  + x[15]*y[14]      


        return z    
                        



    def dtl(self, dict, *e):

       # print "e cool ", e[0] 
        z = 16*[0]
        
##["ee", "ei", "ej", "ek", "ie", "je", "ke", "ii", "jj", "kk", "ij", "ik", "ji", "jk", "ki", "kj"]


        for vector in self.__vlist:
            if dict.has_key(vector):
                pass
            else:
                dict[vector] = 0.0

##        print "e ", e
##        print "e[0] ", e[0]
        
        if e[0].has_key('sig'):
            if not e[0]['sig']:
                del e[0]['sig']
                
           
            
        if e[0].has_key('cyc'):
            if not e[0]['cyc']:
                del e[0]['cyc']
        

##        print "e[0]", e[0]    
        if dict.has_key('ee'):            
            z[15] = dict['ee']

            

        if dict.has_key('ei'):
            if e[0].has_key('sig'):
                z[0] = dict['ie']
                if e[0].has_key('cyc'):
                    z[0] = dict['je']
                    
            elif e[0].has_key('cyc'):
                z[0] = dict['ej']
                    
            else:
                z[0] = dict['ei']

        if dict.has_key('ej'):
            if e[0].has_key('sig'):
                z[1] = dict['je']
                if e[0].has_key('cyc'):
                    z[1] = dict['ke']
                    
            elif e[0].has_key('cyc'):
                z[1] = dict['ek']
                
            else:
                z[1] = dict['ej']
            

        if dict.has_key('ek'):
            if e[0].has_key('sig'):
                z[2] = dict['ke']                
                if e[0].has_key('cyc'):
                    z[2] = dict['ie']
                    
            elif e[0].has_key('cyc'):
                z[2] = dict['ei']
                
            else:
                z[2] = dict['ek']

            

        if dict.has_key('ie'):
            if e[0].has_key('sig'):
                z[3] = dict['ei']
                if e[0].has_key('cyc'):
                    z[3] = dict['ej']
                    
            elif e[0].has_key('cyc'):
                z[3] = dict['je']
                
            else:
                z[3] = dict['ie']
         

        if dict.has_key('je'):
            if e[0].has_key('sig'):
                z[4] = dict['ej']
                if e[0].has_key('cyc'):
                    z[4] = dict['ek']
                    
            elif e[0].has_key('cyc'):
                z[4] = dict['ke']
                
            else:
                z[4] = dict['je']
                
          

        if dict.has_key('ke'):
            if e[0].has_key('sig'):
                z[5] = dict['ek']
                if e[0].has_key('cyc'):
                    z[5] = dict['ei']
                    
            elif e[0].has_key('cyc'):
                z[5] = dict['ie']
                
            else:
                z[5] = dict['ke']
                
           

            

        if dict.has_key('ii'):
            if e[0].has_key('cyc'):
                z[6] = dict['jj']
                
            else:
                z[6] = dict['ii']
                

        if dict.has_key('jj'):
            if e[0].has_key('cyc'):
                z[7] = dict['kk']
                
            else:
                z[7] = dict['jj']
            
        if dict.has_key('kk'):
            if e[0].has_key('cyc'):
                z[8] = dict['ii']
            else:
                z[8] = dict['kk']



            
        if dict.has_key('ij'):
            if e[0].has_key('sig'):
                z[9] = dict['ji']
                if e[0].has_key('cyc'):
                    z[9] = dict['kj']
                    
            elif e[0].has_key('cyc'):
                z[9] = dict['jk']
                
            else:
                z[9] = dict['ij']
                

        if dict.has_key('ik'):
            if e[0].has_key('sig'):
                z[10] = dict['ki']
                if e[0].has_key('cyc'):
                    z[10] = dict['ij']
                    
            elif e[0].has_key('cyc'):
                z[10] = dict['ji']
                
            else:
                z[10] = dict['ik']
            


        if dict.has_key('ji'):
            if e[0].has_key('sig'):
                z[11] = dict['ij']
                
                if e[0].has_key('cyc'):
                    z[11] = dict['jk']
                    
            elif e[0].has_key('cyc'):
                z[11] = dict['kj']
                
            else:
                z[11] = dict['ji']
                

        if dict.has_key('jk'):
            if e[0].has_key('sig'):
                z[12] = dict['kj']
                
                if e[0].has_key('cyc'):
                    z[12] = dict['ik']
                    
            elif e[0].has_key('cyc'):
                z[12] = dict['ki']
                
            else:
                z[12] = dict['jk']
              



        if dict.has_key('ki'):
            if e[0].has_key('sig'):
                z[13] = dict['ik']
                
                if e[0].has_key('cyc'):
                    z[13] = dict['ji']
                    
            elif e[0].has_key('cyc'):
                z[13] = dict['ij']
                
            else:
                z[13] = dict['ki']

                

        if dict.has_key('kj'):
            if e[0].has_key('sig'):
                z[14] = dict['jk']
                
                if e[0].has_key('cyc'):
                    z[14] = dict['ki']
                    
            elif e[0].has_key('cyc'):
                z[14] = dict['ik']
                
            else:
                z[14] = dict['kj']
                
            

       


##        for vector in self.__vlist:
##            if dict.has_key(vector):
##                print vector, 'True'
##            #print vector, dict.get(vector)
##            
##        print z

##        for i in range(16):
##            if 4*z[i] != int(4*z[i]):
##                print 'This is not a floretion: dtl'
##                z = 16*[0]
##                return
##            else:
##                pass
##                #z[i] = int(4*z[i])
            
        return z

    ## Record the values in flostring (i.e. liste) in a dictionary


    def std(self, flostring, **e):

        def stringtofloat(g, IsPositive):
            if g == "":
                g = 1
                
            if not IsPositive:
                gfloat = -1*float(g)
                
            else: gfloat = float(g)

           
            return gfloat

    
        dicty = {}
        t = 0
        
        CorrectFormat = True
        flostring = flostring.replace(' ', '')
        flostring = flostring.lower()

        print "e ", e.get('dodicty')


        

        

        for ju in flostring:
            #print ju
            if ju.isalnum() or ju == "+" or ju == "-" or ju == ".":
                pass
            else:
                print ju
                print "Incorrect format: please use only spaces, decimals +, -, and alphanumeric characters!"
                CorrectFormat = False

        flostring = flostring.replace("+", " +")
        flostring = flostring.replace("-", " -")
        liste = flostring.split()




        if (CorrectFormat):
            for vector in self.__vlist:
                t = 0
                for eintrag in liste:            
                    if eintrag.count(vector) == 1:
                        t = t + 1
                        dicty[vector] = eintrag.replace(vector, "")
                        
                        if dicty[vector].count("-") == 1:
                            dicty[vector] = dicty[vector].replace("-", "")
                            IsPositive = False
                        else:
                            dicty[vector] = dicty[vector].replace("+", "")
                            IsPositive = True
            ##            print eintrag, t, stringtofloat(dicty['ij'], IsPositive)
                        dicty[vector] = stringtofloat(dicty[vector], IsPositive)
                        if t > 1:
                            print "Incorrect format: there is more than one instance of " + vector + \
                                  " in the input line."
                            break
                    
                    

##        u = 16*[0]
##        r = 16*[0]
       # print self.floretproduct(u,r)

       # print self.dtl(dicty)

               
    
        return self.dtl(dicty, e)

##["ee", "ei", "ej", "ek", "ie", "je", "ke", "ii", "jj", "kk", "ij", "ik", "ji", "jk", "ki", "kj"]

    def returndict(self, z):
        if len(z) != 16:
            return 16*[0]

        dictz = {}
        
        dictz['ee'] = z[15]
        
        dictz['ei'] = z[0]
        dictz['ej'] = z[1]
        dictz['ek'] = z[2]
        
        dictz['ie'] = z[3]
        dictz['je'] = z[4]
        dictz['ke'] = z[5]
        
        dictz['ii'] = z[6]
        dictz['jj'] = z[7]
        dictz['kk'] = z[8]
        
        dictz['ij'] = z[9]
        dictz['ik'] = z[10]
        dictz['ji'] = z[11]
        dictz['jk'] = z[12]
        dictz['ki'] = z[13]
        dictz['kj'] = z[14]

        #print "Dictz ", dictz
        return dictz
        
        
            
    



##    def StD (self,flostring):
##        self.std(flostring)
         
        
  #  print self.std("0.055ie + 5ik - 2.5jk - 5iJ + 4ee - ji -2KK + 2345.435346ii + hello ")
        
            













########### Pre-defined Functions ################

global firsttime
draw_predefcurves = Create(0)
choose_floretions = Create(0)
choose_cyc = Create(0)
numofterms=Create(1)
maxterms = Create(20000)
history = Create(0)




	    
def geralds_spiral():
	global bottomstring, topstring, startat, ymax ,yw, sumateI, sumateJ, sumateK, sumatEE, modat, zap, twoD, men, addX, em_sequence, six_sequence, pull_sequence
        global cyc_sequence, sig_sequence, sumatIe, sumatJe, sumatKe, addXFac
	
	zap = Create("hi")
	men = Create("hi")	
	twoD = Create("twoD")
	em_sequence = Create("Hi")
	six_sequence = Create("Hi")
	pull_sequence = Create("Hi")
	cyc_sequence = Create("Hi")
	sig_sequence = Create("Hi")
	
	bottomstring = Create("0.5eI + 0.5eJ + 0.5eK + 0.5ee")
	topstring = Create("ee")
	 	 	
	#yw=Create(0.5)
	startat = Create(1)
	ymax = Create(36)
	sumatIe = Create(0)
	sumatJe = Create(0)
	sumatKe = Create(0)
	
	addXFac = Create(0)

	sumateI = Create(0)
	sumateJ = Create(0)
	sumateK = Create(0)
	
	sumatEE = Create(0)
	modat = Create(3)
	
	Register(gui, event, bevent)
	
def chung_shu_spiral():
	global bottomstring, topstring, startat, ymax ,yw, sumateI, sumateJ, sumateK, sumatEE, modat, zap, twoD, men, addX, em_sequence, six_sequence, pull_sequence
        global cyc_sequence, sig_sequence, sumatIe, sumatJe, sumatKe, addXFac

        zap = Create("hi")
	addX = Create("hi")
	twoD = Create("twoD")
	men = Create("hi")
	em_sequence = Create("Hi")
	six_sequence = Create("Hi")
	pull_sequence = Create("Hi")
	cyc_sequence = Create("Hi")
	sig_sequence = Create("Hi")


	#topstring = Create("-.5eI+eJ-.5eK-.5Ie+Je-.5Ke+II-KK+.5IJ+.5JI-.5JK-.5KJ+ee ")
	topstring = Create("-.5eJ + .5eK - .5Je + .5Ke - II - .5IJ - .5IK - .5JI - .5KI")
	bottomstring = Create("-.5eI + .5eJ - .5Ie + .5Je - KK - .5IK - .5JK - .5KI - .5KJ")
	
	 	 	
	#yw=Create(0.5)
	startat = Create(1)
	ymax = Create(36)
	sumateI = Create(0)
	sumateJ = Create(0)
	sumateK = Create(0)

	addXFac = Create(0)

	sumatIe = Create(0)
	sumatJe = Create(0)
	sumatKe = Create(0)
	
	sumatEE = Create(0)
	modat = Create(3)
	
	Register(gui, event, bevent)

def alex_spiral():
	global bottomstring, topstring, startat, ymax ,yw, sumateI, sumateJ, sumateK, sumatEE, modat, zap, twoD, men, addX, em_sequence, six_sequence, pull_sequence
        global cyc_sequence, sig_sequence, sumatIe, sumatJe, sumatKe, addXFac
        
	zap = Create("hi")
	addX = Create("hi")
	twoD = Create("twoD")
	men = Create("hi")
	em_sequence = Create("Hi")
	six_sequence = Create("Hi")
	pull_sequence = Create("Hi")
	cyc_sequence = Create("Hi")
	sig_sequence = Create("Hi")
	
	bottomstring = Create("ee")
	topstring = Create("eI + 0.25II + 0.25JJ + 0.25KK + 0.25ee")
	
	 	 	
	#yw=Create(0.5)
	startat = Create(1)
	ymax = Create(36)
	sumateI = Create(0)
	sumateJ = Create(0)
	sumateK = Create(0)

	addXFac = Create(0)

	sumatIe = Create(0)
	sumatJe = Create(0)
	sumatKe = Create(0)
	
	sumatEE = Create(0)
	modat = Create(3)
	
	Register(gui, event, bevent)
	
def florets_cube():
	global bottomstring, topstring, startat, ymax,yw, sumateI, sumateJ, sumateK, sumatEE, modat, zap, twoD, men, addX, em_sequence, six_sequence, pull_sequence
	global cyc_sequence, sig_sequence, sumatIe, sumatJe, sumatKe, addXFac

	zap = Create("hi")
	addX = Create("hi")
	twoD = Create("twoD")
	men = Create("hi")
	em_sequence = Create("Hi")
	six_sequence = Create("Hi")
	pull_sequence = Create("Hi")
	cyc_sequence = Create("Hi")
	sig_sequence = Create("Hi")
	
	bottomstring = Create("0.5eI + 0.5II + 0.5IJ + 0.5IK")
	topstring = Create("ee")
	
	 	 	
	#yw=Create(0.5)
	startat = Create(1)
	ymax = Create(1)
	sumateI = Create(0)
	sumateJ = Create(0)
	sumateK = Create(0)

	addXFac = Create(0)

	sumatIe = Create(0)
	sumatJe = Create(0)
	sumatKe = Create(0)
	
	sumatEE = Create(0)
	modat = Create(3)
	
	Register(gui, event, bevent)
	
	
def caspers_cube():
	global bottomstring, topstring, startat, ymax ,yw, sumateI, sumateJ, sumateK, sumatEE, modat, zap, twoD, men, addX, em_sequence, six_sequence, pull_sequence
	global cyc_sequence, sig_sequence, sumatIe, sumatJe, sumatKe, addXFac

	zap = Create("hi")
	addX = Create("hi")
	twoD = Create("twoD")
	men = Create("hi")
	em_sequence = Create("Hi")
	six_sequence = Create("Hi")
	pull_sequence = Create("Hi")
	cyc_sequence = Create("Hi")
	sig_sequence = Create("Hi")
	
	bottomstring = Create("0.5eI + 0.5eJ + 0.5eK + 0.5ee")
	topstring = Create("0.5Ie + 0.5Je + 0.5Ke + 0.5ee")
	
		 	
	#yw=Create(0.5)
	startat = Create(1)
	ymax = Create(1)
	sumateI = Create(0)
	sumateJ = Create(0)
	sumateK = Create(0)

	addXFac = Create(0) 

	sumatIe = Create(0)
	sumatJe = Create(0)
	sumatKe = Create(0)
	
	sumatEE = Create(0)
	modat = Create(3)
	
	Register(gui, event, bevent)
	


	

########### Funktion zeichnen #################


def draw(bottomFlo,topFlo,numofterms, startat, ymax, sumateI, sumateJ, sumateK, sumatIe, sumatJe, sumatKe, sumatEE, modat, zaptype, cyctype, seqtype):
        global thelastlist, zap, men, addX, six_sequence, pull_sequence, cyc_sequence, sig_sequence, addXFac

     
         

        u = Floretify()
        #print 'top ', u.std(topstring.val) 
    
       # btopstringtring = topstring.getName()
##        print 'topstring: ', u.std(topstring.val)
##        print 'bottom: ', u.std(bottomstring.val)
       

##       novel**************
##        Y  = u.std(bottomstring.val)
##        X = u.std(topstring.val)        
##        Yd = u.floretproduct(X, Y)

##        traditional***********
        Y  = u.std(bottomstring.val)
        X = u.std(topstring.val)
        
        Y = u.floretproduct(X, Y)
        X = Y
        Yd = u.std(bottomstring.val)
        
        #print "Here it is... ", u.std(bottomstring.val, dodicty=True, sig=True, cyc=False)

##        pp = 16*[0]
##        pp[1] = 1
##        pp[5] = 1.4
##        print "Here it is... ", u.returndict(pp)

        
##        print X
##        print Y

##      This is Gerald's Spiral


        
        
        

        theteslist = numofterms*[0]
        theemlist = numofterms*[0]
        theeilist = numofterms*[0]
        
        product = 16*[0]
        
##        product[1] = 1
##        product[2] = 2
##        productdict = u.returndict(product)
##        print "The product is ", u.dtl(productdict, {'sig': True})
        
    

        

            
        sumYstate = 16*[0]
        
        ## Gerald's Spiral

        Ietorator = 0
        
        for number in range(0,numofterms):
            sumYstate = 16*[0]
            
            if number == 0:
                r = 0
                try: r = thelastseq[number]
                except:
                    thelastseq = numofterms*[0]
                    NameError

            
            if zap.val == 1 or zaptype == 1:
                #in previous versions: X = u.floretproduct(X, Yd)
                Y = u.floretproduct(Y, Yd)
##            if number == 3:
##                print "Y ", Y
##                print "Yd ", Yd
##                print "addX", addX.val
##                
           # Y = u.floretproduct(Y, X)
            
            stepone = u.floretproduct(X, Y)
            

            
            #sum it
            sum = 0
            possum = 0
            negsum = 0
            ito = 0
            for vector in stepone:  # vector in stepone
                sum = sum + vector - int(vector)
                sumYstate[ito] = vector - int(vector)
                if number == 5:
                    pass
##                    print "ito: ", ito
##                    print "vector: ", vector
##                    print "sumYstate ", sumYstate[ito]
                
                if int(vector) > 0:
                    possum += vector - int(vector)
                else:
                    negsum += vector - int(vector)
                ito += 1

            sum2 = 0
            sallywacker = u.returndict(sumYstate)
            
##            if number < 6:
##                print ""
##                print "sallywacker ", sallywacker
##                print "SumYstate ", sumYstate
##                print "stepone ", stepone
##                print "Y ", Y

            
##                
##            if number == 0:
##                print "sallywacker ", sallywacker
##            sumYstate = u.dtl(sallywacker, {'sig': True})
            
##            for i in range(0,16):
##                Y[i] += 2*sumYstate[i]

        
            
          #  print "sum ", sum
          #  print "ito ", sum2 
            

            steptwo = sum
            stepthree = 16*[0]
            

            stepthree = u.floretadd(16*[0], stepone)

##            add "Add X" option to this!
##            if addX.val == 1:
##                stepthree = u.floretadd(X, stepone)  # stepthree = X + X*Y
            if addXFac.val > 0:
                for c in range(addXFac.val):
                    stepthree = u.floretadd(X, stepthree)
            elif addXFac.val < 0:
                for c in range(-1*addXFac.val):
                    stepthree = u.floretsub(stepthree, X) 
                
                
                
               
                    #stepthree = u.floretadd(X, stepthree)

            
                 
                

    
    ## 'i,  'j,  'k,   i',  j',  k',  'ii',  'jj',  'kk',  'ij',  'ik',  'ji',  'jk',  'ki',  'kj',  1  x
    ##  0    1    2    3    4    5      6      7      8      9     10     11     12     13     14   15  x
                    
            
##          #  stepthree = u.floretadd(Yd, stepthree)
    
            

            if cyctype == 3: # PURPLE-CYC
                
                if number%modat.val==0:
                    P = 16*[0]
                     
              
                    
                  #  stepthree = u.floretproduct(P, stepthree)

                
          
                    
                       
              


                    if stepthree[0] >  2*abs(stepthree[3]):
                        stepthree[3] += sumateI.val*sumYstate[0]/4
                        
                        stepthree[1] = stepthree[0]
                        stepthree[2] = stepthree[1]
                        stepthree[0] = stepthree[2]

                         
##                        stepthree[0] += .5 #.25/4
##                        stepthree[3] += .5
                      #  stepthree = u.floretproduct(X, stepthree)
                       
                       # stepthree = u.floretadd(Y,stepthree) 
 
            
                            

                        
                        
##                        stepthree[15] -= 1 nice turn on bottom as well
                        
                          

                    elif stepthree[0] < 2*abs(stepthree[3]):
                        
                        pass

                    #    stepthree = u.floretproduct(stepthree, Y)

                        
                       # stepthree[0] += sumatIe.val*sumYstate[3]/4
                        
##                        stepthree[0] += .5 # .25/4
##                        stepthree[3] += .5 #.25/4
##                        stepthree[15] -= .5
##                        stepthree[6] -= .5

                        
##                        stepthree[13] = 0
##                        stepthree[15] += 1
                        

                    
                        
##                    if sumYstate[0] > 0:
##                        stepthree[0] += sumateI.val*sumYstate[1]/4
##                        stepthree[0] -= .5
##                        stepthree[3] -= .5
##                        
####                        stepthree[0] += .25
####                        stepthree[3] += .25
####                        stepthree[6] += .25
####                        stepthree[7] += .25
####                        stepthree[8] += .25
####                        stepthree[12] += .25
####                        stepthree[14] += .25
####                        stepthree[15] += .25
####                        
##                        
##                    elif sumYstate[0] < 0:
##                      
##         
##                        stepthree[3] += sumatIe.val*sumYstate[3]/4
##                        stepthree[0] += .5
##                        stepthree[3] -= .5
##                         
##                        
##                    else:
##                        stepthree[6] += sumateI.val*sumYstate[1]/4
                        
                elif number%modat.val==1:
                    if sumYstate[1] > 0:
                        stepthree[1] += sumateJ.val*sumYstate[2]/4

                        stepthree[4] = stepthree[5]
                        stepthree[5] = stepthree[6]
                        stepthree[6] = stepthree[7]

                 
            
                  
                        
##                        stepthree[6] += .5
##                        stepthree[7] += .5
                        
                    elif sumYstate[1] > 0:
                        stepthree[4] += sumatJe.val*sumYstate[5]/4
##                        stepthree[6] -= .5
##                        stepthree[7] -= .5
                        
                    else:
                        stepthree[7] += sumateJ.val*sumYstate[2]/4

                        
                elif number%modat.val==2:
                    if sumYstate[2] > 0:
                        stepthree[2] += sumateK.val*sumYstate[0]/4

                    
                        
##                        stepthree[2] += .5
##                        stepthree[5] += .5
                    elif sumYstate[2] < 0:
                        stepthree[5] += sumatKe.val*sumYstate[3]/4
##                        stepthree[2] -= .5
##                        stepthree[5] -= .5
                    else:
                        stepthree[8] += sumateK.val*sumYstate[0]/4

                Ietorator = stepthree[0] + stepthree[1] + stepthree[2]



                
            elif cyctype == 2:   #MANDELA-CYC
                
                if number%modat.val==0:

                    if stepthree[0] >  2*abs(stepthree[3]):
                        stepthree[0] += sumateI.val*sumYstate[3]/4
                        stepthree[0] += .5
                        stepthree[3] += .5
                     
             
 


                elif number%modat.val==1:
                    
                    if sumYstate[1] > 0:
                        stepthree[1] += sumateJ.val*sumYstate[2]/4

                       
                 
            
                  
                        
##                        stepthree[6] += .5
##                        stepthree[7] += .5
                        
                    elif sumYstate[1] > 0:
                        stepthree[4] += sumatJe.val*sumYstate[5]/4
##                        stepthree[6] -= .5
##                        stepthree[7] -= .5
                        
                    else:
                        stepthree[7] += sumateJ.val*sumYstate[2]/4

                        
                elif number%modat.val==2:
                    if sumYstate[2] > 0:
                        stepthree[2] += sumateK.val*sumYstate[0]/4

                    
                        
##                        stepthree[2] += .5
##                        stepthree[5] += .5
                    elif sumYstate[2] < 0:
                        stepthree[5] += sumatKe.val*sumYstate[3]/4
##                        stepthree[2] -= .5
##                        stepthree[5] -= .5
                    else:
                        stepthree[8] += sumateK.val*sumYstate[0]/4

                Ietorator = stepthree[0] + stepthree[1] + stepthree[2]
                  

                    
 

            elif cyctype == 1:  #SILVER-CYC
                
                if number%modat.val==0:
                    stepthree[0] += sumateI.val*sumYstate[1]/2 #dividing by higher numbers results in figure "approaching division by infinity"
                elif number%modat.val==1:
                    stepthree[1] += sumateJ.val*sumYstate[2]/2
                elif number%modat.val==2:
                    stepthree[2] += sumateK.val*sumYstate[0]/2

                


            stepthree[15] += sumatEE.val*sum/2 #sumatEE.val*steptwo
        
                        
                    
            
                

            



##            if stepthree[0]>0 and stepthree[15]>0:
##                stepthree[15] += 2*steptwo
##            elif stepthree[0]<0 and stepthree[15]<0:
##                stepthree[15] += 2*steptwo
##            else: stepthree[15] += steptwo
                

                                  
##            if number%4 == 0:
##                stepthree[0] += steptwo   # stepthree = X + x*y +s*ee
##            elif number%4 == 1:
##                stepthree[1] += steptwo
##            elif number%4 == 2:
##                stepthree[2] += steptwo
##            elif number%4 == 3:
##                stepthree[15] += 2*steptwo
##                
            
            
            Y = stepthree

            
            
            if abs(stepthree[15]) > 10**12:
                PupMenu('The sequence of numbers generated by this floretion grows too fast! Try making coefficients smaller (in the Floretion x=, y= text fields). Numbers out of range, aborting draw!')                
                return

        
           # if abs(int(Y[0])) < int(Y[15]):
          #  Y[15] += 1 # Y[15] - int(Y[15])  #put in later!
        

        #    print "Y before: ", Y

##            Ydict = u.returndict(Y)
##            #print "doZap", zap
##            if cyc_sequence == 1 and sig_sequence == 0:
##                Y = u.dtl(Ydict, {'cyc': True, 'sig': False})
##                
##            elif cyc_sequence == 1 and sig_sequence == 1:
##                Y = u.dtl(Ydict, {'cyc': True, 'sig': True})
##                
##            elif cyc_sequence == 0 and sig_sequence == 1:
##                Y = u.dtl(Ydict, {'cyc': False, 'sig': True})
##
##            else:
##                pass
##                
            

          #  print "Y after: ", Y
        
            
##            if number == 0:
##                theteslist[0] = stepthree[15]
##            else:
##                if theteslist[number-1] > theteslist[number]:
##                    theteslist[number] = stepthree[15]
##                else:
##                    theteslist[number] = -stepthree[15]
##           
##                    
##            theeilist[number] = stepthree[0]

            if six_sequence.val == 1:                
                if number%6 == 0:
                    theteslist[number/6] = stepthree[15]
                    theeilist[number/6] = stepthree[0]
            else:
                theteslist[number] = stepthree[15]
                theeilist[number] = stepthree[0]
                

            
            
    ## 'i,  'j,  'k,   i',  j',  k',  'ii',  'jj',  'kk',  'ij',  'ik',  'ji',  'jk',  'ki',  'kj',  1  x
    ##  0    1    2    3    4    5      6      7      8      9     10     11     12     13     14   15  x
            
            for i in range(0,16):
                if i == 0 or i == 3 or i == 6 or i == 7 or i == 8 or i == 12 or i == 14:
                    theemlist[number] += stepthree[i] 


    
        tesnorm = 1
        emnorm = 1
        einorm = 1
        tesjump = numofterms*[0.01]
        longesttesjump = 0
        tesjumpaverage = 0
        place = 0

        if six_sequence.val == 1:
            numofterms = int(numofterms/6)
            

        
        for number in range(1,numofterms-1):
           # print theteslist[number]
            if abs(theteslist[number]) > tesnorm:
                tesnorm = abs(theteslist[number])
            if abs(theemlist[number]) > emnorm:
                emnorm = abs(theemlist[number])
            if abs(theeilist[number]) > einorm:
                einorm = abs(theeilist[number])

            if abs(einorm) > 10**8 or abs(tesnorm) > 10**8 or abs(emnorm) > 10**8:
                PupMenu('Numbers out of range, aborting draw.')
                return

##  For determining interesting numerical constants. 
##            if number < numofterms - 2:
##                tesjump[number] = sqrt(abs(theteslist[number]-theteslist[number+1])**2 + abs(theteslist[number+1]-theteslist[number+2])**2)
##                
##                if abs(tesjump[number] - longesttesjump) < .0001:
##                    print "Number, tesjump, longesttesjump: ", number, tesjump[number], longesttesjump
##
####                if abs(longesttesjumprelative - tesjump[number]/tesjump[number-1]) < .0001:
####                    print "Number, tesjumpf., longesttesjumprelative: ", number, tesjump[number-1]/tesjump[number], longesttesjumprelative
##            
##                if sqrt(abs(theteslist[number]-theteslist[number+1])**2 + abs(theteslist[number+1]-theteslist[number+2])**2) > longesttesjump:
##                    longesttesjump = sqrt(abs(theteslist[number]-theteslist[number+1])**2 + abs(theteslist[number+1]-theteslist[number+2])**2)
##                   # print number, longesttesjump
##
##            tesjumpaverage += tesjump[number]
##        tesjumpaverage = tesjumpaverage/(numofterms-1)
##        print "Tessjumaverage ", tesjumpaverage
##            
##                   
##                        
                
           
             
##            
##
##        print "Longest tesjump (absolute) ", longesttesjump
   

               
                

                


 
        for number in range(1,numofterms):
            theteslist[number] = 6*theteslist[number]/tesnorm
            theemlist[number] = 6*theemlist[number]/emnorm
            theeilist[number] = 6*theeilist[number]/einorm
   
            
                

##        print "Longest tesjump (normed)", longesttesjump/tesnorm


 

        cu = Curve.New("Floretion Curve");
       # cu.setFlag(11)
        nurb = cu.appendNurb([0, 0, 0, 1.0]);

        q = startat
        r = numofterms - 1

        if pull_sequence.val == 1:
            q = 1
        else:
            q = 0

        for number in range(startat, numofterms-1):  #int(numofterms-1)

            if twoD.val == 1:                
                if last_sequence.val == 1:

                    if em_sequence.val == 1:
                           # Buttons pressed 2-D, last sequence, em sequence

                        try:
                            if number%2 == 0:
                                nurb.append([theemlist[number], thelastlist[number+1], 6*1.0*pull_sequence.val*(number-startat)/(numofterms-startat-1), 1.0]);
                            else:
                                nurb.append([theemlist[number], thelastlist[number+1], 6*1.0*pull_sequence.val*(number-startat)/(numofterms-startat-1), 1.0]);
                                
                     
             

                            if number == startat+1:
                                print "Plotting em-values from this list against tes-values from last list along the xy-axis."
                                print "Plot:"
                                print "x-axis: em-values from the current list, offset 0."
                                print "y-axis: tes-values from the last list, offset 0."
                                print "z-axis: (0,0,0,0,0,...)"
                            
                        except:
                            print "No Sequence yet"
                            NameError

                    elif  em_sequence.val == 0:
                        #Buttons pressed: 2-D, last sequence

                        try:
                            if number%2 == 0:
                                nurb.append([theteslist[number], thelastlist[number+1], 6*1.0*pull_sequence.val*(number-startat)/(numofterms-startat-1), 1.0]);
                            else:
                                nurb.append([theteslist[number], thelastlist[number+1], 6*1.0*pull_sequence.val*(number-startat)/(numofterms-startat-1), 1.0]);
                                
                            if number == startat+1:
                             
                                print "Plot:"
                                print "x-axis: tes-values from the current list, offset 0."
                                print "y-axis: tes-values from the last list, offset 0."
                                print "z-axis: (0,0,0,0,0,...)"
                                #make option to increase offset!!
                                
                            
                        except:
                            print "No Sequence yet"
                            NameError
                            
                        

                            
                elif last_sequence.val == 0:
                    
                    if em_sequence.val == 1:
                        # Buttons pressed 2-D, em sequence

                        try:
                            if number%2 == 0:
                                nurb.append([theemlist[number], theteslist[number+1], 6*1.0*pull_sequence.val*(number-startat)/(numofterms-startat-1), 1.0]);
                            else:
                                nurb.append([theemlist[number], theteslist[number+1], 6*1.0*pull_sequence.val*(number-startat)/(numofterms-startat-1), 1.0]);
                                
             

                            if number == startat+1:
                                print "Plotting em-values from this list against tes-values from last list along the xy-axis."
                                print "Plot:"
                                print "x-axis: em-values from the current list, offset 0."
                                print "y-axis: tes-values from the current list, offset 0."
                                print "z-axis: (0,0,0,0,0,...)"
                            
                        except:
                            print "No Sequence yet"
                            NameError

                    elif  em_sequence.val == 0:
                        #Buttons pressed: 2-D, last sequence
                        try:
                            if number%2 == 0:
                                nurb.append([theteslist[number], theteslist[number+1], 6*1.0*pull_sequence.val*(number-startat)/(numofterms-startat-1), 1.0]); # 3*pull_sequence.val, 1.0]);
                            else:
                                nurb.append([theteslist[number], theteslist[number+1], 6*1.0*pull_sequence.val*(number-startat)/(numofterms-startat-1), 1.0]); # -3*pull_sequence.val, 1.0]);

                          
                                

                            if number == startat+1:
                             
                                print "Plot:"
                                print "x-axis: tes-values from the current list, offset 0."
                                print "y-axis: tes-values from the current list, offset 1."
                                print "z-axis: (0,0,0,0,0,...)"
                                #make option to increase offset!!
                                
                            
                        except:
                            print "No Sequence yet"
                            NameError
  



                    
            elif twoD.val == 0:
                if last_sequence.val == 1:
                    try:
        ##                nurb.append([theteslist[number], theteslist[number+1], 0, 1.0]);
                        nurb.append([theteslist[number], theteslist[number+1], thelastlist[number], 1.0]);
                        if number == startat+1:
                            print "Plot:"
                            print "x-axis: tes-values from the current list, offset by 0."
                            print "y-axis: tes-values from this list, offset by 1."
                            print "z-axis: tes-values from the last list, offset by 0."
                    except:
                        print "No Sequence yet"
                        NameError
                elif last_sequence.val == 0:
                    nurb.append([theteslist[number], theteslist[number+1], 0, 1.0]);

                                    
              
                    
                
              
                
        nurb.setType(0)
        Scene.GetCurrent().objects.new(cu)
        thelastlist = theteslist        
         
	Blender.Redraw()


	
global doZap

COLORS  = { 
  'clear_color': (0.4, 0.4, 0.4, 1.0),
  'output_color': (.6, .8, 1)
}
##
##from Blender import *
##
##COLORS  = { 
##  'clear_color': (0.4, 0.4, 0.4, 1.0),
##  'output_color': (.6, .8, 1)
##}
##def gui():
##  scn = Scene.GetCurrent()
##  objs = scn.objects
##  names = []
##  for obj in objs:
##    names.append(obj.name)
##  objectsStr = ", ".join(names)
##  BGL.glClearColor(*COLORS['clear_color'])
##  BGL.glClear(BGL.GL_COLOR_BUFFER_BIT)
##  BGL.glColor3f(*COLORS['output_color'])
##  BGL.glRasterPos2i(5, 5)
##  Draw.Text("Objects: %s" % objectsStr, "large")
##
##Draw.Register(gui, None, None)


############# Oberflaeche zeichnen ############
def gui():
	global bottomstring, topstring, startat, ymax, numofterms, last_sequence, em_sequence
	global six_sequence, pull_sequence, zap, sumateI, sumateJ, sumateK, sumatEE, modat #addX
	global doZap, twoD, cyc_sequence, sig_sequence, sumatIe, sumatJe, sumatKe, addXFac
	global draw_predefcurves, choose_floretions, maxterms, history, SaveH, choose_cyc
	
	
	doZap = False

	##glClearColor(.80,.80,.78,1)#(.71,.7,.66,1)
	glClearColor(.47,.79,.89,1) #(.71,.7,.66,1)
	glClear(GL_COLOR_BUFFER_BIT)
	
	glColor3f(1.0, 1.0, 1.0)
	 

 





##	glClearColor(0.5,0.5,0.5, 0.0)
##	glClear(GL_COLOR_BUFFER_BIT)	

#button (name, ?, x, y)
	Button("Exit", 1, 310, 10, 80, 19)
	Button("Plot Curve", 3,  10, 10, 100, 19)
##	Button("Save History", 102, 400, 10, 80, 19)

	glRasterPos2i(10, 545)	
	Text("Note: All plotted curves have an additional point at (0,0,0) (which can be deleted by hand).")
	

	glRasterPos2i(10, 530)	
	Text("Floretion basis vectors are: [eI, eJ, eK, Ie, Je, Ke, II, JJ, KK, IJ, IK, JI, JK, KI, KJ, ee]")

	glRasterPos2i(10, 515)	
	Text("Quaternion basis vectors are: [eI, eJ, eK, ee] _or_  [Ie, Je, Ke, eI, ee] (an isomorphic copy)")

	glRasterPos2i(10, 500)	
	Text("We have eI*eJ = -eJ*eI = eK (etc.) and ")

	glRasterPos2i(10, 485)
	Text("(eI)^2 = (eJ)^2 = (eK)^2 = (Ie)^2 = (Je)^2 = (Ke)^2 = -1 (defined in each case as the usual quaternion multiplication)")

	glRasterPos2i(10, 470)
	Text("eI*Ie = II = Ie*eI, eJ*Je = JJ = Je*eJ, eK*Ke = KK = Ke*eK")

	glRasterPos2i(10, 455)
	Text("eI*Je = IJ = Je*eI, eI*Ke = IK = Ke*eI, etc.")

	glRasterPos2i(10, 440)
	Text("(II)^2 = (JJ)^2 = (KK)^2 = (IJ)^2 = (IK)^2 = ... = 1  (follows from the above rules and required associativity!)")
	
    ## 'i,  'j,  'k,   i',  j',  k',  'ii',  'jj',  'kk',  'ij',  'ik',  'ji',  'jk',  'ki',  'kj',  1  x
    ##  0    1    2    3    4    5      6      7      8      9     10     11     12     13     14   15  x

	
	topstring= String("Floretion: x = ", 2, 10, 70, 600, 19, topstring.val, 70, "Any coefficient\'s sign or value may be changed by hand. Caution is required: changing a .5 to a 1.5, for ex. may lead to too large values!")
	glRasterPos2i(615, 45)
	Text("(used as seed)")
	bottomstring= String("Floretion: y = ", 4, 10, 40, 600, 19, bottomstring.val, 70, "Any coefficient\'s sign or value may be changed by hand. Caution is required: changing a .5 to a 1.5, for ex. may lead to too large values!")

	draw_predefcurves = Menu("Draw Pre-defined Curves %t|Draw Pre-defined Curves %x0|Manela I %x1|Mandela II \
%x2|Crawfish Mandela %x6|Chung shu\'s Spiral %x3|A Floretion Table %x4|Gerald\'s Spiral %x5|Six Ellipses %x7|",88,10,400,180,14,draw_predefcurves.val,"Adjust sliders below to set the number of terms!")
	#draw_predefcurves

##        history = Number("History: ", 101, 10, 190, 350, 18, history.val, 0, 5, "Not yet functinal.")
        
        maxterms = Slider("Max. number of terms: ", 7, 10, 160, 450, 18, maxterms.val, 1000, 100000)
	numofterms = Slider("Number of terms to calculate: ", 7, 10, 130, 450, 18, numofterms.val, 100, maxterms.val)
	startat = Slider("Begin drawing at term number: ", 5, 10, 100, 450, 18, startat.val, 0, numofterms.val)

	
	
 	sumatEE = Number("Sum ee-Factor:", 5, 10, 340, 180, 19, sumatEE.val, -10, 100, "Adds the sum of the fractional parts of all basis vectors to ee during each iteration, then multiplies by ee-Factor.")
        sumateI = Number("Sum eI-Factor:", 5, 10, 310, 180, 19, sumateI.val, -10, 100, "Adds the fractional parts of eI during an intermediate stage of the iteration, then multiplies this by eI-Factor.")
        sumateJ = Number("Sum eJ-Factor:", 5, 10, 280, 180, 19, sumateJ.val, -10, 100, "Adds  the fractional parts of eJ during an intermediate stage of the iteration, then multiplies this by eJ-Factor.")
        sumateK = Number("Sum eK-Factor:", 5, 10, 250, 180, 19, sumateK.val, -10, 100, "Adds the the fractional parts of eK during an intermediate stage of the iteration, then multiplies this by eK-Factor.")
        
        modat = Number("Mod:", 5, 10, 220, 180, 19, modat.val, 1, 100, "Mod 3 means that the above eI-, eJ-, eK-Factors are performed in cyclic order: 1,2,3,1,2,3...")

        addXFac = Number("Add X Factor:", 5, 250, 250, 180, 19, addXFac.val, -10, 100, "Performs a vector sum of the floretion X and the intermediate iteration result for the number of times specified (will subtract if negative).")
        
##        
##        sumatIe = Number("Sum Ie-Factor:", 5, 10, 290, 180, 19, sumatIe.val, -10, 100, "Warning: calibration may change here in later versions!. Adds the fractional parts of Ie, then multiplies this by Ie-Factor.")
##        sumatJe = Number("Sum Je-Factor:", 5, 10, 260, 180, 19, sumatJe.val, -10, 100, "Warning: calibration may change here in later versions! Adds the fractional parts of Je, then multiplies this by Je-Factor.")
##        sumatKe = Number("Sum Ke-Factor:", 5, 10, 230, 180, 19, sumatKe.val, -10, 100, "Warning: calibration may change here in later versions! Adds the fractional parts of Ke, then multiplies this by Ke-Factor.")
##        
##	
	#line()
 
	         
	try:
            twoD = Blender.Draw.Toggle("2-D", 18, 250, 340, 100, 20, twoD.val, "Plot only along the xy-axis.")
        except:
            UnboundLocalError 
            twoD = Blender.Draw.Toggle("2-D", 18, 250, 340, 100, 20, 1, "Plot only along the xy-axis.")
 


            
	try:
            zap = Toggle("Zap it!", 13, 250, 310, 100, 20, zap.val, "Multiply result again by Y at an intermediate stage of the iteration.")
        except:
            UnboundLocalError 
            zap = Toggle("Zap it!", 13, 250, 310, 100, 20, 0, "Multiply result again by Y at an intermediate stage of the iteration.")



        choose_cyc = Menu("Choose Cyclic Transform Type: %t|White %x0|Silver %x1 |Mandela %x2|Purple %x3", 103, 250, 220, 180, 20, choose_cyc.val, "Perform a cyclic transform i->j, j->k, k->i using the eI, eJ, and eK-Factors.")

#   "Choose a Floretion %t|Choose a Floretion %x0|Gerald\'s Spiral %x1|Chung shu\'s Spiral %x2| Alex\'s Spiral %x3| Floret\'s Cube %x4| Casper\'s Cube %x5|",89,10,500,180,14,choose_floretions.val,"Inserts two floretions to be multiplied into the fields, below. Note: You can change the signs of the coefficients, etc. by hand!")


##        try:
##            cyc_sequence = Toggle("Cyc", 16, 350, 410, 100, 20, cyc_sequence.val, "Perform a cyclic transform i->j, j->k, k->i using the eI, eJ, and eK-Factors.")
##        except:
##            UnboundLocalError
##            cyc_sequence = Toggle("Cyc", 16, 350, 410, 100, 20, 0, "Perform a cyclic transform i->j, j->k, k->i using the eI, eJ, and eK-Factors.")
##            
            
            
        try:
            last_sequence = Toggle("Last Sequence", 14, 250, 280, 100, 20, last_sequence.val, "Uses the sequence from the last draw when plotting the z-axis (or y-axis if 2-D button is depressed).")
        except:
            UnboundLocalError
            last_sequence = Toggle("Last Sequence", 14, 250, 280, 100, 20, 0, "Uses the sequence from the last draw when plotting the z-axis (or y-axis if 2-D button is depressed).")
            

        try:
            em_sequence = Toggle("em Sequence", 15, 350, 310, 100, 20, em_sequence.val, "Adds over basis vectors eI, Ie, II, JJ, KK, JK, KJ, ee.")
        except:
            UnboundLocalError
            em_sequence = Toggle("em Sequence", 15, 350, 310, 100, 20, 0, "Adds over basis vectors eI, Ie, II, JJ, KK, JK, KJ, ee.")

        try:
            six_sequence = Toggle("Show 6th", 16, 350, 280, 100, 20, six_sequence.val, "Only plot every 6th term.")
        except:
            UnboundLocalError
            six_sequence = Toggle("Show 6th", 16, 350, 280, 100, 20, 0, "Only plot every 6th term.")

        

        try:
            pull_sequence = Toggle("Grow", 17, 350, 340, 100, 20, pull_sequence.val, "If the 2-D button is pressed, this maps the curve\'s z-coordinates to the natural numbers (normed to a height of 6).")
        except:
            UnboundLocalError
            pull_sequence = Toggle("Grow", 17, 350, 340, 100, 20, 0, "If the 2-D button is pressed, this maps the curve\'s z-coordinates to the natural numbers (normed to a height of 6).")


#not yet working:            
##        try:
##            sig_sequence = Toggle("Sig", 17, 250, 320, 100, 20, sig_sequence.val, "Mirrors eX to Xe.")
##        except:
##            UnboundLocalError
##            sig_sequence = Toggle("Sig", 17, 250, 320, 100, 20, 0, "Mirrors eX to Xe.")





	
	choose_floretions = Menu("Choose a Floretion %t|Choose a Floretion %x0|Gerald\'s Spiral %x1|Chung shu\'s \
Spiral %x2| Alex\'s Spiral %x3| Floret\'s Cube %x4| Casper\'s Cube %x5|",89,250,400,180,14,choose_floretions.val,"Inserts \
two floretions to be multiplied into the fields, below. Note: You can change the signs of the coefficients, etc. by hand!")

##	Button("Gerald\'s Spiral",    9, 10,  200, 100, 19)
##	Button("Chung-shu\'s Spiral",10, 110, 200, 120, 19)	 
##	Button("Alex\'s Spiral",     11, 230, 200, 120, 19)
##	Button("Floret\'s Cube",     12, 10, 175, 100, 19)
##	Button("Casper\'s Cube",     20, 110, 175, 120, 19)
	
	#Button("Sombrero",           11, 230, 200, 100, 19)

def event(evt, val):	
	if (evt== QKEY and not val): Exit()

def bevent(evt):
        global zap, men
        global choose_floretions
        global zap
        global choose_cyc
        global pull_sequence
        global em_sequence
        global addXFac
        global bottomstring, topstring
        
	if   (evt ==  1): Exit()
	elif (evt ==  2 or evt == 4):
            pass
##            PupMenu("Any coefficient\'s sign or value may be changed by hand. Caution is required: changing a .5 to a 1.5, for ex. may lead to too large values!")
	
	elif (evt ==  3): # Draw!
            history.val += 1
            draw(bottomstring.val,topstring.val,numofterms.val,startat.val,ymax.val, sumateI, sumateJ, sumateK, sumatIe, sumatJe, sumatKe, sumatEE, modat, zaptype=0, cyctype=choose_cyc.val, seqtype=0)
            
            
            
	elif (evt ==  5): pass # numofterms.val = startat.val
	elif (evt ==  9):
                geralds_spiral()
                #PupMenu("gh objects selected. Not enough objects selected.")
	elif (evt == 10): chung_shu_spiral()
	elif (evt == 11): alex_spiral()
	elif (evt == 12): florets_cube()
	elif (evt == 20): caspers_cube()
	elif (evt == 13): print "togglezap: ", zap.val
        elif (evt == 14): print "last sequence" , last_sequence.val
        elif (evt==88):
            if draw_predefcurves.val != 0:
          
            
                PupMenu("Will now load curve-object parameters: press \'Plot Curve\' button to plot.")


            if draw_predefcurves.val == 4: # A Floretion Table                 

                caspers_cube()                
                sumateI.val = 1
                sumateJ.val = 1
                sumateK.val = 1
                sumatIe.val = 0
                sumatJe.val = 0
                sumatKe.val = 0
                sumatEE.val = 0
                
                choose_floretions = Create(5)
                choose_cyc = Create(3)
                zap = Create(1)
                pull_sequence = Create(1)
                addXFac = Create(0)
                numofterms.val = min(maxterms.val, 3000)

                Redraw(1)

            elif draw_predefcurves.val == 6: # Crawfish Mandela

                geralds_spiral()  
                bottomstring = Create("0.5eI - 0.5eJ + 0.5eK + 0.5ee")
             

                                
                sumateI.val = -1
                sumateJ.val = -1
                sumateK.val = -1
                sumatIe.val = 0
                sumatJe.val = 0
                sumatKe.val = 0
                
                sumatEE.val = 0
                
               # choose_floretions = Create(2)
                choose_cyc = Create(2)
                zap = Create(0)                 
                em_sequence = Create(0)
                pull_sequence = Create(0)
                addXFac = Create(0)
                numofterms.val = min(maxterms.val, 6000)

                PupMenu("Note: the Crawfish Mandela is nice for experimenting. For ex., change the addX factor before plotting.")

            elif draw_predefcurves.val == 7: # Six Ellipses

                geralds_spiral()  
                          

                                
                sumateI.val = -1
                sumateJ.val = -1
                sumateK.val = -1
                sumatIe.val = 0
                sumatJe.val = 0
                sumatKe.val = 0
                
                sumatEE.val = 0
                
               # choose_floretions = Create(2)
                choose_cyc = Create(1)
                zap = Create(0)                 
                em_sequence = Create(0)
                pull_sequence = Create(0)
                addXFac = Create(0)
                numofterms.val = min(maxterms.val, 3000)

                
                
                
                

            elif draw_predefcurves.val == 3: # Chung shu's spiral
             

                chung_shu_spiral()                
                sumateI.val = 0
                sumateJ.val = 0
                sumateK.val = 0
                sumatIe.val = 0
                sumatJe.val = 0
                sumatKe.val = 0
                
                sumatEE.val = 2
                
                choose_floretions = Create(2)
                choose_cyc = Create(0)
                zap = Create(1)                 
                em_sequence = Create(1)
                pull_sequence = Create(1)
                addXFac = Create(0)
                numofterms.val = min(maxterms.val, 3000)

                

            elif draw_predefcurves.val == 2: # Mandela II             

                geralds_spiral()                
                sumateI.val = -1
                sumateJ.val = -1
                sumateK.val = -1
                sumatIe.val = 0
                sumatJe.val = 0
                sumatKe.val = 0
                
                sumatEE.val = 0
                
                choose_floretions = Create(1)
                choose_cyc = Create(2)
                zap = Create(0)
                pull_sequence = Create(0)
                em_sequence = Create(0)
                addXFac = Create(0)                
                numofterms.val = min(maxterms.val, 3000)              

                

            elif draw_predefcurves.val == 1: # Mandela I              

                geralds_spiral()                
                sumateI.val = 1
                sumateJ.val = 1
                sumateK.val = 1
                sumatIe.val = 0
                sumatJe.val = 0
                sumatKe.val = 0
                
                sumatEE.val = 0
                
                choose_floretions = Create(1)
                choose_cyc = Create(2)
                zap = Create(0)
                pull_sequence = Create(0)
                em_sequence = Create(0)
                addXFac = Create(0)        

                numofterms.val = min(maxterms.val, 3000)

                

            elif draw_predefcurves.val == 5: # Gerald's Spiral               

                geralds_spiral()                
                sumateI.val = 0
                sumateJ.val = 0
                sumateK.val = 0
                sumatIe.val = 0
                sumatJe.val = 0
                sumatKe.val = 0
                
                sumatEE.val = 2
                
                choose_floretions = Create(1)
                choose_cyc = Create(0)
                zap = Create(0)
                pull_sequence = Create(1)
                em_sequence = Create(0)
                addXFac = Create(1)          

                numofterms.val = min(maxterms.val, 3000)

            Redraw(1)
           
           

                
     

        elif (evt==89): #Choose a floretion
            if choose_floretions.val != 0:
                PupMenu("Note: All settings can be changed. Object will not appear in 3D Window until draw button is pressed.")

            if choose_floretions.val == 1:
                geralds_spiral()
            elif choose_floretions.val == 2:
                chung_shu_spiral()
            elif choose_floretions.val == 3:
                alex_spiral()
            elif choose_floretions.val == 4:
                florets_cube()
            elif choose_floretions.val == 5:
                caspers_cube()
                
        elif (evt ==101): #History
            #H = 
            Redraw(1)
            pass

        elif (evt ==102): #Save History
            PupMenu("Not yet functional.")


        elif (evt ==103): #Cyc Menu
            PupMenu("There are many ways to perform a cyclic transform. White does nothing.")
            #PupMenu(".")
                
                

                
                
                
            
        
        elif (evt == 18):
            if twoD.val == 0:
                pull_sequence.val = 0
	
	

############# Los!############################
geralds_spiral()
