             /*

      Nosayba A.Abdullah

             */


#include<gl/glut.h>
#include<math.h>
#include<iostream.h>
#include <windows.h>

const int maxSize   = 20;
int screenHeight=480;
static int numCorners = 0; // initial value is 0

class Point2   //single point w/ floating point coordinates
{
public:
	Point2() {x = y =  0.0f;} //constructor 1
	Point2(float xx, float yy ) {x=xx; y=yy; } //constructor 2
	void setX (float xx) {x=xx;  }
   void setY( float yy) {y=yy; }
	float getX() {return x;}
	float getY() {return y;}



	void draw(void)
	{
		glBegin(GL_POINTS); //draw this point
			glVertex2f((GLfloat)x, (GLfloat)y); //type casting from float to glfloat..the different between them is system dependand
		glEnd();
	}
private:
	float x, y;
};

Point2 pt2[maxSize];

void drawDot(int x, int y){


glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
glFlush();

}

void drawLine(Point2 a, Point2 b){

glBegin(GL_LINES);
glVertex2i(a.getX(),a.getY());
glVertex2i(b.getX(),b.getY());
glEnd();
glFlush();

}




Point2  bezCurve(float t,Point2 a[] ){
 //compute a point on the cuve with a value of t
 
 for(int i=0;i<=numCorners;i++){
  for(int j=0;j<numCorners-i;j++){
   a[j]=a[j]*(1-t)+a[j+1]*t;

  }
  return a[i];
 }

 // Point2 pt;
  //pt.setX ( pow((1- t),2)*a.getX() + 2*t * (1- t)* b.getX() + pow(t,2)*c.getX());

  //pt.setY ( pow((1- t),2)*a.getY() + 2*t * (1- t)* b.getY() + pow(t,2)*c.getY()) ;
 // return a[];

}







void myMouse(int button, int state, int x, int y) {



if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{

pt2[numCorners].setX((float)x);
pt2[numCorners].setY((float)( screenHeight-y));

numCorners++; // have another point

drawDot(x, screenHeight-y);
 glutPostRedisplay();
}
else if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)

glClear(GL_COLOR_BUFFER_BIT); // clear the window


glFlush();
}


void myDisplay(){
        if(numCorners == maxSize){

 glColor3f(rand()/32767.0,rand()/32767.0,rand()/32767.0);

 for(int i=0;i<numCorners;i++){
  drawLine(pt2[i],pt2[i+1]);
 }
//drawLine(pt2[0],pt2[1]);
//drawLine(pt2[1],pt2[2]);
Point2 firstPoint=pt2[0];

for(float t=0.0;t<= 1.0; t+=0.1){

Point2 P ;
P= bezCurve(t,pt2);
drawLine(firstPoint, P);
firstPoint=P;

}
numCorners = 0; // back to 0 corners

}

 }

int main(int argc, char **argv)
{

 	glutInit(&argc, argv);
 	glutInitDisplayMode ( GLUT_SINGLE | GLUT_RGB );

 	glutInitWindowPosition(100,100);
 	glutInitWindowSize(640,480);
 	glutCreateWindow ("Draw Bezier Curve");
 	gluOrtho2D(0,640,0,480);
 	glClearColor(0.9, 0.9, 1.0, 0.0);
   glPointSize(4.0);
   glutDisplayFunc(myDisplay);
   glutMouseFunc(myMouse);
   glutMainLoop();
   return 0;
}