#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>

GLfloat xRight, xLeft, yUp, yDown;
GLfloat p1[2], p2[2];
GLfloat cp1[2], cp[2];

void myInit () {
	
	glClearColor (1.0, 1.0, 1.0, 1.0);
	
	glMatrixMode (GL_PROJECTION);
	glLoadIdentity();
	glOrtho (-200.0, 200.0, -200.0, 200.0, -200.0, 200.0);
	glMatrixMode (GL_MODELVIEW);
}

void display () {
	
	glClear (GL_COLOR_BUFFER_BIT);
	int wW, wH;
	
	/* draw the original line in red */
	glColor3f (1.0, 0.0, 0.0);
	glBegin (GL_LINES);
		glVertex2fv (p1);
		glVertex2fv (p2);
	glEnd();
	
	/* show the clipping window */
	glColor3f (0.0, 0.0, 0.0);
	glBegin (GL_LINE_LOOP);
		glVertex2f (xRight, yUp);
		glVertex2f (xLeft, yUp);
		glVertex2f (xLeft, yDown);
		glVertex2f (xRight, yDown);
	glEnd();

	glEnable (GL_SCISSOR_TEST);

	/* convert xLeft, xRight, yUp and yDown to window co-ordinates */
	glScissor (xLeft+200, yDown+200, xRight-xLeft, yUp-yDown);
	
	/* draw the clipped line in blue */
	glLineWidth (2);
	glColor3f (0.0, 0.0, 1.0);
	glBegin (GL_LINES);
	glVertex2fv (p1);
	glVertex2fv (p2);
	glEnd();
	glLineWidth (1);
	glDisable (GL_SCISSOR_TEST);
	glFlush();
}

void reshape (int x, int y) {
	
	glViewport (0, 0, 400, 400);
	/* if the viewport changes, scissor will not work properly.
	scissor is based on window co-ordinates and not world co-ordinates */
}

int main (int argc, char *argv[]) {
	
	printf ("Enter xLeft, xRight, yUp, yDown: ");
	scanf ("%f%f%f%f", &xLeft, &xRight, &yUp, &yDown);
	
	printf ("Enter p1 (x, y): ");
	scanf ("%f%f", &p1[0], &p1[1]);
	printf ("Enter p2 (x, y): ");
	scanf ("%f%f", &p2[0], &p2[1]);
	
	glutInit (&argc, argv);
	glutInitDisplayMode (GLUT_RGB | GLUT_SINGLE);
	glutCreateWindow ("Clipping");
	glutDisplayFunc (display);
	glutReshapeFunc (reshape);
	glutReshapeWindow (400, 400);
	myInit();
	glutMainLoop();
	
	return 0;
}


