//Vladimir Tenev
//PIC 10A
//January 27, 2009
//Draws regression line from a bunch of user-generated points

#include "ccc_win.h"

int ccc_win_main()
{
	int count=0; // keeps track of number of points 
	Point p; //create point for storing where user clicks
	double sumx=0, sumy=0, sumxsquared=0,sumxy=0; //keeps track of relevant variables to compute slope 
	cwin << Line(Point(9,-9),Point(9,-10)) << Line(Point(9,-9),Point(10,-9)); //draw stopping box in lower right corner
	cwin << Message(Point(9,-9),"Stop"); //label the stopping box
	while(1) //infinite loop (1 means true)
	{
		p = cwin.get_mouse("Click anywhere"); //prompt user for mouseclick, stores the point in p
		if(p.get_x()>=9 && p.get_y()<=-9) //check if user clicked on stopping box, and if so break out of loop
			break;
		cwin << p; //display point user clicked on 
		count++; //update number of points
		sumx+=p.get_x(); //update sum of x coordinates
		sumy+=p.get_y(); //update sum of y coordinates
		sumxsquared+=p.get_x()*p.get_x(); //update sum of x^2
		sumxy+=p.get_x()*p.get_y(); //update sum of xy
	}
	if(count>0) //check to prevent division by zero
	{
		double meanx = sumx/count; //compute average of x coordinates
		double meany = sumy/count; //compute average of y coordinates
		double slope = (sumxy-count*meanx*meany)/(sumxsquared-count*meanx*meanx); //compute slope of line
		double lefty = meany - slope*(10+meanx); //compute y coordinate of left endpoint of line on the screen (corresponding to x-coordinate is -10)
		double righty = meany + slope*(10-meanx);// compute y coordinate of right endpoint of line on the screen (corresponding to x-coordinate is 10)
		cwin << Line(Point(-10,lefty),Point(10,righty)); //draw the regression line
	}
	return 0;
}
