// P1101.java:$B%8%'%M%l!<%?$K$h$k%U%i%/%?%k?^7A(B

package applet;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import Glib.*;

public class P1101 extends xApplet
	implements ActionListener
{	JTextField tf;
	JComboBox cb;
	JButton[]bt=new JButton[3];
	String[]str={"Start","Clear","Exit"};
	xTurtle T;
	int n_gene,N;
	double k,leng0=800.0,kOrg_y=4.0/3;
	double gene[]=new double[10];

	public void init()
	{	app_init(7);
		Container cp=getContentPane();
		cp.setBackground(getBackground());
		cp.setLayout(new FlowLayout(FlowLayout.LEFT));
		JLabel lb0=new JLabel("$B%8%'%M%l!<%?!'(B");
		lb0.setForeground(Color.black);
		cp.add(lb0);
		tf=new JTextField(32);
		tf.setBackground(Color.lightGray);
		tf.addActionListener(this);
		cp.add(tf);
		JLabel lb1=new JLabel("$B:F5"<!?t!'(BN=");
		lb1.setForeground(Color.black);
		cp.add(lb1);
		cb=new JComboBox();
		cb.setEditable(false);
		for(int i=0;i<10;i++)
			cb.addItem(Integer.toString(i));
		cb.addActionListener(this);
		cp.add(cb);
		for(int i=0;i<str.length;i++)
		{	bt[i]=new JButton(str[i]);
			bt[i].addActionListener(this);
			cp.add(bt[i]);
		}
		T=new xTurtle(getGraphics());
	}

	public void actionPerformed(ActionEvent evt)
	{	if(evt.getSource()==tf)
		{	int n=0,count=1;
			String s,str;
			str=tf.getText();
			gene[0]=0.0;
			while(n>=0)
			{	n=str.indexOf("/");
				if(n==-1)
					s=str;
				else
					s=str.substring(0,n);
				gene[count]=(double)Integer.parseInt(s);
				str=str.substring(n+1);
				count++;
			}
			n_gene=count;
			T.setlp(0.0,0.0);
			T.setangle(0.0);
			for(int i=0;i<n_gene;i++)
			{	T.turn(gene[i]);
				T.warp(1.0);
			}
			double t=Math.atan(T.getlp().y/T.getlp().x);
			k=Math.cos(t)/T.getlp().x;
			gene[0]=-180.0*t/Math.PI;
			gene[n_gene]=-T.getangle()-gene[0];
		}
		if(evt.getSource()==cb)
			N=cb.getSelectedIndex();
		if(evt.getSource()==bt[0])
		{	T.set0(CA.x,(int)(kOrg_y*CA.y),1);
			T.setlp(-leng0/2,0.0);
			T.setangle(0.0);
			fractal(leng0,0);
		}
		if(evt.getSource()==bt[1])
			repaint();
		if(evt.getSource()==bt[2])
			System.exit(0);
	}

	private void fractal(double leng,int n)
	{	if(n<N)
		{	for(int i=0;i<n_gene;i++)
			{	T.turn(gene[i]);
				fractal(k*leng,n+1);
			}
			T.turn(gene[n_gene]);
		}
		else
		{	T.warp(leng);
			T.putpixel(xMath.fint(T.getlp()),0);
		}
	}
}
