#undef EXPERT
#undef EXPERT

#include "MStarguider.h"

#include <fstream>    // ifstream

#include <TH2F.h>
#include <TGraph.h>
#include <TTimer.h>
#include <TSystem.h>
#include <TFile.h> // temp writeout of histos
#include <TSocket.h>

#include <TGMenu.h>
#include <TGLabel.h>
#include <TGButton.h>
#include <TGSplitter.h>    // TGHorizontal3DLine
#include <TGTextEntry.h>
#include <TGLayout.h>
#include "MString.h"

#include "MLog.h"
#include "MLogManip.h"

#include "MAstro.h"
#include "MString.h"


#include "MCosy.h"
#include "MCaos.h"
// #include "MStargLeds.h"
#include "MStargHistograms.h"
#include "MDriveCom.h"

#include "MGStarg.h" 
#include "MGNumStars.h"

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

#include "Camera.h"
#include "PngReader.h"

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

#include "MGCosy.h"

ClassImp(MStarguider);

using namespace std;

enum {
    IDM_kFilter,
    IDM_kFindStar,
    IDM_kCaosFilter,
    IDM_kCatalog,
    IDM_kStarguider,
    IDM_kStart,
    IDM_kStop,
    IDM_kFileType,
    IDM_kPPM,
    IDM_kPNG,
    IDM_kOnce,
    IDM_kStretch,
    IDM_kInput,
    IDM_kChannel1,
    IDM_kChannel2,
    IDM_kChannel3,
    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_kCut,
    IDM_kInterpol250,
    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,
    IDM_kStargAnalysis,
    IDM_kStargCaosFilter,
    IDM_kStargFindStar,
    IDM_kRoqueLampAna,
    IDM_kStarguiderMode,
    IDM_kTpointMode

};

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

    if (fCosy && fCosy->GetWin()->IsMapped())
        fCosy->GetWin()->GetImage()->DoRedraw();

    fGStarg->Update(fPos, fD);   
    if (fDisplay->IsEntryChecked(IDM_kStarguider))
        fGNumStars->Update(fNumStarsDetected, fNumStarsCorrelated);
 
    return kTRUE;
}

#define kZOOM 96

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

void MStarguider::InitGui(Int_t channel)
{
    fList = new MGList;
    fList->SetOwner();

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

    fChannel = new TGPopupMenu(p);
    fChannel->AddEntry("Starfield Camera", IDM_kChannel1);
    fChannel->AddEntry("TPoint Camera",    IDM_kChannel2);
    fChannel->AddEntry("Read from File",   IDM_kChannel3);
    if (channel<0)
        fChannel->CheckEntry(IDM_kChannel3);
    else
        fChannel->CheckEntry(channel==0?IDM_kChannel1:IDM_kChannel2);
    fChannel->Associate(this);
    fList->Add(fChannel);

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

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

    fWriteRate = new TGPopupMenu(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;

    fLimMag = new TGPopupMenu(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_kLimMag9);
    fLimMag->Associate(this);
    fList->Add(fLimMag);

    fSao->SetLimitMag(9.0);

    fInterpol = new TGPopupMenu(p);
    fInterpol->AddEntry("250", IDM_kInterpol250);
    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->Associate(this);
    fList->Add(fInterpol);

    TString disp=gVirtualX->DisplayName();
    gLog << all << "Display: " << disp << endl;
    if (disp.First(':')>=0)
        disp=disp(0, disp.First(':'));

    if (disp.IsNull() || disp==(TString)"localhost")
    {
        fInterpol->CheckEntry(IDM_kInterpol5);
        fIntRate = 50;
    }
    else
    {
        fInterpol->CheckEntry(IDM_kInterpol125);
        fIntRate = 125;
    }

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

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

    fCaosAnalyse = new TGPopupMenu(p);
    fCaosAnalyse->AddEntry("S&tart Analysis", IDM_kCaosAnalStart);
    fCaosAnalyse->AddEntry("St&op Analysis",  IDM_kCaosAnalStop);
    fCaosAnalyse->DisableEntry(IDM_kCaosAnalStop);
    fCaosAnalyse->Associate(this);
    fList->Add(fCaosAnalyse);

    fMenu = new TGMenuBar(this, 0, 0, kHorizontalFrame);
    fDisplay       = fMenu->AddPopup("&Display");
    fMode          = fMenu->AddPopup("&Mode");
    fWritePictures = fMenu->AddPopup("&WritePics");
    fSetup         = fMenu->AddPopup("&Setup");
    fOperations    = fMenu->AddPopup("&Operations");
    fMenu->Resize(fMenu->GetDefaultSize());
    AddFrame(fMenu); 

    //
    // Create Menu for MStarguider Display
    //
    //fDisplay = new MMGPopupMenu(p);
    fDisplay->AddEntry("&Filter",               IDM_kFilter);
    fDisplay->AddEntry("Stretch",               IDM_kStretch);
    fDisplay->AddSeparator();
    fDisplay->AddEntry("Find &Star",            IDM_kFindStar);
    fDisplay->AddEntry("C&aos Filter",          IDM_kCaosFilter);
    fDisplay->AddSeparator();
    fDisplay->AddEntry("SAO &Catalog",          IDM_kCatalog);
    fDisplay->AddEntry("Starguider",            IDM_kStarguider);
    fDisplay->AddEntry("Starguider LED Filter", IDM_kStargCaosFilter);
    fDisplay->AddEntry("Starguider Find Star",  IDM_kStargFindStar);
    fDisplay->AddSeparator();    
    if (channel>=0)
        fDisplay->AddPopup("&Input",   fChannel);
    fDisplay->DisableEntry(IDM_kStargFindStar);
    fDisplay->CheckEntry(IDM_kStretch);
    fDisplay->Associate(this);

    fMode->AddEntry("Starguider", IDM_kStarguiderMode);
    fMode->AddEntry("Tpoint",     IDM_kTpointMode);
    fMode->Associate(this);

    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);

    fSetup->AddPopup("Lim. &Magnitude",      fLimMag);
    fSetup->AddPopup("Disp. &Interpolation", fInterpol);
    fSetup->Associate(this);

    fOperations->AddEntry("Roque Lamp Analysis", IDM_kRoqueLampAna);
    fOperations->AddEntry("Starguider Analysis", IDM_kStargAnalysis);
    fOperations->DisableEntry(IDM_kStargAnalysis);
    fOperations->Associate(this);

    fCaOs = new TGPopupMenu(p);
    fCaOs->AddPopup("&Write",   fCaosWrite);
    fCaOs->AddPopup("&Print",   fCaosPrint);
    fCaOs->AddPopup("&Analyse", fCaosAnalyse);
    fCaOs->Associate(this);
    fList->Add(fCaOs);

    fGStarg = new MGStarg(this, 235);
    fGStarg->DrawText("0.75'", "1.50'", "3.00'", "Mispointing [min]");
    fGStarg->DrawHexagon();
    fGStarg->Move(530,596+5);
    fList->Add(fGStarg);

    //RA,Dec for catalog
    fCRaDec = new MGCoordinates(this, kETypeRaDec);
    fCRaDec->Move(4, fMenu->GetDefaultHeight()+584);
    AddFrame(fCRaDec);

    //telescope position
    fCZdAz = new MGCoordinates(this, kETypeZdAz, 2);
    fCZdAz->Move(240+12+28, fMenu->GetDefaultHeight()+597);
    AddFrame(fCZdAz);

    //starguider position
    fPZdAz = new MGCoordinates(this, kETypeZdAz, 2);
    fPZdAz->Move(240+12+28, fMenu->GetDefaultHeight()+640);
    AddFrame(fPZdAz);

    //mispointing
    fDZdAz = new MGCoordinates(this, kETypeZdAz, 2);
    fDZdAz->Move(240+12+28, fMenu->GetDefaultHeight()+683);
    AddFrame(fDZdAz);

    fSZdAz = new MGCoordinates(this, kETypeZdAz, 2);
    fSZdAz->Move(240+12+28, fMenu->GetDefaultHeight()+795);
    AddFrame(fSZdAz);

    fGNumStars = new MGNumStars(this, 235);
    fGNumStars->DrawText("Number of stars");
    fGNumStars->Move(278, fMenu->GetDefaultHeight()+713);
    fList->Add(fGNumStars);

    fTPoint = new TGTextButton(this, "TPoint");
    fTPoint->Move(4, fMenu->GetDefaultHeight()+785);
    fTPoint->AllowStayDown(kTRUE);
    AddFrame(fTPoint);

    fStargTPoint = new TGTextButton(this, "StargTPoint");
    fStargTPoint->Move(170, fMenu->GetDefaultHeight()+785);
    fStargTPoint->AllowStayDown(kTRUE);
    AddFrame(fStargTPoint);

    fFps = new TGLabel(this, "---fps");
    fFps->SetTextJustify(kTextRight);
    fFps->Move(650-495, fMenu->GetDefaultHeight()+714+23);
    AddFrame(fFps);

    fPosZoom = new TGLabel(this, "(----, ----) ----.--d/----.--d");
    fPosZoom->SetTextJustify(kTextLeft);
    fPosZoom->Move(4, fMenu->GetDefaultHeight()+765);
    AddFrame(fPosZoom);

    fSkyBright = new TGLabel(this, "Sky Brightness: ---         ");
    fSkyBright->SetTextJustify(kTextLeft);
    fSkyBright->Move(4, fMenu->GetDefaultHeight()+785);
    AddFrame(fSkyBright);

    TGLabel *l = new TGLabel(this, "deg");
    l->SetTextJustify(kTextLeft);
    l->Move(606-412, fMenu->GetDefaultHeight()+669);
    AddFrame(l);

    l = new TGLabel(this, "arcsec/pix");
    l->SetTextJustify(kTextLeft);
    l->Move(606-412, fMenu->GetDefaultHeight()+692);
    AddFrame(l);

    l = new TGLabel(this, "sigma");
    l->SetTextJustify(kTextLeft);
    l->Move(606-412, fMenu->GetDefaultHeight()+715);
    AddFrame(l);

    fCZdAzText = new TGLabel(this, "Zd/Az telescope pointing at");
    fCZdAzText->SetTextJustify(kTextLeft);
    fCZdAzText->Move(240+12+20+7, fMenu->GetDefaultHeight()+584-5);
    AddFrame(fCZdAzText);

    fPZdAzText = new TGLabel(this, "Zd/Az starguider pointing at");
    fPZdAzText->SetTextJustify(kTextLeft);
    fPZdAzText->Move(240+12+20+7, fMenu->GetDefaultHeight()+630+20-5-23);
    AddFrame(fPZdAzText);

    fDZdAzText = new TGLabel(this, "Zd/Az mispointing");
    fDZdAzText->SetTextJustify(kTextLeft);
    fDZdAzText->Move(240+12+20+7, fMenu->GetDefaultHeight()+676+2*20-5-46);
    AddFrame(fDZdAzText);

#ifdef EXPERT
    l = new TGLabel(this, "Mispointing/FindStar (Experts Only!)");
    l->SetTextJustify(kTextLeft);
    l->Move(240+12+20, fMenu->GetDefaultHeight()+722+3*20-5);
    AddFrame(l);
#endif

    // Set input box for rotation angle
    const Double_t angle = -0.2;
    fSao->SetRotationAngle(angle);

    TString txt;
    txt += angle;

    fAngle = new TGTextEntry(this, txt, IDM_kAngle);
    fAngle->SetAlignment(kTextCenterX);
    fAngle->Move(547-410, fMenu->GetDefaultHeight()+667);
    AddFrame(fAngle);

    // Set input box for pixel size
    const Double_t pixsize = 48.9; // used to be 23.4

    fSao->SetPixSize(pixsize);

    txt = "";
    txt += pixsize;

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

    // Set input box for cleaning cut
    const Double_t cut = 3.0;

    txt = "";
    txt += cut;

    fCut = new TGTextEntry(this, txt, IDM_kCut);
    fCut->SetAlignment(kTextCenterX);
    fCut->Move(547-410, fMenu->GetDefaultHeight()+713);
    AddFrame(fCut);

    // 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);
    fZoomImage->Move(4, 700-kZOOM-2+85);
    AddFrame(fZoomImage);

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

    const Int_t w = 768;
    const Int_t h = 840;
    SetWMSizeHints(w, h, w, h, 1, 1);  // set the smallest and biggest size of the Main frame

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

    MapSubwindows();
    fTPoint->UnmapWindow();
    fStargTPoint->UnmapWindow();
    fGStarg->UnmapWindow();
    fGNumStars->UnmapWindow();
    fCRaDec->UnmapWindow();
    fCZdAz->UnmapWindow();
    fCZdAzText->UnmapWindow();
    fPZdAz->UnmapWindow();
    fPZdAzText->UnmapWindow();
    fDZdAz->UnmapWindow();
    fDZdAzText->UnmapWindow();
    fSZdAz->UnmapWindow();
    fSkyBright->UnmapWindow();
    MapWindow();


    //IconifyWindow();

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

MStarguider::MStarguider(MObservatory::LocationName_t obs, Int_t channel)
    : TGMainFrame(gClient->GetRoot(), 768, 840), 
      fNumStarsDetected(0),
      fNumStarsCorrelated(0),
      fCosy(NULL),
      fOutTp(0),
      fOutStargTp(0),
      fOutRq(0),
      fDx((768-kZOOM)/2),
      fDy((512-kZOOM)/2),
      fStatus(MDriveCom::kStandby)
{
    gLog << warn << " #### FIXME: Make MCaos Thread safe!" << endl;

    // This means that all objects added with AddFrame are deleted
    // automatically, including all LayoutHints.
    SetCleanup();

    fAmcSocket = new TSocket("amc", 7307);

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

    //    fStargLeds = new MStargLeds;
    //    fStargLeds->ReadResources();

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

    fStargCaos = new MCaos;
    fStargCaos->ReadResources("stargleds.txt");
    fStargCaos->SetMinNumberRings(3);
    fStargCaos->SetRadii(158,164);

    fStargHistograms = new MStargHistograms();

    InitGui(channel);

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

    fTime.Now();

    fTimeFromTp.Set(1970,1,1);
    fAltAzOffsetFromTp = AltAz(-1000,-1000);
                                             
    gVirtualX->GrabButton(fId, kButton2, 0, 0, 0, 0, kTRUE);

    if (channel<0)
        fGetter = new PngReader(*this);
    else
        fGetter = new Camera(*this, channel);
}

MStarguider::~MStarguider()
{
    fGetter->ExitLoop();
    delete fGetter;

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

    fTimer->TurnOff();
    delete fTimer;

    delete fList;

    delete fCaos;
    delete fStargCaos;
    //    delete fStargLeds;
    delete fStargHistograms;
    delete fSao;
    delete fRaDec;

    if (fOutTp)
        delete fOutTp;

    if (fOutStargTp)
        delete fOutStargTp;

    if (fOutRq)
        delete fOutRq;

    delete fAmcSocket;

    gLog << inf2 << "Camera Display destroyed." << endl;
}

bool MStarguider::SendAmcTrigger(const char *msg)
{
    if (!fAmcSocket->IsValid())
        return false;

    TString txt("TRIGGER ");
    txt += msg;

    const Int_t len = fAmcSocket->SendRaw(txt.Data(), txt.Length());
    if (len<0)
    {
        gLog << err << "ERROR - Sending Trigger to Amc" << endl;
        return false;
    }
    if (len!=txt.Length())
    {
        gLog << err << "Send wrong number (" << len << ") of Bytes to Amc." << endl;
        return false;
    }

    return true;
}

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

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

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

void MStarguider::SwitchOff(TGPopupMenu *p, UInt_t id)
{
    p->UnCheckEntry(id);
    p->DisableEntry(id);
}

void MStarguider::SetChannel()
{
    if (fChannel->IsEntryChecked(IDM_kChannel3))
    {
        if (dynamic_cast<PngReader*>(fGetter)==0)
        {
            delete fGetter;
            fGetter=new PngReader(*this);
        }
    }
    else
    {
        const Int_t ch = fChannel->IsEntryChecked(IDM_kChannel1) ? 0 : 1;
        if (dynamic_cast<Camera*>(fGetter)==0)
        {
            delete fGetter;
            fGetter = new Camera(*this, ch);
        }
        else
            fGetter->SetChannel(ch);
    }
}

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

void MStarguider::ToggleStargAnalysis()
{
    if (fOperations->IsEntryChecked(IDM_kStargAnalysis))
        fStargHistograms->OpenFile();
    else
        fStargHistograms->CloseFile();
}

void MStarguider::ToggleFindStar()
{
    if (fDisplay->IsEntryChecked(IDM_kFindStar) && fCosy)
        fTPoint->MapWindow();
    else
    {
        fTPoint->UnmapWindow();
        fTPoint->SetDown(kFALSE);
    }
}

void MStarguider::ToggleStarguider()
{
    if (fDisplay->IsEntryChecked(IDM_kStarguider))
    {
        fLastBright = 0xff;

        fChannel->EnableEntry(IDM_kChannel1);
        fDisplay->DisableEntry(IDM_kFindStar);
        fDisplay->DisableEntry(IDM_kCaosFilter);
        fOperations->EnableEntry(IDM_kStargAnalysis);

        fStargTPoint->MapWindow();

        fPZdAz->MapWindow();
        fDZdAz->MapWindow();
        fSkyBright->MapWindow();

        for (int i=IDM_kLimMag3; i<=IDM_kLimMag9; i++)
            fLimMag->UnCheckEntry(i);
        fLimMag->CheckEntry(IDM_kLimMag9);
        fSao->SetLimitMag(9.0);

        for (int i=IDM_kInterpol250; i<=IDM_kInterpol1; i++)
            fInterpol->UnCheckEntry(i);
        fInterpol->CheckEntry(IDM_kInterpol125);
        fIntRate = 125;

        //catalog
        fDisplay->CheckEntry(IDM_kCatalog);
        fCRaDec->MapWindow();
        fCZdAz->MapWindow();
        fCZdAzText->MapWindow();

        fPZdAz->MapWindow();
        fPZdAzText->MapWindow();
        fDZdAz->MapWindow();
        fDZdAzText->MapWindow();

        fGStarg->MapWindow();
        fGNumStars->MapWindow();

        SwitchOff(fChannel, IDM_kChannel2);
        fChannel->CheckEntry(IDM_kChannel1);

    }
    else
    {
        fStatus = MDriveCom::kStandby;

        fStargTPoint->UnmapWindow();
        fStargTPoint->SetDown(kFALSE);

        fPZdAz->UnmapWindow();
        fPZdAzText->UnmapWindow();
        fDZdAz->UnmapWindow();
        fDZdAzText->UnmapWindow();
        fSkyBright->UnmapWindow();
        //catalog
        fCRaDec->UnmapWindow();
        fCZdAz->UnmapWindow();
        fCZdAzText->UnmapWindow();
        fDisplay->UnCheckEntry(IDM_kCatalog);

        fGStarg->UnmapWindow();
        fGNumStars->UnmapWindow();

        fChannel->EnableEntry(IDM_kChannel2);
        fDisplay->EnableEntry(IDM_kFindStar);
        fDisplay->EnableEntry(IDM_kCaosFilter);
        fOperations->DisableEntry(IDM_kStargAnalysis);
    }

    SetChannel();
    //gSystem->Unlink("tracking_error.txt");
}

void MStarguider::ToggleCaosFilter()
{
    if (fDisplay->IsEntryChecked(IDM_kCaosFilter))
    {
        if (!fMode->IsEntryChecked(IDM_kStarguiderMode)
            && !fMode->IsEntryChecked(IDM_kTpointMode))
            fMenu->AddPopup("&CaOs", fCaOs, NULL);

        SwitchOff(fDisplay, IDM_kStarguider);
        SwitchOff(fDisplay, IDM_kStargCaosFilter);
        fDisplay->DisableEntry(IDM_kStargFindStar);
    }
    else
    {
        fCaosWrite->UnCheckEntry(IDM_kCaosPrintLeds);
        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");

        fDisplay->EnableEntry(IDM_kStargCaosFilter);
        fDisplay->EnableEntry(IDM_kStarguider);
    }
    fMenu->Resize(fMenu->GetDefaultSize());
    MapSubwindows(); // maps everything, but we don't want that
    fTPoint->UnmapWindow();
    fStargTPoint->UnmapWindow();
    fGStarg->UnmapWindow();
    fGNumStars->UnmapWindow();
    fCRaDec->UnmapWindow();
    fCZdAz->UnmapWindow();
    fCZdAzText->UnmapWindow();
    fPZdAz->UnmapWindow();
    fPZdAzText->UnmapWindow();
    fDZdAz->UnmapWindow();
    fDZdAzText->UnmapWindow();
    fSZdAz->UnmapWindow();
    fSkyBright->UnmapWindow();
    MapWindow();
}

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());
                    gLog << all << "Pixel Size changed to " << pixsize << "\"/pix" << endl;
                    fSao->SetPixSize(pixsize);
                    return kTRUE;
                }
            case IDM_kAngle:
                {
                    const Float_t angle = atof(fAngle->GetText());
                    gLog << all << "Rotation Angle changed to " << angle << "deg" << endl;
                    fSao->SetRotationAngle(angle);
                    return kTRUE;
                }
            case IDM_kCut:
                {
                    const Float_t cut = atof(fCut->GetText());
                    gLog << all << "Starguider cleaning level changed to " << cut << " sigma." << endl;
                    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))
                {
                    fCRaDec->MapWindow();
                    fCZdAz->MapWindow();
                    fCZdAzText->MapWindow();
                }
                else
                {
                    fCRaDec->UnmapWindow();
                    fCZdAz->UnmapWindow();
                    fCZdAzText->UnmapWindow();
                }
                return kTRUE;

	   case IDM_kRoqueLampAna:
  	        Toggle(fOperations, IDM_kRoqueLampAna);
                if (fOperations->IsEntryChecked(IDM_kRoqueLampAna))
                    fDisplay->CheckEntry(IDM_kStargCaosFilter);
                else
                    fDisplay->UnCheckEntry(IDM_kStargCaosFilter);
		  
		return kTRUE;

           case IDM_kStargFindStar:
	        Toggle(fDisplay, IDM_kStargFindStar);         
                if (fDisplay->IsEntryChecked(IDM_kStargFindStar))
                    fSZdAz->MapWindow();
                else
                    fSZdAz->UnmapWindow();
                return kTRUE;

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

            case IDM_kStargAnalysis:
                Toggle(fOperations, IDM_kStargAnalysis);
                ToggleStargAnalysis();
                return kTRUE;

            case IDM_kStarguiderMode:
                Toggle(fMode, IDM_kStarguiderMode);

                if (fMode->IsEntryChecked(IDM_kStarguiderMode))
                {
                    //uncheck not needed items
                    //general
                    fDisplay->UnCheckEntry(IDM_kStargFindStar);
                    SwitchOff(fDisplay, IDM_kFilter);
                    SwitchOff(fChannel, IDM_kChannel3);
                    SwitchOff(fOperations, IDM_kRoqueLampAna);
                    SwitchOff(fOperations, IDM_kStargAnalysis);

                    //tpoint
                    SwitchOff(fDisplay, IDM_kFindStar);
                    ToggleFindStar();
                    SwitchOff(fDisplay, IDM_kCaosFilter);
                    ToggleCaosFilter();
                    fMode->UnCheckEntry(IDM_kTpointMode);

                    //enable starguider items
                    fDisplay->EnableEntry(IDM_kStargCaosFilter);
                    fDisplay->EnableEntry(IDM_kStarguider);
                    fDisplay->EnableEntry(IDM_kCatalog);

                    //check needed items
                    fDisplay->CheckEntry(IDM_kStretch);
                    fDisplay->CheckEntry(IDM_kStargCaosFilter);
                    fDisplay->CheckEntry(IDM_kStarguider);
                    ToggleStarguider();
                }
                else
                {
                    //uncheck
                    //starguider items
                    fDisplay->UnCheckEntry(IDM_kStargCaosFilter);
                    fDisplay->UnCheckEntry(IDM_kStarguider);
                    ToggleStarguider();

                    //general
                    fDisplay->UnCheckEntry(IDM_kCatalog);
                    fDisplay->EnableEntry(IDM_kFilter);
                    fDisplay->EnableEntry(IDM_kCaosFilter);
                    fDisplay->EnableEntry(IDM_kFindStar);
                    fChannel->EnableEntry(IDM_kChannel3);
                    fOperations->EnableEntry(IDM_kRoqueLampAna);
                }
                return kTRUE;

            case IDM_kTpointMode:
                Toggle(fMode, IDM_kTpointMode);

                if (fMode->IsEntryChecked(IDM_kTpointMode))
                {
                    //unchecking not needed items
                    //general
                    fDisplay->UnCheckEntry(IDM_kStargFindStar);
                    SwitchOff(fDisplay, IDM_kFilter);
                    SwitchOff(fChannel, IDM_kChannel3);
                    SwitchOff(fOperations, IDM_kRoqueLampAna);

                    //from starguider
                    SwitchOff(fDisplay, IDM_kStargCaosFilter);
                    SwitchOff(fDisplay, IDM_kCatalog);
                    SwitchOff(fDisplay, IDM_kStarguider);
                    ToggleStarguider();
                    fMode->UnCheckEntry(IDM_kStarguiderMode);
                    SwitchOff(fOperations, IDM_kStargAnalysis);
                    ToggleStargAnalysis();

                    //switch camera
                    SwitchOff(fChannel, IDM_kChannel1);
                    fChannel->CheckEntry(IDM_kChannel2);

                    SetChannel();

                    //checking needed items
                    fDisplay->CheckEntry(IDM_kStretch);
                    fDisplay->CheckEntry(IDM_kCaosFilter);
                    ToggleCaosFilter();
                    fDisplay->CheckEntry(IDM_kFindStar);
                    ToggleFindStar();
                }
                else
                {
                    //enable
                    //starguider items
                    fDisplay->EnableEntry(IDM_kStargCaosFilter);
                    fDisplay->EnableEntry(IDM_kCatalog);
                    fDisplay->EnableEntry(IDM_kStarguider);
                    fOperations->EnableEntry(IDM_kStargAnalysis);

                    //general
                    fDisplay->EnableEntry(IDM_kFilter);
                    fChannel->EnableEntry(IDM_kChannel1);
                    fChannel->EnableEntry(IDM_kChannel3);
                    fOperations->EnableEntry(IDM_kRoqueLampAna);

                    //tpoint
                    fDisplay->UnCheckEntry(IDM_kCaosFilter);
                    ToggleCaosFilter();
                    fDisplay->UnCheckEntry(IDM_kFindStar);
                    ToggleFindStar();
                }
                return kTRUE;

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

            case IDM_kFindStar:
                Toggle(fDisplay, IDM_kFindStar);
                ToggleFindStar();
                return kTRUE;

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

            case IDM_kCaosFilter:
                Toggle(fDisplay, IDM_kCaosFilter);
                ToggleCaosFilter();
                return kTRUE;

            case IDM_kStargCaosFilter:
		Toggle(fDisplay, IDM_kStargCaosFilter);                
                if (fDisplay->IsEntryChecked(IDM_kStargCaosFilter))
                {
                    fDisplay->EnableEntry(IDM_kStargFindStar);
                    SwitchOff(fDisplay, IDM_kCaosFilter);
                    SwitchOff(fDisplay, IDM_kFindStar);
                    SwitchOff(fDisplay, IDM_kFilter);
                }
                else
                {
                    fDisplay->EnableEntry(IDM_kFilter);
                    fDisplay->EnableEntry(IDM_kFindStar);
                    fDisplay->EnableEntry(IDM_kCaosFilter);
                    fDisplay->DisableEntry(IDM_kStargFindStar);
                }
                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_kChannel1:
            case IDM_kChannel2:
                {
                    const Int_t ch0 = fChannel->IsEntryChecked(IDM_kChannel1) ? 0 : 1;
                    const Int_t ch1 = mp1==IDM_kChannel1                      ? 0 : 1;

		    if (ch0==ch1)
                        return kTRUE;

                    fChannel->CheckEntry  (ch1==0?IDM_kChannel1:IDM_kChannel2);
                    fChannel->UnCheckEntry(ch1==1?IDM_kChannel1:IDM_kChannel2);

                    SetChannel();
                }
                return kTRUE;

            case IDM_kInterpol250:
            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_kInterpol250; 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;
                case IDM_kInterpol250:
                    fIntRate = 250;
                    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,
                                Int_t &num) const
{
    num = -1;

    // Width of the final 2D gaussian
    const Double_t width = 0.8;

    // The binning is made 1.7 sigma (which, in the 1D case, gives the 
    // highest significance of a gaussian signal)  (1bin equiv 3x3 sigma)
    const Double_t max =  50;
    const Int_t    n   = TMath::Nint(2*max/(1.77*1.7*width));
    //1.77=sqrt(pi) comes from pir=bin

    // Fill a histogram with the dx/dy values from the file
    TH2F hist("Hist", "dX/dY", n, -max, max, n, -max, max);
//    hist.SetDirectory(0);

    //
    // 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]);
    //}

    // fill dx and dy into histogram
    for (int i=0; i<mag.GetSize(); i++)
        hist.Fill(x[i], y[i]);

    // Remove all bins which have content of only a single event
    // including under- and overflow bins
    for (int i=0; i<hist.GetSize(); i++)
        if (hist.GetBinContent(i)<1.5)
            hist.SetBinContent(i, 0);

    // Find the bin containing the maximum
    Int_t bx, by, bz;
    hist.GetMaximumBin(bx, by, bz);

    // In the worst case the events are spread through the
    // bins which are the neighbors of the maximum
    // Normally neighbors which do not belong to the signal are empty!
    hist.GetXaxis()->SetRange(bx-1, bx+1); // 3x3bins  ~8x8pix  ~9x9sigma
    hist.GetYaxis()->SetRange(by-1, by+1); // 3x3bins  ~8x8pix  ~9x9sigma

    // Check whether this region contains events
    num = TMath::Nint(hist.Integral());
    if (num<1)
        return ZdAz();

    // Get Mean for the given axis range
    Double_t mx = hist.GetMean(1);
    Double_t my = hist.GetMean(2);

    const Int_t max1 = TMath::Nint(hist.GetBinContent(bx, by));

    // Check if the maximum is unique
    Int_t bx2, by2, bz2;
    hist.GetXaxis()->SetRange(-1, 9999);
    hist.GetYaxis()->SetRange(-1, 9999);
    hist.SetBinContent(bx, by, 0);
    hist.GetMaximumBin(bx2, by2, bz2);

    const Int_t max2 = TMath::Nint(hist.GetBinContent(bx2, by2));
    if (max1==max2 && TMath::Abs(bx2-bx)+TMath::Abs(by2-by)>1)
        return ZdAz();

    // loop again over the file and fill the histogram again.
    // to get closer to the correct value
    Double_t sumx = 0;
    Double_t sumy = 0;
             num  = 0;
    for (int i=0; i<mag.GetSize(); i++)
    {
        // only fill values into the histogram which
        // are inside 2*1.7=3.4 sigma (99.7%)
        if (TMath::Hypot(x[i]-mx, y[i]-my)>width*3.4)
            continue;

        sumx += x[i];
        sumy += y[i];
        num++;
    }

    if (num<1)
        return ZdAz();

    // calc MeanX and MeanY
    mx = sumx/num;
    my = sumy/num;

    // loop again to fill the mispointing corrected histograms
    // and fill another histogram to check the quality of the calculated
    // mispointing.
    sumx = 0;
    sumy = 0;
    num  = 0;
    for (int i=0; i<mag.GetSize(); i++)
    {
        // only fill values into the histogram which
        // are inside 1.7=3.4 sigma (92%)
        // Cut at 1.7 sigma which gives the best background supression
        if (TMath::Hypot(x[i]-mx, y[i]-my)>width*1.7)
            continue;

        sumx += x[i];
        sumy += y[i];
        num++;
    }

    if (num<1)
        return ZdAz(); // FIXME!!!!!!!!!!!!

    // Mispointing
    mx = sumx/num;
    my = sumy/num;

#ifdef EXPERT
    cout << "Offset-XY:    " << mx << " +- " << my << endl;
#endif

    AltAz pos0 = fSao->CalcAltAzFromPix(768/2,    576/2)*kRad2Deg;
    AltAz pos1 = fSao->CalcAltAzFromPix(768/2+mx, 576/2+my)*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());
}

Int_t MStarguider::CalcTrackingError(Leds &leds, MStarList &stars,
                                     ZdAz &d, MTime &t, double &bright, Int_t &num)
{
    num = leds.GetEntries();
    //cout << "Num: " << num << endl;
    if (num < 3) //was 1
    {
        gLog << warn << "Sorry, less than 3 detected spot in FOV!" << endl;
        if (fStargTPoint->IsDown())
            fStargTPoint->SetDown(kFALSE);
        return 0;
    }

    //cout << "Cat: " << stars.GetRealEntries() << endl;
    if (stars.GetRealEntries() < 3)
    {
        gLog << warn << "Sorry, less than 3 stars in FOV!" << endl;
        if (fStargTPoint->IsDown())
            fStargTPoint->SetDown(kFALSE);
        return 0;
    }

    stars.Sort(); // Sort by magnitude

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

    ofstream fout(str);
#endif

    TArrayF x, y, mag;

    // FIXME: Is predefined value 3 a good idea?
    Int_t cnt=0;

    MStar *star;
    MStarListIter NextStar(&stars);
    while ((star=NextStar()) && cnt<num+5)
    {
        TIter NextSp(&leds);
        Led *spot=NULL;
        while ((spot=(Led*)NextSp())) 
	{
            const XY dpos(spot->GetX()-(768-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(log(spot->GetMag())/star->GetMag(), idx);

#ifdef EXPERT
            if (fout)
            {
                fout << spot->GetX() << " "
                    << spot->GetY()  << " "
                    << -2.5*log(spot->GetMag())  << " "
                    << star->GetX() << " "
                    << star->GetY()  << " "
                    << star->GetMag()  << " ";
                fout << x[idx] << " " << y[idx] << " " << mag[idx] << endl;
            }
#endif
        }
        cnt++;
    }

    Int_t numcor = 0;
    d = TrackingError(x, y, mag, numcor);
    if (numcor<1)
        return 0;

    //cout << "Cor: " << numcor << endl;

    fDZdAz->SetCoordinates(d);

    //
    // Calculated offsets
    //

#ifdef EXPERT
    // 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;
#endif

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

    // Check StargTPoint data set request
    if (!fStargTPoint->IsDown())
        return numcor;
    fStargTPoint->SetDown(kFALSE);

    // If no file open: open new file
    if (!fOutStargTp)
    {
        // open tpoint file
        const TString name = MCosy::GetFileName("tpoint", "starg", "txt");
        gLog << all << "TPoint-Starg File ********* " << name << " ********** " << endl;

        fOutStargTp = new ofstream(name);
        *fOutStargTp << "Magic Model  STARGTPOINT data file" << endl;
        *fOutStargTp << ": ALTAZ" << endl;
        *fOutStargTp << "49 48 0 ";
        *fOutStargTp << t << endl;
    }

    // Get tracking coordinates
    const XY    xy = fCRaDec->GetCoordinates();
    const RaDec rd(xy.X()*TMath::DegToRad()*15, xy.Y()*TMath::DegToRad());

    // From the star position in the camera we calculate the Alt/Az
    // position we are currently tracking (real pointing position)
    fSao->SetMjd(t.GetMjd());
    AltAz za0 = fSao->CalcAltAz(rd)*kRad2Deg;

    //correction with offset from last tpoint measurement
    za0 -= fAltAzOffsetFromTp;
    MTime t2 = fTimeFromTp;

    //if the difference between the tpoint and the starguider tpoint
    //is too big, the starguider tpoint is not stored
    cout << "     mjd difference: " << t.GetMjd()-t2.GetMjd() << endl;
//        cout << "t: " << setprecision(11) << t.GetMjd() << endl;
//        cout << "t2: " << setprecision(11) << t2.GetMjd() << endl;
    if ((t.GetMjd()-t2.GetMjd())>0.001) //1min20sec
    {
        cout << "     time difference between tpoint and starguider-tpoint > 1 min *" <<
            t.GetMjd()-t2.GetMjd() << "s) " << endl;
        cout << "     => starguider tpoint hasn't been stored. " << endl;
        cout << "     Please repeat whole procedure. " << endl;
        return numcor;
    }


    // Write real pointing position
    cout << "     Alt/Az: " << za0.Alt() << "° " << za0.Az() << "°" << endl;
    *fOutStargTp << setprecision(7) << za0.Az() << " " << za0.Alt() << " ";

    // Write system pointing position
    cout << "     SE-Pos: " << 90-cpos.Zd() << "° " << cpos.Az() << "°" << endl;
    *fOutStargTp << fmod(cpos.Az()+360, 360) << " " << 90-cpos.Zd();

    *fOutStargTp << " " << xy.X() << " " << xy.Y();
    *fOutStargTp << " " << d.Zd() << " " << d.Az();
    *fOutStargTp << " " << setprecision(11) << t.GetMjd();
    *fOutStargTp << " " << num;
    *fOutStargTp << " " << bright;
    *fOutStargTp << endl;

    fTimeFromTp.Set(1970,1,1);

    return numcor;
}

XY MStarguider::FindRoqueLamp(FilterLed &f, FilterLed &f2, Ring &CameraCenter, MTime &t, Double_t cut, Int_t box, XY SearchCenter)
{
    // Set search Paremeters (FIXME: Get them from user input!)
    f.SetCut(cut);  // 3.5
    f.SetBox(box);  // 70

    // Try to find Led in this area
    Leds leds;
    f.FindStar(leds, (Int_t)SearchCenter.X(), (Int_t)SearchCenter.Y(), true);

    // Check whether star found
    Led *star = (Led*)leds.At(0);
    if (!star || leds.GetEntries()<1)
        return XY(.0,.0);

//    cout << "Found Roque Lamp @ " << flush;
    star->Print();
    f.MarkPoint(star->GetX(), star->GetY(), 500);

//    cout << "RoquePos: " << star->GetX() << "," << star->GetY() << endl;

    XY roquepos(star->GetX(), star->GetY());
    XY relroquepos(roquepos.X()-CameraCenter.GetX(), roquepos.Y()-CameraCenter.GetY());

    // If no file open: open new Roque Lamp file
    if (!fOutRq)
    {
        const TString name = MCosy::GetFileName("tpoint", "roquelamp", "txt");
        cout << "Starg_RoqueLamp File ********* " << name << " ********** " << endl;
        fOutRq = new ofstream(name);
        *fOutRq << "# Magic Roque Lamp file  " << t << endl;
    }

    return relroquepos;
}

ZdAz MStarguider::FindStar(FilterLed &f, FilterLed &f2, Ring &center, MTime &t, Double_t cut, Int_t box, Double_t scalefactor = 1.0)
{
    // Set search Paremeters (FIXME: Get them from user input!)
    f.SetCut(cut);  // 3.5
    f.SetBox(box);  // 70

    // Try to find Led in this area
    Leds leds;
    f.FindStar(leds, (Int_t)center.GetX(), (Int_t)center.GetY(), true);

    if (leds.GetEntries()<0)
        return ZdAz(0, 0);

    // Check whether star found
    Led *star = (Led*)leds.At(0);
    if (!star)
    {
        if (fTPoint->IsDown())
        {
            fTPoint->SetDown(kFALSE);
            gLog << warn << "No star found. Couldn't take a tpoint." << endl;
        }
        return ZdAz(.0,.0);
    }
    cout << "Found star @ " << flush;
    star->Print();
    f2.MarkPoint(star->GetX(), star->GetY(), 2<<2);

    // Initialize Star Catalog on th camera plane
    MGeomCamMagic geom;
    MAstroCamera ac;
    ac.SetGeom(geom);
    ac.SetRadiusFOV(3);
    ac.SetObservatory(*fSao);
    ac.SetTime(t);

    // Get tracking coordinates
    const XY    xy = fCRaDec->GetCoordinates();
    const RaDec rd(xy.X()*TMath::DegToRad()*15, xy.Y()*TMath::DegToRad());

    ac.SetRaDec(rd.Ra(), rd.Dec());

    // Adapt coordinate system (GUIs and humans are counting Y in different directions)
    Double_t x = star->GetX()-center.GetX();
    Double_t y = center.GetY()-star->GetY();

#ifdef EXPERT
    cout << "STAR-Offset: " << MTime(-1) << " dx=" << x << "pix  dy=" << y << "pix" << endl;
#endif

    // MAKE SURE THAT THIS VALUE CAN BE SETUP
    // (Scalefactor describes the difference between the tpoint (=1)
    //  and the starguider (!=1) camera
    // Convert from Pixel to millimeter (1pix=2.6mm)
    x *= (2.58427 * scalefactor);
    y *= (2.58427 * scalefactor);

    // Correct for abberation.
    x /= 1.0713;
    y /= 1.0713;

    // Convert offset from camera plane into local ccordinates
    Double_t dzd, daz;
    ac.GetDiffZdAz(x, y, dzd, daz);

#ifdef EXPERT
    cout << "STAR-Offset: " << MTime(-1) << " dZd=" << dzd << "d  dAz=" << daz << "d" << endl;
#endif

    ZdAz zdaz(dzd,daz);

    // Check TPoint data set request
    if (!fTPoint->IsDown())
        return zdaz;
    fTPoint->SetDown(kFALSE);

    // If no file open: open new file
    if (!fOutTp)
    {
        //
        // open tpoint file
        //
        const TString name = MCosy::GetFileName("tpoint", "tpoint", "txt");
        cout << "TPoint-Starg File ********* " << name << " ********** " << endl;

        fOutTp = new ofstream(name);
        *fOutTp << "Magic Model  TPOINT data file" << endl;
        *fOutTp << ": ALTAZ" << endl;
        *fOutTp << "49 48 0 ";
        *fOutTp << t << endl;
        // temp(°C) pressure(mB) height(m) humidity(1) wavelength(microm) troplapserate(K/m)
    }

    // Output Ra/Dec the drive system thinks that it is currently tracking
    cout << "TPoint Star: " << xy.X() << "h " << xy.Y() << "°" << endl;

    // From the star position in the camera we calculate the Alt/Az
    // position we are currently tracking (real pointing position)
    fSao->SetMjd(t.GetMjd());
    AltAz za0 = fSao->CalcAltAz(rd)*kRad2Deg;

    //ZdAz za0 = fSao->GetZdAz();
    za0 -= AltAz(-dzd, daz);
    fAltAzOffsetFromTp = AltAz(-dzd, daz);
    fTimeFromTp=t;


    // From the Shaftencoders we get the current 'pointing' position
    // as it is seen by the drive system (system pointing position)
    const ZdAz za1 = fCosy->GetTrackingPosRaw();

    // Write real pointing position
    cout << "     Alt/Az: " << za0.Alt() << "° " << za0.Az() << "°" << endl;
    *fOutTp << setprecision(7) << za0.Az() << " " << za0.Alt() << " ";

    // Write system pointing position
    cout << "     SE-Pos: " << 90-za1.Zd() << "° " << za1.Az() << "°" << endl;
    *fOutTp << fmod(za1.Az()+360, 360) << " " << 90-za1.Zd();

    *fOutTp << " " << xy.X() << " " << xy.Y();
    *fOutTp << " " << -dzd << " " << -daz;
    *fOutTp << " " << setprecision(11) << t.GetMjd();
    *fOutTp << " " << setprecision(4) << center.GetMag();
    *fOutTp << " " << star->GetMag();
    *fOutTp << endl;

    MLog &outrep = *fCosy->GetOutRep();
    if (outrep.Lock("MStarguider::FindStar"))
    {
        outrep << "FINDSTAR-REPORT 00 " << MTime(-1) << " " << setprecision(7);
        outrep << 90-za0.Alt() << " " << za0.Az() << " ";
        outrep << za1.Zd() << " " << za1.Az() << " ";
        outrep << xy.X() << " " << xy.Y() << " ";
        outrep << -dzd << " " << -daz << " ";
        outrep << star->GetX() << " " << star->GetY() << " ";
        outrep << center.GetX() << " " << center.GetY() << " ";
        outrep << x*1.0713/2.58427 << " " << y*1.0713/2.58427 << " " << star->GetMag();
        outrep << setprecision(11) << t.GetMjd() << endl;
        outrep.UnLock("MStarguider::FindStar");
    }
    
    return zdaz;
}

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;

    MTime t(*tm);

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

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

    byte cimg[768*576];
    memset(cimg, 0, 768*576);

    FilterLed f(img,   768, 576, 2.5); // 2.5
    FilterLed f2(cimg, 768, 576); // former color 0xb0

    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, fCRaDec->GetCoordinates());

        if (fFileType->IsEntryChecked(IDM_kPPM))
            Writer::Ppm("pix/file", img, tm, fCRaDec->GetCoordinates());
	
        if (fWriteType->IsEntryChecked(IDM_kOnce))
            ProcessMessage(MK_MSG(kC_COMMAND, kCM_MENU), IDM_kStop, 0);
    }

    // Visual Filter, whole FOV
    if (fDisplay->IsEntryChecked(IDM_kFilter))
        f.Execute();

    // Find Center of Camera for Caos and Tpoints
    Ring center(768/2, 576/2);
    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();
        center = fCaos->Run(img, printl, printr, pos, t, 19, 3.0);
	cout << "Caos Filter Camera center position: " << center.GetX() << " " << center.GetY() << endl;

    }

    // Find Star at Center---for Tpoint Procedure
    if (fDisplay->IsEntryChecked(IDM_kFindStar) &&
        center.GetX()>0 && center.GetY()>0)
    {
        // SCALE FACTOR ASSUMED TO BE 70
        FindStar(f, f2, center, t, 3/*3.5*/, 70);
        SendAmcTrigger("TPoint");
    }

    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 (fCosy)
    {
	byte simg[(768/2-1)*(576/2-1)];
	for (int y=0; y<576/2-1; y++)
	    for (int x=0; x<768/2-1; x++)
		simg[x+y*(768/2-1)] = ((unsigned int)img[2*x+2*y*768]+img[2*x+2*y*768+1]+img[2*x+2*(y+1)*768]+img[2*x+2*(y+1)*768+1])/4;	

	fCosy->GetWin()->GetImage()->DrawImg(simg);
    }

    // Find Center of Camera in Starfield Camera picture 

    Ring sgcenter(53.2, 293.6); // Center of camera in SG picture [px]
    //ZdAz sgcenterzdaz(0, 0);    // Center of camera in SG picture [deg]
    //                            // (0,0)_deg is at (53.2, 293.6)_px
    ZdAz star(0, 0);            // Star on curtain in [deg]

    if (fDisplay->IsEntryChecked(IDM_kStargCaosFilter))
    {
        ZdAz pos;
        if (fCosy)
            pos = fCosy->GetPointingPos();

        sgcenter = fStargCaos->Run(img, kFALSE, kFALSE, pos, t, 19, 3.0); // [px]

        //const Float_t pixsize = atof(fPixSize->GetText()); // [arcsec/px]

        // BE CAREFULL: This transformation is WRONG. It is just
        // a transformation of units, but this implies, that the
        // coordiante axis in both units look the same. This is
        // wrong exspecially near the zenith were az-lines are highly
        // curved around the zenith!
        //sgcenterzdaz.Zd((sgcenter.GetY()-293.6) * pixsize /3600 );
	//sgcenterzdaz.Az((sgcenter.GetX()-53.2)  * pixsize /3600 );
#ifdef EXPERT
	cout << "- LEDs imply offset of Zd=" 
	     << sgcenter.GetX()-53.2 << "pix Az=" 
	     << sgcenter.GetY()-293.6<< "pix" << endl; 	
#endif
        if (fDisplay->IsEntryChecked(IDM_kStargFindStar) &&
            sgcenter.GetX()>0 && sgcenter.GetY()>0)
        {
            star = FindStar(f, f2, sgcenter, t, 4.5, 30, 267/161.9); // [deg]
#ifdef EXPERT
            cout << "- Star is found to be off Zd=" << star.Zd()*60 << "' Az="
                << star.Az()*60 << "'" << endl;
#endif
            fSZdAz->SetCoordinates(star); // Mispointing found from Camera

            SendAmcTrigger("Starguider");
        }
    }

// Find Roque Lamp

    if (fOperations->IsEntryChecked(IDM_kRoqueLampAna))
    {

        Double_t imageclean = 1.5;
        Int_t    boxradius = 60;
	//Double_t scalefactor = 1;
	XY searchcenter(768/2-1,576/2+25);

	XY roquelamp = FindRoqueLamp(f, f2, sgcenter, t, imageclean, boxradius, searchcenter);

        if (fOutRq)
        {
            ZdAz pos = fCosy->GetPointingPos();

            *fOutRq << "RoqueLampDirect:    " << MTime(-1) << "  "
                << pos.Zd() << " " << pos.Az() << "   "
                << roquelamp.X() << " " << roquelamp.Y() << endl;
        }

        cout << "Starguider Camera Center: " << sgcenter.GetX() << "," << sgcenter.GetY() << endl;
	cout << ">=>=>=> Roque Lamp found at:         >=>=>=> (" << roquelamp.X() << "," 
	     << roquelamp.Y() << ") <=<=<=<" << endl;

    }

    // Find Spot on Camera Center in Starguider camera
    if (fOperations->IsEntryChecked(IDM_kRoqueLampAna))
    {
        XY cameraspot(0,0);

        Double_t imageclean = 5;
	Int_t    boxradius = 60;
	//Double_t scalefactor = 1;
	//	XY searchcenter(sgcenter.GetX(),sgcenter.GetY());
	XY searchcenter(60.,290.);

	cameraspot = FindRoqueLamp(f, f2, sgcenter, t, imageclean, boxradius, searchcenter);

        if (fOutRq)
        {
            ZdAz pos = fCosy->GetPointingPos();

            *fOutRq << "RoqueLampReflected: "  << MTime(-1) << "  "
                << pos.Zd() << " " << pos.Az() << "   "
                << cameraspot.X() << " " << cameraspot.Y() << endl;
        }

        cout << ">>>>> Spot on Magic camera found at: >>>>> (" << cameraspot.X() << ","
	     << cameraspot.Y() << ") <<<<<" << endl;

        f2.DrawCircle(sgcenter, 5.0, 0x0fa);
        f2.DrawCircle(sgcenter, 115.0, 0x0fa);
    }
    // we calculate the offset given by the three ETH Leds visible to
    // the guide camera
    // This is an (inferior, obsolete) alternative to the StarCaosFilter
    // Led offset;
    // if (fDisplay->IsEntryChecked(IDM_kStargLEDFilter))	
    //	fStargLeds->Run(img,offset);

    // Position corresponding to the camera center (53.2, 293.6)
    //Ring skycenter(392, 318);
    // MStarList spots;

    // we obtain a list of stars in the FOV from the SAO catalog
    if (fDisplay->IsEntryChecked(IDM_kCatalog))
    {
        MTime time(*tm);

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

	UpdatePosZoom();

	// Always call SetMjd first!
        fSao->SetPointing(time.GetMjd(), *fRaDec);
  	fCZdAz->SetCoordinates(fSao->GetZdAz());

  	MStarList stars;
    	fSao->SetBox(230); // Region of interest around center

        // very careful: If center of camera cannot be determined
	// sgcenter jumps to (0,0)  

        //Please never change this offsets!!!
        // 53.2 and 293.6 are the "preliminary" camera center
        // -9 and 28.5 are the offsets of the pointing position in the sky

        const Bool_t centerisvalid = sgcenter.GetX()>0 && sgcenter.GetY()>0;
//        if (centerisvalid)
//            skycenter.SetXY(sgcenter.GetX() -  53.2,
//                            sgcenter.GetY() - 293.6);

    	// we obtain stars in the effective star FOV and draw them.
    	// coordinates are video frame coords.
	// We determine the ideal starfield using camera sagging info
        // from the LEDs
        const XY off(sgcenter.GetX()- 53.2-9,
                     sgcenter.GetY()-293.6+28.5);

        fSao->CalcStars(stars, 530, 292, TMath::FloorNint(off.X()), TMath::FloorNint(off.Y()));
	fSao->DrawStars(stars, cimg);

        // Position around which the circles are drawn.
        const Ring skycenter(768/2-off.X(), 576/2+off.Y());

	// There are two corrections to the mispointing
	// - Sagging of the camera as measured with the LEDs
	// - Star not ideally centered on MAGIC Camera

	// Next we evaluate the offset given by the LEDs. This we obtain
        // in Zd/Az and add it to the tracking error.
	if (fDisplay->IsEntryChecked(IDM_kStarguider))
        {
            const Float_t cut = atof(fCut->GetText());

  	    Leds spots;
  	    f.SetBox(230);
	    f.SetCut(cut);

            double bright;
  	    f.ExecuteAndMark(spots, 530, 292, bright);

            ULong_t color;
	    gClient->GetColorByName("Green", color);
            if (bright> 60)
                gClient->GetColorByName("Yellow", color);
            if (bright> 85)
                gClient->GetColorByName("Orange", color);
            if (bright> 95)
                gClient->GetColorByName("Red", color);
            fSkyBright->SetBackgroundColor(color);

            MString txt;
 	    txt.Print("Sky Brightness: %.1f", bright);
 	    fSkyBright->SetText(txt);

            const Bool_t brightnessisvalid = bright<1.75*fLastBright &&
                bright>30 && bright<110;

            fLastBright = bright;

            Int_t numstars = 0;
            const Int_t rc = CalcTrackingError(spots, stars, fD, t, bright, numstars);

            const Bool_t monitoring = brightnessisvalid && centerisvalid && fNumStarsCorrelated>2;

            fStatus = monitoring ? MDriveCom::kMonitoring : MDriveCom::kError;

            if (fCosy)
                fPos = fCosy->GetPointingPos();

            if (fOperations->IsEntryChecked(IDM_kStargAnalysis))
                fStargHistograms->Fill(spots, stars, fD,
                                       fSao->GetZdAz(), sgcenter, /*sgcenterzdaz,*/
                                       star, bright, fPos, t);

            fNumStarsDetected   = numstars;
            fNumStarsCorrelated = rc;

            if (fCosy)
            {
                MDriveCom *com = fCosy->GetDriveCom();
                if (com)
                    com->SendStargReport(fStatus, fD, fSao->GetZdAz(),
                                         sgcenter, numstars, rc, bright,
                                         time.GetMjd(), 0, 0);    // Report
            }

        } //kStarguider

        if (centerisvalid && fNumStarsCorrelated>2)
        {
            f2.DrawCircle(skycenter,   2.0,     0x0a);

            const Double_t ap = fSao->GetPixSize()/3600; //[deg/pix]

            f2.DrawCircle(skycenter,  0.10/ap, 0x0a); //0.1deg
            f2.DrawHexagon(skycenter, 2.06/ap, 0x0a);
            f2.DrawHexagon(skycenter, 3.50/ap, 0x0a);
        }

    } //CalcStars

    // Draw Circles around center of Camera
    if (fDisplay->IsEntryChecked(IDM_kCaosFilter) &&
        center.GetX()>0 && center.GetY()>0)
    {
        f2.DrawCircle(center, 0x0a);
        f2.DrawCircle(center,   7.0,
		      fDisplay->IsEntryChecked(IDM_kFindStar)?3:0xb0);
        f2.DrawCircle(center, 115.0, 0x0a);
        f2.DrawCircle(center, 230.0, 0x0a);
        f2.DrawCircle(center, 245.0, 0x0a);
    }

    if (fDisplay->IsEntryChecked(IDM_kStargCaosFilter) &&
        sgcenter.GetX()>0 && sgcenter.GetY()>0)
    {
        f2.DrawCircle(sgcenter, 0x0a);
        f2.DrawCircle(sgcenter,   5.0,
                      fDisplay->IsEntryChecked(IDM_kFindStar)?3:0xb0);
    }

    if (fDisplay->IsEntryChecked(IDM_kCaosFilter) ||
        fDisplay->IsEntryChecked(IDM_kCatalog)    ||
        fDisplay->IsEntryChecked(IDM_kFindStar)   ||
        fOperations->IsEntryChecked(IDM_kRoqueLampAna))
        fImage->DrawColImg(img, cimg);
    else
        fImage->DrawImg(img);
}

void MStarguider::UpdatePosZoom()
{
    MString txt;
    if (fDisplay->IsEntryChecked(IDM_kCatalog))
    {
        // FIXME: Necessary?
        fSao->Now();
        AltAz aa = fSao->CalcAltAzFromPix(fDx, fDy)*kRad2Deg;
        if (aa.Az()<0)
            aa.Az(aa.Az()+360);
        txt.Print("(%d, %d) %.1fd/%.1fd", fDx, fDy, -aa.Alt(), aa.Az()-180);
    }
    else
        txt.Print("(%d, %d)", fDx, fDy);
    fPosZoom->SetText(txt);
}

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;
}

void MStarguider::Print(TString &str, Double_t deg) const
{
    Char_t sgn;
    UShort_t d, m, s;

    MAstro::Deg2Dms(deg, sgn, d, m, s);

    MString txt;
    str += txt.Print("%c %03d %02d %03d ", sgn, d, m, s);
}
