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) {



    /*
*******************NOTE**************NOTE*****************
My algorithm does not act in the same way as the one given in class
for all 8 octants, but I feel the one in class is more incorrect since the
same line drawn from 2 directions end up to be different lines in pixels
It also does not have a reflective property, that is, if you draw one line and
reflect it over an axis, it may not be the same line.

For this reason, I left my code as it is, differing from the class code.
I feel my way is just intuitive if not more intuitive.
Also, these are errors from p being 0, and in this case, you could really do
anything you want, there is really no rule, but just an implemenation choice
where you want to go when p is 0.
    **********************************************************/


      
    int dx = Math.abs(x2-x1);
    int dy = Math.abs(y2-y1);
    boolean slope_greater_than_one = false;
    int y_inc;


    if( (((y2-y1) > 0) && ((x2-x1) > 0)) || (((y2-y1) < 0) && ((x2-x1) < 0)) ) 
    {
      y_inc = 1;
    }
    else
    {
      y_inc = -1;
    }

    if(dx < dy)
    {
      int temp = x1;
      x1 = y1;
      y1 = temp;
      temp = x2;
      x2 = y2;;
      y2 = temp;
      slope_greater_than_one = true;
      dx = Math.abs(x2-x1);
      dy = Math.abs(y2-y1);
    }

      
      
    int p = (2*dy) - dx;
    int twoDy = (2 * dy);
    int twoDyDx = (2 * (dy - dx));

    int x, y, xEnd;

      
    if(x1 > x2)
    {
      x = x2;
      y = y2;
      xEnd = x1;
    }
    else
    {
      x = x1;
      y = y1;
      xEnd = x2;
    }

    if(slope_greater_than_one)
    {
      view.setPixel(y, x);
    }
    else
    {
      view.setPixel(x, y);
    }
       

    while(x < xEnd)
    {
      x++;
    
      if(p <= 0)
      {
	p = p + twoDy;
      }
      else
      {
	y += y_inc;
	p += twoDyDx; 
      }
    	
      //      System.out.println("p="+p+" y="+y+" x="+x);

      if(slope_greater_than_one)
      {
	view.setPixel(y, x);
      }
      else
      {
	view.setPixel(x, y);
      }
    }
      
      
      
    //For debugging:
    System.out.println("Entering BresenhamAlgorithm");

  }
}





