double Sensor::zScore(double arr[]) {
	double mean = findMean(arr), dev = findDeviation(arr);
	for (int i = 0; i < NUM_OF_DATA; i++) {
		double zNum = (mean - arr[i]) / dev;
		if (zNum > 1 || zNum < -1) {
			arr[i] = mean;
		}
	}

	return findMean(arr);
}
Exemple #2
0
int main(){
	double first = 12.0; //, second = 99.33;
	/* TO DO: This is where you initialize your house prices array.
	 * The rest of the values will default to 0.0 if you do not provide enough
	 * values to fill the entire array */
	int numberOfHomes = 71; // change this value here and on the next line.
	// C does not like you to initialize a variable-sized array.
	double houses[71] = {129500.0, 129900.0, 138900.0, 159900.0, 
    44900.0, 490000.0, 89500.0, 34000.0, 82000.0, 219900.0,
    47500.0, 144900.0, 159999.0, 99900.0, 166900.0, 229900.0,
    240000.0, 89900.0, 299900.0, 49900.0, 585000.0, 275000.0,
    209900.0, 259900.0, 269900.0, 389900.0, 86500.0, 99900.0,
    79900.0, 175000.0, 54900.0, 139900.0, 129900.0, 34900.0,
    119900.0, 257700.0, 149900.0, 139900.0, 149900.0, 174900.0,
    145900.0, 189900.0, 212900.0, 48900.0, 75900.0, 330000.0,
    17500.0, 235000.0, 449900.0, 179900.0, 119900.0, 147000.0,
    155000.0, 239000.0, 219900.0, 309000.0, 131900.0, 345000.0,
    165000.0, 299900.0, 45000.0, 230000.0, 99500.0, 83500.0,
    156900.0, 289900.0, 45900.0, 185500.0, 19000.0, 124000.0,
    159900.0};
	//testSwap(&first, &houses[2]);
	sort(houses, numberOfHomes);
	//printArray(&houses[0], numberOfHomes);
	double mean, median;
	mean = findMean(houses, numberOfHomes);
	median = findMedian(houses, numberOfHomes);
	printf("The mean price of 4 bedroom houses in Vigo County is $%2.1lf\n", mean);
	printf("The median price of 4 bedroom houses in Vigo Country is $%2.1lf\n", median);
	printNHighestPrices(houses, 10, 5);
	printNlowestPrices(houses, 10, 5);
	//int a[3] = {4}, b[] = {4};
	//printf ("Array equality: %d\n", a == b);
 	return 0;
 }
double Sensor::findDeviation(double arr[]) {
	double total = 0, devResult = 0, mean = findMean(arr);

	for (int i = 0; i < NUM_OF_DATA; i++) {
		total += (arr[i] - mean) * (arr[i] - mean);
	}
	if (total != 0) {
		total = total / double(NUM_OF_DATA);
		total = sqrt(total);
		devResult += total;
	}

	return devResult;
}
double Sensor::findTrimmed(double arr[], double percent) {
	
  double median = findMedian(arr);
  double trim = NUM_OF_DATA * (percent / 100.0);
  for (int i = 0; i < trim; i++) {
    arr[i] = median;
    arr[(NUM_OF_DATA - i) - 1] = median;
  }
  /////////////////////////////////test
  //  Serial.print("trimmed\n");
  //  testingArray(arr);
  ////////////////////////////////

  return findMean(arr);
}
//==============================================================================
double PitchDetector::detectPitch (float* samples, int numSamples) noexcept
{
    Array<double> pitches;
    pitches.ensureStorageAllocated (int (numSamples / numSamplesNeededForDetection));
    
    while (numSamples >= numSamplesNeededForDetection)
    {
        double pitch = detectPitchForBlock (samples, numSamplesNeededForDetection);//0.0;
        
        if (pitch > 0.0)
            pitches.add (pitch);
        
        numSamples -= numSamplesNeededForDetection;
        samples += numSamplesNeededForDetection;
    }
    
    if (pitches.size() == 1)
    {
        return pitches[0];
    }
    else if (pitches.size() > 1)
    {
        DefaultElementComparator<double> sorter;
        pitches.sort (sorter);
        
        const double stdDev = findStandardDeviation (pitches.getRawDataPointer(), pitches.size());
        const double medianSample = findMedian (pitches.getRawDataPointer(), pitches.size());
        const double lowerLimit = medianSample - stdDev;
        const double upperLimit = medianSample + stdDev;
        
        Array<double> correctedPitches;
        correctedPitches.ensureStorageAllocated (pitches.size());
        
        for (int i = 0; i < pitches.size(); ++i)
        {
            const double pitch = pitches.getUnchecked (i);
            
            if (pitch >= lowerLimit && pitch <= upperLimit)
                correctedPitches.add (pitch);
        }
        
        const double finalPitch = findMean (correctedPitches.getRawDataPointer(), correctedPitches.size());
        
        return finalPitch;
    }
    
    return 0.0;
}
Exemple #6
0
void doPlot(pulsar *psr,int npsr,float *scale,int nScale,char *grDev,int plotUs,float fontSize,float centreMJD,int ptStyle,float ptSize,int error,float minyv,float maxyv,float minxv,float maxxv,int nOverlay,float labelsize,float fracX)
{
  int i,j,fitFlag=2,exitFlag=0,scale1=0,scale2,count[MAX_PSR],p,xautoscale=0,k,graphics=1;
  int yautoscale=0,plotpre=1;
  int ps,pe,pi;
  int time=0;
  char xstr[1000],ystr[1000];
  float px[2],py[2],pye1[2],pye2[2];
  float x[MAX_PSR][MAX_OBSN],y[MAX_PSR][MAX_OBSN],yerr1[MAX_PSR][MAX_OBSN],yerr2[MAX_PSR][MAX_OBSN],tmax,tmin,tmaxy1,tminy1,tmaxy2,tminy2;
  float sminy[MAX_PSR],smaxy[MAX_PSR];
  float minx[MAX_PSR],maxx[MAX_PSR],miny[MAX_PSR],maxy[MAX_PSR],plotx1,plotx2,ploty1,ploty2,mean;
  float fx[2],fy[2];
  float mouseX,mouseY;
  char key;
  //  float widthPap=0.0,aspectPap=0.618;
  float widthPap=0.0,aspectPap=1;
  float xx[MAX_OBSN],yy[MAX_OBSN],yyerr1[MAX_OBSN],yyerr2[MAX_OBSN];
  int num=0,colour;

  /* Obtain a graphical PGPLOT window */
  cpgbeg(0,grDev,1,1);
  //    cpgpap(widthPap,aspectPap);
  cpgsch(fontSize);
  cpgscf(2);
  cpgslw(2);
  cpgask(0);

  for (p=0;p<npsr;p++)
    {
      scale2 = psr[p].nobs;
      
      /*      sprintf(xstr,"MJD-%.1Lf",psr[0].param[param_pepoch].val[0]); */
      if (centreMJD == -1)
	sprintf(xstr,"Year"); 
      else
	sprintf(xstr,"MJD-%.1f",centreMJD); 

      sprintf(ystr,"Residual (\\gmsec)");
      
      count[p]=0;
      printf("points = %d\n",psr[p].nobs);
      for (i=0;i<psr[p].nobs;i++)
	{	  
	  if (psr[p].obsn[i].deleted == 0 &&
	      (psr[p].param[param_start].paramSet[0]!=1 || psr[p].param[param_start].fitFlag[0]!=1 ||
	       psr[p].param[param_start].val[0] < psr[p].obsn[i].bat) &&
	      (psr[p].param[param_finish].paramSet[0]!=1 || psr[p].param[param_finish].fitFlag[0]!=1 ||
	       psr[p].param[param_finish].val[0] > psr[p].obsn[i].bat))
	    {
	      /* x[p][count[p]] = (double)(psr[p].obsn[i].bat-psr[0].param[param_pepoch].val[0]);	     	       */
	      if (centreMJD == -1)
		x[p][count[p]] = calcYr(psr[p].obsn[i].bat);
	      else
		x[p][count[p]] = (double)(psr[p].obsn[i].bat-centreMJD); 
	      y[p][count[p]] = (double)psr[p].obsn[i].residual*1.0e6;
	      if (nScale>0)
		y[p][count[p]] *= scale[p];
	      count[p]++;
	    }
	}
      /* Remove mean from the residuals and calculate error bars */
      mean = findMean(y[p],psr,p,scale1,count[p]);
      count[p]=0;
      for (i=0;i<psr[p].nobs;i++)
	{
	  if (psr[p].obsn[i].deleted==0   &&
	      (psr[p].param[param_start].paramSet[0]!=1 || psr[p].param[param_start].fitFlag[0]!=1 ||
	       psr[p].param[param_start].val[0] < psr[p].obsn[i].bat) &&
	      (psr[p].param[param_finish].paramSet[0]!=1 || psr[p].param[param_finish].fitFlag[0]!=1 ||
	       psr[p].param[param_finish].val[0] > psr[p].obsn[i].bat))
	    {
	      psr[p].obsn[i].residual-=mean/1.0e6;
	      y[p][count[p]]-=mean;
	      yerr1[p][count[p]] = y[p][count[p]]-(float)psr[p].obsn[i].toaErr;
	      yerr2[p][count[p]] = y[p][count[p]]+(float)psr[p].obsn[i].toaErr;
	      count[p]++;
	    }
	}
    	  
      /* Get scaling for graph */
      if (minxv == maxxv) {
	minx[p] = findMin(x[p],psr,p,scale1,count[p]);
	maxx[p] = findMax(x[p],psr,p,scale1,count[p]);
      }
      else {
	minx[p] = minxv;
	maxx[p] = maxxv;
      }
      if (minyv == maxyv){
	miny[p] = findMin(y[p],psr,p,scale1,count[p]);
	maxy[p] = findMax(y[p],psr,p,scale1,count[p]);
      }
      else {
	miny[p] = minyv;
	maxy[p] = maxyv;
      }
      sminy[p] = miny[p]/1e6;
      smaxy[p] = maxy[p]/1e6;
    }
  for (p=0;p<npsr;p++)
    {
      for (i=0;i<count[p];i++)
	{
	  y[p][i] = (y[p][i]-miny[p])/(maxy[p]-miny[p]);
	  yerr1[p][i] = (yerr1[p][i]-miny[p])/(maxy[p]-miny[p]);
	  yerr2[p][i] = (yerr2[p][i]-miny[p])/(maxy[p]-miny[p]);
	}
      //      maxy[p] = 1.0;
      //      miny[p] = 0.0;
    }
  

  tmin = findMinVal(minx,npsr);
  tmax = findMaxVal(maxx,npsr);

  tminy2 = 0.0; //findMinVal(miny,npsr);
  tmaxy2 = 1.0; //findMaxVal(maxy,npsr);

  plotx1 = tmin-(tmax-tmin)*0.1;
  plotx2 = tmax+(tmax-tmin)*0.1;
  
  //  ploty1 = tminy2-(tmaxy2-tminy2)*0.1;
  //  ploty2 = tmaxy2+(tmaxy2-tminy2)*0.1;
	
  ploty1 = 0.1;
  ploty2 = 0.9;

  for (p=0;p<npsr;p++)
    {
      for (i=0;i<count[p];i++)
	{
	  y[p][i]=(p)+ploty1+y[p][i]*(ploty2-ploty1);
	  yerr1[p][i]=(p)+ploty1+yerr1[p][i]*(ploty2-ploty1);
	  yerr2[p][i]=(p)+ploty1+yerr2[p][i]*(ploty2-ploty1);
	}
    } 
  
  printf("ytick = %g\n",ploty2-ploty1);
      /*  cpgenv(plotx1,plotx2,ploty1,ploty2+(ploty2-ploty1)*(npsr-1),0,0); */
  //  cpgenv(plotx1,plotx2,0,npsr+1,0,-1);

  if (labelsize!=-1)
    cpgsch(labelsize);
  cpgsvp(fracX,1.0,0.1,1.0);
  cpgswin(0,1,0,npsr);
  cpgbox("ABC",0.0,0,"C",0.0,0);
  cpgsch(fontSize);
  char str[1000];
  for (p=0;p<npsr;p++)
    {
      cpgsch(fontSize);
      //      cpgtext(tmax+(tmax-tmin)*0.05,p+1.5-0.5,psr[p].name);
      cpgtext(0,p+0.6,psr[p].name);
      //      cpgsch(fontSize);
      if (plotUs==0)
	{
	  sprintf(str,"%.2f",(double)((smaxy[p]-sminy[p])*psr[p].param[param_f].val[0]));
	  cpgtext(0,p+0.4,str);
	  //	  cpgtext(tmax+(tmax-tmin)*0.05,p+1.1-0.5,str);
	}
      else
	{
	  sprintf(str,"%.2f\\gms",(double)((smaxy[p]-sminy[p])/1e-6));
	  //	  cpgtext(tmax+(tmax-tmin)*0.05,p+1.1-0.5,str);
	  cpgtext(0,p+0.1,str);
	}
      cpgsch(1);
      px[0] = 0;
      //      px[1] = tmax; //+(tmax-tmin)*0.03;
	px[1] = 1;
      py[0] = p;
      py[1] = p;
      cpgline(2,px,py);
      
    }
  if (labelsize!=-1)
    cpgsch(labelsize);

  cpgsvp(0.1,fracX,0.1,1.0);
  cpgswin(plotx1,plotx2,0,npsr);
  cpgbox("ATNSBC",0.0,0,"B",0.0,0);
  cpglab(xstr,"","");	    
  cpgsch(fontSize);

  for (p=0;p<npsr;p++)
    {
      cpgsls(1);
      px[0] = plotx1;
      //      px[1] = tmax; //+(tmax-tmin)*0.03;
      px[1] = plotx2;
      py[0] = p;
      py[1] = p;
      cpgline(2,px,py);
      cpgsls(4);
      px[0] = tmin;
      px[1] = tmax+(tmax-tmin)*0.03;

      py[0]=py[1] =(p)+ploty1+(-miny[p]/(maxy[p]-miny[p]))*(ploty2-ploty1);
      //      py[0]=py[1] = (p)+ploty1;
      //      py[0] = py[1] = (0-miny[p])/(maxy[p]-miny[p])/(ploty2-ploty1)+p;
      cpgline(2,px,py);

      px[0] = plotx1+0.005*(plotx2-plotx1);
      py[0] = p;
      pye1[0] = p + 5/(ploty2-ploty1);
      pye2[0] = p - 5/(ploty2-ploty1);
      cpgsls(1);
      cpgsch(3);
      //      cpgerry(1,px,pye1,pye2,1); 
      cpgsch(1);

      for (colour=0;colour<5;colour++)
	{
	  num=0;
	  for (i=0;i<count[p];i++)
	    {
	      if ((colour==0 && psr[p].obsn[i].freq<=500) ||
		  (colour==1 && psr[p].obsn[i].freq>500 && psr[p].obsn[i].freq<=1000) ||
		  (colour==2 && psr[p].obsn[i].freq>1000 && psr[p].obsn[i].freq<=1500) ||
		  (colour==3 && psr[p].obsn[i].freq>1500 && psr[p].obsn[i].freq<=3300) ||
		  (colour==4 && psr[p].obsn[i].freq>3300))
		{
		  xx[num]=x[p][i];
		  yy[num]=y[p][i];
		  yyerr1[num]=yerr1[p][i];
		  yyerr2[num]=yerr2[p][i];
		  //		  printf("plotting: %g\n",yy[num]);

		  num++;
		}
	    }
	  cpgsci(colour+1);
	  cpgsch(ptSize);
	  cpgpt(num,xx,yy,ptStyle);
	  if (error==1)
	    cpgerry(num,xx,yyerr1,yyerr2,1);
	  cpgsch(fontSize);
	  // Plot arrow giving one period
	  fx[0] = fx[1] = tmin-(tmax-tmin)*0.05;
	  //	  fy[0] = (p+1)+0.5-(float)(1.0/psr[p].param[param_f].val[0])/2.0/(ploty2-ploty1);
	  //	  fy[1] = (p+1)+0.5+(float)(1.0/psr[p].param[param_f].val[0])/2.0/(ploty2-ploty1);

	  //	  fy[0] = (-(float)(1.0/psr[p].param[param_f].val[0])/2.0/1.0e6 - miny[p])/(maxy[p]-miny[p])/(ploty2-ploty1) + (p+1)+0.5;
	  //	  fy[1] = ((float)(1.0/psr[p].param[param_f].val[0])/2.0/1.0e6 - miny[p])/(maxy[p]-miny[p])/(ploty2-ploty1) + (p+1)+0.5;
	  fy[0] = (p+1)+0.5+(float)(1.0/psr[p].param[param_f].val[0])/2.0/(maxy[p]-miny[p])*1e6;
	  fy[1] = (p+1)+0.5-(float)(1.0/psr[p].param[param_f].val[0])/2.0/(maxy[p]-miny[p])*1e6;
	  if (fy[0] > (p+1)+1) fy[0] = (p+1)+1;
	  if (fy[1] < (p+1)) fy[1] = (p+1);
	  
	  //	  cpgsls(1); cpgline(2,fx,fy); cpgsls(1);
	}
      cpgsci(1);
    }

  
  cpgend();
}
Exemple #7
0
int resistmean (float *in, int npix, float sigrej, float *mean, 
		float *sigmean, float *min, float *max) {

/* Arguments:
**	in	i: pointer to array of input values 
**	npix	i: size of the input array
**	sigrej	i: the sigma level for pixel rejection
**	mean	o: mean value of unrejected pixels
**	sigmean	o: standard deviation of unrejected pixels
**		   (NOT the uncertainty or sigma of the mean)
**      min	o: minimum of input values
**      max	o: maximum of input values
*/

	/* Local variables */
	int i, j;	  /* loop indexes */
	float median;     /* median value of input array */
	float *absdev; 	  /* absolute deviation array */
	float medabsdev;  /* median of the absdev array */
	float *tempdata;  /* array of good pixel values */
	float *tempdata2; /* array of good pixel values */
	double sum;       /* sum of pixel values */
	float cutoff;	  /* value limitation */
	int   npix1, npix2;  /* number of pixels in temp arrays */
    
	/* Function definitions */
	float findRMedian (float *, int );        /* compute median of array */
   	float findMean(float *, int );              /* compute mean of array */
	float findSigma(float *, int , float *);  /* compute stddev of array */
	void arrayDiff(float *, float *, float , int );   /* subtract median */
	void arrayAbs(float *,int);       /* compute absolute value of array */
	void wheregood(float *, float , int * );   /* flag outliers in array */
    
	/* Initialize the counters and results */
	npix1 = npix;
	*mean = 0.;
	*sigmean = 0.;
	*min = 0;
	*max = 0;
	median = 0.;
	medabsdev = 0.;
	cutoff = 0.;

	/* allocate temp arrays to store and manipulate the input array */
	if (npix != 0) {
        
	    /* an array to store a copy of the data*/
	    tempdata = (float *) calloc(npix, sizeof(float));
	    if (tempdata == NULL) {
		sprintf (MsgText, "Memory allocation failure in resistmean");
        	trlmessage (MsgText);
		return (1);
	    }

	    /* and an array to store absolute deviation */
	    absdev = (float *) calloc(npix, sizeof(float));
	    if (absdev == NULL) {
		sprintf (MsgText, "Memory allocation failure in resistmean");
        	trlmessage (MsgText);
		return (1);
	    }

	} else {
	    sprintf (MsgText, "Zero size array passed to resistmean");
	    trlerror (MsgText);
	    return (1);
	}
              
	/* Copy the input array, computing the initial sum, min, max */
	sum = 0.;
	*min = tempdata[0];
	*max = tempdata[0];
	for (i=0; i<npix1; i++) {
	     tempdata[i] = in[i];
	     sum  += tempdata[i];
	     if (tempdata[i] < *min) *min = tempdata[i];
	     if (tempdata[i] > *max) *max = tempdata[i];
	}

	/* Compute the mean and median of the unrejected values */
	*mean = (float) (sum/(double)npix1);
	median = findRMedian (tempdata, npix1);

	/* Subtract the median from every element in the array */
	arrayDiff (tempdata, absdev, median, npix1);

	/* Get the absolute value for each element in the resulting array */
	arrayAbs (absdev, npix1);

	/* Get the median of the absolute deviation array and divide by a 
	   constant with some logic attached */
	medabsdev = findRMedian (absdev, npix1) / 0.6745; 
	if (medabsdev < 1.0E-24)
	    medabsdev = findMean(absdev,npix1) / 0.8;

	/* Compute the cutoff value in terms of the median absolute deviation */
	cutoff = (sigrej) * medabsdev;

	/* Flag values in the array that are beyond the cutoff */
	wheregood (absdev, cutoff, &npix1);

	/* Start a new temp array to populate with the good values;
	   npix1 should be the count of unrejected pixels here */
	tempdata2 = (float *) calloc(npix1, sizeof(float));
	if (tempdata2 == NULL) {
	    sprintf (MsgText, "Memory allocation failure in resistmean");
	    trlmessage (MsgText);
	    return (1);
	}

	/* Copy only the good values into the new temp array.
	   npix is still the number of original input values, while npix1
	   is now the number of remaining good values. */
	j=0;
	for (i=0; i<npix; i++) {
	     if (absdev[i] != PFLAG) {	
		 tempdata2[j]=tempdata[i];
		 j++;
	     }
	}

	/************ ROUND 2 ***********/

	/* Compute the mean and stddev of the values in the new array */
	*mean = findMean(tempdata2, npix1);    
	*sigmean = findSigma(tempdata2, npix1, mean); 

	/* Compensate sigma for truncation and compute new cutoff */
 	if (sigrej <= 4.5) {
	    *sigmean = *sigmean / (-0.15405+0.90723*sigrej - 0.23584*sigrej*sigrej+0.020142*sigrej*sigrej*sigrej);
	}
 	cutoff = sigrej * (*sigmean); 

	/* Reinitialize the absdev array to hold new set of values */
	free(absdev); /* clear the old array */
	absdev = (float *) calloc(npix1, sizeof(float));
	if (absdev == NULL) {
	    sprintf (MsgText, "Memory allocation failure in resistmean");
	    return (1);
	}
    
	/* Find the median of the good values. */
	median = findRMedian(tempdata2, npix1);

	/* Subtract the median from every element in the array */
	arrayDiff (tempdata2, absdev, median, npix1);

	/* Get the absolute value for each element in the resulting array */
	arrayAbs (absdev, npix1);

	/* Get the median of the absolute deviation array */
	medabsdev = findRMedian(absdev, npix1) / 0.6745; 
	if (medabsdev < 1.0E-24)
	    medabsdev = findMean(absdev, npix1) / 0.8;

	/* Flag values in the array that are beyond the new cutoff */
	npix2 = npix1;
	wheregood(absdev, cutoff, &npix2);

	/* Start a new temp array to populate with just the final good values */
	free (tempdata); /* free the previous copy */
	tempdata = (float *) calloc(npix2, sizeof(float));
	if (tempdata == NULL) {
	    sprintf (MsgText, "Memory allocation failure in resistmean");
	    return (1);
	}
    
	/* Copy only the good values to the new array */
	j=0;
	for (i=0; i<npix1; i++) {
	     if (absdev[i] != PFLAG) {	
		 tempdata[j] = tempdata2[i];
		 j++;
	     }
	}

	/* Compute the mean and stddev of the latest array of good values */
	*mean    = findMean (tempdata, npix2);
	*sigmean = findSigma(tempdata, npix2, mean); 

	/* Compensate sigma for truncation :*/
 	if (sigrej <= 4.5) {
	    *sigmean = *sigmean / (-0.15405+0.90723*sigrej-0.23584*sigrej*sigrej+0.020142*sigrej*sigrej*sigrej);
	}

	/* Free all local arrays */
	free(absdev);
	free(tempdata);
	free(tempdata2);

	return (0);    	/* Successful return */
}
Exemple #8
0
void doPlot(pulsar *psr,int npsr,int overlay)
{
  int i,j,fitFlag=1,exitFlag=0,scale1=0,scale2,count,p,xautoscale=1,k,graphics=1;
  int yautoscale=1,plotpre=1;
  int time=0;
  char xstr[1000],ystr[1000];
  float x[MAX_OBSN],y[MAX_OBSN],yerr1[MAX_OBSN],yerr2[MAX_OBSN],tmax,tmin,tmaxy1,tminy1,tmaxy2,tminy2;
  float minx,maxx,miny,maxy,plotx1,plotx2,ploty1,ploty2,mean;
  float mouseX,mouseY;
  float fontSize=1.8;
  char key;
  float widthPap=0.0,aspectPap=0.618;

  /* Obtain a graphical PGPLOT window */
  if (overlay==1)
    cpgbeg(0,"?",2,1);
  else
    cpgbeg(0,"?",2,npsr);
  cpgpap(widthPap,aspectPap);
  cpgsch(fontSize);
  cpgask(0);

  do {
    for (p=0;p<npsr;p++)
      {
	scale2 = psr[p].nobs;
	for (j=0;j<2;j++)
	  {
	    if (j==0) fitFlag=1;
	    else if (j==1) fitFlag=2;

	    ld_sprintf(xstr,"MJD-%.1Lf",psr[0].param[param_pepoch].val[0]); 
	    sprintf(ystr,"Residual (\\gmsec)");

	    count=0;
	    for (i=0;i<psr[p].nobs;i++)
	      {
		if (psr[p].obsn[i].deleted == 0  &&
	    (psr[p].param[param_start].paramSet[0]!=1 || psr[p].param[param_start].fitFlag[0]!=1 ||
	      psr[p].param[param_start].val[0] < psr[p].obsn[i].bat) &&
	    (psr[p].param[param_finish].paramSet[0]!=1 || psr[p].param[param_finish].fitFlag[0]!=1 ||
	     psr[p].param[param_finish].val[0] > psr[p].obsn[i].bat))
		  {
		    if (xautoscale==1)
		      x[count] = (double)(psr[p].obsn[i].bat-psr[p].param[param_pepoch].val[0]);
		    else
		      x[count] = (double)(psr[p].obsn[i].bat-psr[0].param[param_pepoch].val[0]);
		    
		    if (fitFlag==1)  /* Get pre-fit residual */
		      y[count] = (double)psr[p].obsn[i].prefitResidual*1.0e6;
		    else if (fitFlag==2) /* Post-fit residual */
		      y[count] = (double)psr[p].obsn[i].residual*1.0e6;
		    count++;
		  }
	      }
	    /* Remove mean from the residuals and calculate error bars */
	    mean = findMean(y,psr,p,scale1,count);
	    count=0;
	    for (i=0;i<psr[p].nobs;i++)
	      {
		if (psr[p].obsn[i].deleted==0   &&
	    (psr[p].param[param_start].paramSet[0]!=1 || psr[p].param[param_start].fitFlag[0]!=1 ||
	      psr[p].param[param_start].val[0] < psr[p].obsn[i].bat) &&
	    (psr[p].param[param_finish].paramSet[0]!=1 || psr[p].param[param_finish].fitFlag[0]!=1 ||
	     psr[p].param[param_finish].val[0] > psr[p].obsn[i].bat))
		  {
		    psr[p].obsn[i].residual-=mean/1.0e6;
		    y[count]-=mean;
		    yerr1[count] = y[count]-(float)psr[p].obsn[i].toaErr;
		    yerr2[count] = y[count]+(float)psr[p].obsn[i].toaErr;
		    count++;
		  }
	      }
	    
	    /* Get scaling for graph */
	    minx = findMin(x,psr,p,scale1,count);
	    maxx = findMax(x,psr,p,scale1,count);
	    if (xautoscale==1)
	      {
		plotx1 = minx-(maxx-minx)*0.1;
		plotx2 = maxx+(maxx-minx)*0.1;
	      }
	    else
	      {
		plotx1 = tmin-(tmax-tmin)*0.1;
		plotx2 = tmax+(tmax-tmin)*0.1;
	      }
	    miny = findMin(y,psr,p,scale1,count);
	    maxy = findMax(y,psr,p,scale1,count);

	    if (yautoscale==1)
	      {
		ploty1 = miny-(maxy-miny)*0.1;
		ploty2 = maxy+(maxy-miny)*0.1;
	      }
	    else
	      {
		if (j==0)
		  {
		    ploty1 = tminy1-(tmaxy1-tminy1)*0.1;
		    ploty2 = tmaxy1+(tmaxy1-tminy1)*0.1;
		  }
		else
		  {
		    ploty1 = tminy2-(tmaxy2-tminy2)*0.1;
		    ploty2 = tmaxy2+(tmaxy2-tminy2)*0.1;
		  }
	      }

	    /* Plot the residuals */	    
	    if (plotpre==1 || j!=0)
	      {
		float xx[MAX_OBSN],yy[MAX_OBSN],yyerr1[MAX_OBSN],yyerr2[MAX_OBSN];
		int num=0,colour;
		if (overlay==0 || (overlay==1 && p==0))
		  {
		    cpgenv(plotx1,plotx2,ploty1,ploty2,0,0);
		    cpglab(xstr,ystr,psr[p].name);	    
		  }

		for (colour=0;colour<5;colour++)
		  {
		    num=0;
		    for (i=0;i<count;i++)
		      {
			if ((colour==0 && psr[p].obsn[i].freq<=500) ||
			    (colour==1 && psr[p].obsn[i].freq>500 && psr[p].obsn[i].freq<=1000) ||
			    (colour==2 && psr[p].obsn[i].freq>1000 && psr[p].obsn[i].freq<=1500) ||
			    (colour==3 && psr[p].obsn[i].freq>1500 && psr[p].obsn[i].freq<=3300) ||
			    (colour==4 && psr[p].obsn[i].freq>3300))
			  {
			    xx[num]=x[i];
			    yy[num]=y[i];
			    yyerr1[num]=yerr1[i];
			    yyerr2[num]=yerr2[i];
			    num++;
			  }
		      }
		    cpgsci(colour+1);
		    if (overlay==1)
		      cpgsci(p+1);
		    cpgpt(num,xx,yy,16);
		    cpgerry(num,xx,yyerr1,yyerr2,1);
		  }
		cpgsci(1);
	      }
	  }
      }
    printf("------------------------------\n");
    printf("`a'     set aspect ratio\n");
    printf("`f'     set font size\n");
    printf("`g'     set graphics device\n");
    printf("`q'     quit\n");
    printf("`x'     toggle autoscale x axis\n");
    printf("`y'     toggle autoscale y axis\n");
    printf("`p'     toggle prefit plotting\n");
    printf("`r'     output residuals to file\n");

    if (graphics==1)
      {
	cpgcurs(&mouseX,&mouseY,&key);
	
	/* Check key press */
	if (key=='q') exitFlag=1;
	if (key=='p') {
	  plotpre*=-1;
	  if (plotpre==-1)
	    {
	      cpgend();
	      if (overlay==1)
		cpgbeg(0,"/xs",1,1);
	      else
		cpgbeg(0,"/xs",1,npsr);
	      cpgpap(widthPap,aspectPap);
	      cpgsch(fontSize);
	      cpgask(0);	      
	    }
	  else
	    {
	      cpgend();
	      if (overlay==1)
		cpgbeg(0,"/xs",2,1);
	      else
		cpgbeg(0,"/xs",2,npsr);
	      cpgpap(widthPap,aspectPap);
	      cpgsch(fontSize);
	      cpgask(0);	      
	    }
	}
	else if (key=='a') /* Change aspect ratio */
	  {
	    printf("Please enter a new aspect ratio ");
	    scanf("%f",&aspectPap);
	    cpgend();
	    cpgbeg(0,"/xs",2,npsr);
	    cpgpap(widthPap,aspectPap);
	    cpgsch(fontSize);
	    cpgask(0);	      
	  }
	else if (key=='f') /* Change font size */
	  {
	    printf("Please enter a new font size ");
	    scanf("%f",&fontSize);
	    cpgend();
	    cpgbeg(0,"/xs",2,npsr);
	    cpgpap(widthPap,aspectPap);
	    cpgsch(fontSize);
	    cpgask(0);	      
	  }
	else if (key=='g')
	  {
	    graphics=0;
	    cpgend();
	    if (plotpre==-1)
	      {
		cpgend();
		if (overlay==1)
		  cpgbeg(0,"?",1,1);
		else
		  cpgbeg(0,"?",1,npsr);
		cpgpap(widthPap,aspectPap);
		cpgsch(fontSize);
		cpgask(0);	      
	      }
	    else
	      {
		cpgend();
		if (overlay==1)
		  cpgbeg(0,"?",1,1);
		else
		  cpgbeg(0,"?",2,npsr);
		cpgpap(widthPap,aspectPap);
		cpgsch(fontSize);
		cpgask(0);	      
	      }
	  }
	else if (key=='r') /* Output residuals to file */
	  {
	    FILE *fout;
	    char fname[1000];
	    int ii,jj;

	    for (ii=0;ii<npsr;ii++)
	      {
		sprintf(fname,"%s.res",psr[ii].name);
		fout = fopen(fname,"w");
		/* Print header */
		fprintf(fout,"#PSR %s\n",psr[ii].name);
		ld_fprintf(fout,"#F0  %.14Lf\n",psr[ii].param[param_f].val[0]);
		fprintf(fout,"#RAJ %s\n",psr[ii].rajStrPre);
		fprintf(fout,"#DECJ %s\n",psr[ii].decjStrPre);
		for (jj=0;jj<psr[ii].nobs;jj++)
		  fprintf(fout,"%.5lf %.5lg %.5lg\n",
			  (double)(psr[ii].obsn[jj].bat-psr[0].param[param_pepoch].val[0]),
			  (double)(psr[ii].obsn[jj].residual),(double)(psr[ii].obsn[jj].toaErr)/1.0e6);
		fclose(fout);
	      }
	  }
	else if (key=='x') 
	  {
	    xautoscale*=-1;
	    if (xautoscale==-1)
	      {
		for (k=0;k<npsr;k++)
		  {
		    count=0;
		    for (i=0;i<psr[k].nobs;i++)
		      {
			if (psr[k].obsn[i].deleted==0   &&
			    (psr[k].param[param_start].paramSet[0]!=1 || psr[k].param[param_start].fitFlag[0]!=1 ||
			     psr[k].param[param_start].val[0] < psr[k].obsn[i].bat) &&
			    (psr[k].param[param_finish].paramSet[0]!=1 || psr[k].param[param_finish].fitFlag[0]!=1 ||
			     psr[k].param[param_finish].val[0] > psr[k].obsn[i].bat))

			  {x[count] = (double)(psr[k].obsn[i].bat-psr[0].param[param_pepoch].val[0]); count++;}
		      }
		    minx = findMin(x,psr,k,scale1,count);
		    maxx = findMax(x,psr,k,scale1,count);
		    if (k==0)
		      {
			tmin = minx;
			tmax = maxx;
			printf("Have1 tmin = %f, tmax = %f\n",tmin,tmax);
		      }
		    else
		      {
			if (tmin > minx) tmin = minx;
			if (tmax < maxx) tmax = maxx;
			printf("Have2 tmin = %f, tmax = %f\n",tmin,tmax);

		      }
		  }
	      }
	  }       
	else if (key=='y') 
	  {
	    yautoscale*=-1;
	    if (yautoscale==-1)
	      {
		for (k=0;k<npsr;k++)
		  {
		    count=0;
		    for (i=0;i<psr[k].nobs;i++)
		      {
			if (psr[k].obsn[i].deleted==0   &&
			    (psr[k].param[param_start].paramSet[0]!=1 || psr[k].param[param_start].fitFlag[0]!=1 ||
			     psr[k].param[param_start].val[0] < psr[k].obsn[i].bat) &&
			    (psr[k].param[param_finish].paramSet[0]!=1 || psr[k].param[param_finish].fitFlag[0]!=1 ||
			     psr[k].param[param_finish].val[0] > psr[k].obsn[i].bat))			  
			  {y[count] = (double)psr[k].obsn[i].prefitResidual*1e6; count++;}
		      }
		    miny = findMin(y,psr,k,scale1,count);
		    maxy = findMax(y,psr,k,scale1,count);
		    if (k==0)
		      {
			tminy1 = miny;
			tmaxy1 = maxy;
		      }
		    else
		      {
			if (tminy1 > miny) tminy1 = miny;
			if (tmaxy1 < maxy) tmaxy1 = maxy;
		      }

		    count=0;
		    for (i=0;i<psr[k].nobs;i++)
		      {
			if (psr[k].obsn[i].deleted==0   &&
			    (psr[k].param[param_start].paramSet[0]!=1 || psr[k].param[param_start].fitFlag[0]!=1 ||
			     psr[k].param[param_start].val[0] < psr[k].obsn[i].bat) &&
			    (psr[k].param[param_finish].paramSet[0]!=1 || psr[k].param[param_finish].fitFlag[0]!=1 ||
			     psr[k].param[param_finish].val[0] > psr[k].obsn[i].bat))
			  {y[count] = (double)psr[k].obsn[i].residual*1e6; count++;}
		      }
		    miny = findMin(y,psr,k,scale1,count);
		    maxy = findMax(y,psr,k,scale1,count);
		    if (k==0)
		      {
			tminy2 = miny;
			tmaxy2 = maxy;
		      }
		    else
		      {
			if (tminy2 > miny) tminy2 = miny;
			if (tmaxy2 < maxy) tmaxy2 = maxy;
		      }
		  }
		printf("Have tminy2 = %g %g\n",tminy2,tmaxy2);
	      }
	  }       
	else printf("Unknown key press %c\n",key);
      }
    else
      {
	graphics=1;

	cpgend();
	if (plotpre==-1)
	  {
	    cpgend();
	    if (overlay==1)
	      cpgbeg(0,"/xs",1,1);
	    else
	      cpgbeg(0,"/xs",1,npsr);
	    cpgpap(widthPap,aspectPap);
	    cpgsch(fontSize);
	    cpgask(0);	      
	  }
	else
	  {
	    cpgend();
	    if (overlay==1)
	      cpgbeg(0,"/xs",2,1);
	    else
	      cpgbeg(0,"/xs",2,npsr);
	    cpgpap(widthPap,aspectPap);
	    cpgsch(fontSize);
	    cpgask(0);	      
	  }
      }
  } while (exitFlag==0);
  
  cpgend();
}