import java.awt.event.*;
import java.awt.*;
import java.awt.geom.*;
import java.util.Arrays;

/**This class builds the polygon from the holonomy and data
   and the control vertices*/


public class DataToPolygon {

    
    public static void createPolygon(EnhancedPolygon E) {
    	for(int i=0;i<E.count;++i) E.scratch[i]=E.free[i];
	initPolygon(E);

	boolean test=false;
	int cc=0;
	while(test==false) {
	    
	    int x=nextIndex(E);
	    
  	    if((x!=-1)&&(x<100)) {
		addEdge(E,x);
		++cc;
	    }

	    if(x>1000) {
		x=x-1000;
		addEdgeSpecial(E,x);
		++cc;
	    }
	    
	    if(x==-1) test=true;
	}
	E.READY=true;
    }
    


    /**this is the initial step of the polygon creation*/
    public static void initPolygon(EnhancedPolygon E) {
	for(int i=0;i<E.count;++i) E.z[i]=new Complex(0,0);
	E.z[0]=new Complex(0,0);
	int n=1;
	for(int i=1;i<E.count;++i) {
	    if(E.free[i]==1) {
      		E.z[i]=Complex.eis(E.geom[n]);
		++n;
	    }
	}
    }


    public static void addEdgeSpecial(EnhancedPolygon E,int x) {
	int y=E.pair[x-1];
	Complex a0=E.z[x-1];
	int xx=(x+1)%E.count;
	Complex a1=E.z[xx];
	Complex w=Complex.alpha(E.holo[x-1]);
	Complex b1=Complex.minus(a0,Complex.times(w,a1));
	Complex b2=Complex.minus(new Complex(1,0),w);
	Complex b3=Complex.divide(b1,b2);
	E.z[x]=b3;
	E.scratch[x]=1;
    }




    public static void addEdge(EnhancedPolygon E,int x) {
	int y=E.pair[x-1];
	Complex a0=E.z[y];
	Complex a1=E.z[(y+1)%E.count];
	Complex w=Complex.alpha(E.holo[x-1]);
	Complex b0=E.z[x-1];
	Complex b1=Complex.plus(b0,Complex.times(w,Complex.minus(a1,a0)));
	E.z[x]=b1;
	E.scratch[x]=1;
    }


    public static int nextIndex(EnhancedPolygon E) {
	for(int i=0;i<E.count-1;++i) {
	    if((E.scratch[i]==1)&&(E.scratch[i+1]==0)) {
		int j=E.pair[i];
		int k=(j+1)%E.count;
		if((E.scratch[j]==1)&&(E.scratch[k]==1)) return i+1;
		if(i+1==j) return i+1+1000;
	    }
	}
	return -1;
    }

}
