import easel.* ;
import java.util.Random ;

public class MidpointLine implements Algorithm2D{

	public static int Round( double a )
	{
		return (int) Math.round(a) ; // Math.round returns (long)
	}

	public static void MidpointLineDraw( double x0, double y0, double x1, double y1, int red, int green, int blue){

		// make sure that x0 < x1 so in octant 1, 2, 7, 8
		if( x0 > x1 ) {
			double xt = x0 ; x0 = x1 ; x1 = xt ;
			double yt = y0 ; y0 = y1 ; y1 = yt ;
		}
		
		// setup line variables for k=ax+by+c
		double a = y1 - y0;
		double b = x0 - x1;
		double c = x1*y0 - y1*x0;

		// first octant
		if( a > 0 ) { // octant 1 or 2
			if( a < -b ) { // octant 1
				int x = Round(x0) ;
				int y = Round(( -a * ((double) x) - c ) / b) ;
				double d = a * (x+1) + b * (y+0.5) + c ;

				while ( x <= Round(x1) ) {
					Renderer.setPixel(x,y,red, green, blue);
					if ( d < 0 ) {
						d = d + a;
					}
					else {
						y = y + 1;
						d = d + a + b;
					}
					x = x + 1;
				}
			}
			else { // octant 2
				int y = Round(y0) ;
				int x = Round(( -b * ((double) y) - c ) / a) ;
				double d = a * (x+0.5) + b * (y+1) + c ;
				while ( y <= Round(y1) ) {
					Renderer.setPixel(x, y, red, green, blue);
					if ( d > 0 ) {
						d = d + b;
					}
					else {
						x = x + 1;
						d = d + a + b;
					}
					y = y + 1;
				}
			}
		}
		else { // octant 7 or 8
			if( a > b ) { // octant 8
				int x = Round(x0) ;
				int y = Round(( -a * ((double) x) - c ) / b)  ;
				double d = a * (x+1) + b * (y-0.5) + c ;

				while ( x <= Round(x1) ) {
					Renderer.setPixel(x,y,red, green, blue);
					if ( d > 0 ) {
						d = d + a;
					}
					else {
						y = y - 1;
						d = d + a - b;
					}
					x = x + 1;
				}
			}
			else { // octant 7
				int y = Round(y0) ;
				int x = Round(( -b * ((double) y) - c ) / a) ;
				double d = a * (x+0.5) + b * (y-1) + c ;
				while ( y >= Round(y1) ) {
					Renderer.setPixel(x, y, red, green, blue);
					if ( d < 0 ) {
						d = d - b;
					}
					else {
						x = x + 1;
						d = d + a - b;
					}
					y = y - 1;
				}
			}
		}
	}

	public void runAlgorithm( int width, int height ) {

		for( int i = 0 ; i < 64 ; i++ ) {
			double x0 = new Random().nextDouble() * (width-1);
			double y0 = new Random().nextDouble() * (height-1);
			double x1 = new Random().nextDouble() * (width-1);
			double y1 = new Random().nextDouble() * (height-1);
			int red = i > 32  ? (i-32) * 7 : 0 ;
			int gre = i < 32  ? (32-i) * 7 : 0 ;
			int blu = i < 32 ? i * 7 : ( 64 - i ) * 7 ;
			MidpointLineDraw( x0, y0, x1, y1, red, gre, blu);
		}
	}
	
	public static void main( String[] args ) {
		System.out.println( "Hello" );
		Renderer.init2D( 40, 30, new MidpointLine() );
	}
}