#include "MStarguider.h"

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

#include <TH2F.h>
#include <TGraph.h>
#include <TTimer.h>

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

#include "MCosy.h"
#include "MCaos.h"

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

#include "coord.h"

#include "Led.h"
#include "Writer.h"
#include "FilterLed.h"
#include "MStarList.h"
#include "CaosFilter.h"
#include "StarCatalog.h"

#include "MGMenu.h"

ClassImp(MStarguider);

enum {
    IDM_kFilter,
    IDM_kCaosFilter,
    IDM_kCatalog,
    IDM_kStarguider,
    IDM_kStart,
    IDM_kStop,
    IDM_kFileType,
    IDM_kPPM,
    IDM_kPNG,
    IDM_kOnce,
    IDM_kStretch,
//    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_kAngle,
    IDM_kInterpol125,
    IDM_kInterpol50,
    IDM_kInterpol25,
    IDM_kInterpol10,
    IDM_kInterpol5,
    IDM_kInterpol2,
    IDM_kInterpol1,
    IDM_kCaosPrintRings,
    IDM_kCaosPrintLeds,
    IDM_kCaosAnalStart,
    IDM_kCaosAnalStop,
    IDM_kCaosWriteStart,
    IDM_kCaosWriteStop,
    IDM_kResetHistograms
};

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

#define kZOOM 96

XY MStarguider::GetCoordinates() const
{
    return fPZdAz->GetCoordinates();
}

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

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

    //
    // Create Menu for MStarguider 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->AddEntry("Stretch",      IDM_kStretch);
    fDisplay->DisableEntry(IDM_kStarguider);
    fDisplay->CheckEntry(IDM_kStretch);
    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->CheckEntry(IDM_kOnce);
    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("50",  IDM_kInterpol50);
    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);

    fCaosPrint = new MGPopupMenu(p);
    fCaosPrint->AddEntry("&Leds",  IDM_kCaosPrintLeds);
    fCaosPrint->AddEntry("&Rings", IDM_kCaosPrintRings);
    fCaosPrint->Associate(this);
    fList->Add(fCaosPrint);

    fCaosWrite = new MGPopupMenu(p);
    fCaosWrite->AddEntry("&Start", IDM_kCaosWriteStart);
    fCaosWrite->AddEntry("Sto&p",  IDM_kCaosWriteStop);
    fCaosWrite->DisableEntry(IDM_kCaosWriteStop);
    fCaosWrite->Associate(this);
    fList->Add(fCaosWrite);

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

    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); 
    fList->Add(fMenu);

    fCaOs = new MGPopupMenu(p);
    fCaOs->AddPopup("&Write",   fCaosWrite);
    fCaOs->AddPopup("&Print",   fCaosPrint);
    fCaOs->AddPopup("&Analyse", fCaosAnalyse);
    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);

    fFps = new TGLabel(this, "---fps");
    fFps->SetTextJustify(kTextRight);
    fFps->Move(633, fMenu->GetDefaultHeight()+578);
    AddFrame(fFps);
    fList->Add(fFps);

    fPosZoom = new TGLabel(this, "----.--d/----.--d (----, ----)");
    fPosZoom->SetTextJustify(kTextRight);
    fPosZoom->Move(620, fMenu->GetDefaultHeight()+678);
    AddFrame(fPosZoom);
    fList->Add(fPosZoom);

    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+13);
    AddFrame(l);
    fList->Add(l);

    l = new TGLabel(this, "deg");
    l->SetTextJustify(kTextLeft);
    l->Move(605, fMenu->GetDefaultHeight()+619-10);
    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/3600);
    fSao->SetRotationAngle(0);

    TString txt;
    txt += pixsize;

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

    fAngle = new TGTextEntry(this, "         0", IDM_kAngle);
    fAngle->SetAlignment(kTextCenterX);
    fAngle->Move(547, fMenu->GetDefaultHeight()+617-10);
    AddFrame(fAngle);
    fList->Add(fAngle);

    // 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("MStarguider Main Window");
    SetIconName("MStarguider");

    MapSubwindows();
    MapWindow();

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

MStarguider::MStarguider(MObservatory::LocationName_t obs)
: TGMainFrame(gClient->GetRoot(), 768, 740), fCosy(NULL), fDx((768-kZOOM)/2), fDy((512-kZOOM)/2)
{
    cout << " #### FIXME: Make MCaos Thread safe!" << endl;

    fSao = new StarCatalog(obs);
    fRaDec = new RaDec(180, 40);

    fCaos = new MCaos;
    fCaos->ReadResources();

    InitGui();

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

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

    fTime.Now();
}

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

    fTimer->TurnOff();
    delete fTimer;

    delete fList;

    delete fCaos;
    delete fSao;
    delete fRaDec;

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

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

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

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

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

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

    case kC_COMMAND:
        switch (GET_SUBMSG(msg))
        {
        case kCM_MENU:
            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);
                gSystem->Unlink("tracking_error.txt");
                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_kStretch:
                Toggle(fDisplay, IDM_kStretch);
                return kTRUE;

            case IDM_kCaosFilter:
                //if (!fDisplay->IsEntryChecked(IDM_kCaosFilter))
                //    fCaos->OpenFile();
                Toggle(fDisplay, IDM_kCaosFilter);
                if (fDisplay->IsEntryChecked(IDM_kCaosFilter))
                    fMenu->AddPopup("&CaOs", fCaOs, NULL);
                else
                {
                    if(fCaosWrite->IsEntryChecked(IDM_kCaosPrintLeds))
                        fCaosWrite->UnCheckEntry(IDM_kCaosPrintLeds);
                    if(fCaosWrite->IsEntryChecked(IDM_kCaosPrintRings))
                        fCaosWrite->UnCheckEntry(IDM_kCaosPrintRings);
                    if(fCaosAnalyse->IsEntryEnabled(IDM_kCaosAnalStop))
                    {
                        fCaosAnalyse->DisableEntry(IDM_kCaosAnalStop);
                        fCaosAnalyse->EnableEntry(IDM_kCaosAnalStart);
                        fCaos->DeleteHistograms();
                    }
                    if(fCaosWrite->IsEntryEnabled(IDM_kCaosWriteStop))
                    {
                        fCaosWrite->DisableEntry(IDM_kCaosWriteStop);
                        fCaosWrite->EnableEntry(IDM_kCaosWriteStart);
                        fCaos->CloseFile();
                    }
                    fMenu->RemovePopup("CaOs");
                }
                fMenu->Resize(fMenu->GetDefaultSize());
                MapSubwindows();
                MapWindow();
                return kTRUE;

            case IDM_kCaosPrintLeds:
            case IDM_kCaosPrintRings:
                Toggle(fCaosPrint, mp1);
                return kTRUE;

            case IDM_kCaosAnalStart:
                fCaosAnalyse->DisableEntry(IDM_kCaosAnalStart);
                fCaosAnalyse->EnableEntry(IDM_kCaosAnalStop);
                fCaos->InitHistograms();
                return kTRUE;

            case IDM_kCaosAnalStop:
                fCaosAnalyse->DisableEntry(IDM_kCaosAnalStop);
                fCaosAnalyse->EnableEntry(IDM_kCaosAnalStart);
                fCaos->ShowHistograms();
                fCaos->DeleteHistograms();
                return kTRUE;

            case IDM_kCaosWriteStart:
                fCaosWrite->DisableEntry(IDM_kCaosWriteStart);
                fCaosWrite->EnableEntry(IDM_kCaosWriteStop);
                fCaos->OpenFile();
                return kTRUE;

            case IDM_kCaosWriteStop:
                fCaosWrite->DisableEntry(IDM_kCaosWriteStop);
                fCaosWrite->EnableEntry(IDM_kCaosWriteStart);
                fCaos->CloseFile();
                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_kInterpol50:
            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_kInterpol50:
                    fIntRate = 50;
                    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 MStarguider::SetPointingPosition(RaDec rd)
{
    rd.Ra(rd.Ra()*24/360);
    fCRaDec->SetCoordinates(rd);
}

ZdAz MStarguider::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;

    ofstream fout1("pointingpos.txt");
    fout1 << setprecision(10) << fSao->GetMjd()-52000 << " ";
    if (fCosy)
        fout1 << fCosy->GetPointingPos() << " ";
    fout1 << -pos1.Alt() << " " << pos1.Az() << endl;

    pos1 -= pos0;

    ofstream fout2("tracking_error.txt", ios::app);
    fout2 << setprecision(10) << fSao->GetMjd()-52000 << " ";
    if (fCosy)
        fout2 << fCosy->GetPointingPos() << " ";
    fout2 << -pos1.Alt() << " " << pos1.Az() << endl;

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

void MStarguider::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);
}

bool MStarguider::Interpolate(const unsigned long n, byte *img) const
{
    if (fIntRate<=1)
        return true;

    static unsigned short myimg[768*576];

    unsigned short *f = myimg;
    byte *i = img;
    byte *e = img+768*576;

    while (i<e)
        *f++ += *i++;

    if (n%fIntRate)
        return false;

    f = myimg;
    i = img;
    e = img+768*576;

    while (i<e)
        *i++ = (byte)(*f++/fIntRate);

    memset(myimg, 0, sizeof(myimg));

    return true;
}

void MStarguider::ProcessFrame(const unsigned long n, byte *img, struct timeval *tm)
{
    static unsigned long n0 = n;

    Timer t(tm);

    const Double_t d = t-fTime;
    if (d>1)
    {
        fFps->SetText(Form("%dfps", (int)((n-n0)/d+.5)));
        fTime = t;
        n0 = n;
    }

    if (!Interpolate(n, img))
        return;

    FilterLed f(img, 768, 576, 2.5); // 2.5

    if (fDisplay->IsEntryChecked(IDM_kStretch))
        f.Stretch();

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

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

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

    MStarList spots;
    if (fDisplay->IsEntryChecked(IDM_kFilter))
        f.Execute();

    if (fDisplay->IsEntryChecked(IDM_kCaosFilter))
    {
        const bool printl = fCaosPrint->IsEntryChecked(IDM_kCaosPrintLeds);
        const bool printr = fCaosPrint->IsEntryChecked(IDM_kCaosPrintRings);
        ZdAz pos;
        if (fCosy)
            pos = fCosy->GetPointingPos();

        fCaos->Run(img, printl, printr, pos, t);
    }

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

    fZoomImage->DrawImg(zimg);

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

        XY xy = fCRaDec->GetCoordinates();
        fRaDec->Set(xy.X()*360/24, xy.Y());

        UpdatePosZoom();

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

        if (fDisplay->IsEntryChecked(IDM_kStarguider))
        {
            Leds leds;
            f.Execute(leds);

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

            CalcTrackingError(leds, stars);
        }

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

        const float r = 60*60/fSao->GetPixSize()+1;
        f.DrawCircle(0.5*r);
        f.DrawCircle(1.0*r);
        f.DrawCircle(1.5*r);

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

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

void MStarguider::UpdatePosZoom()
{
    if (fDisplay->IsEntryChecked(IDM_kCatalog))
    {
        fSao->Now();
        AltAz aa = fSao->CalcAltAzFromPix(fDx, fDy)*kRad2Deg;

        if (aa.Az()<0)
            aa.Az(aa.Az()+360);
        fPosZoom->SetText(Form("%.1fd/%.1fd (%d, %d)",
                               -aa.Alt(), aa.Az()-180, fDx, fDy));
    }
    else
        fPosZoom->SetText(Form("(%d, %d)", fDx, fDy));
}

Bool_t MStarguider::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/4) dx=766-kZOOM/4;
    if (dy>574-kZOOM/4) dy=574-kZOOM/4;

    fDx = dx;
    fDy = dy;

    UpdatePosZoom();
    return kTRUE;
}
