import math
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import Program
import Command

C = math.sqrt(3)

def koch( x, y, smin=1, nmax=None ):
    r=min(x,y)
    pts, tmp = [ ( x, y + r ),
                 ( x - C * r / 2, y - r / 2 ),
                 ( x + C * r / 2, y - r / 2 ) ], []
    s, n = 3 * r / C, 0
    while s > smin and ( nmax is None or n < nmax ):
        for i in range( len( pts ) ):
            ( x1, y1 ), ( x5, y5 ) = pts[ i - 1 ], pts[ i ]
            dx, dy = ( x5 - x1 ) / 3, ( y5 - y1 ) / 3
            tmp += [ ( x1 + dx, y1 + dy ),
                     ( ( x1 + x5 + C * dy ) / 2, ( y1 + y5 - C * dx ) / 2 ),
                     ( x5 - dx, y5 - dy ),
                     ( x5, y5 ) ]
        pts, tmp = tmp, []
        s /= 4
        n += 1
    print 'Laenge'+ str(s) + 'Iterationen' + str(n)
    return pts
    
def koche(plt):
	list=koch(plt.center[0],plt.center[1],smin=1,nmax=5)
	print list[-1]
	return Program([Command('IN'),Command('SP1'),Command('PU',*list[-1])]\
	+[Command('PD',*p) for p in list]\
	+[Command('PU')])
