/*
	scatterRegress applet takes pairs of numbers from a HTML
	TEXTAREA FORM field, and computes Means and R square
	Version 1.0 - 26 Oct 1999 Chris Thiel <cct@ktb.net>
	
	This allows for use to dynamically show/hide Regression line & r^2,
	Change the x and y axis values.
	
	Next Version: Label x and Y axis
			
*/

import java.lang.*;
import java.awt.*;
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Event;
import java.util.*;

public class scatterRegress extends Applet
{
	int MAX=50;
	int MARGIN=30;
	int n=0;
	String userInput=null;
	String s=null;
	String message=null;
	float x[] = new float[MAX];
	float y[] = new float[MAX];
	float xMean, yMean;
    float B0, B1, R_square,Var_x,Var_y;
	float xMin, yMin, xMax,yMax;
	int xM,yM,i=0;
	double w,h, xFactor, yFactor;
	boolean autoRange=true;
	boolean showLine=true;
	boolean showFormula=true;
	
/*
	Compute is the routine called to compute the Statistical Data
*/	

	public void  compute(){
	// Now calculate regression coeffecients
    	float Sx = 0, Sy =0;
    	float Sxx = 0, Sxy = 0, Syy = 0;
    	 w=(double)(size().width)-2*MARGIN;
    	 h=(double)(size().height)-2*MARGIN;
		// first see if axes' range will be based on data or not 
		if (autoRange) {
			xMin = (999999);
			yMin = (999999);
			xMax = (-999999);
			yMax = (-999999);
			for (int i=0; i<n; i++){
				if (x[i]<xMin) xMin=x[i];
    			if (x[i]>xMax) xMax=x[i];
    			if (y[i]<yMin) yMin=y[i];
    			if (y[i]>yMax) yMax=y[i];
			}
		}
    	for(int i=0; i< n; i++)
    	{
    		
      		Sx += x[i]; 
      		Sy += y[i];
    	}
    	xFactor= (w-10.0)/(xMax-xMin);
    	yFactor= (h-10.0)/(yMax-yMin);
    	xMean = Sx / n;
    	yMean = Sy / n;
    	for(int i=0; i< n; i++)
    	{
      		Sxx += (x[i]-xMean) * (x[i]-xMean);
      		Sxy += (x[i]-xMean) * (y[i]-yMean);
      		Syy += (y[i]-yMean) * (y[i]-yMean);
    	}
    	B1=Sxy/Sxx;
    	B0 = yMean - B1 * xMean;
    	R_square=(Sxy*Sxy)/(Sxx*Syy);
	}
/** Check for Showin Regression Line and/or Formula */
	public void setLine (int a) {
		if (a==0) showLine=false; else showLine=true;
	}
	
	public void setFormula (int a) {
		if (a==0) showFormula=false; else showFormula=true;
	}
	public void setAxes (int a) {
		if (a==0) autoRange=true; else autoRange=false;
	}
	public void setAxesValues (String x0, String x1, String y0, String y1) {
		xMin=Float.valueOf(x0).floatValue();
		xMax=Float.valueOf(x1).floatValue();
		yMin=Float.valueOf(y0).floatValue();
		yMax=Float.valueOf(y1).floatValue();
		compute();
		repaint();
	}
	
 /**parse the user's input String from an HTML document */
    public void setString (String userInput) {
	i=0; //reset number of pairs
	message=null; //reset error message
	//convert new line chars from unix/win
	userInput.trim(); 
	while (userInput.indexOf("\n") >=0) {
	   userInput= 
	     userInput.substring(0, userInput.indexOf("\n")) + " ; " +
	     userInput.substring(userInput.indexOf("\n")+1);
	}
	//convert return chars from macOS 
	while (userInput.indexOf("\r") >=0) {
	   userInput= 
	     userInput.substring(0, userInput.indexOf("\r")) + " ; " +
	     userInput.substring(userInput.indexOf("\r")+1);
	}
	if ( !(userInput.endsWith(" ; "))) userInput = userInput+" ; ";
	StringTokenizer t= new StringTokenizer(userInput, " ", false);
	
	// Now that the lines are cleaned up read in pairs  
	while ((t.hasMoreTokens()) && (i<MAX)) {
	  try{
	  	s = t.nextToken();
	  	if (s.charAt(0)!=';'){	
	  	 x[i]=Float.valueOf(s).floatValue(); 
      	 y[i]=Float.valueOf(t.nextToken()).floatValue(); 
      	 if (t.hasMoreTokens() ) s=t.nextToken();// the ; separator
	  	 i++;
	  	 }//end of if
	  	}// end of try
	  catch(Exception e) {
	    //message = e.toString();
	    message = "Line "+(i+1)+" around \""+s+"\"";
	  }//end of catch
	}//end of while loop
	n = i;
	if (n > 0) {compute();}
	repaint();
    }// of parsing the userInput string
    
    public void init() {
    	i =0;
		repaint();
	}
	private int CX(float x0){
		return (int)( (x0-xMin)*xFactor)+MARGIN;
	}
	private int CY(float y0){
		return size().height-(int)((y0-yMin)*yFactor)-MARGIN;
	}
	public void paint( Graphics g ) {
		
		g.drawString( "Number of Pairs Found:"+n, 30, 15 );
		if (n == MAX) {
			g.drawString( "WARNING: Maximum number of Pairs found", 5,size().height-48);
		 	g.drawString( "subsequent pairs ignored", 35,size().height-36);
		 	}
		if (showFormula){
			g.drawString("Regression Line Equation:",2*MARGIN,30);
    		g.drawString("y  = "+B1+" * x + "+B0,2*MARGIN,45);
    		g.drawString("r   = "+R_square,2*MARGIN,60); 
    		g.drawString("^",2*MARGIN,43);
        	g.drawString("2",2*MARGIN+5,57);
        }
        if (showLine){
        	g.setColor(Color.red);
        	g.drawLine(CX(xMin),CY(B1*xMin+B0) ,CX(xMax), CY(B1*xMax+B0));
        }
    	g.setColor(Color.magenta);
    	g.drawString("("+xM+", "+yM+")", CX(xM),CY(yM));
		
		//draw y labels and axis
		g.setColor(Color.black);
		g.drawLine(MARGIN,MARGIN, MARGIN,size().height-MARGIN);
		for (float i=yMin; i<= yMax; i+= (yMax-yMin)/10){
			g.drawString(" "+i,0, CY(i)+2);
			g.drawLine(MARGIN-2,CY(i),MARGIN+2,CY(i));
		}
		//draw xlabels and axis
		g.drawLine(MARGIN,size().height-MARGIN, size().width-MARGIN,size().height-MARGIN);
		for (float i=xMin; i<= xMax; i+= (xMax-xMin)/10){
			g.drawString(" "+i, CX(i)-10,size().height);
			g.drawLine(CX(i),size().height-MARGIN+2,CX(i),size().height-MARGIN-2);
		}
		//draw scatterplot
		g.setColor(Color.blue);
		for (int i=0; i<n; i++){
			g.fillOval( CX(x[i]), CY(y[i]), 3,3);
		
		}
		if (message != null) {
	    	g.drawString("Error in data: "+message, 10, size().height-24);
	    	g.drawString("Two numbers per line separated by space", 10, size().height-12);

			}
		}
	/*
     * Mouse methods
     */
    public boolean mouseDown(java.awt.Event evt, int x0, int y0) {
      
        repaint();
        return true;
    }
	
  	
  	
    public boolean mouseMove(java.awt.Event evt, int x0, int y0) {
        
         
        	y0 = size().height - y0 + 4;
         	requestFocus();
         	xM = (int)((x0-MARGIN)/xFactor+xMin);
        	yM = (int)((y0-MARGIN)/yFactor+yMin);
        	//getAppletContext().showStatus("Location of mouse: (" + xM + ", " + yM + ")");
        repaint();
         
        return true;
    }

    public void mouseEnter() {
        repaint();
    }

    public void mouseExit() {
       
        repaint();
    }

}    
    