void plotAnitaEventMap(Adu5Pat *patPtr,double phi,double theta){

  double sourceLon,sourceLat,headLon,headLat,phi10Lon,phi10Lat,phi6Lon,phi6Lat,phi14Lon,phi14Lat,actualLat,actualLon,actual2Lat,actual2Lon;
  float xEvent,yEvent,xAnita,yAnita,anitaLat,anitaLon,anitaAlt,xHead,yHead,x10,y10,x6,y6,x14,y14,yActual,xActual,yActual2,xActual2;

  anitaLat = patPtr->latitude;
  anitaLon = patPtr->longitude;
  anitaAlt = patPtr->altitude;

  UsefulAdu5Pat usefulPat(patPtr);
  std::cout << "source " << std::endl;
  //int sourceLoc = usefulPat.getSourceLonAndLatAltZero((180-phi)/180.*PI,(theta)/180.*PI,sourceLon,sourceLat);
  int sourceLoc = usefulPat.getSourceLonAndLatAltZero((phi)/180.*PI,(theta)/180.*PI,sourceLon,sourceLat);
  std::cout << std::endl << "heading " << std::endl;
  int headLoc = usefulPat.getSourceLonAndLatAltZero(0./180.*PI,10./180.*PI,headLon,headLat);
  std::cout << std::endl << "phi 10 " << std::endl;
  int headLoc10 = usefulPat.getSourceLonAndLatAltZero(180./180.*PI,10./180.*PI,phi10Lon,phi10Lat);
  std::cout << std::endl << "phi 14 " << std::endl;
  int headLoc14 = usefulPat.getSourceLonAndLatAltZero(270./180.*PI,10./180.*PI,phi14Lon,phi14Lat);
  std::cout << std::endl << "phi 6 " << std::endl;
  int headLoc6 = usefulPat.getSourceLonAndLatAltZero(90./180.*PI,10./180.*PI,phi6Lon,phi6Lat);
  std::cout << std::endl << "actual 14.5 " << std::endl;
  int actualLoc = usefulPat.getSourceLonAndLatAltZero(phi/180.*PI,12.5/180.*PI,actualLon,actualLat);
  std::cout << std::endl << "actual 4.5 " << std::endl;
  int actualLoc2 = usefulPat.getSourceLonAndLatAltZero(phi/180.*PI,7.5/180.*PI,actual2Lon,actual2Lat);
  //int sourceLoc = usefulPat.getSourceLonAndLatAltZero((phi)/180.*PI,(TMath::PiOver2()-theta)/180.*PI,sourceLon,sourceLat);
  TImage *map = TImage::Open("/home/mottram/work/eventCorrelator/macros/antarcticaIceMap.png");

  std::cout << "sourceLoc " << sourceLoc << " phi " << phi << " theta " << theta << " lon " << sourceLon << " lat " << sourceLat << std::endl;
  gStyle->SetMarkerColor(kBlack);
  //gStyle->SetMarkerSize(2);
  gStyle->SetTextSize(0.02);
  TMarker *anitaPos = new TMarker(xAnita,yAnita,23);

  getRelXYFromLatLong(anitaLat,anitaLon,xAnita,yAnita);
  getRelXYFromLatLong(static_cast<float>(sourceLat),static_cast<float>(sourceLon),xEvent,yEvent);
  getRelXYFromLatLong(static_cast<float>(headLat),static_cast<float>(headLon),xHead,yHead);
  getRelXYFromLatLong(static_cast<float>(phi10Lat),static_cast<float>(phi10Lon),x10,y10);
  getRelXYFromLatLong(static_cast<float>(phi14Lat),static_cast<float>(phi14Lon),x14,y14);
  getRelXYFromLatLong(static_cast<float>(phi6Lat),static_cast<float>(phi6Lon),x6,y6);
  getRelXYFromLatLong(static_cast<float>(actualLat),static_cast<float>(actualLon),xActual,yActual);
  getRelXYFromLatLong(static_cast<float>(actual2Lat),static_cast<float>(actual2Lon),xActual2,yActual2);

  TCanvas *canMap=(TCanvas*)gROOT->FindObject("canMap");
  if(!canMap)
     canMap = new TCanvas("canMap","canMap",(int)xSize,(int)ySize);
  canMap->Clear();
  canMap->SetLogz();
  canMap->SetTopMargin(0);
  canMap->SetBottomMargin(0);
  canMap->SetLeftMargin(0);
  canMap->SetRightMargin(0);

  map->Draw("");

  TMarker *headingPos = new TMarker(xHead,yHead,29);
  TMarker *heading14Pos = new TMarker(x14,y14,29);
  TMarker *heading10Pos = new TMarker(x10,y10,29);
  TMarker *heading6Pos = new TMarker(x6,y6,29);
  TMarker *actualPos = new TMarker(xActual,yActual,29);
  TMarker *actual2Pos = new TMarker(xActual2,yActual2,29);
  headingPos->SetMarkerColor(kRed);
  heading14Pos->SetMarkerColor(kGray);
  heading10Pos->SetMarkerColor(kGray+2);
  heading6Pos->SetMarkerColor(kViolet);
  actualPos->SetMarkerColor(kRed+2);//12.5 theta
  actual2Pos->SetMarkerColor(kBlue+2);//7.5 theta

  headingPos->Draw("");
  heading14Pos->Draw("");
  heading10Pos->Draw("");
  heading6Pos->Draw("");
  actualPos->Draw("");
  actual2Pos->Draw("");
  anitaPos->DrawMarker(xAnita,yAnita);
  

  TLatex *positionLabel=0;
  char label[FILENAME_MAX];

  if(sourceLoc==0){
    if(anitaAlt<0){
      sprintf(label,"Could not get event position, ANITA below 0 altitude!");
    }
    else if(theta>0){
      sprintf(label,"Pointing upwards!  Cannot locate source at ground position");
    }
    else{
      sprintf(label,"Unkown error, cannot position source at 0 altitude");
    }
    positionLabel = new TLatex();
    positionLabel->DrawLatex(0.05,0.95,label);
    return;
  }

  TMarker *eventPos = new TMarker(xEvent,yEvent,29);
  eventPos->SetMarkerColor(kBlack);
  eventPos->Draw("");

  sprintf(label,"ANITA location: lat %f; long %f; alt %f, x %f, y %f",anitaLat,anitaLon,anitaAlt,xAnita,yAnita);
  positionLabel = new TLatex();
  positionLabel->DrawLatex(0.05,0.97,label);
  sprintf(label,"Event location: lat %f; long %f, x %f, y %f",sourceLat,sourceLon,xEvent,yEvent);
  positionLabel->DrawLatex(0.05,0.94,label);

}
TH2D *crossCorrelate(RawAnitaEvent *evPtr,RawAnitaHeader *hdPtr,Adu5Pat *patPtr){

  gStyle->SetPalette(1);

  int triggeredPhi[16];
  int triggeredAnt[32];

  double thetaArray[NUM_BINS_THETA];
  double phiArray[NUM_BINS_PHI];
  double cosThetaArray[NUM_BINS_THETA];
  double sinThetaArray[NUM_BINS_THETA];
  double cosPhiArray[NUM_BINS_PHI];
  double sinPhiArray[NUM_BINS_PHI];

  PrettyAnitaEvent realEvent(evPtr,WaveCalType::kVTFullAGCrossCorClock,hdPtr);
  UsefulAdu5Pat usefulPat(patPtr);

  getTriggeredPhi(hdPtr,triggeredPhi);
  getTriggeredAnt(triggeredPhi,triggeredAnt);
  setupCosSinArray(thetaArray,phiArray,cosThetaArray,sinThetaArray,cosPhiArray,sinPhiArray);

  TGraph *grTemp[32]={0};
  TGraph *grTemp2[32]={0};
  TGraph *grTemp3[32]={0};
  TGraph *grInt[32]={0};
  TGraph *grCorr[528]={0};
  double firstCorrTime[528];
  double dummyY;
  Double_t deltaT=1/(2.6*8.);

  for(int ant=0;ant<32;ant++){
    if(triggeredAnt[ant]){
      //grInt[ant]=realEvent.getGraph(AnitaGeomTool::getChanIndexFromAntPol(ant,AnitaPol::kVertical));
      grTemp[ant]=realEvent.getGraph(AnitaGeomTool::getChanIndexFromAntPol(ant,AnitaPol::kVertical));
      grTemp2[ant]=FFTtools::simpleNotchFilter(grTemp[ant],370.,520.);
      grTemp3[ant]=FFTtools::simpleNotchFilter(grTemp2[ant],920.,980.);
      grInt[ant]=FFTtools::simpleNotchFilter(grTemp3[ant],1120,1220);
    }
  }
  int arrayRef=0;

  char canName[FILENAME_MAX];
  TCanvas *canny[528];

  for(int ant1=0;ant1<32;ant1++){
    for(int ant2=ant1;ant2<32;ant2++){

      if(triggeredAnt[ant1] && triggeredAnt[ant2] && ant1!=ant2){
	grCorr[arrayRef]=FFTtools::getInterpolatedCorrelationGraph(grInt[ant1],grInt[ant2],deltaT);
	grCorr[arrayRef]->GetPoint(0,firstCorrTime[arrayRef],dummyY);
	/*
	sprintf(canName,"can%d",arrayRef);
	canny[arrayRef] = new TCanvas(canName,canName,800,600);
	canny[arrayRef]->Divide(1,3);
	canny[arrayRef]->cd(1);
	sprintf(canName,"ant %d (phi %d)",ant1+1,AnitaGeomTool::getPhiFromAnt(ant1)+1);
	grInt[ant1]->SetTitle(canName);
	grInt[ant1]->Draw("al");
	canny[arrayRef]->cd(2);
	sprintf(canName,"ant %d (phi %d)",ant2+1,AnitaGeomTool::getPhiFromAnt(ant2)+1);
	grInt[ant2]->SetTitle(canName);
	grInt[ant2]->Draw("al");
	canny[arrayRef]->cd(3);
	sprintf(canName,"corr %d %d",ant1+1,ant2+1);
	grCorr[arrayRef]->SetTitle(canName);
	grCorr[arrayRef]->Draw("al");
	*/
	arrayRef++;
      }
      else{
	if(ant1!=ant2) arrayRef++;
      }

    }
  }

  double deltaTarray[NUM_BINS_PHI][NUM_BINS_THETA];
  double correlationArray[NUM_BINS_PHI][NUM_BINS_THETA];

  for(int phi=0;phi<NUM_BINS_PHI;phi++){
    for(int theta=0;theta<NUM_BINS_THETA;theta++){
      deltaTarray[phi][theta]=0.;
      correlationArray[phi][theta]=0.;
    }
  }

  int getPoint;
  double xVal1;
  double xVal2;
  double weight1;
  double weight2;
  double pointVal1;
  double pointVal2;

  arrayRef=0;
  for(int ant1=0;ant1<32;ant1++){
    for(int ant2=ant1;ant2<32;ant2++){

      if(triggeredAnt[ant1] && triggeredAnt[ant2] && ant1!=ant2){// && ant1==2 && ant2==21){

	for(int phi=0;phi<NUM_BINS_PHI;phi++){
	  for(int theta=0;theta<NUM_BINS_THETA;theta++){

	    //deltaTarray[phi][theta] = usefulPat.getDeltaTExpected(ant1,ant2,cosPhiArray[phi],sinPhiArray[phi],cosThetaArray[theta],sinThetaArray[theta]);
	    deltaTarray[phi][theta] = usefulPat.getDeltaTExpected(ant1,ant2,phiArray[phi],thetaArray[theta]);

	    getPoint=static_cast<int>((deltaTarray[phi][theta]-firstCorrTime[arrayRef])*1/deltaT);

	    grCorr[arrayRef]->GetPoint(getPoint,xVal1,pointVal1);
	    grCorr[arrayRef]->GetPoint(getPoint+1,xVal2,pointVal2);

	    //std::cout << "delta T" << deltaTarray[phi][theta] << " xVal " << xVal1 << " xVal2 " << xVal2 << std::endl;

	    weight1 = 1 - fabs(deltaTarray[phi][theta]-xVal1)/(deltaT);
	    weight2 = 1 - fabs(deltaTarray[phi][theta]-xVal2)/(deltaT);

	    correlationArray[phi][theta]+=(pointVal1*weight1+pointVal2*weight2);

	  }//theta
	}//phi

      }//if

      if(ant1!=ant2) arrayRef++;

    }//ant2
  }//ant1

  char histName[FILENAME_MAX];
  sprintf(histName,"sumCrossCorrs");
  //H2D *sumCrossCorrs = new TH2D(histName,histName,NUM_BINS_PHI,2,17,NUM_BINS_THETA,-90,90);
  TH2D *sumCrossCorrs = new TH2D(histName,histName,NUM_BINS_PHI,0,360,NUM_BINS_THETA,-90,90);
  double phiscale = (15./360.);
  for(int phi=0;phi<NUM_BINS_PHI;phi++){
    for(int theta=0;theta<NUM_BINS_THETA;theta++){
      //sumCrossCorrs->Fill(phiArray[phi]*180/PI*phiscale+2.,thetaArray[theta]*180./PI,correlationArray[phi][theta]);
      if(thetaArray[theta]*180./PI < 50. && thetaArray[theta]*180./PI > -50.)// && phiArray[phi]*180./PI >270)
        sumCrossCorrs->Fill(phiArray[phi]*180./PI,thetaArray[theta]*180./PI,correlationArray[phi][theta]);

    }
  }

  //sprintf(histName,"crossCorrCan");
  //TCanvas *crossCorrCan = new TCanvas(histName,histName,800,400);
  //sumCrossCorrs->Draw("aitoff");
  //sumCrossCorrs->Draw("colz");

  return sumCrossCorrs;

}
double thetaOpt2(double *par){

  int upperAntNums[NUM_PHI]={8,0,9,1,10,2,11,3,12,4,13,5,14,6,15,7};
  int lowerAntNums[NUM_PHI]={16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
  int lowerAntFromUpper[NUM_PHI]={17,19,21,23,25,27,29,31,16,18,20,22,24,26,28,30};
  int nadirAntNums[NUM_PHI]={32,-1,33,-1,34,-1,35,-1,36,-1,37,-1,38,-1,39,-1};
  int bottomFromNadir[8]={16,18,20,22,24,26,28,30};

  Double_t deltaR[40]={0};  
  Double_t deltaZ[40]={0};  
  Double_t deltaPhi[40]={0};  
  Double_t deltaHeading[1]={0};
  double  deltaTArrayMod[40]={0};
 
 int count3 = 0;


//   for(int i = 0; i<32;i++){
//     deltaR[i]=par[i];   
//     deltaZ[i]=par[i+32];
//     deltaPhi[i]=par[i+64];

//     cout << i << "  " <<0 << " " << deltaR[i] << " " << deltaPhi[i] << " " << deltaZ[i] << endl;

//   }

  for(int i = 7; i<8;i++){
    deltaR[7]=par[0];   
    deltaZ[7]=par[1];
    deltaPhi[7]=par[2];

    cout << i << "  " <<0 << " " << deltaR[i] << " " << deltaPhi[i] << " " << deltaZ[i] << endl;

  }


  // for(int i = 0; i<16;i++){
  //  deltaPhi[i]=deltaPhi[i] + par[16]; 
  //  deltaPhi[i+16]=deltaPhi[i+16] + par[17];     
  // }

  double theReturn = 0;
  double sumMean = 0;
  double sumMean2 = 0;
  int count8 = 0;
  double sumGrads = 0;

  TMultiGraph *myMG = new TMultiGraph;
  TMultiGraph *myMG3 = new TMultiGraph;
  TMultiGraph *myMG2 = new TMultiGraph;;

  AnitaGeomTool *fGeomTool = AnitaGeomTool::Instance();
  char eventName[FILENAME_MAX];
  char headerName[FILENAME_MAX];
  char hkName[FILENAME_MAX];
  char gpsName[FILENAME_MAX];
  char corrName[FILENAME_MAX];
  char outName[FILENAME_MAX];
  char baseDir[FILENAME_MAX];
  char *corTreeDir = "../../../Outfiles";
  double dummyArray[40][1] ={{0}}; 
  TGraph *tempAntGraph;

  vector<vector<double> > phiAngle;
  vector<vector<double> > deltaTVec;
  vector<vector<int> > firstAntVec;
  vector<vector<int> > secondAntVec;

  vector<vector<double> > phiAngleArray2;
  vector<vector<double> > deltaTArray2;

  vector<double> temp;
  vector<int> temp2;
  temp.push_back(0);
  temp2.push_back(0);

  double deltaTArrayLoop[6000] ={0};
  double phiAngleArrayLoop[6000] = {0};


  int leftOpt, rightOpt;


  double meanPhi[40] = {0}; 
  meanPhi[0] =22.5-12.5;
  meanPhi[1] =67.5-12.5;
  meanPhi[2] =112.5-12.5;
  meanPhi[3] =157.5-12.5;
  meanPhi[4] =202.5-12.5;
  meanPhi[5] =247.5-12.5;
  meanPhi[6] =292.5-12.5;
  meanPhi[7] =337.5-12.5;
  meanPhi[8] =45-12.5;
  meanPhi[9] =90-12.5;
  meanPhi[10] =135-12.5;
  meanPhi[11] =180-12.5;
  meanPhi[12] =225-12.5;
  meanPhi[13] =270-12.5;
  meanPhi[14] =315-12.5;
  meanPhi[15] =360-12.5;

  meanPhi[16] = 22.5-12.5;
  meanPhi[17] = 45-12.5;
  meanPhi[18] = 67.5-12.5;
  meanPhi[19] = 90-12.5;
  meanPhi[20] = 112.5-12.5;
  meanPhi[21] = 135-12.5;
  meanPhi[22] = 157.5-12.5;
  meanPhi[23] = 180-12.5;
  meanPhi[24] = 202.5-12.5;
  meanPhi[25] = 225-12.5;
  meanPhi[26] = 247.5-12.5;
  meanPhi[27] = 270-12.5;
  meanPhi[28] = 292.5-12.5;
  meanPhi[29] = 315-12.5;
  meanPhi[30] = 337.5-12.5;
  meanPhi[31] = 360-12.5;


  meanPhi[32] = 22.5-12.5;
  meanPhi[33] = 67.5-12.5;
  meanPhi[34] = 112.5-12.5;
  meanPhi[35] = 157.5-12.5;
  meanPhi[36] = 202.5-12.5;
  meanPhi[37] = 247.5-12.5;
  meanPhi[38] = 292.5-12.5;
  meanPhi[39] = 337.5-12.5;

  for(int i =0; i < 40; i++){
    phiAngleArray2.push_back(temp);
    deltaTArray2.push_back(temp);

  }

  for(int loop = 1; loop <4; loop++){
    int run = 16+loop;
    //int run = 18;

    canSurf->cd(loop+1);

    phiAngle.clear();
    deltaTVec.clear();
    firstAntVec.clear();
    secondAntVec.clear();

    for(int i = 0; i < 40; i++){
      phiAngle.push_back(temp);
      deltaTVec.push_back(temp);
      firstAntVec.push_back(temp2);
      secondAntVec.push_back(temp2);
    }

    //sprintf(baseDir,"http://www.hep.ucl.ac.uk/uhen/anita/private/monitor2/runs/fromLoki/");
    sprintf(baseDir,"/Users/simonbevan/Desktop/");
    sprintf(eventName,"%s/run%d/eventFile%d.root",baseDir,run,run);
    sprintf(headerName,"%s/run%d/headFile%d.root",baseDir,run,run);
    sprintf(gpsName,"%s/run%d/gpsFile%d.root",baseDir,run,run);
    sprintf(corrName,"%s/corRun%d.root",corTreeDir,run);

   
    RawAnitaEvent *event = 0;
    PrettyAnitaHk *hk = 0;
   
    RawAnitaHeader *header =0;
    Adu5Pat *pat =0;
    CorrelationSummary *corSum =0;
   
  
    TFile *fpHead = TFile::Open(headerName);
    TTree *headTree = (TTree*) fpHead->Get("headTree");
    headTree->SetBranchAddress("header",&header);
    headTree->BuildIndex("eventNumber");
   
    TFile *fpGps = TFile::Open(gpsName);
    TTree *adu5PatTree = (TTree*) fpGps->Get("adu5PatTree");
    adu5PatTree->BuildIndex("realTime");
    adu5PatTree->SetBranchAddress("pat",&pat);
   
    Int_t labChip;
    TFile *fpCor = new TFile(corrName);
    TTree *corTree = (TTree*) fpCor->Get("corTree");
    corTree->SetBranchAddress("cor",&corSum);
    corTree->SetBranchAddress("labChip",&labChip);

    Long64_t numEntries=corTree->GetEntries();
    int counter=0;

    Long64_t entry=0;
    UInt_t eventNumber, triggerTime, triggerTimeNs;
    Int_t firstAnt,secondAnt,maxAnt,corInd;
    Double_t deltaT,deltaTExpected;
    Double_t phiWave, phiMaxAnt;
    Double_t corPeak, corRMS;
    Double_t balloonLat, balloonLon, balloonAlt;
    Double_t heading,pitch,roll;
  

    Double_t thetaWave;

    for(entry=0;entry<numEntries;entry++) {

      corTree->GetEntry(entry);
      Long64_t headEntry=headTree->GetEntryNumberWithIndex(corSum->eventNumber);
      if(headEntry<0) 
	continue;
      headTree->GetEntry(headEntry);
     
      if( (header->triggerTimeNs>0.5e6) || (header->triggerTimeNs<0.2e6) )  
	continue; 

      triggerTimeNs=header->triggerTimeNs;
      triggerTime=header->triggerTime;
      eventNumber=header->eventNumber;
  

      Long64_t bestEntry = adu5PatTree->GetEntryNumberWithBestIndex(header->triggerTime);
      if(bestEntry>-1) 
	adu5PatTree->GetEntry(bestEntry);
      else 
	continue;
      
      balloonLat=pat->latitude;
      balloonLon=pat->longitude;
      balloonAlt=pat->altitude;
      heading=pat->heading;
      pat->pitch=0.64;
      pat->roll=0.14;

      pitch=pat->pitch;
      roll=pat->roll;

      UsefulAdu5Pat usefulPat(pat);
      
      for(corInd=0;corInd<19;corInd++) {
	
	firstAnt=corSum->firstAnt[corInd];
	secondAnt=corSum->secondAnt[corInd];

	//replace taylor dome
	
	usefulPat.fSourceLongitude=0;
	//	deltaTExpected=usefulPat.getDeltaTTaylor(corSum->firstAnt[corInd],corSum->secondAnt[corInd]);
	deltaTExpected=usefulPat.getDeltaTTaylorOpt(corSum->firstAnt[corInd],corSum->secondAnt[corInd],deltaR,deltaZ,deltaPhi);
	
	deltaT=corSum->maxCorTimes[corInd];
	maxAnt=corSum->centreAntenna;
	phiWave=usefulPat.getPhiWave()*TMath::RadToDeg();
	phiMaxAnt=fGeomTool->getAntPhiPositionRelToAftFore(corSum->centreAntenna)*TMath::RadToDeg();
	corPeak=corSum->maxCorVals[corInd];
	corRMS=corSum->rmsCorVals[corInd];

	if((deltaT - deltaTExpected)*(deltaT - deltaTExpected) < 1 && (corPeak/corRMS)>8 ){
	  phiAngle[0].push_back(phiWave);
	  deltaTVec[0].push_back(deltaT - deltaTExpected + deltaTArrayMod[firstAnt] - deltaTArrayMod[secondAnt]);
	  firstAntVec[0].push_back(firstAnt);
	  secondAntVec[0].push_back(secondAnt);  
	}
      }

      counter++; 
    
    }

 

    double deltaTArray[40][3000] = {{0}};
    double phiAngleArray[40][3000]= {{0}};

    double deltaTArrayCut[40][3000]= {{0}};
    double phiAngleArrayCut[40][3000]= {{0}};
    int whichCut[40][3000] = {{0}};

    int middleAnt; 
    int leftAnt,rightAnt;

    int countArray[40] = {0};





    //fill arrays
    //for(int ants = par[0]; ants < par[0]+1; ants++){
    for(int ants = 0; ants < 32; ants++){

      double lower  = meanPhi[ants] - 20;
      double upper = meanPhi[ants] + 10;
      //	double lower  = 0;
      //  	double upper = 360;


	     if(ants<8){
	lower = lower;
	upper=upper;

	if(lower < 0){
	  lower = 0;
	  upper = 20;
	}

	if(upper > 360){
	  lower = 330;
	  upper = 360;
	}

      }else if(ants<16){
	       	lower = lower;
	       upper= upper;
	if(lower < 0){
	  lower = 330;
	  upper = 355;
	}

	if(upper > 360){
	  lower = 330;
	  upper = 360;
	}

      }




      int count = 0;
      int count2 = 0;
       count3 = 0;
      double sumPhi = 0;
      bool true1 = false;
      bool true2 = false;

      if(ants <32){
	fGeomTool->getThetaPartners(ants,leftAnt,rightAnt); 
      }else{
	leftAnt = ants;
	rightAnt = ants +1;
	if(ants == 39){
	  leftAnt = ants;
	  rightAnt = 32;
	}
      }    

      for(int events = 1; events < phiAngle[0].size(); events++){
	int firstAntTemp = (int)firstAntVec[0][events];
	int secondAntTemp = (int)secondAntVec[0][events];
	int rightTemp = int(rightAnt);

	int aboveTemp = 0;

	if(ants <16){
	  aboveTemp = lowerAntFromUpper[ants];
	}else{
	  aboveTemp = upperAntNums[ants-16];
	}
  
	if(firstAntTemp < 32){
      
 	  if( ((firstAntTemp == ants) &&  (secondAntTemp == rightTemp))){
	    //if((firstAntTemp == ants) &&  (secondAntTemp == rightTemp)){
	    if((phiAngle[0][events] > lower ) && (phiAngle[0][events]< upper)){
 	    deltaTArray[ants][count] = deltaTVec[0][events];
 	    phiAngleArray[ants][count] = phiAngle[0][events];
 	    whichCut[ants][count] = 1; 

	    count++;
	     }


	  } else if(((firstAntTemp == ants) &&  (secondAntTemp == aboveTemp))){
// 	    //if((firstAntTemp == ants) &&  (secondAntTemp == rightTemp)){

      double lower  = meanPhi[ants] - 20;
      double upper = meanPhi[ants] + 10;
      //	double lower  = 0;
      //  	double upper = 360;


	     if(ants<8){
	lower = lower;
	upper=upper;

	if(lower < 0){
	  lower = 0;
	  upper = 20;
	}

	if(upper > 360){
	  lower = 330;
	  upper = 360;
	}

      }else if(ants<16){
	       	lower = lower - 45;
	       upper= upper - 45;
	if(lower < 0){
	  lower = 330;
	  upper = 355;
	}

	if(upper > 360){
	  lower = 330;
	  upper = 360;
	}

      }



	    //    if((phiAngleArray[ants][events] > lower ) && (phiAngleArray[ants][events]< upper)){
	  if((phiAngle[0][events] > lower ) && (phiAngle[0][events]< upper)){
	    deltaTArray[ants][count] = deltaTVec[0][events];
	      phiAngleArray[ants][count] = phiAngle[0][events];
	      whichCut[ants][count] = 0; 

	      count++;   
	      }
	  }
 
	}else{
      
	  rightTemp = firstAntTemp+1;
	  if(rightTemp>39){
	    rightTemp = 32;
	  }
      
	  if(firstAntTemp == ants){
	
	  }
      
	  if((firstAntTemp == ants) &&  (secondAntTemp == rightTemp)){
		
	    deltaTArray[ants][count] = deltaTVec[0][events];
	    phiAngleArray[ants][count] = phiAngle[0][events];
	whichCut[ants][count] = 3; 
	    count++;
	  }
	}
    
    
      }
      countArray[ants] = count;
      
  
    }
    
    
    //make cuts
    for(int ants = 0; ants < 32; ants++){
   
       count3 = 0;
      if(ants <32){
	fGeomTool->getThetaPartners(ants,leftAnt,rightAnt); 
      }else{
	leftAnt = ants -1;
	rightAnt = ants +1;
	if(ants == 39){
	  leftAnt = ants - 1;
	  rightAnt = 32;
	}
      }    

      double sumPhi = 0;
    double   lower  = meanPhi[ants] - 20;
    double   upper = meanPhi[ants] + 10;
      //	double lower  = 0;
      //   	double upper = 360;


 

	     if(ants<8){
	lower = lower;
	upper=upper;

	if(lower < 0){
	  lower = 0;
	  upper = 20;
	}

	if(upper > 360){
	  lower = 330;
	  upper = 360;
	}

      }else if(ants<16){
	       	lower = lower;
	       upper= upper;
	if(lower < 0){
	  lower = 330;
	  upper = 355;
	}

	if(upper > 360){
	  lower = 330;
	  upper = 360;
	}

      }


      for(int events = 0; events < countArray[ants]; events++){
	  
 
// 	if(whichCut[ants][events]==1){
//      lower  = meanPhi[ants] - 20;
//       upper = meanPhi[ants] + 20;
// 		if(lower < 0){
// 	  lower = 0;
// 	  upper = 20;
// 	}

// 	if(upper > 360){
// 	  lower = 330;
// 	  upper = 360;
// 	}



// 	}

//	if((phiAngleArray[ants][events] > lower ) && (phiAngleArray[ants][events]< upper)){
	  phiAngleArrayCut[ants][count3] = phiAngleArray[ants][events];
	  deltaTArrayCut[ants][count3] = deltaTArray[ants][events];
	    
	  	  count3++;
	      
		  //		  	}

      }
	
      for(int events = 0; events < count3-1; events++){
	phiAngleArray2[ants].push_back(phiAngleArrayCut[ants][events]);
	deltaTArray2[ants].push_back(deltaTArrayCut[ants][events]);
      }

	
    }
    
    delete event;
    delete hk; 
    delete header;
    delete pat;
    delete corSum;

    delete fpHead;
    delete fpGps ;
    delete fpCor;

  }

  sumMean = 0;
  sumMean2 = 0;
  sumGrads = 0;
  for(int ants = 0; ants < 32; ants++){
    count8 = 0;
    for(int events = 1; events < phiAngleArray2[ants].size(); events++){

      if( deltaTArrayLoop[count8]<1){      
	deltaTArrayLoop[count8] = deltaTArray2[ants][events];
	phiAngleArrayLoop[count8] = phiAngleArray2[ants][events];
	count8++;
      }
      
    }
    
    if(count8==0){
      tempAntGraph  = new TGraph(1, dummyArray[ants], dummyArray[ants]);
    }else{
      
      tempAntGraph  = new TGraph(count8-1,  phiAngleArrayLoop, deltaTArrayLoop);
      
      if(ants == 7){  
	
	canSurf->cd(1);
	
	tempAntGraph->SetMinimum(-0.5);
	tempAntGraph->SetMaximum(0.5);
	tempAntGraph->Draw("ap");    

	tempAntGraph->SetMarkerStyle(1);
	tempAntGraph->GetXaxis()->SetLimits(0,360);
    
	sumMean = sumMean + tempAntGraph->GetMean(2)*tempAntGraph->GetMean(2);

	if(ants == 8 || ants == 16 || ants == 12 || ants == 24){
	  tempAntGraph->SetMarkerColor(8);
	}

	if(ants == 3 || ants == 7 || ants == 23 || ants == 31){
	  tempAntGraph->SetMarkerColor(1);
	}
    
	if(ants == 9 || ants == 13 || ants == 18 || ants == 26){
	  tempAntGraph->SetMarkerColor(2);
	}
    
    
	if(ants == 10 || ants == 14 || ants == 20 || ants == 28){
	  tempAntGraph->SetMarkerColor(3);
	}
    
	if(ants == 11 || ants == 15 || ants == 22 || ants == 30){
	  tempAntGraph->SetMarkerColor(4);
	}
    
	if(ants == 0 || ants == 4 || ants == 17 || ants == 25){
	  tempAntGraph->SetMarkerColor(5);
	}


	if(ants == 2 || ants == 6 || ants == 21 || ants == 29){
	  tempAntGraph->SetMarkerColor(6);
	}

	if(ants == 1 || ants == 5 || ants == 19 || ants == 27){
	  tempAntGraph->SetMarkerColor(7);
	}
    
	tempAntGraph->GetXaxis()->SetTitle("phi (degrees)");
	tempAntGraph->GetYaxis()->SetTitle("actual - expected time");
	myMG2->Add(tempAntGraph);
	myMG2->Draw("p");
	
 	vector<double> myFit = leastSquares(phiAngleArrayLoop, deltaTArrayLoop, count8-1);
	double slope = myFit[0];
	double intercept = myFit[1];
	
	double tempX[2] = {slope*(meanPhi[ants]-20)+intercept,slope*(meanPhi[ants]+20)+intercept};
	double tempY[2] = {(meanPhi[ants]-20),(meanPhi[ants]+20)};
	sumGrads = sumGrads + myFit[0]*myFit[0]*10000;
      
      }
    } 
    

  }
  
  cout << " " << endl;
  cout << sumMean << "  " << sumGrads <<endl;
  canSurf->Update();
  cout << "  " << endl;  

  theReturn = sumMean+sumGrads;

  return theReturn;
   
}
void correlationTreeLoop(int run,char *baseDir, char *corTreeDir, char *outputDir) {
// antTimeOffset[0] = 0.292591; deltaR[0] = -0.0384839; deltaPhi[ 0] = -0.0100608; deltaZ[0] = 0;
// antTimeOffset[1] = 0.172375; deltaR[1] = 0.00634697; deltaPhi[ 1] = -0.00313443; deltaZ[1] = 0;
// antTimeOffset[2] = 0.342454; deltaR[2] = -0.0861167; deltaPhi[ 2] = -0.015312; deltaZ[2] = 0;
// antTimeOffset[3] = 0.0248334; deltaR[3] = 0.0461873; deltaPhi[ 3] = 0.00206827; deltaZ[3] = 0;
// antTimeOffset[4] = 0.0372539; deltaR[4] = 0.0153388; deltaPhi[ 4] = -0.0227948; deltaZ[4] = 0;
// antTimeOffset[5] = 0.137506; deltaR[5] = -0.00927728; deltaPhi[ 5] = 0.00750385; deltaZ[5] = 0;
// antTimeOffset[6] = 0.0475841; deltaR[6] = 0.0239867; deltaPhi[ 6] = 0.00388065; deltaZ[6] = 0;
// antTimeOffset[7] = 0.123741; deltaR[7] = 0.0125282; deltaPhi[ 7] = -0.00131021; deltaZ[7] = 0;
// antTimeOffset[8] = 0.380551; deltaR[8] = -0.0111636; deltaPhi[ 8] = -0.0299233; deltaZ[8] = 0;
// antTimeOffset[9] = 0.445956; deltaR[9] = -0.0959452; deltaPhi[ 9] = -0.00165365; deltaZ[9] = 0;
// antTimeOffset[10] = 0.439757; deltaR[10] = -0.0330808; deltaPhi[ 10] = -0.0107407; deltaZ[10] = 0;
// antTimeOffset[11] = 0.244031; deltaR[11] = -0.0475617; deltaPhi[ 11] = 0.0145914; deltaZ[11] = 0;
// antTimeOffset[12] = 0.321419; deltaR[12] = 0.0196292; deltaPhi[ 12] = -0.0150373; deltaZ[12] = 0;
// antTimeOffset[13] = 0.118473; deltaR[13] = -0.0190837; deltaPhi[ 13] = -0.0121967; deltaZ[13] = 0;
// antTimeOffset[14] = 0.27363; deltaR[14] = -0.00922367; deltaPhi[ 14] = -0.0038106; deltaZ[14] = 0;
// antTimeOffset[15] = 0.187377; deltaR[15] = -0.0294811; deltaPhi[ 15] = 0.0106842; deltaZ[15] = 0;
// antTimeOffset[16] = 0.0682454; deltaR[16] = 0.0140245; deltaPhi[ 16] = -0.0087849; deltaZ[16] = 0;
// antTimeOffset[17] = 0.296899; deltaR[17] = -0.0621836; deltaPhi[ 17] = 0.000682206; deltaZ[17] = 0;
// antTimeOffset[18] = 0.180588; deltaR[18] = -0.0379325; deltaPhi[ 18] = -0.00516052; deltaZ[18] = 0;
// antTimeOffset[19] = 0.165257; deltaR[19] = -0.0108062; deltaPhi[ 19] = -0.00770935; deltaZ[19] = 0;
// antTimeOffset[20] = 0.176423; deltaR[20] = -0.0601935; deltaPhi[ 20] = -0.00862535; deltaZ[20] = 0;
// antTimeOffset[21] = 0.301777; deltaR[21] = -0.0968276; deltaPhi[ 21] = -0.00920648; deltaZ[21] = 0;
// antTimeOffset[22] = 0.0969425; deltaR[22] = -0.0348523; deltaPhi[ 22] = 0.00037431; deltaZ[22] = 0;
// antTimeOffset[23] = 0.0422886; deltaR[23] = 0.0121726; deltaPhi[ 23] = 0.00310935; deltaZ[23] = 0;
// antTimeOffset[24] = -0.01737; deltaR[24] = 0.0405193; deltaPhi[ 24] = -0.00546085; deltaZ[24] = 0;
// antTimeOffset[25] = 0.0412981; deltaR[25] = 0.0239992; deltaPhi[ 25] = -0.00901249; deltaZ[25] = 0;
// antTimeOffset[26] = 0.166311; deltaR[26] = -0.0405203; deltaPhi[ 26] = -0.0145529; deltaZ[26] = 0;
// antTimeOffset[27] = 0.139405; deltaR[27] = -0.00401756; deltaPhi[ 27] = -0.00666063; deltaZ[27] = 0;
// antTimeOffset[28] = 0.104575; deltaR[28] = -0.0362955; deltaPhi[ 28] = -0.00372999; deltaZ[28] = 0;
// antTimeOffset[29] = 0.0345155; deltaR[29] = -0.00587152; deltaPhi[ 29] = 0.00197442; deltaZ[29] = 0;
// antTimeOffset[30] = 0.082859; deltaR[30] = -0.00611182; deltaPhi[ 30] = -0.000789595; deltaZ[30] = 0;
// antTimeOffset[31] = 0.078192; deltaR[31] = -0.00321244; deltaPhi[ 31] = 0.000188257; deltaZ[31] = 0;
// antTimeOffset[32] = 0.0143052; deltaR[32] = -0.0437687; deltaPhi[ 32] = -0.00289577; deltaZ[32] = 0;
// antTimeOffset[33] = 0.0671887; deltaR[33] = -0.0643475; deltaPhi[ 33] = -0.0203117; deltaZ[33] = 0;
// antTimeOffset[34] = 0.0819606; deltaR[34] = -0.0804245; deltaPhi[ 34] = -0.00503387; deltaZ[34] = 0;
// antTimeOffset[35] = -0.0659071; deltaR[35] = -0.0112675; deltaPhi[ 35] = -0.000220575; deltaZ[35] = 0;
// antTimeOffset[36] = -0.212624; deltaR[36] = 0.0337428; deltaPhi[ 36] = -0.00416114; deltaZ[36] = 0;
// antTimeOffset[37] = -0.00431668; deltaR[37] = -0.0525977; deltaPhi[ 37] = -0.0223176; deltaZ[37] = 0;
// antTimeOffset[38] = 0.0899397; deltaR[38] = -0.101587; deltaPhi[ 38] = 0.0058874; deltaZ[38] = 0;
// antTimeOffset[39] = 0.0294537; deltaR[39] = -0.0401037; deltaPhi[ 39] = 0.00899651; deltaZ[39] = 0;

// antTimeOffset[0] = 0.16044; deltaR[0] = -0.0618352; deltaPhi[ 0] = -0.00280991; deltaZ[0] = 0.0287513;
// antTimeOffset[1] = 0.290365; deltaR[1] = -0.110188; deltaPhi[ 1] = -0.00372876; deltaZ[1] = 0.0170052;
// antTimeOffset[2] = 0.349607; deltaR[2] = -0.140583; deltaPhi[ 2] = -0.024769; deltaZ[2] = 0.0623979;
// antTimeOffset[3] = 0.033917; deltaR[3] = -0.0260668; deltaPhi[ 3] = 0.00113633; deltaZ[3] = 0.0423352;
// antTimeOffset[4] = -0.074643; deltaR[4] = -0.0356161; deltaPhi[ 4] = -0.0141947; deltaZ[4] = -0.00394529;
// antTimeOffset[5] = 0.156259; deltaR[5] = -0.095648; deltaPhi[ 5] = 0.0117896; deltaZ[5] = 0.0105241;
// antTimeOffset[6] = 0.212836; deltaR[6] = -0.0907411; deltaPhi[ 6] = -0.0122972; deltaZ[6] = 0.0516748;
// antTimeOffset[7] = 0.541271; deltaR[7] = -0.157934; deltaPhi[ 7] = -0.00368077; deltaZ[7] = 0.130464;
// antTimeOffset[8] = -0.128575; deltaR[8] = 0.0582477; deltaPhi[ 8] = -0.0111813; deltaZ[8] = -0.035067;
// antTimeOffset[9] = -0.122485; deltaR[9] = -0.0119241; deltaPhi[ 9] = -0.00668961; deltaZ[9] = -0.0579302;
// antTimeOffset[10] = -0.263916; deltaR[10] = 0.0811694; deltaPhi[ 10] = -0.00717066; deltaZ[10] = -0.0897962;
// antTimeOffset[11] = -0.229033; deltaR[11] = 0.00897635; deltaPhi[ 11] = -5.65709e-05; deltaZ[11] = -0.0366053;
// antTimeOffset[12] = -0.222093; deltaR[12] = 0.0800239; deltaPhi[ 12] = -0.00901442; deltaZ[12] = -0.0750748;
// antTimeOffset[13] = -0.68459; deltaR[13] = 0.108285; deltaPhi[ 13] = -0.0148342; deltaZ[13] = -0.133195;
// antTimeOffset[14] = -0.516002; deltaR[14] = 0.107793; deltaPhi[ 14] = -0.00133016; deltaZ[14] = -0.143198;
// antTimeOffset[15] = -0.749822; deltaR[15] = 0.145538; deltaPhi[ 15] = -0.00448024; deltaZ[15] = -0.118927;
// antTimeOffset[16] = 0.0961751; deltaR[16] = -0.0564912; deltaPhi[ 16] = -0.00220892; deltaZ[16] = 0.0532255;
// antTimeOffset[17] = -0.166225; deltaR[17] = 0.00298098; deltaPhi[ 17] = 0.00128378; deltaZ[17] = -0.0263557;
// antTimeOffset[18] = 0.178941; deltaR[18] = -0.0972098; deltaPhi[ 18] = -0.00837075; deltaZ[18] = 0.0461125;
// antTimeOffset[19] = 0.171386; deltaR[19] = -0.0643506; deltaPhi[ 19] = -0.00831496; deltaZ[19] = 0.0592813;
// antTimeOffset[20] = -0.0204964; deltaR[20] = -0.0803763; deltaPhi[ 20] = -0.00428327; deltaZ[20] = -0.00602899;
// antTimeOffset[21] = 0.160323; deltaR[21] = -0.101956; deltaPhi[ 21] = -0.0151547; deltaZ[21] = 0.0514858;
// antTimeOffset[22] = 0.053953; deltaR[22] = -0.0773129; deltaPhi[ 22] = -0.00414444; deltaZ[22] = 0.0562807;
// antTimeOffset[23] = 0.00325878; deltaR[23] = -0.0378326; deltaPhi[ 23] = 0.000528826; deltaZ[23] = 0.0517299;
// antTimeOffset[24] = -0.0670197; deltaR[24] = -0.0225655; deltaPhi[ 24] = -0.00391848; deltaZ[24] = 0.0263552;
// antTimeOffset[25] = 0.0035097; deltaR[25] = -0.0427118; deltaPhi[ 25] = -0.00285503; deltaZ[25] = 0.0211308;
// antTimeOffset[26] = -0.0337735; deltaR[26] = -0.062921; deltaPhi[ 26] = -0.00747562; deltaZ[26] = -0.0138518;
// antTimeOffset[27] = -0.110361; deltaR[27] = -0.0144298; deltaPhi[ 27] = -0.0028118; deltaZ[27] = -0.0318333;
// antTimeOffset[28] = -0.227861; deltaR[28] = -0.0389804; deltaPhi[ 28] = -0.0012114; deltaZ[28] = -0.0674168;
// antTimeOffset[29] = -0.081439; deltaR[29] = -0.0449712; deltaPhi[ 29] = -0.00826954; deltaZ[29] = 0.00548985;
// antTimeOffset[30] = 0.17098; deltaR[30] = -0.0938958; deltaPhi[ 30] = -0.00969672; deltaZ[30] = 0.0597671;
// antTimeOffset[31] = 0.0258336; deltaR[31] = -0.052614; deltaPhi[ 31] = -0.000359792; deltaZ[31] = 0.044548;
// antTimeOffset[32] = -0.425254; deltaR[32] = -0.0372025; deltaPhi[ 32] = -0.00536103; deltaZ[32] = -0.0978299;
// antTimeOffset[33] = -0.440596; deltaR[33] = -0.0534945; deltaPhi[ 33] = -0.0144455; deltaZ[33] = -0.136331;
// antTimeOffset[34] = -0.256048; deltaR[34] = -0.0884831; deltaPhi[ 34] = -0.00580407; deltaZ[34] = -0.0676089;
// antTimeOffset[35] = -0.601107; deltaR[35] = 0.0224642; deltaPhi[ 35] = -0.00283517; deltaZ[35] = -0.115955;
// antTimeOffset[36] = -0.472965; deltaR[36] = 0.0023781; deltaPhi[ 36] = -0.00319073; deltaZ[36] = -0.049661;
// antTimeOffset[37] = -0.498374; deltaR[37] = -0.0241109; deltaPhi[ 37] = -0.0168551; deltaZ[37] = -0.102832;
// antTimeOffset[38] = -0.466373; deltaR[38] = -0.0623884; deltaPhi[ 38] = 0.00665517; deltaZ[38] = -0.131102;
// antTimeOffset[39] = -0.382128; deltaR[39] = -0.040161; deltaPhi[ 39] = 0.00508923; deltaZ[39] = -0.100047;

   AnitaGeomTool *fGeomTool = AnitaGeomTool::Instance();
   fGeomTool->useKurtAnitaIINumbers(1);
   char eventName[FILENAME_MAX];
   char headerName[FILENAME_MAX];
   char gpsName[FILENAME_MAX];
   char corrName[FILENAME_MAX];
   char outName[FILENAME_MAX];

   //   sprintf(baseDir,"http://www.hep.ucl.ac.uk/uhen/anita/private/monitor2/runs/fromLoki/");
   sprintf(eventName,"%s/run%d/eventFile%d.root",baseDir,run,run);
   sprintf(headerName,"%s/run%d/headFile%d.root",baseDir,run,run);
   sprintf(gpsName,"%s/run%d/gpsEvent%d.root",baseDir,run,run);
   sprintf(corrName,"%s/corRun%d.root",corTreeDir,run);
   sprintf(outName,"%s/deltaTFile%d.root",outputDir,run);

   
   RawAnitaHeader *header =0;
   Adu5Pat *pat =0;
   CorrelationSummary *corSum =0;
   
   
   TFile *fpHead = TFile::Open(headerName);
   TTree *headTree = (TTree*) fpHead->Get("headTree");
   headTree->SetBranchAddress("header",&header);
   headTree->BuildIndex("eventNumber");
   
   TFile *fpGps = TFile::Open(gpsName);
   TTree *adu5PatTree = (TTree*) fpGps->Get("adu5PatTree");
   adu5PatTree->BuildIndex("realTime");
   adu5PatTree->SetBranchAddress("pat",&pat);
   
   Int_t labChip;
   UInt_t expTaylorTime;
   TFile *fpCor = new TFile(corrName);
   TTree *corTree = (TTree*) fpCor->Get("corTree");
   corTree->SetBranchAddress("cor",&corSum);
   corTree->SetBranchAddress("labChip",&labChip);
   corTree->SetBranchAddress("expTaylorTime",&expTaylorTime);

   Long64_t numEntries=corTree->GetEntries();
   int counter=0;

   TFile *fpOut = new TFile(outName,"RECREATE");

   Long64_t entry=0;
   UInt_t eventNumber, triggerTime, triggerTimeNs;
   Int_t firstAnt,secondAnt,maxAnt,corInd;
   Double_t deltaT,deltaTExpected;
   Double_t phiWave, phiMaxAnt;
   Double_t thetaWave;
   Double_t corPeak, corRMS;
   Double_t balloonLat, balloonLon, balloonAlt;
   Double_t heading,pitch,roll;
   //   Double_t deltaZ;
   //   Double_t deltaR;
   Double_t meanPhiAntPair;
   Double_t deltaPhiAntPair;
   


   TTree *deltaTTree = new TTree("deltaTTree","Tree of Delta T's");
   deltaTTree->Branch("entry",&entry,"entry/L");
   deltaTTree->Branch("firstAnt",&firstAnt,"firstAnt/I");
   deltaTTree->Branch("secondAnt",&secondAnt,"secondAnt/I");
   deltaTTree->Branch("maxAnt",&maxAnt,"maxAnt/I");
   deltaTTree->Branch("labChip",&labChip,"labChip/I");
   deltaTTree->Branch("deltaT",&deltaT,"deltaT/D");
   deltaTTree->Branch("deltaTExpected",&deltaTExpected,"deltaTExpected/D");
   deltaTTree->Branch("corPeak",&corPeak,"corPeak/D");
   deltaTTree->Branch("corRMS",&corRMS,"corRMS/D");
   deltaTTree->Branch("phiMaxAnt",&phiMaxAnt,"phiMaxAnt/D");
   deltaTTree->Branch("phiWave",&phiWave,"phiWave/D");
   deltaTTree->Branch("thetaWave",&thetaWave,"thetaWave/D");
   deltaTTree->Branch("eventNumber",&eventNumber,"eventNumber/i");
   deltaTTree->Branch("triggerTime",&triggerTime,"triggerTime/i");
   deltaTTree->Branch("triggerTimeNs",&triggerTimeNs,"triggerTimeNs/i");
   deltaTTree->Branch("corInd",&corInd,"corInd/I");
   deltaTTree->Branch("balloonLat",&balloonLat,"balloonLat/D");
   deltaTTree->Branch("balloonLon",&balloonLon,"balloonLon/D");
   deltaTTree->Branch("balloonAlt",&balloonAlt,"balloonAlt/D");
   deltaTTree->Branch("heading",&heading,"heading/D");
   deltaTTree->Branch("pitch",&pitch,"pitch/D");
   deltaTTree->Branch("roll",&roll,"roll/D");
   //   deltaTTree->Branch("deltaZ",&deltaZ,"deltaZ/D");
   //   deltaTTree->Branch("deltaR",&deltaR,"deltaR/D");
   deltaTTree->Branch("meanPhiAntPair",&meanPhiAntPair,"meanPhiAntPair/D");
   deltaTTree->Branch("deltaPhiAntPair",&deltaPhiAntPair,"deltaPhiAntPair/D");
   deltaTTree->Branch("expTaylorTime",&expTaylorTime,"expTaylorTime/i");

  // Double_t thetaWave;

   for(entry=0;entry<numEntries;entry++) { 
  

      corTree->GetEntry(entry);
      Long64_t headEntry=headTree->GetEntryNumberWithIndex(corSum->eventNumber);
      if(headEntry<0) 
	continue;
      headTree->GetEntry(headEntry);
     
      // if(header->triggerTimeNs*1e-9< 0.097 || header->triggerTimeNs*1e-9>0.1)

      triggerTimeNs=header->triggerTimeNs;
      triggerTime=header->triggerTime;
      eventNumber=header->eventNumber;

      adu5PatTree->GetEntry(headEntry);
      
      
   // PrettyAnitaEvent realEvent(event,WaveCalType::kVTFullAGCrossCorClock,header);
      balloonLat=pat->latitude;
      balloonLon=pat->longitude;
      balloonAlt=pat->altitude;
      heading=pat->heading;
      pitch=pat->pitch;
      roll=pat->roll;

	//Simon 30/04/09 numbers     
      //      pat->pitch=0.64;
      //      pat->roll=0.14;


	//Simon 02/05/09 numbers     
      //      pat->pitch=0.76;
      //      pat->roll=0.13;

      //Test heading offset
      //      pat->heading+=0.19;
      //      if(pat->heading>=360) pat->heading-=360;
      //      if(pat->heading<0) pat->heading+=360;

     // 

      //      pat->pitch=0.5;
      //      pat->roll=-0.1;


      //Kurt numbers 
      pat->pitch=-0.29;
      pat->roll=0.89;
//       //Test heading offset
//      pat->heading-=0.32;
      if(pat->heading>=360) pat->heading-=360;
      if(pat->heading<0) pat->heading+=360;

      UsefulAdu5Pat usefulPat(pat);
     
      for(corInd=0;corInd<35;corInd++) {

	 firstAnt=corSum->firstAnt[corInd];
	 secondAnt=corSum->secondAnt[corInd];
	 deltaT=corSum->maxCorTimes[corInd];
	 maxAnt=corSum->centreAntenna;
	 phiMaxAnt=fGeomTool->getAntPhiPositionRelToAftFore(corSum->centreAntenna,AnitaPol::kHorizontal)*TMath::RadToDeg();
	 
	 //Default values
	 deltaTExpected=usefulPat.getDeltaTTaylor(corSum->firstAnt[corInd],corSum->secondAnt[corInd],AnitaPol::kHorizontal);
	 deltaTExpected=usefulPat.getDeltaTWillySeavey(corSum->firstAnt[corInd],corSum->secondAnt[corInd],AnitaPol::kHorizontal);

	 //These two lines are for use with Simon's array of numbers
	 //	 deltaTExpected=usefulPat.getDeltaTTaylorOpt(corSum->firstAnt[corInd],corSum->secondAnt[corInd],deltaR,deltaZ,deltaPhi);
	 //	 deltaT+=(antTimeOffset[firstAnt]-antTimeOffset[secondAnt]);



	 phiWave=usefulPat.getPhiWave();
	 thetaWave=usefulPat.getThetaWave();
	 corPeak=corSum->maxCorVals[corInd];
	 corRMS=corSum->rmsCorVals[corInd];
	 
	 meanPhiAntPair=fGeomTool->getMeanAntPairPhiRelToAftFore(firstAnt,secondAnt,AnitaPol::kHorizontal);
	 deltaPhiAntPair=fGeomTool->getPhiDiff(phiWave,meanPhiAntPair);//,AnitaPol::kHorizontal);
	 
	 //	 std::cout << phiWave << "\t" << meanPhiAntPair << "\t" << deltaPhiAntPair << "\n";

	 //Convert to degrees
	 deltaPhiAntPair*=TMath::RadToDeg();
	 phiWave*=TMath::RadToDeg();
	 thetaWave*=TMath::RadToDeg();	       

	 //Actually fill the tree
	 deltaTTree->Fill();
      }


      counter++; 
      if(counter%100==0)
	 cerr << "*";
   }
   deltaTTree->AutoSave();
   fpOut->Close();
   //   histSimpleDtDiff->Draw();
}
void fillArrays(double *eventNumberIndex, double *thetaWaveIndex, double *phiWaveIndex, int *antIndex1, int *antIndex2, double *maxCorrTimeIndex, bool *adjacent){
 // char headerName[FILENAME_MAX];
  char gpsName[FILENAME_MAX];
  char corName[FILENAME_MAX];
  fGeomTool->useKurtAnita3Numbers(1);

  // RawAnitaHeader *header =0;
  Adu5Pat *pat =0;
  CorrelationSummaryAnita3 *cor=0;

  TChain *gpsChain = new TChain("adu5PatTree");
  // TChain *headChain = new TChain("headTree");
  TChain *corChain = new TChain("corTree");

  for (unsigned int run=331;run<356;++run){
      
    //    sprintf(headerName,"/unix/anita3/flight1415/root/run%d/headFile%d.root",run,run);
    // sprintf(headerName,"/unix/anita3/flight1415/root/run%d/timedHeadFile%d.root",run,run);
    //    sprintf(gpsName,"/unix/anita3/flight1415/root/run%d/gpsFile%d.root",run,run);
    sprintf(gpsName,"/unix/anita3/flight1415/root/run%d/gpsEvent%d.root",run,run);

    //    sprintf(corName, "/unix/anita3/linda/corTrees/corRun_NEW6_HPOL_%d.root", run);
    sprintf(corName, "/unix/anita3/linda/corTrees/corRun_NEW11_HPOL_%d.root", run);
    
    // headChain->Add(headerName);
    gpsChain->Add(gpsName);
    corChain->Add(corName);
    
  }
  // headChain->SetBranchAddress("header",&header);
  gpsChain->SetBranchAddress("pat",&pat);
  corChain->SetBranchAddress("cor",&cor);

  // headChain->BuildIndex("header->eventNumber");
  //  gpsChain->BuildIndex("pat->realTime");
  gpsChain->BuildIndex("eventNumber");

  int maxEntry=corChain->GetEntries();
  

  AnitaPol::AnitaPol_t pol = AnitaPol::kHorizontal;
  // AnitaPol::AnitaPol_t pol = AnitaPol::kVertical;
  Double_t sourceLat, sourceLon, sourceAlt, timeOffset;
  char cpol[100];

  if (pol == AnitaPol::kVertical){
    sourceLat = - (79 + (27.93728/60));
    sourceLon = -(112 + (6.74974/60));
    sourceAlt = 1813.42;
    timeOffset = + 92.8;
    //    timeOffset = -99756.6;
    sprintf(cpol, "VPOL");
  }else{ 
    sourceLat = - (79 + (27.94097/60));
    sourceLon = -(112 + (6.76208/60));
    sourceAlt = 1819.62;
    timeOffset = + 92.8;
    sprintf(cpol, "HPOL");
  }


  Double_t phiWave, thetaWave, lower, upper;
  Double_t maxCorrTime, deltaTExpected;
  int ant1, ant2;

  int countIndex = 0;
  int countNotsaved = 0;

  bool save = false;


  for (unsigned int ant=0;ant<MAX_ANTENNAS;++ant){
    antPhi[ant] = fGeomTool->getAntPhiPositionRelToAftFore(ant, pol);
    //    meanPhi[ant] = fGeomTool->getAntPhiPosition(ant, pol);
  }
  Double_t additionalPhi = 22.5*TMath::DegToRad();//22.5*TMath::DegToRad();
  Double_t TwoPi = TMath::Pi()*2.;
  for(Long64_t entry=0;entry<maxEntry;++entry) {
    save=false;
    corChain->GetEntry(entry);

    // Long64_t headEntry = headChain->GetEntryNumberWithIndex(cor->eventNumber);
    // if(headEntry < 0 ) continue;
    // headChain->GetEntry(headEntry);    
    
    //    Long64_t gpsEntry = gpsChain->GetEntryNumberWithIndex(header->realTime);
    Long64_t gpsEntry = gpsChain->GetEntryNumberWithIndex(cor->eventNumber);
    if(gpsEntry < 0 ) continue;
    gpsChain->GetEntry(gpsEntry);
    //gpsChain->GetEntry(headEntry);


    UsefulAdu5Pat usefulPat(pat);
    
    usefulPat.getThetaAndPhiWave(sourceLon, sourceLat, sourceAlt, thetaWave, phiWave);


    for(unsigned int corInd=0;corInd<NUM_CORRELATIONS_ANITA3;++corInd) {
      
      
      if (corInd>11 && corInd!=37 && corInd!=38 && corInd!=39) continue;

      maxCorrTime = cor->maxCorTimes[corInd];
      ant1 = cor->firstAnt[corInd];
      ant2 = cor->secondAnt[corInd];
      
      deltaTExpected=usefulPat.getDeltaTExpected(ant1, ant2, sourceLon, sourceLat, sourceAlt);

      lower = antPhi[ant1] - additionalPhi ;
      upper = antPhi[ant2] + additionalPhi ;
      if (lower<0) lower+=TwoPi;
      if (upper>TwoPi) upper-=TwoPi;

      if (lower>upper){
      	if (phiWave<TwoPi*0.5) lower-=TwoPi;
      	else upper+=TwoPi;
      }
      
      
      if ( phiWave>lower && phiWave<upper && (maxCorrTime-deltaTExpected)*(maxCorrTime-deltaTExpected)<1) {

	thetaWaveIndex[countIndex] = thetaWave;
	phiWaveIndex[countIndex] = phiWave;
	maxCorrTimeIndex[countIndex] = maxCorrTime;
	eventNumberIndex[countIndex]= cor->eventNumber;
	antIndex1[countIndex] = ant1;
	antIndex2[countIndex] = ant2;
	if (corInd>5 && corInd<12) adjacent[countIndex] = true;
	else adjacent[countIndex]=false;

	countIndex++;
	
      }
    }

	
  }

  // delete header;
  delete pat;
  delete cor;
  delete gpsChain;
  // delete headChain;
  delete corChain;


  antIndex1[countIndex] = -999;

  cout << "ARRAY FILLED! : " << countIndex << " " << countNotsaved << endl;


}