
package Ui ;

import java.awt.*;

import java.applet.*;

import java.util.*;

import java.awt.event.* ;

import Maths.*;




public class CurvePanel extends Canvas {



    //the type of generationmethod that is currently active
    protected Generationmethod  mode;

    //the list of available generationmethods
    public Vector gen_methods = new Vector(4,1);

    //the object that permits additional functionalities
    public Ui.Additional_Functionality addf ;

    // the size of the screen
    public int size = 4000;

    //the integers that internally define the different manipulations
    public static final int ADD = 0; 

    public static final int AVANT = 1; 

    public static final int MOVE = 2; 

    public static final int DELETE = 3; 

    public static final int NEW_CURVE = 4;

    public static final int MOVE_CURVE = 5;

    public static final int MOVE_ALL = 6;

    public static final int DELETE_CURVE = 7;

    public static final int SELECT_CURVE = 8;

    public static final int CURVE_SPLIT = 9;

    public static final int CURVE_JOIN = 10;

    public static final int COPY_CURVE = 11;

    public static final int SELECT_POINT = 12;

    public static final int ADD_FUNC = 13;

    private int    action = NEW_CURVE;

    public static final int EUCLIDIAN = 0;

    public static final int CENTRIPETAL = 1;

    public static final int ARCLENGTH = 2;

    public static final int CONSTANT = 3;

    private int param_mode = CONSTANT;

    //the current degree
    public static int degree = 3;
  
    //the current working language
    public static  Languages language;

    //Holds the flag that permits the drawing of the controlpoints
    protected boolean draw_ControlPoints = true;

    //Holds the flag that permits the drawing of the polygone
    protected boolean draw_Polygone = true;

    //Holds the flag that permits the drawing of the curves
    protected boolean draw_Curves = true;

    //Holds the flag that permits the drawing of the curves when moving them
    protected boolean draw_movingCurves = true;

    //Holds the flag that permits the drawing of the curvesegments
    protected boolean draw_CurveSegments = false;

    // Holds the controlpoints that define one curve
    private Vector pointslist = new Vector(16,4);


    // Holds the list of respective curves
    protected static Vector curveslist = new Vector(3,1);

    // Holds the list of  the old curves
    protected static Vector oldcurveslist = new Vector(3,1);


    protected static Point cur_point = new Point(-1,-1);

    protected static Point oldcur_point = new Point(-1,-1);

    // Holds a reference to the curve that is being worked upon
    protected static int cur_curve = -1;

    // Holds a reference to the old curve that was being worked upon
    protected static int oldcur_curve = -1;

    // Holds the point that will precede a point that is inserted into the curve
    private Point preceding_point = new Point(-1,-1);

    // Holds the old point
    private Point oldpreceding_point = new Point(-1,-1);

  // Holds a temporary list of selected points
  private Point search_point = new Point(-1,-1);
  
  private Vector search_point_list = new Vector(10,3);


  // Contains the first of two curves that get joined

  private int first_curve = -1;


  // For moving a curve, original_pos contains the original position of the reference point
  // curve_moving_curvelist contains the list of points that need be moved

  private ControlPoint original_pos;

  private Vector curve_moving_curveslist =new Vector(10,5);

  private ControlPoint point;


   public   CurvePanel() {

	/* constructor */

        setBackground(Color.white); 

	language =  CurveWindow.the_language;


	// defining and grouping the available curve generation methods
       // Generationmethod (String name,Polynom polynom, Color colorname,boolean deg_elev, boolean weights,boolean add_f ,int index){

       /////////////////////////////////////ADD NEW METHODS HERE/////////////////////////////////////////////////////////
	Generationmethod interpolation = new Generationmethod((String)(language.methodnames).elementAt(0),new Interpolating_Polynom(),Color.blue, false, false,true,0);

	Generationmethod bezier = new Generationmethod((String)(language.methodnames).elementAt(1),new Bezier(),Color.orange, true,false,true,1);

	Generationmethod bspline = new Generationmethod((String)(language.methodnames).elementAt(2),new BSpline(),Color.black, true,false,true,2);

	Generationmethod nurbs = new Generationmethod((String)(language.methodnames).elementAt(3),new NURBS(),Color.magenta, true,true,true,3);

	gen_methods.addElement(interpolation);

	gen_methods.addElement(bezier);

	gen_methods.addElement(bspline);

	gen_methods.addElement(nurbs);

       /////////////////////////////////////////////////////////////////////////////////////////////////////////////


	addf = new Ui.Additional_Functionality(this);

	mode = interpolation;

	enableEvents( AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK);


   }


  public static void ChangeLanguage(){

	language = CurveWindow.the_language;

  }





  public static Vector giveCurveslist(){

	/* returns a copy of the list of curves, e.g. to save them to disk */

	if (curveslist.size() > 0  ) { Vector v = (Vector)curveslist.clone();

				       return v;
	}

	else return new Vector(1);

  }



  public static void setCurveslist(Vector list){

	 /* sets the list of curves to the vector 'list'
	    this method is used after loading a list of curves from disk
	Last change:  TMC   6 Jan 98    2:36 pm
	  */

	 curveslist = list;

	 (Curvegeneration.cp).repaint() ;
  }



  public boolean setDegree(int degree){
    /* changes the degree of the selected curve
	Last change:  TMC   5 Jan 98   11:15 am
    */
    int change = degree - this.degree;

    boolean ok=true;

    this.degree = degree;

    if ( cur_curve != -1 && curveslist.size() > 0){//a curve was chosen and curves have been drawn

    Curve temp_curve = (Curve)curveslist.elementAt(cur_curve) ;

    ok = (temp_curve).deg_change(change);

    // we see to it that no point has a multiplicity higer then the new degree
    if ( ok ) temp_curve.CheckMultiplicity(degree);

    };

    return ok;
  } ;    
 

    public void setAction(int action) { 

    // Change the action type 

        switch (action) { 

          case ADD: 

          case AVANT:

          case MOVE: 

          case DELETE: 

	  case NEW_CURVE:  

	  case MOVE_CURVE:

	  case MOVE_ALL:
	  
	  case DELETE_CURVE:  

          case SELECT_CURVE:  

	  case CURVE_SPLIT:  

	  case CURVE_JOIN:  

	  case COPY_CURVE:

	  case SELECT_POINT :

            this.action = action;

	    {addf.RemoveFuncSupport();};

	    break;

	  case ADD_FUNC :

            this.action = action;

            break;

          default: 

            throw new IllegalArgumentException(); 

        } 

    } 



    public void setParameterisation( int param){
	/* sets the parametrisation type */

	switch ( param )
	{

	    case  EUCLIDIAN:

	    case CENTRIPETAL :

	    case ARCLENGTH :

	    case  CONSTANT :

		this.param_mode = param;

		if ( cur_curve != -1 ) { // The current curve gets another curvegenerationmethod

		    Curve temp_curve = (Curve)curveslist.elementAt(cur_curve) ;

		    temp_curve.parameterisation_mode = param;

		    temp_curve.CalculateDrawPoints();

		};

		break;

	    default :

	        throw new IllegalArgumentException();

	}

    }



    public void setCurveType(int mde) {

    // Change the curve generation method

      if (mde < gen_methods.size()) {

	int oldindex = mode.index;

	this.mode = (Generationmethod)(gen_methods.elementAt(mde));//adapt the mode

	if ( cur_curve != -1 ) { // The current curve gets another curvegenerationmethod

	    Curve temp_curve = (Curve)curveslist.elementAt(cur_curve) ;

	    temp_curve.polynom = (this.mode).NewPolynom();

	    (temp_curve.polynom).curve = temp_curve;

	    temp_curve.generation_mode = this.mode;

	    temp_curve.color = (this.mode).color;

	    temp_curve.CalculateDrawPoints();

	};

	{addf.RemoveFuncSupport();};

	(Curvegeneration.ap).repaint();//redraw the action panel

	return;


      };

     throw new IllegalArgumentException();

    }



    public void clearPoints() { 
	// clears all points/curves from the canvas and resets the current point and  curve

        curveslist.removeAllElements();

        preceding_point.move(-1,-1); 

	cur_curve = -1;

	cur_point.move(-1,-1);

    } 


    private Point findPoint_on_curve(int a, int b, int crve) {

    /* Scan the list of control points to find out which (if any) point

       contains the coordinates (a,b) within its square and that is part of curvenumber crve.

       If a controlpoint is found, return the controlpoint's coded index, otherwise return (-1,-1)

      | The code that identifies a controlpoint  is  constituted by a Java Point object whose:
      |
      | x value indicates which curve the controlpoint belongs to
      |
      | y value indicates the index of the controlpoint within the curve

    */

	int max;

	Vector temp = ((Curve)curveslist.elementAt(crve)).controlpoints;

	max = temp.size();

	for(int i = 0; i < max; i++){//check all controlpoints of the given curve

           ControlPoint pnt = (ControlPoint)(temp.elementAt(i));

           if (pnt.within(a,b)) {

               return new Point(crve,i);

           }

        }

        return new Point(-1,-1);

    }


    private Point findPoint(int a,int b){

	//Searches for a point by scanning every curve, using the method findPoint_on_curve

        int max = curveslist.size();

	Point search_pnt ;

	for(int i = 0; i < max; i++){//check all curves for the controlpoint that contains the given (a,b)

	  search_pnt = findPoint_on_curve(a, b, i);

	  if ( search_pnt.x >=0 ) return search_pnt;

	}			;

	return new Point(-1,-1);

     }



     private void joinAt( Vector f, int f_direct, int f_index, Vector s, int s_direct, int s_index, Curve firstcurve, Curve seccurve){

	/* this method join two controlpolygons,
	   according to a given direction we traverse the curves in a certain direction,
	   the new controlpolygon is created the first old polygon and
	   the second polygon are discarded.

	   input: 	vector f : the first controlpolygon
			int f_direct : the direction in which we have to traverse the first polygon
			int f_index : the index in the curveslist of the first curve (eases removal)

	   	 	vector s : the second controlpolygon
			int s_direct : the direction in which we have to traverse the second polygon
			int s_index : the index in the curveslist of the second curve (eases removal)

			Curve firstcurve, seccurve: a link to the associated curves
	*/

	// if direct = 1 , then the curve is traversed in ascending order


	Vector points;

	int max;

	if ( f_direct == 1 ) {points = (Vector)f.clone();}

	else { //first has to be traveresed in inverse order

	    max = f.size();

	    points = new Vector(max);

	    for (int i = max-1; i >= 0; i--){

		points.addElement((ControlPoint)f.elementAt(i)) ;};

	};

	max = (s.size()-1);

	if ( s_direct == 1 ){

	    for (int i = 1; i <= max; i++){

		points.addElement((ControlPoint)s.elementAt(i));};

	}

        else{

	    for (int i = (max-1); i >= 0; i--){

		points.addElement((ControlPoint)s.elementAt(i));};

	}

	Curve temp_curve = new Curve(points, firstcurve.polynom,firstcurve.generation_mode, firstcurve.parameterisation_mode , firstcurve.degree, firstcurve.color);

	temp_curve.additional_multiplicity = firstcurve.additional_multiplicity + seccurve.additional_multiplicity;

	temp_curve.setAdditionalMultiplicity( );

	temp_curve.CalculateDrawPoints();

	curveslist.addElement(temp_curve);

	curveslist.removeElementAt(f_index);

	curveslist.removeElementAt(s_index);

     }



     public void processMouseEvent(MouseEvent e){
	//handle all the mouse clicking events


        // How we handle a MOUSE_DOWN depends on the action mode
	if ( e.getID() == MouseEvent.MOUSE_PRESSED ){

            switch (action) {

              case ADD:

                // Add a new control point at the specified location, but first checks to see if the new point
		
		// was intended to coincide with an existing point. A new curve has to be announced first!

		// Current curve is not affected by add, since it had to be changed to the curve where one is 

		// adding the point to.

		preceding_point.move(-1,-1);

		first_curve = -1;

		if (cur_curve >= 0){//a curve was chosen

		  Curve temp_curve = ((Curve)curveslist.elementAt(cur_curve));

		  if (! temp_curve.closed ){//adding a point to a closed curve cannot be achieved by this function

			  int x = e.getX();

			  int y = e.getY();


			  Point search_point = findPoint(x,y);
		

			  if (search_point.x >= 0) {//the user clicked a valid point on the canvas, i.e. we found a match

			    point = (ControlPoint)(((Vector)(((Curve)(curveslist.elementAt(search_point.x))).controlpoints)).elementAt(search_point.y)) ;

			    x = point.x;

			    y = point.y;

			    search_point.move(-1,-1);

			  } 		  ;

			  //the new point is added
			  (temp_curve.controlpoints).addElement(new ControlPoint(x,y));

			  //calculate the new curve
			  temp_curve.CalculateDrawPoints();

			  repaint();

			  (Curvegeneration.cm).repaint();


		 }

		 else{	//choose insert with a closed curve !
		        WarningDialog d = new WarningDialog(CurveWindow.getFrame(this),language.remark, language.choose_insert_w);

			d.setBounds(150,150,350,150);

			d.show();
		 }

		}

		else {	//choose a curve !
		        WarningDialog d = new WarningDialog(CurveWindow.getFrame(this),language.remark, language.choose_curve_w);

			d.setBounds(150,150,300,150);

			d.show();
		}

                break;


              case AVANT:

                // Add a new control point at the specified location 

                // precursing the point first selected

                // ControlPoint pnt;

		// FIRST you have to select a curve !!!!
		first_curve = -1;
		

		if (cur_curve >= 0){//a curve was chosen

		  if ( preceding_point.y >=0 ) {//a following (!) point was chosen

		    cur_curve = preceding_point.x;

                    Curve tempcurve = ((Curve)curveslist.elementAt(cur_curve));

		    point = new ControlPoint(e.getX(), e.getY());

		    if ( tempcurve.closed && preceding_point.y == 0 )
			//the user wants to insert a point before the first controlpoint of a closed curve, but:
			//since the endpoints of a closed polygon both still exist(!) and that the find returns
			//the smallest index (for preceding_point.y==0) we have to insert the point before the last
			//controlpoint (which coincides with the first)

 			{(tempcurve.controlpoints).insertElementAt(point, ((tempcurve.controlpoints).size()-1));

		    }

		    else
			//insert into a open curve or not before the first point a closed curve
		    	(tempcurve.controlpoints).insertElementAt(point, preceding_point.y);

		    tempcurve.CalculateDrawPoints();

		    repaint();

		    preceding_point.move(-1,-1);

		  } 

		 else//the user first chooses a following(!) point

		    preceding_point = findPoint_on_curve(e.getX(), e.getY(), cur_curve);

		}

		else { WarningDialog d = new WarningDialog(CurveWindow.getFrame(this),language.remark, language.choose_curve_w);

			d.setBounds(150,150,300,150);

			d.show();

		};  

                break;

                  
              case MOVE:

                // Attempt to select the point at the location specified.

                // If there is no point at the location, findPoint returns

                // (-1,-1) (i.e. there is no point to be moved)

		first_curve = -1;

		preceding_point.move(-1,-1);


		if (cur_curve == -1){
		  /*so we have to move every instance on different curves of this point*/

		  int max = curveslist.size();

		  for ( int i = 0 ; i < max ; i++ ){//check all curves

			  search_point = findPoint_on_curve(e.getX(), e.getY(),i);

			  if (search_point.y >= 0 ) {//we found a match

			    //add to the list of point to be moved
			    curve_moving_curveslist.addElement(new Point(search_point.x, search_point.y));

			    //for a closed polygon, the last point also has to be moved in the first one does
	   	            if ( ((Curve)curveslist.elementAt(search_point.x)).closed && search_point.y == 0 )

		  	       curve_moving_curveslist.addElement(new Point(search_point.x, (((Curve)curveslist.elementAt(search_point.x)).controlpoints).size()-1 ));


			    search_point.move(-1,-1);

 			    original_pos = new ControlPoint(e.getX(), e.getY());

			  };

		  }

		}

		else{//we have to move only that controlpoints that belongs to the current curve

			  search_point = findPoint_on_curve(e.getX(), e.getY(), cur_curve) ;

			  int y = search_point.y;

			  if (y >= 0) {

			    Curve tempcurve = ((Curve)curveslist.elementAt(cur_curve));

			    Vector controlp = tempcurve.controlpoints;

			    ControlPoint point = (ControlPoint)controlp.elementAt(y);

			    int  y2 = 0;

			    while (y2 < controlp.size()   ){//we check all controlpoints to see if any coincide

			      if (point.Coincides((ControlPoint)controlp.elementAt(y2))  ){

	 			    curve_moving_curveslist.addElement(new Point(search_point.x,y2));

			      }

  			     y2++;

			    };

			  };

			  search_point.move(-1,-1);

			  original_pos = new ControlPoint(e.getX(), e.getY());

		};


                break;


              case DELETE:

                // Delete a point if one has been clicked

		// 
		first_curve = -1;

               	preceding_point.move(-1,-1);

		if (cur_curve == -1){
		  /*so we have to delete every instance of this point*/

		  int max = curveslist.size();

		  for ( int i = 0; i < max; i++ ){//check all curves

	   		  search_point = findPoint_on_curve(e.getX(), e.getY(), i);

			  if (search_point.y >= 0 ){//we found a matching point

			    Curve temp_curve = (Curve)curveslist.elementAt(search_point.x);

			    //a	closed curve gets opened if we delete the first point
                            if ( temp_curve.closed && search_point.y == 0 ) temp_curve.closed = false;

			    //we adapt the multiplicity of the curve to the loss of a possibly multiple controlpoint
			    int mult = ((ControlPoint)(temp_curve.controlpoints).elementAt(search_point.y)).multiplicity;

                            if (mult > 1) temp_curve.AddMultiplicity(-mult+1);

			    //remove point from the list
			    (temp_curve.controlpoints).removeElementAt(search_point.y);

			    if ( search_point.x == cur_point.x && search_point.y == cur_point.y ) cur_point.move(-1,-1);
			    temp_curve.CalculateDrawPoints();

			    search_point.move(-1,-1);

			  }

		  }

		}

		else {// only the instance of this point that belongs to the selected curve

		  search_point = findPoint_on_curve(e.getX(), e.getY(), cur_curve) ;


		  if (search_point.y >= 0){

			 Curve temp_curve = ((Curve) curveslist.elementAt(cur_curve));

			 //a closed curve gets opened
                         if ( temp_curve.closed && search_point.y == 0 ) temp_curve.closed = false;

		         //we adapt the multiplicity of the curve to the loss of a possibly multiple controlpoint
                	 int mult = ((ControlPoint)(temp_curve.controlpoints).elementAt(search_point.y)).multiplicity;

                         if (mult > 1) temp_curve.AddMultiplicity(-mult+1);

		         //remove point from the list
		    	 (temp_curve.controlpoints).removeElementAt(search_point.y);

   		         if ( search_point.x == cur_point.x && search_point.y == cur_point.y ) cur_point.move(-1,-1);

			 temp_curve.CalculateDrawPoints();

		  cur_curve = -1;

		  }

		}  
 

		original_pos = new ControlPoint(e.getX(), e.getY());

		repaint();

  	        search_point.move(-1,-1);

                break;


	    case NEW_CURVE:

	      // Begin the building of a new curve, with a set of its own controlpoints, the first point being the 

	      // location of mouse clicking

		int x = e.getX();

		int y = e.getY();

		first_curve = -1;

		preceding_point.move(-1,-1);

		//we check if it was intended that the first point of the new curve coincides with an existing controlpoint
		search_point = findPoint(x,y);

		cur_curve = curveslist.size();

		if (search_point.x >= 0) {//coincide !

		 point = (ControlPoint)(((Vector)((Curve)curveslist.elementAt(search_point.x)).controlpoints).elementAt(search_point.y)) ;

		 //set the coordinates exactly to those of the existing point
		 x = point.x;

		 y = point.y;

		 search_point.move(-1,-1);

		} ;

		//create new list of controlpoints
 		pointslist = new Vector(16,4);
		
		pointslist.addElement(new ControlPoint(x,y));

		//create new curve
		Curve temp_curve = new Curve(pointslist, mode.NewPolynom(),mode, param_mode, degree, mode.color);

		temp_curve.CalculateDrawPoints();

                curveslist.addElement(temp_curve);
 
                repaint();

		search_point.move(-1,-1);

		//activate the addition mode, since we suppose what is required
		setAction(ADD);

              break;


	    case MOVE_CURVE :
		// A whole curve is moved, ie current curve needs to be set

		first_curve = -1;

		preceding_point.move(-1,-1);

		if ( cur_curve >= 0  ){//a curve was chosen

		   int max = ((Vector)(((Curve)(curveslist.elementAt(cur_curve))).controlpoints)).size();

		   //building the list of all the controlpoint that have to be moved
		   for (int i = 0; i < max; i++ )	curve_moving_curveslist.addElement(new Point(cur_curve, i));

		   original_pos = new ControlPoint(e.getX(), e.getY());

		}

		else{WarningDialog d = new WarningDialog(CurveWindow.getFrame(this),language.remark, language.choose_curve_w);

			d.setBounds(150,150,300,150);

			d.show();
		};

		break;

	    case MOVE_ALL :
		//ALL the points get moved
		first_curve = -1;

		preceding_point.move(-1,-1);

		int max = curveslist.size();

		for ( int i = 0; i < max; i++ ){//all curves

			int max2 = ((Vector)(((Curve)(curveslist.elementAt(i))).controlpoints)).size() ;

			//all points
			for (int j = 0; j < max2; j++) curve_moving_curveslist.addElement(new Point(i,j));

			original_pos = new ControlPoint(e.getX(), e.getY());

                }

		break;

	    case DELETE_CURVE:
	      // The selected curve gets deleted, selection is done by clicking one of the controlpoints
	      

              first_curve = -1;

  	      preceding_point.move(-1,-1);

	      search_point = findPoint(e.getX(),e.getY());


	      if(search_point.x >= 0){//we found a matching controlpoint

		curveslist.removeElementAt(search_point.x);

 	        if ( search_point.x == cur_point.x ) cur_point.move(-1,-1);

		search_point.move(-1,-1);

		cur_curve = -1;

	      };

	      repaint();
	      
	      break;
	      




	    case SELECT_CURVE:
	      // Selection is done by clicking one of the controlpoints
	      // Deselection must be done likewise

	      first_curve = -1;

	      preceding_point.move(-1,-1);

	      search_point = findPoint(e.getX(),e.getY());

	      if(search_point.x >= 0){//we found a matching controlpoint
		
	        int temp = search_point.x;

                if ( cur_curve == temp ) { cur_curve = -1;} // The curve gets deselected

		else {cur_curve = temp; // The selected curves becomes the current curve

		      mode = ((Curve)curveslist.elementAt(cur_curve)).generation_mode;

		      (mode.cb).setState(true);
		};

	        search_point.move(-1,-1);

  	      };

	      repaint();
	      
	      (Curvegeneration.cm).repaint();

	      (Curvegeneration.pp).repaint();

	      (Curvegeneration.ap).repaint();

	      break;
	      

	    case CURVE_SPLIT:
	      // to split a polygon into 2

		first_curve = -1;

		preceding_point.move(-1,-1);

	      Vector temppointslist;

	      ControlPoint temppoint;

	      if ( cur_curve >= 0  ){ // The curve needs be selected

		     search_point = findPoint_on_curve(e.getX(), e.getY(), cur_curve);

		     if (search_point.x >= 0 ){//the user indicated a valid controlpoint, belonging to the current curve
					       //where he/she wants to split the polygon

			Curve tempcurve = (Curve)(curveslist.elementAt(cur_curve));

			pointslist = tempcurve.controlpoints;

			max = pointslist.size();

			if ( tempcurve.closed ){

				if (search_point.y != 0 && search_point.y != max-1){
				      // then we're splitting the polygon at a controlpoint that was fomerly not the first or last point,
				      //so now we have to change the numbering of the conrolpolygon, the controlpoint
				      //where the split takes places now becomes the first controlpoint !

				      pointslist.removeElementAt(max-1);

				      for ( int i = 0; i < search_point.y  ; i++ ){

        				  temppoint = (ControlPoint)(pointslist.firstElement());

        				  pointslist.removeElementAt(0);

					  pointslist.addElement(temppoint);

				      }

	 			      temppoint = ((ControlPoint)(pointslist.firstElement())).Clone();

  				      pointslist.addElement(temppoint);

			        }

			       //reposition one of the former coinciding points, so it can be manipulated
                               ((ControlPoint)(pointslist.lastElement())).y += (int)2*ControlPoint.PT_SIZE;

			       //the curve is open now
			       tempcurve.closed = false;

			       //check the multiplicity
			       tempcurve.setAdditionalMultiplicity( );

			       tempcurve.CalculateDrawPoints();

			}

			else {
				//new curve 1
	         		temppointslist = new Vector(16,4);

				for ( int i = 0 ;i < search_point.y ; i++ ){//split the list of controlpoints

					temppoint = (ControlPoint)((pointslist).elementAt(i));

					temppointslist.addElement(temppoint);

				}

  			//We have to create a new controlpoint to duplicate the coincident point, the second
			// curve gets the original
				temppoint =((ControlPoint)((pointslist).elementAt(search_point.y))).Clone();

				temppoint.y += (int)2*ControlPoint.PT_SIZE ;

				temppointslist.addElement(temppoint);

				//create a new curve which contains the first halve of the list of controlpoints
				temp_curve = new Curve(temppointslist, tempcurve.polynom,tempcurve.generation_mode, tempcurve.parameterisation_mode, tempcurve.degree, tempcurve.color );

				temp_curve.setAdditionalMultiplicity( );

				temp_curve.CalculateDrawPoints();

		                curveslist.addElement(temp_curve);

				//new curve 2
        	 		temppointslist = new Vector(16,4);

				for ( int i = search_point.y ;i <  max; i++ ){//the second halve of controlpoints

					temppoint = (ControlPoint)((pointslist).elementAt(i));

					temppointslist.addElement(temppoint);

				}

				temp_curve = new Curve(temppointslist, tempcurve.polynom,tempcurve.generation_mode, tempcurve.parameterisation_mode, tempcurve.degree, tempcurve.color );

		                curveslist.addElement(temp_curve);

				curveslist.removeElementAt(cur_curve);

				temp_curve.setAdditionalMultiplicity( );

				temp_curve.CalculateDrawPoints();


				cur_point.move(-1,-1);

				cur_curve = -1;



			}

			repaint();


		     }

	      }

	      else{WarningDialog d = new WarningDialog(CurveWindow.getFrame(this),language.remark, language.choose_curve_w);

			d.setBounds(150,150,300,150);

			d.show();
	      }

	      break;

	    case CURVE_JOIN:
	      // at the common point the two curves(polygons) get joined together

		preceding_point.move(-1,-1);

		if (cur_curve >=0 ){//a curve was chosen to be the first

                int punt= findPoint(e.getX(),e.getY()).x;

		  if (punt >= 0  ) {//a valid point was chosen

		       Curve firstcurve = (Curve)(curveslist.elementAt(cur_curve));

		       Vector frst = firstcurve.controlpoints;

			if ( punt == cur_curve && ((ControlPoint)frst.firstElement()).Coincides((ControlPoint)frst.lastElement()) ){

				// So we're closing the polygon upon itself

				((ControlPoint)frst.lastElement()).x = ((ControlPoint)frst.firstElement()).x;

				((ControlPoint)frst.lastElement()).y = ((ControlPoint)frst.firstElement()).y;

				((ControlPoint)frst.lastElement()).multiplicity = 1;

				((ControlPoint)frst.firstElement()).multiplicity = 1;

				((ControlPoint)frst.lastElement()).weight = ((ControlPoint)frst.firstElement()).weight;

				firstcurve.closed = true;

				firstcurve.setAdditionalMultiplicity( );

				firstcurve.CalculateDrawPoints();

		        }


     		        else if (punt != cur_curve){

			       // So we're really joining two polygons

			       Curve secondcurve = (Curve)(curveslist.elementAt(punt));

			       Vector second = secondcurve.controlpoints;

			       //we now check which of the two extremes of the two curves coincide and call on the
			       //joining function 'joinAt'
			       if (((ControlPoint)frst.firstElement()).Coincides((ControlPoint)second.firstElement())){

				   joinAt(frst, 0,cur_curve, second, 1, punt,firstcurve,secondcurve);

			       }else if(((ControlPoint)frst.firstElement()).Coincides((ControlPoint)second.lastElement())){

				   joinAt(frst, 0,cur_curve, second, 0, punt,firstcurve,secondcurve);

			       }else if(((ControlPoint)frst.lastElement()).Coincides((ControlPoint)second.firstElement())){

				   joinAt(frst, 1,cur_curve, second, 1, punt, firstcurve,secondcurve);

			       }else if(((ControlPoint)frst.lastElement()).Coincides((ControlPoint)second.lastElement())){

				   joinAt(frst, 1,cur_curve, second, 0, punt, firstcurve,secondcurve);

			       }else{WarningDialog d = new WarningDialog(CurveWindow.getFrame(this),language.remark, language.common_point_w);

				   d.setBounds(150,150,300,150);

				   d.show();

			       };

	 		       cur_curve = -1;


		    cur_point.move(-1,-1);

		        }else{WarningDialog d = new WarningDialog(CurveWindow.getFrame(this),language.remark, language.another_curve_w);

                               d.setBounds(150,150,350,150);

			       d.show();

			}


		  }



                    repaint();




		}
		else{WarningDialog d = new WarningDialog(CurveWindow.getFrame(this),language.remark, language.choose_curve_w);

			d.setBounds(150,150,300,150);

			d.show();

		}
	      break;
	      
	      case COPY_CURVE:
		//makes a copy of the curve, and places it a little further,
		//of course first a curve needs be selected

		first_curve = -1;

		preceding_point.move(-1,-1);

		if ( cur_curve !=-1 ){

			temp_curve = (Curve)(curveslist.elementAt(cur_curve));

			Vector temp_list =(Vector)(((Vector)(temp_curve.controlpoints)).clone());

  			max = temp_list.size();

    			Vector new_list = new Vector(max);

		      original_pos = new ControlPoint (((ControlPoint)(temp_list.elementAt(0))).x, ((ControlPoint)(temp_list.elementAt(0))).y);

		      int  distance[] = new int[2];

		      distance[0] = e.getX() - original_pos.x;

		      distance[1] = e.getY() - original_pos.y;

      		      for (int i = 0; i < max; i++){

			ControlPoint temppnt = ((ControlPoint)(temp_list.elementAt(i)));

	       	        ControlPoint point = new ControlPoint (temppnt.x, temppnt.y,temppnt.weight,temppnt.multiplicity);

        	        point.x +=distance[0];

	                point.y += distance[1];

			new_list.addElement(point);

		      }

		      Curve temp_curve2 = new Curve(new_list, (temp_curve.polynom).Clone(),temp_curve.generation_mode, temp_curve.parameterisation_mode, temp_curve.degree, temp_curve.color);

		      temp_curve2.closed = temp_curve.closed;

		      temp_curve2.additional_multiplicity = temp_curve.additional_multiplicity;

		      temp_curve2.CalculateDrawPoints();

	     	      curveslist.addElement(temp_curve2);


		      repaint();

	       }

	       else{WarningDialog d = new WarningDialog(CurveWindow.getFrame(this),language.remark, language.choose_curve_w);

			d.setBounds(150,150,300,150);

			d.show();

	       };

	      break;

	    case SELECT_POINT:

	      // Selection is done by clicking one of the controlpoints
	      // Deselection must be done likewise

	      first_curve = -1;

	      preceding_point.move(-1,-1);

	      search_point = findPoint(e.getX(),e.getY());

	      if(search_point.x >= 0){
		
                if ( cur_point.x == search_point.x && cur_point.y == search_point.y) { cur_point.move(-1,-1);} // The point gets deselected

		else{

		     cur_point.move(search_point.x,search_point.y); // The selected point becomes the current point

		};

	        search_point.move(-1,-1);

	      };


	      repaint();
	      
	      (Curvegeneration.pp).repaint();

	      break;

	      //This next case was included, should the additional functionality ever need info about the
	      //input made on the canvas !!!!!!
	      case ADD_FUNC:

				addf.MousePressed(this.mode.index, e.getX(), e.getY());

	      break;

              default:

                throw new IllegalArgumentException();

            }

	}

     else if (e.getID() == MouseEvent.MOUSE_RELEASED){

            // We only care about MOUSE_UP's if we've been moving control

            // points.  If so, drop the control points.

	switch ( action ){

	 case MOVE:

	 case MOVE_CURVE:

	 case MOVE_ALL:

            if (!curve_moving_curveslist.isEmpty()) {

                    curve_moving_curveslist.removeAllElements();

		    if ( action == MOVE ){

			    search_point.move(-1,-1);

		    }

		draw_Curves = true;// Now we draw the curves again

                repaint();

            };


       	    break;

      //This next case was included, should the additional functionality ever need info about the
      //input made on the canvas !!!!!!
    case ADD_FUNC:

          addf.MouseReleased(this.mode.index, e.getX(), e.getY());

     break;

     }

     if (preceding_point.y >= 0){

                  repaint();

     };

    (Curvegeneration.pp).repaint();

    }

    }



    public void processMouseMotionEvent(MouseEvent e){
     //handle the mouse motion events

     if ( e.getID() == MouseEvent.MOUSE_DRAGGED ){
            // We only care about MOUSE_DRAG's while we are moving  control

            // points.  Otherwise, do nothing.


            if (!curve_moving_curveslist.isEmpty()) {//we have to move controlpoints

		      int  distance[] = new int[2];

		      distance[0] = e.getX() - original_pos.x;

		      distance[1] = e.getY() - original_pos.y;

	      int oldcurve = -1;

	      for (int i = 0; i < curve_moving_curveslist.size(); i++){//move all the points

		Point temp = (Point) curve_moving_curveslist.elementAt(i);

		Curve temp_curve = (Curve) (curveslist.elementAt(temp.x));

                ControlPoint pnt =(ControlPoint) (((Vector)(temp_curve).controlpoints).elementAt(temp.y));

                pnt.x += distance[0];

                pnt.y += distance[1];

		if ( oldcurve != temp.x ){//a new curve is being handled

			if ( action == MOVE){

				temp_curve.CalculateDrawPoints();

			}

			else if (action == MOVE_ALL || action == MOVE_CURVE){

				temp_curve.MoveDrawPoints(distance);//also move the drawing points

		        }

		oldcurve = temp.x;

		}

		draw_Curves = draw_movingCurves;// To speed up the drawing process we may not draw the curves whilest moving one

                repaint();

	      }	

		original_pos = new ControlPoint(e.getX(), e.getY());

                repaint();

            }


     //This next case was included, should the additional functionality ever need info about the
     //input made on the canvas !!!!!!
     if (action == ADD_FUNC){

          addf.MouseDragged(this.mode.index, e.getX(), e.getY());

     }


     };
   

    }



    public void paint(Graphics g) {
    /* the method that draws the controlpoints,polygons, curves,.. */

    try {

	setSize(size,size);

        g.setColor(getForeground());

        g.setPaintMode();

        // draw a border around the canvas

	g.setColor(Color.blue);

        g.setPaintMode();


	int nc;
	
	int np;

	Vector tempvect;

        // draw the control points
	if ( draw_ControlPoints ){

		nc = curveslist.size();

		for (int c = 0; c < nc; c++ ) {//all the polygons

		  if ( c == cur_curve ) g.setColor(Color.red); // The current curve gets a different color

		  Curve tempcurve = ((Curve)curveslist.elementAt(c));

		  tempvect = tempcurve.controlpoints;

		  np = tempvect.size();

		  boolean weightable = (tempcurve.generation_mode).point_weights_functional;

		  for (int i = 0; i < np; i++) {//draw all the controlpoints of the polygon

        	    ControlPoint p = (ControlPoint)(tempvect.elementAt(i));

		    if ( cur_point.x == c && cur_point.y == i ){

			    Color temp_color = g.getColor();

		            g.setColor(Color.green);

                            if (!(tempcurve.closed && i == np-1)){//the coinciding controlpoints, only get one numbering

		            	g.drawRect(p.x-p.PT_SIZE, p.y-p.PT_SIZE, p.PT_SIZE*2, p.PT_SIZE*2);

        		    	if (i==0){g.drawString(String.valueOf(c)+"."+String.valueOf(i),p.x+p.PT_SIZE,p.y-p.PT_SIZE);}
        		    	else g.drawString(String.valueOf(i),p.x+p.PT_SIZE,p.y-p.PT_SIZE);

			    }

			    g.setColor(temp_color);

		    }

		    else{

        	            if (p.multiplicity >1 ) {g.fillRect(p.x-p.PT_SIZE, p.y-p.PT_SIZE, p.PT_SIZE*2, p.PT_SIZE*2);}

        	            if ( weightable && p.weight != 1) {

				        g.fillOval(p.x-p.PT_SIZE, p.y-p.PT_SIZE, p.PT_SIZE*2, p.PT_SIZE*2);}


			    else {if (!(tempcurve.closed && i == np-1))g.drawRect(p.x-p.PT_SIZE, p.y-p.PT_SIZE, p.PT_SIZE*2, p.PT_SIZE*2);} ;

        		    if (!(tempcurve.closed && i == np-1))
			        if (i==0){g.drawString(String.valueOf(c)+"."+String.valueOf(i),p.x+p.PT_SIZE,p.y-p.PT_SIZE);}
        		    	else g.drawString(String.valueOf(i),p.x+p.PT_SIZE,p.y-p.PT_SIZE);
;

		    }

		  }

		 g.setColor(Color.blue);

		}
        

        	if (preceding_point.y >= 0){//indicate the special character the following point

	            ControlPoint p = (ControlPoint)((((Curve)(curveslist.elementAt(preceding_point.x))).controlpoints).elementAt(preceding_point.y));

		    g.setColor(Color.black);

        	    g.fillRect(p.x-p.PT_SIZE, p.y-p.PT_SIZE, p.PT_SIZE*2, p.PT_SIZE*2);

		    g.setColor(Color.blue);

	        }
	}

        // draw the control polygon

	if ( draw_Polygone){

		nc = curveslist.size();

		for (int c = 0; c < nc; c++ ) {

		  if (c == cur_curve) g.setColor(Color.red); // The current curve's knots get a different color

		  tempvect = ((Curve)curveslist.elementAt(c)).controlpoints;

		  np = tempvect.size();

		  if (np >= 0){

		    for (int i=0; i < np-1; i++) {

		      ControlPoint p = (ControlPoint)(tempvect.elementAt(i));

		      ControlPoint p2 = (ControlPoint)(tempvect.elementAt(i+1));
	    
		      g.drawLine(p.x, p.y, p2.x, p2.y);

	            }

        	  }

		g.setColor(Color.blue);

		}
     	}


	//draw the curves
	if ( draw_Curves ){

		int max = curveslist.size();


		for (int i = 0; i < max; i++ ){//draw all curves

		       Curve tempcurve =(Curve)(curveslist.elementAt(i));

		       int drawpoint[][] = tempcurve.drawingpoints ;

		       g.setColor(tempcurve.color);

		       g.setPaintMode();

		       int mx = drawpoint[0].length-1;

		       for ( int j = 0; j < mx ; j++ ){

		       		g.drawLine(drawpoint[0][j],drawpoint[1][j],drawpoint[0][j+1], drawpoint[1][j+1]);

		       }

		       int cspoint[][] = tempcurve.curvesegmentpoints;

		       if ( draw_CurveSegments && cspoint[0][0] > 0){

			int ns = cspoint[0].length;

			int xcoor[] = new int[3];

			int ycoor[] = new int[3];



			for (int j = 0; j < ns; j++  ){


			 xcoor[1] = cspoint[0][j]; ycoor[1] = cspoint[1][j];

			 xcoor[0] = xcoor[1]-5; ycoor[0] = ycoor[1] -5;

			 xcoor[2] = xcoor[1]+5; ycoor[2] = ycoor[1]-5;

			 g.setPaintMode();

			 g.setColor(Color.red);

			 g.fillPolygon(xcoor,ycoor,3);

			 g.setColor(Color.black);


			}


		       }

		}

	}//end if draw_Curves

     }//end try block

     catch (Exception ex){};

   }//end paint

}// end class


