#include "MGPngReader.h"

#include <fstream.h>    // ifstream
#include <iostream.h>   // cout
#include <iomanip.h>   // cout

#include <TTimer.h>

#include <TGMenu.h>
#include <TGLabel.h>
#include <TSystem.h>
#include <TGSplitter.h>    // TGHorizontal3DLine
#include <TGTextEntry.h>

#include "MGImage.h"
#include "MGCoordinates.h"
#include "MGDispCoordinates.h"

#include "coord.h"

#include "StarCatalog.h"

#include "Filter.h"
#include "Filter2.h"
#include "CaosFilter.h"
#include "Writer.h"
#include "MTime.h"

#include "MStarList.h"

#include <TH1.h>
#include <TH2.h>
#include <TGraph.h>
#include <TCanvas.h>

#include <TFile.h>
#include <TTree.h>
#include <TBranch.h>

#include "Led.h"
#include "Leds.h"
#include "Rings.h"

#include "MGMenu.h"

ClassImp(MGPngReader);

enum {
    IDM_kFilter,
    IDM_kCaosFilter,
    IDM_kCatalog,
    IDM_kStarguider,
    IDM_kStart,
    IDM_kStop,
    IDM_kFileType,
    IDM_kPPM,
    IDM_kPNG,
    IDM_kOnce,
    IDM_kUseFileRaDec,
    IDM_kContinous,
    IDM_kRate25ps,
    IDM_kRate5ps,
    IDM_kRate1s,
    IDM_kRate5s,
    IDM_kRate30s,
    IDM_kRate1m,
    IDM_kRate5m,
    IDM_kSetup,
    IDM_kLimMag3,
    IDM_kLimMag4,
    IDM_kLimMag5,
    IDM_kLimMag6,
    IDM_kLimMag7,
    IDM_kLimMag8,
    IDM_kLimMag9,
    IDM_kPixSize,
    IDM_kInterpol125,
    IDM_kInterpol25,
    IDM_kInterpol10,
    IDM_kInterpol5,
    IDM_kInterpol2,
    IDM_kInterpol1,
    IDM_kPositions,
    IDM_kRings,
    IDM_kLeds,
    IDM_kStartAnalyse,
    IDM_kStopAnalyse,
    IDM_kResetHistograms
};

Bool_t MGPngReader::HandleTimer(TTimer *t)
{
    fImage->DoRedraw();
    fZoomImage->DoRedraw();
    return kTRUE;
}

#define kZOOM 96

void MGPngReader::InitHists()
{
    Double_t xmin = 480.1-1.0;
    Double_t xmax = 480.1+1.0;

    Double_t ymin = 217.5-1.0;
    Double_t ymax = 217.5+1.0;

    Double_t rmin = 117.4-1.0;
    Double_t rmax = 117.4+1.0;

    Int_t xbin = 60;
    Int_t ybin = 60;
    Int_t rbin = 60;

    fHistpr = new TH1F;
    fHistpr->SetNameTitle("pr","Radius of the ring");
    fHistpr->SetBins(rbin, rmin, rmax);
    fHistpr->SetXTitle("r [mm]");
    fHistpr->SetYTitle("counts");

    fHistprx = new TH1F;
    fHistprx->SetNameTitle("prx","x-coordinate of the ring-center");
    fHistprx->SetBins(xbin, xmin, xmax);
    fHistprx->SetXTitle("x [mm]");
    fHistprx->SetYTitle("counts");

    fHistpry = new TH1F;
    fHistpry->SetNameTitle("pry","y-coordniate of the ring-center");
    fHistpry->SetBins(ybin, ymin, ymax);
    fHistpry->SetXTitle("y [mm]");
    fHistpry->SetYTitle("counts");

    for (int i=0; i<6; i++)
    {
        TString name  = "Angle";
        TString title = "Angle of Led ";

        name += i;
        title += i;

        fHistw[i] = new TH1F;
        fHistw[i]->SetNameTitle(name, title);
        fHistw[i]->SetBins(26, -25, 25);
        fHistw[i]->SetXTitle("\\Phi [arcmin]");
        fHistw[i]->SetYTitle("counts");

        name = "Angles";
        title = "Angles of the Leds ";

        name += i;
        title += i;

        fHistv[i] = new TH1F;
        fHistv[i]->SetNameTitle(name, title);
        fHistv[i]->SetBins(721, -180.5, 180.5);
        fHistv[i]->SetXTitle("\\Phi [deg]");
        fHistv[i]->SetYTitle("counts");
    }

    fHistallw = new TH1F;
    fHistallw->SetNameTitle("allw","Rotation angel");
    fHistallw->SetBins(26, -25, 25);
    fHistallw->SetXTitle("\\Phi [arcmin]");
    fHistallw->SetYTitle("counts");

    fHistprxpry = new TH2F;
    fHistprxpry->SetNameTitle("prx und pry","x- and y-coordniate of the ring-center");
    fHistprxpry->SetBins(xbin, xmin, xmax, ybin, ymin, ymax);
    fHistprxpry->SetXTitle("x [mm]");
    fHistprxpry->SetYTitle("y [mm]");
    fHistprxpry->SetZTitle("counts");
}

void MGPngReader::InitGraphs()
{
    fGraphprx = new TGraph;
    fGraphprx->SetTitle("time-developement of the x-coordinate of the ring-center");

    fGraphpry = new TGraph;
    fGraphpry->SetTitle("time-developement of the y-coordinate of the ring-center");

    for (int i=0; i<6; i++)
    {
        TString title = "Time-developement of the angle ";
        title += i;

        fGraphw[i] = new TGraph;
        fGraphw[i]->SetTitle(title);
    }
}

void MGPngReader::InitGui()
{
    fList = new MGList;

    const TGWindow *p=gClient->GetRoot();

    //
    // Create Menu for MGPngReader Display
    //
    fDisplay = new MGPopupMenu(p);
    fDisplay->AddEntry("&Filter",      IDM_kFilter);
    fDisplay->AddEntry("C&aosFilter",  IDM_kCaosFilter);
    fDisplay->AddEntry("Sao &Catalog", IDM_kCatalog);
    fDisplay->AddEntry("Starguider",   IDM_kStarguider);
    fDisplay->DisableEntry(IDM_kStarguider);
    fDisplay->Associate(this);
    fList->Add(fDisplay);

    fFileType = new MGPopupMenu(p);
    fFileType->AddEntry("PP&M", IDM_kPPM);
    fFileType->AddEntry("&PNG", IDM_kPNG);
    fFileType->CheckEntry(IDM_kPNG);
    fFileType->Associate(this);
    fList->Add(fFileType);

    fWriteType = new MGPopupMenu(p);
    fWriteType->AddEntry("&Once",      IDM_kOnce);
    fWriteType->AddEntry("&Continous", IDM_kContinous);
    fWriteType->Associate(this);
    fList->Add(fWriteType);

    fWriteRate = new MGPopupMenu(p);
    fWriteRate->AddEntry("25/s", IDM_kRate25ps);
    fWriteRate->AddEntry("5/s",  IDM_kRate5ps);
    fWriteRate->AddEntry("1s",   IDM_kRate1s);
    fWriteRate->AddEntry("5s",   IDM_kRate5s);
    fWriteRate->AddEntry("30s",  IDM_kRate30s);
    fWriteRate->AddEntry("1min", IDM_kRate1m);
    fWriteRate->AddEntry("5min", IDM_kRate5m);
    fWriteRate->CheckEntry(IDM_kRate1m);
    fWriteRate->Associate(this);
    fList->Add(fWriteRate);

    fWrtRate = 25*60;

    fWritePictures = new MGPopupMenu(p);
    fWritePictures->AddEntry("&Start",      IDM_kStart);
    fWritePictures->AddEntry("Sto&p",       IDM_kStop);
    fWritePictures->AddSeparator();
    fWritePictures->AddPopup("File &Type",  fFileType);
    fWritePictures->AddPopup("&Write Type", fWriteType);
    fWritePictures->AddPopup("Write &Rate", fWriteRate);
    fWritePictures->DisableEntry(IDM_kStop);
    fWritePictures->Associate(this);
    fList->Add(fWritePictures);

    fLimMag = new MGPopupMenu(p);
    fLimMag->AddEntry("3", IDM_kLimMag3);
    fLimMag->AddEntry("4", IDM_kLimMag4);
    fLimMag->AddEntry("5", IDM_kLimMag5);
    fLimMag->AddEntry("6", IDM_kLimMag6);
    fLimMag->AddEntry("7", IDM_kLimMag7);
    fLimMag->AddEntry("8", IDM_kLimMag8);
    fLimMag->AddEntry("9", IDM_kLimMag9);
    fLimMag->CheckEntry(IDM_kLimMag8);
    fLimMag->Associate(this);
    fList->Add(fLimMag);

    fSao->SetLimitMag(7.0);

    fInterpol = new MGPopupMenu(p);
    fInterpol->AddEntry("125", IDM_kInterpol125);
    fInterpol->AddEntry("25",  IDM_kInterpol25);
    fInterpol->AddEntry("10",  IDM_kInterpol10);
    fInterpol->AddEntry("5",   IDM_kInterpol5);
    fInterpol->AddEntry("2",   IDM_kInterpol2);
    fInterpol->AddEntry("Off", IDM_kInterpol1);
    fInterpol->CheckEntry(IDM_kInterpol1);
    fInterpol->Associate(this);
    fList->Add(fInterpol);

    fIntRate = 1;

    fSetup = new MGPopupMenu(p);
    fSetup->AddPopup("Lim. &Magnitude",      fLimMag);
    fSetup->AddPopup("Disp. &Interpolation", fInterpol);
    fSetup->AddEntry("Use Ra/Dec from file", IDM_kUseFileRaDec);
    fSetup->Associate(this);
    fList->Add(fSetup);

    fWrite = new MGPopupMenu(p);
    fWrite->AddEntry("&Positions",  IDM_kPositions);
    fWrite->AddEntry("&Leds", IDM_kLeds);
    fWrite->AddEntry("&Rings", IDM_kRings);
    fWrite->Associate(this);
    fList->Add(fWrite);

    fAnalyse = new MGPopupMenu(p);
    fAnalyse->AddEntry("S&tart Analyse", IDM_kStartAnalyse);
    fAnalyse->AddEntry("St&opp Analyse", IDM_kStopAnalyse);
    fAnalyse->DisableEntry(IDM_kStopAnalyse);
    fAnalyse->AddEntry("&Reset Histograms", IDM_kResetHistograms);
//    fAnalyse->AddEntry("Reset &Graph", IDM_kResetGraph);
    fAnalyse->Associate(this);
    fList->Add(fAnalyse);

    fMenu = new MGMenuBar(this, 0, 0, kHorizontalFrame);
    fMenu->AddPopup("&Display", fDisplay, NULL);
    fMenu->AddPopup("&WritePics",   fWritePictures,   NULL);
    fMenu->AddPopup("&Setup",   fSetup,   NULL);
    fMenu->Resize(fMenu->GetDefaultSize());
    fMenu->BindKeys(this);
    AddFrame(fMenu); //, new TGLayoutHints (kLHintsNormal, 0, 4, 0, 0));
    fList->Add(fMenu);

    fCaOs = new MGPopupMenu(p);
    fCaOs->AddPopup("&Write", fWrite);
    fCaOs->AddPopup("&Analyse", fAnalyse);
    fCaOs->Associate(this);
    fCaOs->BindKeys(fMenu, this);
    fList->Add(fCaOs);

    fCRaDec = new MGCoordinates(this, kETypeRaDec);
    fCRaDec->Move(1, fMenu->GetDefaultHeight()+584);
    AddFrame(fCRaDec);
    fList->Add(fCRaDec);

    fCZdAz = new MGCoordinates(this, kETypeZdAz, kFALSE);
    fCZdAz->Move(240+12+10, fMenu->GetDefaultHeight()+584);
    AddFrame(fCZdAz);
    fList->Add(fCZdAz);

    fPZdAz = new MGCoordinates(this, kETypeZdAz, kFALSE);
    fPZdAz->Move(240+12+10, fMenu->GetDefaultHeight()+630);
    AddFrame(fPZdAz);
    fList->Add(fPZdAz);

    TGLabel *l = new TGLabel(this, "Arb.-Sky Pos");
    l->SetTextJustify(kTextLeft);
    l->Move(480+32, fMenu->GetDefaultHeight()+590);
    AddFrame(l);
    fList->Add(l);

    l = new TGLabel(this, "arcsec/pix");
    l->SetTextJustify(kTextLeft);
    l->Move(605, fMenu->GetDefaultHeight()+619);
    AddFrame(l);
    fList->Add(l);

    l = new TGLabel(this, "Pointing Pos");
    l->SetTextJustify(kTextLeft);
    l->Move(480+32, fMenu->GetDefaultHeight()+655);
    AddFrame(l);
    fList->Add(l);

    const Double_t pixsize = 23.4;

    fSao->SetPixSize(pixsize);

    TString txt;
    txt += pixsize;

    fPixSize = new TGTextEntry(this, txt, IDM_kPixSize);
    fPixSize->SetAlignment(kTextCenterX);
    fPixSize->Move(547, fMenu->GetDefaultHeight()+617);
    AddFrame(fPixSize);
    fList->Add(fPixSize);

    // TGHorizontal3DLine *fLineSep = new TGHorizontal3DLine(this);
    // AddFrame(fLineSep, new TGLayoutHints (kLHintsNormal | kLHintsExpandX));
    // fList->Add(fLineSep);

    //
    // Create Image Display
    //
    fZoomImage = new MGImage(this, kZOOM, kZOOM);
    fZoomImage->Move(768-kZOOM-2, 700-kZOOM-2);
    AddFrame(fZoomImage);
    fList->Add(fZoomImage);

    fImage = new MGImage(this, 768, 576);
    fImage->Move(0, fMenu->GetDefaultHeight());
    AddFrame(fImage);
    fList->Add(fImage);

    //
    // Make everything visible
    //
    SetWindowName("MGPngReader Main Window");
    SetIconName("MGPngReader");

    MapSubwindows();
    MapWindow();

    //------------------------------------------------------------
    //    XY xy(3.819444, 24.05333);
    //    fCRaDec->SetCoordinates(xy);
    //    fRaDec->Set(xy.X()*360/24, xy.Y());
    //------------------------------------------------------------
}

MGPngReader::MGPngReader(MObservatory::LocationName_t obs)
: TGMainFrame(gClient->GetRoot(), 768, 740), fFile(NULL), fDx((768-kZOOM)/2), fDy((512-kZOOM)/2)
{
    fSao = new StarCatalog(obs);
    fRaDec = new RaDec(180, 40);

    InitHists();
    InitGraphs();

    InitGui();

    gVirtualX->GrabButton(fId, kButton2, 0, 0, 0, 0, kTRUE);

    fTimer=new TTimer(this, 100); // 100ms
    fTimer->TurnOn();
}

MGPngReader::~MGPngReader()
{
    gVirtualX->GrabButton(fId, kButton2, 0, 0, 0, 0, kFALSE);

    fTimer->TurnOff();
    delete fTimer;

    delete fList;

    delete fSao;
    delete fRaDec;

    delete fHistpr;
    delete fHistprx;
    delete fHistpry;
    delete fHistprxpry;
    delete fHistallw;
    delete fGraphprx;
    delete fGraphpry;

    for (int i=0; i<6; i++)
    {
        delete fHistw[i];
        delete fHistv[i];
        delete fGraphw[i];
    }

    cout << "Camera Display destroyed." << endl;
}

void MGPngReader::Layout()
{
    // Resize(GetDefaultSize());
}

void MGPngReader::CloseWindow()
{
    cout << "EventDisplay::CloseWindow: Exit Application Loop." << endl;

    //fClient.ExitLoop();
    //    cout << "FIXME: ExitLoop not called!!!!!!" << endl;
    gSystem->ExitLoop();
}

void MGPngReader::Toggle(MGPopupMenu *p, UInt_t id)
{
    if (p->IsEntryChecked(id))
        p->UnCheckEntry(id);
    else
        p->CheckEntry(id);
}

void MGPngReader::ResetHists()
{
    fHistprx->Reset();
    fHistpry->Reset();
    fHistpr->Reset();
    fHistprxpry->Reset();
    fHistallw->Reset();
    for (int i=0; i<6; i++)
    {
        fHistw[i]->Reset();
        fHistv[i]->Reset();
    }
}

void MGPngReader::DisplayAnalysis()
{
    TCanvas *c = new TCanvas("cring", "Center of the ring", 800, 800);
    c->Divide(2,2);
    c->cd(1);
    fHistprx->Fit("gaus");
    fHistprx->DrawCopy();
    c->cd(2);
    fHistpry->Fit("gaus");
    fHistpry->DrawCopy();
    c->cd(3);
    fHistpr->Fit("gaus");
    fHistpr->DrawCopy();
    c->cd(4);
    fHistprxpry->DrawCopy(/*"surf2"*/);
    c->Update();

    c = new TCanvas("c3", "Absolute angles of the leds", 800, 800);
    c->Divide(2,3);
    for (int i=0; i<6; i++)
    {
        c->cd(i+1);
        TH1 *h = fHistv[i]->DrawCopy();
        h->SetLineColor(i+1);
        cout << "Led #" << i << ": MeanPhi=" << h->GetMean() << endl;
    }
    c->Update();

    c = new TCanvas("c5", "timedevelopement of prx", 800, 800);
    fGraphprx->Draw("ALP*");
    fGraphprx->GetHistogram()->SetXTitle("time [1/25 s]");
    fGraphprx->GetHistogram()->SetYTitle("x-coordinate");
    c->Modified();
    c->Update();

    c = new TCanvas("c6", "timedevelopement of pry", 800, 800);
    fGraphpry->Draw("ALP*");
    fGraphpry->GetHistogram()->SetXTitle("time [1/25 s]");
    fGraphpry->GetHistogram()->SetYTitle("y-coordinate");
    c->Modified();
    c->Update();

    c = new TCanvas("c2", "Relative angles of the Leds", 800, 800);
    c->Divide(2,3);
    for (int i=0; i<6; i++)
    {
        c->cd(i+1);
        fHistw[i]->DrawCopy();
    }
    c->Update();

    c = new TCanvas("c7", "timedevelopement of the relative angles of the Leds", 800, 800);
    c->Divide(2,3);
    for (int i=0; i<6; i++)
    {
        c->cd(i+1);
        fGraphw[i]->Draw("ALP*");
        fGraphw[i]->GetHistogram()->SetXTitle("t [1/25s]");
        fGraphw[i]->GetHistogram()->SetYTitle("[deg]");
    }
    c->Modified();
    c->Update();

    c = new TCanvas("c4", "rotation angle ", 800, 800);
    fHistallw->Fit("gaus");
    fHistallw->DrawCopy();
}

void MGPngReader::OpenFile()
{
    int i=0;
    char name[100];
    while (1)
    {
        sprintf(name, "data/data%03d.root", i++);
        if (gSystem->AccessPathName(name, kFileExists))
            break;
    }

    fFile = new TFile(name, "RECREATE");

    if (!fFile->IsOpen())
    {
        delete fFile;
        fFile = NULL;

        cout << "Error: Cannot open file '" << name << "'" << endl;

    }

    fTree = new TTree("Data", "Real CaOs Data");

    fLeds = NULL;
    fRings = NULL;
    fTime = 0;

    fBranchL = fTree->Branch("Leds.",  "Leds",  &fLeds);
    fBranchR = fTree->Branch("Rings.", "Rings", &fRings);
    fBranchT = fTree->Branch("Time.", &fTime, "fTime/D");//, &fTime);

    cout << "Root file '" << name << "' open." << endl;
}

Bool_t MGPngReader::ProcessMessage(Long_t msg, Long_t mp1, Long_t mp2)
{
    switch (GET_MSG(msg))
    {
    case kC_TEXTENTRY:
        if (GET_SUBMSG(msg)==kTE_ENTER)
        {
            const Float_t pixsize = atof(fPixSize->GetText());
            cout << "Pixel Size changed to " << pixsize << "\"/pix" << endl;
            fSao->SetPixSize(pixsize);
        }
        return kTRUE;

    case kC_COMMAND:
        //cout << "kC_COMMAND" << endl;
        switch (GET_SUBMSG(msg))
        {
        case kCM_MENU:
            //cout << "kCM_MENU #" << mp1 << endl;
            switch (mp1)
            {
            case IDM_kCatalog:
                Toggle(fDisplay, IDM_kCatalog);
                if (fDisplay->IsEntryChecked(IDM_kCatalog))
                    fDisplay->EnableEntry(IDM_kStarguider);
                else
                {
                    fDisplay->UnCheckEntry(IDM_kStarguider);
                    fDisplay->DisableEntry(IDM_kStarguider);
                }
                return kTRUE;

            case IDM_kStarguider:
                Toggle(fDisplay, IDM_kStarguider);
                return kTRUE;

            case IDM_kFilter:
                Toggle(fDisplay, IDM_kFilter);
                if (fDisplay->IsEntryChecked(IDM_kFilter))
                    fDisplay->EnableEntry(IDM_kStarguider);
                else
                {
                    fDisplay->UnCheckEntry(IDM_kStarguider);
                    fDisplay->DisableEntry(IDM_kStarguider);
                }
                return kTRUE;

            case IDM_kCaosFilter:
                if (!fDisplay->IsEntryChecked(IDM_kCaosFilter))
                    OpenFile();
                Toggle(fDisplay, IDM_kCaosFilter);
                if (fDisplay->IsEntryChecked(IDM_kCaosFilter))
                    fMenu->AddPopup("&CaOs", fCaOs, NULL);
                else
                {
                    fFile->Write();
                    delete fFile;
                    fFile = NULL;

                    cout << "Root file closed." << endl;

                    if(fWrite->IsEntryChecked(IDM_kPositions))
                       fWrite->UnCheckEntry(IDM_kPositions);
                    if(fWrite->IsEntryChecked(IDM_kLeds))
                       fWrite->UnCheckEntry(IDM_kLeds);
                    if(fWrite->IsEntryChecked(IDM_kRings))
                        fWrite->UnCheckEntry(IDM_kRings);
                    if(fAnalyse->IsEntryEnabled(IDM_kStopAnalyse))
                    {
                        fAnalyse->DisableEntry(IDM_kStopAnalyse);
                        fAnalyse->EnableEntry(IDM_kStartAnalyse);
                        ResetHists();
                        // Graphs are not reset !!!
                    }
                    fMenu->RemovePopup("CaOs");
                }
                fMenu->Resize(fMenu->GetDefaultSize());
                MapSubwindows();
                MapWindow();
                return kTRUE;

            case IDM_kPositions:
                Toggle(fWrite, IDM_kPositions);
                return kTRUE;

            case IDM_kLeds:
                Toggle(fWrite, IDM_kLeds);
                return kTRUE;

            case IDM_kRings:
                Toggle(fWrite, IDM_kRings);
                return kTRUE;

            case IDM_kStartAnalyse:
                fAnalyse->DisableEntry(IDM_kStartAnalyse);
                fAnalyse->EnableEntry(IDM_kStopAnalyse);
                return kTRUE;

            case IDM_kStopAnalyse:
                {
                    fAnalyse->DisableEntry(IDM_kStopAnalyse);
                    fAnalyse->EnableEntry(IDM_kStartAnalyse);

                    DisplayAnalysis();

                    return kTRUE;
                }

            case IDM_kResetHistograms:
                ResetHists();
                return kTRUE;

/*            case IDM_kResetGraph:
                {
                    fGraphx->GetHistogram()->Reset();

                }
*/

            case IDM_kUseFileRaDec:
                Toggle(fSetup, IDM_kUseFileRaDec);
                return kTRUE;

            case IDM_kStart:
                fWritePictures->DisableEntry(IDM_kStart);
                fWritePictures->EnableEntry(IDM_kStop);
                return kTRUE;

            case IDM_kStop:
                fWritePictures->DisableEntry(IDM_kStop);
                fWritePictures->EnableEntry(IDM_kStart);
                return kTRUE;

            case IDM_kPNG:
                fFileType->CheckEntry(IDM_kPNG);
                fFileType->UnCheckEntry(IDM_kPPM);
                return kTRUE;

            case IDM_kPPM:
                fFileType->CheckEntry(IDM_kPPM);
                fFileType->UnCheckEntry(IDM_kPNG);
                return kTRUE;

            case IDM_kOnce:
                fWriteType->CheckEntry(IDM_kOnce);
                fWriteType->UnCheckEntry(IDM_kContinous);
                return kTRUE;

            case IDM_kContinous:
                fWriteType->CheckEntry(IDM_kContinous);
                fWriteType->UnCheckEntry(IDM_kOnce);
                return kTRUE;

            case IDM_kRate25ps:
            case IDM_kRate5ps:
            case IDM_kRate1s:
            case IDM_kRate5s:
            case IDM_kRate30s:
            case IDM_kRate1m:
            case IDM_kRate5m:
                for (int i=IDM_kRate25ps; i<=IDM_kRate5m; i++)
                    if (mp1==i)
                        fWriteRate->CheckEntry(i);
                    else
                        fWriteRate->UnCheckEntry(i);
                switch (mp1)
                {
                case IDM_kRate25ps:
                    fWrtRate = 1;
                    return kTRUE;
                case IDM_kRate5ps:
                    fWrtRate = 5;
                    return kTRUE;
                case IDM_kRate1s:
                    fWrtRate = 25;
                    return kTRUE;
                case IDM_kRate5s:
                    fWrtRate = 5*25;
                    return kTRUE;
                case IDM_kRate30s:
                    fWrtRate = 30*25;
                    return kTRUE;
                case IDM_kRate1m:
                    fWrtRate = 60*25;
                    return kTRUE;
                case IDM_kRate5m:
                    fWrtRate = 5*60*25;
                    return kTRUE;
                }
                return kTRUE;

            case IDM_kInterpol125:
            case IDM_kInterpol25:
            case IDM_kInterpol10:
            case IDM_kInterpol5:
            case IDM_kInterpol2:
            case IDM_kInterpol1:
                for (int i=IDM_kInterpol125; i<=IDM_kInterpol1; i++)
                    if (mp1==i)
                        fInterpol->CheckEntry(i);
                    else
                        fInterpol->UnCheckEntry(i);
                switch (mp1)
                {
                case IDM_kInterpol1:
                    fIntRate = 1;
                    return kTRUE;
                case IDM_kInterpol2:
                    fIntRate = 2;
                    return kTRUE;
                case IDM_kInterpol5:
                    fIntRate = 5;
                    return kTRUE;
                case IDM_kInterpol10:
                    fIntRate = 10;
                    return kTRUE;
                case IDM_kInterpol25:
                    fIntRate = 25;
                    return kTRUE;
                case IDM_kInterpol125:
                    fIntRate = 125;
                    return kTRUE;
                }
                return kTRUE;

            case IDM_kLimMag3:
            case IDM_kLimMag4:
            case IDM_kLimMag5:
            case IDM_kLimMag6:
            case IDM_kLimMag7:
            case IDM_kLimMag8:
            case IDM_kLimMag9:
                for (int i=IDM_kLimMag3; i<=IDM_kLimMag9; i++)
                    if (mp1==i)
                        fLimMag->CheckEntry(i);
                    else
                        fLimMag->UnCheckEntry(i);

                fSao->SetLimitMag(mp1-IDM_kLimMag3+3);
                return kTRUE;
            }
            break;
        }
        break;
    }

    return kTRUE;
}

void MGPngReader::GetCoordinates()
{
    XY xy = fCRaDec->GetCoordinates();

    if (fSetup->IsEntryChecked(IDM_kUseFileRaDec))
    {
        ifstream fin("coordinates.txt");
        if (!fin)
            cout << "Error: Cannot open 'coordinates.txt' using fall back solution." << endl;
        else
            fin >> xy;
    }

    fCRaDec->SetCoordinates(xy);
    fRaDec->Set(xy.X()*360/24, xy.Y());
}

ZdAz MGPngReader::TrackingError(TArrayF &x, TArrayF &y, TArrayF &mag) const
{
    //
    // Viewable area (FIXME: AZ)
    //
    TH2F h("Hist", "dX/dY",  77, -768/2-.5,  768/2+.5, 58, -576/2-.5,  576/2+.5); // 3

    /*
    TH1F hmag("HistMag", "Mag", 19, 0, 100);
    for (int i=0; i<mag.GetSize(); i++)
        hmag.Fill(mag[i]);
        */

    //
    // Search for matching Magnitudes
    //
    for (int i=0; i<mag.GetSize(); i++)
    {
        if (mag[i]>48-15 && mag[i]<48+15)
            h.Fill(x[i], y[i]);
    }

    //
    // Serach for an excess in the histogram
    //
    Int_t mx, my, dummy;
    h.GetMaximumBin(mx, my, dummy);

    const double xmax = h.GetXaxis()->GetBinCenter(mx);
    const double dx   = h.GetXaxis()->GetBinWidth(mx);

    const double ymax = h.GetYaxis()->GetBinCenter(my);
    const double dy   = h.GetYaxis()->GetBinWidth(my);

    cout << setprecision(3);
    cout << "Cut-XY:       " << xmax << " +- " << dx << " / " << ymax << " +- " << dy << endl;

    TGraph g;
    for (int i=0; i<mag.GetSize(); i++)
    {
        if (!(x[i]>xmax-dx && x[i]<xmax+dx &&
              y[i]>ymax-dy && y[i]<ymax+dy &&
              mag[i]>48-15 && mag[i]<48+15))
            continue;

        g.SetPoint(g.GetN(), x[i], y[i]);
    }

    cout << "Offset-XY:    " << g.GetMean(1) << " +- " << g.GetRMS(1) << " / ";
    cout << g.GetMean(2) << " +- " << g.GetRMS(2) << endl;

    AltAz pos0 = fSao->CalcAltAzFromPix(768/2,              576/2)*kRad2Deg;
    AltAz pos1 = fSao->CalcAltAzFromPix(768/2+g.GetMean(1), 576/2+g.GetMean(2))*kRad2Deg;

    pos1 -= pos0;

    ofstream fout("tracking_error.txt");
    fout << setprecision(10) << fSao->GetMjd()-52000 << " " << -pos1.Alt() << " " << pos1.Az() << endl;
    fout.close();

    return ZdAz(-pos1.Alt(), pos1.Az());
}

void MGPngReader::CalcTrackingError(Leds &leds, MStarList &stars)
{
    const Int_t max = leds.GetEntries();

    if (stars.GetRealEntries() < 3)
    {
        cout << "Sorry, less than 3 stars in FOV!" << endl;
        return;
    }

    if (max < 1)
    {
        cout << "Sorry, less than 1 detected spot in FOV!" << endl;
        return;
    }

    stars.Sort(); // Sort by magnitude

    TString str = "data/tracking_";
    str += fSao->GetMjd()-52000;
    str += ".txt";

    ofstream fout(str);

    TArrayF x, y, mag;

    Int_t num = 0;

    // FIXME: Is predifined value 3 a good idea?

    MStar *star;
    MStarListIter NextStar(&stars);
    while ((star=NextStar()) && num++<max+3)
    {
        TIter NextSp(&leds);
        Led *spot=NULL;
        while ((spot=(Led*)NextSp()))
        {
            const XY dpos(spot->GetX()-star->GetX(), spot->GetY()-star->GetY());

            const Int_t idx = x.GetSize();

            x.Set(idx+1);
            y.Set(idx+1);
            mag.Set(idx+1);

            x.AddAt(dpos.X(), idx);
            y.AddAt(dpos.Y(), idx);
            mag.AddAt(spot->GetMag()/star->GetMag(), idx);

            if (fout)
                fout << x[idx] << " " << y[idx] << " " << mag[idx] << endl;
        }
    }

    ZdAz d = TrackingError(x, y, mag);

    //
    // Calculated offsets
    //

    // round= floor(x+.5)
    cout << "Offset-ZdAz: " << d.Zd()*60 << "' / " << d.Az()*60 << "'" << endl;
    cout << "Offset-ZdAz: " << d.Zd()/360*16384 << " / " << d.Az()/360*16384 << " (SE) " << endl;

    //
    // Current Pointing position
    //
    ZdAz cpos = fSao->GetZdAz()-d;
    fPZdAz->SetCoordinates(cpos);
}


void MGPngReader::ProcessFrame(const unsigned long n, byte *img, struct timeval *tm)
{
    static float myimg[768*576];

    for (int i=0; i<768*576; i++)
        myimg[i] += img[i];

    if (n%fIntRate)
        return;

    cout << "Img: " << n << endl;

    byte c[768*576];
    for (int i=0; i<768*576; i++)
        c[i] = (byte)(myimg[i]/fIntRate+.5);

    if (!fWritePictures->IsEntryEnabled(IDM_kStart) &&
        (!(n%fWrtRate) || fWriteType->IsEntryChecked(IDM_kOnce)))
    {
        if (fFileType->IsEntryChecked(IDM_kPNG))
            Writer::Png("pix/file", c, tm);

        if (fFileType->IsEntryChecked(IDM_kPPM))
            Writer::Ppm("pix/file", c, tm);

        if (fWriteType->IsEntryChecked(IDM_kOnce))
            ProcessMessage(MK_MSG(kC_COMMAND, kCM_MENU), IDM_kStop, 0);
    }

    MStarList spots;

    /*
    if (fDisplay->IsEntryChecked(IDM_kStarguider))
        Filter2::Execute(spots, c);
    else
     */
    if (fDisplay->IsEntryChecked(IDM_kFilter))
        Filter::Execute(c);

    if (fDisplay->IsEntryChecked(IDM_kCaosFilter))
    {
        // Double_t kConv = 0.502; // [pix/mm]

        static MTime t0(*tm);
        MTime t(*tm);

        fTime = t-t0;

        Leds leds;
        CaosFilter::Execute(c, leds, 1);

        if (fWrite->IsEntryChecked(IDM_kPositions))
            leds.Print();

        CaosFilter::FilterLeds(leds);
        leds.Compress();

        if (fWrite->IsEntryChecked(IDM_kLeds))
            leds.Print();

        Rings rings;
        rings.CalcRings(leds);

        leds.Sort();

        fLeds  = &leds;
        fRings = &rings;

        if (fFile)
            fTree->Fill();

        if (fWrite->IsEntryChecked(IDM_kRings))
            rings.Print();

        if (fAnalyse->IsEntryEnabled(IDM_kStopAnalyse))
        {
            const Ring &center = rings.GetCenter();

            Double_t phi[6] =
            {
                -124.727,
                 -61.0495,
                 -16.7907,
                  49.3119,
                 139.086
            };

            fHistpr->Fill(center.GetR());
            fHistprx->Fill(center.GetX());
            fHistpry->Fill(center.GetY());
            fHistprxpry->Fill(center.GetX(), center.GetY());

            Double_t sum = 0;
            for (int i=0; i<6 && leds.At(i); i++)
            {
                const Double_t w = (leds(i).GetPhi()-phi[i])*60;

                sum += w;

                fHistw[i]->Fill(w);
                fHistv[i]->Fill(leds(i).GetPhi());
                fGraphw[i]->SetPoint(fGraphw[i]->GetN(), fTime, w);
            }
            fHistallw->Fill(sum/5);

            fGraphprx->SetPoint(fGraphprx->GetN(), fTime, center.GetX());
            fGraphpry->SetPoint(fGraphpry->GetN(), fTime, center.GetY());
        }
    }

    byte zimg[kZOOM*kZOOM];
    for (int y=0; y<kZOOM; y++)
        for (int x=0; x<kZOOM; x++)
            zimg[x+y*kZOOM] = c[(fDx+(x-kZOOM/2)/2)+(fDy+(y-kZOOM/2)/2)*768];

    fZoomImage->DrawImg(zimg);

    if (fDisplay->IsEntryChecked(IDM_kCatalog))
    {
        MTime time(*tm);

        GetCoordinates();

        MStarList stars;
        fSao->GetStars(stars, time.GetMjd(), *fRaDec);

        if (fDisplay->IsEntryChecked(IDM_kStarguider))
        {
            Leds leds;
            CaosFilter::Execute(c, leds, 1);

            cout << "Found: " << leds.GetEntries() << " leds" << endl;

            CaosFilter::RemoveTwins(leds, 3);
            leds.Compress();

            cout << "Rest: " << leds.GetEntries() << " leds" << endl;

            CalcTrackingError(leds, stars);
        }

        byte cimg[768*576];
        fSao->GetImg(c, cimg, stars);

        DrawCircle(c, 0.5);
        DrawCircle(c, 1.0);
        DrawCircle(c, 1.5);

        fCZdAz->SetCoordinates(fSao->GetZdAz());

        fImage->DrawColImg(c, cimg);
    }
    else
        fImage->DrawImg(c);

    memset(myimg, 0, 768*576*sizeof(float));
}

void MGPngReader::DrawCircle(byte *img, double r)
{
    const double rpix = r*60*60/fSao->GetPixSize()+1;
    const int cx = 768/2;
    const int cy = 576/2;
    for (int dx=-(int)(rpix*0.7); dx<(int)(rpix*0.7); dx++)
    {
        const int dy = (int)sqrt(rpix*rpix-dx*dx);
        img[cx+dx + (cy-dy)*768] = 0x40;
        img[cx+dx + (cy+dy)*768] = 0x40;
        img[cx-dy + (cy+dx)*768] = 0x40;
        img[cx+dy + (cy+dx)*768] = 0x40;
    }
}

Bool_t MGPngReader::HandleDoubleClick(Event_t *event)
{
    const Int_t w = fImage->GetWidth();
    const Int_t h = fImage->GetHeight();
    const Int_t x = fImage->GetX();
    const Int_t y = fImage->GetY();

    if (!(event->fX>x && event->fX<x+w && event->fY>y && event->fY<y+h))
        return kTRUE;

    Int_t dx = event->fX-x;
    Int_t dy = event->fY-y;

    if (dx<kZOOM/4) dx=kZOOM/4;
    if (dy<kZOOM/4) dy=kZOOM/4;
    if (dx>766-kZOOM/2) dx=766-kZOOM/4;
    if (dy>510-kZOOM/2) dy=510-kZOOM/4;

    fDx = dx;
    fDy = dy;

    cout << "New coordinates for zoom: " << fDx << " " << fDy << endl;

    return kTRUE;
}
