import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.net.URL;
import java.util.*;
import graph.*;
/*************************************************************************
**
**    Applet linear1a
**                                              Version 1.0   January 1996
**
**************************************************************************
**    Copyright (C) 1996 Leigh Brookshaw
**
**    This program is free software; you can redistribute it and/or modify
**    it under the terms of the GNU General Public License as published by
**    the Free Software Foundation; either version 2 of the License, or
**    (at your option) any later version.
**
**    This program is distributed in the hope that it will be useful,
**    but WITHOUT ANY WARRANTY; without even the implied warranty of
**    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
**    GNU General Public License for more details.
**
**    You should have received a copy of the GNU General Public License
**    along with this program; if not, write to the Free Software
**    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
**************************************************************************
**
**    This is a simple applet that demonstrates how to use the basic features
**    of the Plotting Class library. The data is calculated locally by
**    the applet
**
*************************************************************************/

public class growth6g extends Applet implements AdjustmentListener, ActionListener{
	LoadData dynamic;
      	Graph2D graph1; 
     	Image osi=null;	Graphics osg=null;int iwidth = 0;int iheight=0;	
      	DataSet data1;
DataSet data2;
	DataSet data3;
	DataSet data4;
      	Axis    xaxis1;
      	Axis    yaxis1;
      	double data[]; double errorsum;
      	int np = 22; int p = 3;

      	URL markersURL;
      	Markers markers;
      	Panel      panel;
	double newspots[];
     	 Label title;
	Button fullview;
	Scrollbar slope;
	TextField year, equation, yearend,  errortext;
	int i, j, ly, year1,y1, year2, y2, yvalue; double m1,m2,m3,m4,m5,m6, ycalc, s3,s4,s6, newdatax1, newdatax2,newdatay1,newdatay2,a0,r2,r3,a1,b0,b1,z1,z2,z3,z4; 
	double point[], point2[];
	double spots[] =new double[6];
      public void init() {
       
		double point[] =new double[2];
		double point2[] =new double[2];
        		double data[] = new double[2*np];
	        	setLayout( new BorderLayout() );		
		
		year=new TextField("1790 ", 100);
		year.setFont(new Font("TimesRoman",Font.PLAIN,14));
		add("South",year);
		year.reshape(150, 350,60,20); year1=1790;
		year.setText(String.valueOf(year1));
		Label yearlabel=new Label("start year");
		add("South",yearlabel);
		yearlabel.reshape(100, 350,50,20);
		year.addActionListener(this);

		yearend=new TextField("1820 ", 100);
		yearend.setFont(new Font("TimesRoman",Font.PLAIN,14));
		add("South",yearend);
		yearend.reshape(300, 350,60,20); year2=1850;
		yearend.setText(String.valueOf(year2)); 
		Label yearendlabel=new Label("end year");
		add("South",yearendlabel);
		yearendlabel.reshape(250, 350,50,20);
		yearend.addActionListener(this);
		
		fullview = new Button("full view");
		add("South", fullview); fullview.reshape( 550,350,50,20);
		fullview.addActionListener(this);
		equation=new TextField("equation of curve ", 100);
		equation.setFont(new Font("TimesRoman",Font.BOLD,20));
		add("North",equation);
		equation.reshape(200, 10, 200,35);


		errortext =new TextField("sum of squares: ",40);
		add("North", errortext);
		errortext.reshape (300, 20,200, 40);

		slope = new Scrollbar(Scrollbar.HORIZONTAL, 30,1,1,1000);
		add("South",slope); slope.reshape(100,380,200,10);
		slope.addAdjustmentListener(this);
		
		Label slopelabel=new Label("growth rate r+1"); 
		add("South",slopelabel);
/*	
**      Get the passed parameters
*/
       		 String st = getParameter("TITLE");
        		String mfile    = getParameter("MARKERS");
		String points =getParameter("POINTS");
/*
**      Create the Graph instance and modify the default behaviour
*/
       		 graph1 = new Graph2D();
		dynamic = new LoadData();
        		graph1.drawzero = false;
        		graph1.drawgrid = true;
       		 graph1.borderRight = 0;
        		graph1.setDataBackground(new Color(107,188,229));
	

        
/*
**      Build the title
*/
       		 title = new Label(st, Label.CENTER);
        		title.setFont(new Font("TimesRoman",Font.PLAIN,20));



/*
**      Load a file containing Marker definitions
*/
       		 try {
          			 markersURL = new URL(getDocumentBase(),mfile);
          			 markers = new Markers(markersURL);
			 } 
	  	 catch(Exception e) 
			{
          			 System.out.println("Failed to create Marker URL!");
        			}
        
 
        		graph1.setMarkers(markers);
        		add("Center", graph1);


/*
**      Calculate the first data Set.
*/
		a0=3.929214; a1=10;
	 	ly=200; m2=((double) ly)/1000;  r3=m2+1.0;
        		for(i=j=0; i<np-5; i++, j+=2) {
          			 data[j] = (double) (10*i);
           			 r2=(data[j]-a1)/10;
            			data[j+1] = a0*(Math.pow(r3, r2));
        			}

        		data1 = graph1.loadDataSet(data,np-5);
        		data1.linecolor   =  Color.black;
        		data1.linestyle = 1;
        		data1.marker    = 0;
       		data1.markerscale = 1.0;
       		data1.markercolor = new Color(0,0,255);
        

       
/*
**      Start a new thread and load the data
*/
        		try {
        			data3 = dynamic.loadDataSet(new URL(getDocumentBase(),points), graph1);
        			} 
		catch (Exception e) {
         			 System.out.println("Failed to load data file!");
       			 }
/*
**      Specify the data line color
*/
      		 data3.linecolor   =  new Color(0,255,0);
		data3.linestyle=0;
        		data3.marker      = 4;
        		data3.markercolor = Color.red;
        
		data[0]=0;data[1]=0; data[2]=220; data[3]=300;
		z1=0; z2=220; z3=0; z4=300;
		data4 = graph1.loadDataSet(data,2);
        		data4.linecolor   =  Color.black;
        		data4.linestyle = 0;
        		data4.marker    = 0;
       		data4.markerscale = 1.0;
       		data4.markercolor = new Color(0,0,255);
        
/*	
**      Attach data sets to the Xaxes
*/
        		xaxis1 = graph1.createAxis(Axis.BOTTOM);

		xaxis1.attachDataSet(data1);
		xaxis1.attachDataSet(data3);
		xaxis1.attachDataSet(data4);
        		xaxis1.setTitleText("years after 1790");
        		xaxis1.setTitleFont(new Font("TimesRoman",Font.PLAIN,20));
       		 xaxis1.setLabelFont(new Font("Helvetica",Font.PLAIN,15));
  		 xaxis1.setTitleColor( new Color(0,0,255) );
        
/*
**      Attach the first data set to the Left Axis
*/
        		yaxis1 = graph1.createAxis(Axis.LEFT);
    
        		yaxis1.attachDataSet(data1);
		yaxis1.attachDataSet(data3);
		yaxis1.attachDataSet(data4);
        		yaxis1.setTitleText("population (millions)");
       		 yaxis1.setTitleFont(new Font("TimesRoman",Font.PLAIN,20));
       		 yaxis1.setLabelFont(new Font("Helvetica",Font.PLAIN,15));
        		yaxis1.setTitleColor( new Color(0,0,255) );
        		yaxis1.setTitleRotation(90);
		
		equation.setText(" P(t+1) = (1+"+m2+") P(t) ");
		}

void backburner(){
		Graphics g;
		g = graph1.getGraphics();                  
		 if( osi == null || iwidth != graph1.size().width  
                                 || iheight != graph1.size().height  ) 
			{
                     	 	 iwidth = graph1.size().width; 
                     		 iheight = graph1.size().height;
                      		 osi = graph1.createImage(iwidth,iheight);
                      	 	osg = osi.getGraphics(); 
                		 	 }
                   	osg.setColor(this.getBackground());
                   	osg.fillRect(0,0,iwidth,iheight);
                  	 osg.setColor(g.getColor());
                   	osg.clipRect(0,0,iwidth,iheight);
                   	graph1.update(osg);

		osg.setColor(Color.black);
		p=(year2-year1)/10 +1;
			double spots[] = new double[2];
			int places[] =new int[2*p]; errorsum=0.0;
			for(i=j=0; i<p; i++,j+=2) {
				spots=data3.getPoint(i+y1);
           			places[j] = xaxis1.getInteger(spots[0]);
           			places[j+1] = yaxis1.getInteger(spots[1]);
            			ycalc =  a0*(Math.pow(r3, i));
				yvalue = yaxis1.getInteger(ycalc);

				errorsum=errorsum+(ycalc-spots[1])*(ycalc-spots[1]);

				osg.drawLine(places[j],places[j+1],places[j],yvalue);
       				}

			errortext.setText("sum of sq.=  " + ((float)((int)(errorsum*100)))/100); 
			errortext.setFont(new Font("TimesRoman",Font.PLAIN,20));

                   	g.drawImage(osi,0,0,graph1);        								}
public void destroy(){
		osg.dispose();
		}
public void update(Graphics screen){
		paint(screen);
			}



public void adjustmentValueChanged(AdjustmentEvent ade)
	{	ly = slope.getValue();
		slope.setValue(ly);
		
		m2=((double) ly)/1000; r3=m2+1; 
		
		double other[]= new double[2*np];

	
	 	for(i=j=0; i<np; i++, j+=2) {
           			other[j] = (double) (10*i);
            			r2=(other[j]-a1)/10; 
          		 	other[j+1] = a0*(Math.pow(r3, r2));
        			}
       
		data1.delete(0,np);
		try{    data1.append(other,np);}
		     
                   	catch (Exception e) {
                        		System.out.println("Error appending Data!");
                   		}
        
       		
		xaxis1.setManualRange(true);
		data1.xaxis.minimum=z1; data1.xaxis.maximum=z2;
		yaxis1.setManualRange(true);
		       data1.yaxis.minimum=z3; data1.yaxis.maximum=z4; 
		   equation.setText(" P(t+1)= (1+"+m2+" )P(t) ");   
        		
			backburner();
			
	}

	public void actionPerformed(ActionEvent evt)
	{ Object src=evt.getSource();
		if(src==fullview){
			z1=0; z2=220; z3=0; z4=300;}
		else  {year1 = new Integer(year.getText()).intValue();
		year.setText(String.valueOf(year1));
		y1 =(year1-1790)/10;
		point = data3.getPoint(y1);
		a0=point[1]; a1=point[0];
		z1=a1-10; z3=a0-0.5;
		year2 = new Integer(yearend.getText()).intValue();
		yearend.setText(String.valueOf(year2));
		y2 =(year2-1790)/10;
		point2 = data3.getPoint(y2);
		b0=point2[1]; b1=point2[0];
		z2=b1+10; z4=b0+0.5;
		double other[]= new double[2*np];
		
	 	for(i=j=0; i<np; i++,j+=2) {
           			other[j] = (double) (10*i);
           			 r2=(other[j]-a1)/10; 
           			 other[j+1] = a0*(Math.pow(r3, r2));
        			}
       
		data1.delete(0,np);
		try{    data1.append(other,np);}
		     
                   catch (Exception e) {
                        System.out.println("Error appending Data!");
                   		}
        				}
       		xaxis1.setManualRange(true);
		data1.xaxis.minimum=z1; data1.xaxis.maximum=z2;
		yaxis1.setManualRange(true);
		       data1.yaxis.minimum=z3; data1.yaxis.maximum=z4;  
		   equation.setText(" P(t+1)= (1+"+m2+") P(t) ");
        		
			backburner();
			
	}



}

        
		



