import display.*;

//The class that the students will fill up with the correct algorithm.

public class Bresenham {

    /*
      Inputs: x1, y1, x2 and y2 -- the endpoints of the line. The line
				   stretches from (x1, y1) to (x2, y2)
              Grid view         -- an object representing the display

      Outputs: none, just draw the line

      Something useful: in order to draw the line, you must set a
	 	 	series of individual pixels. You can do this
	 	 	by making a call to the setPixel method of the
	 	 	Grid object. In other words, the command
	 	 	         view.setPixel(3,4); 
			would turn the pixel at position (3, 4) black.


      NOTE: If you want to have any auxiliary methods (helpers), you
	    must make sure to declare them "static" as well.

     */
    public static void BresenhamAlgorithm(int x1, int y1, 
					  int x2, int y2, Grid view) {

	// ***** YOUR CODE HERE *****

	// faster, two for loops
	int dx, dy, e, x, xr, y, xinc, yinc, flip, x1t, x2t, y1t, y2t;
	dx = x2 - x1;
	dy = y2 - y1;
	e = 0;
	yinc = 1;
	if ((dx > 0 ? dx : -dx) >= (dy > 0 ? dy : -dy)) {
	    x1t = x1;
	    x2t = x2;
	    y1t = y1;
	    y2t = y2;
	    flip = 0;
	}
	else {
	    int temp;
	    temp = dx;
	    dx = dy;
	    dy = temp;
	    x1t = y1;
	    x2t = y2;
	    y1t = x1;
	    y2t = x2;
	    flip = 1;
	}
	if (x1t <= x2t)
	    xinc = 1;
	else {
	    dx = -dx;
	    xinc = -1;
	}
	if (y1t < y2t) {
	    dy = dy * 2;
	}
	else {
	    dy = dy * -2;
	    yinc = -yinc;
	}
	if (flip == 0) {
	    for (x = x1t, y = y1t; x != x2t ; x = x + xinc) {
		if (e > dx) {
		    e = e - dx - dx;
		    y = y + yinc;
		}
		e = e + dy;
		view.setPixel(x, y);
	    }
	}
	else {
	    for (x = x1t, y = y1t; x != x2t ; x = x + xinc) {
		if (e > dx) {
		    e = e - dx - dx;
		    y = y + yinc;
		}
		e = e + dy;
		view.setPixel(y, x);
	    }
	}
	view.setPixel(x2, y2);
	

	// slower, one for loop though
	/*
	int dx, dy, e, x, xr, y, xinc, yinc, flip, x1t, x2t, y1t, y2t;
	dx = x2 - x1;
	dy = y2 - y1;
	e = 0;
	yinc = 1;
	if ((dx > 0 ? dx : -dx) >= (dy > 0 ? dy : -dy)) {
	    x1t = x1;
	    x2t = x2;
	    y1t = y1;
	    y2t = y2;
	    flip = 0;
	}
	else {
	    int temp;
	    temp = dx;
	    dx = dy;
	    dy = temp;
	    x1t = y1;
	    x2t = y2;
	    y1t = x1;
	    y2t = x2;
	    flip = 1;
	}
	if (x1t <= x2t)
	    xinc = 1;
	else {
	    dx = -dx;
	    xinc = -1;
	}
	if (y1t < y2t) {
	    dy = dy * 2;
	}
	else {
	    dy = dy * -2;
	    yinc = -yinc;
	}
	for (x = x1t, y = y1t; x != x2t ; x = x + xinc) {
	    if (e > dx) {
		e = e - dx - dx;
		y = y + yinc;
	    }
	    e = e + dy;
	    if (flip == 0)
		view.setPixel(x, y);
	    else
		view.setPixel(y, x);
	}
	view.setPixel(x2, y2);
	*/
    }
}





