Index: trunk/MagicSoft/Cosy/Changelog
===================================================================
--- trunk/MagicSoft/Cosy/Changelog	(revision 4104)
+++ trunk/MagicSoft/Cosy/Changelog	(revision 4105)
@@ -1,3 +1,113 @@
                                                                   -*-*- END -*-*-
+ 2004/05/15 - Thomas Bretz (La Palma)
+
+   * Makefile:
+     - added MGMenu links
+
+   * bending_magic.txt:
+     - last calculated pointing model (stil has the hysteresis 
+       problem)
+
+   * cosy.cc:
+     - moved camera stuff to MStarguider
+     - added channel selection
+
+   * base/BaseLinkDef.h:
+     - updated
+
+   * base/MString.[h,cc]:
+     - removed (now in Mars)
+
+   * base/MThread.h, candrv/network.h, candrv/nodedrv.h,
+     candrv/vmodican.h, devdrv/macs.h, videodev/Camera.h:
+     - changed ifndef
+
+   * base/Makefile:
+     - updated
+
+   * candrv/nodedrv.cc:
+     - added cast to MTime
+
+   * candrv/vmodican.cc:
+     - changed priority from 10 to 1
+
+   * caos/Led.cc, caos/Ring.cc:
+     - changed Form to MString
+
+   * caos/Makefile:
+     - added include base
+
+   * caos/Ring.[h,cc]:
+     - added arguments to constructor
+
+   * catalog/CatalogLinkDef.h, catalog/Makefile:
+     - removed SaoFile
+
+   * catalog/Slalib.cc:
+     - removed some obsolete code
+
+   * catalog/StarCatalog.cc:
+     - added a size check for the bitmap
+
+   * devdrv/macs.cc:
+     - no guarding for the moment
+
+   * devdrv/shaftencoder.[h,cc]:
+     - added code to communicate with the Macs
+
+   * gui/GuiLinkDef.h, gui/Makefile:
+     - removed MGVelocity
+
+   * gui/MGCosy.[h,cc]:
+     - added weather data to display
+     - added image of the camera to window
+     - removed velocity from window
+     - replaced Form by MString
+
+   * main/MBending.cc:
+     - changed handling in GetAnAw - Hopefully correct???
+       the old handling gave problems
+
+   * main/MCosy.[h,cc]:
+     - added SetTrackingPosRE
+     - display interpolated position when tracking
+     - added SetMotor calls
+
+   * main/MStarguider.[h,cc]:
+     - added code to find star in the display
+     - added corresponding menus
+     - added code to support more than one ccd channel
+
+   * main/MTracking.[h,cc]:  
+     - complete change to the algorithm. The position which is 
+       send to CC need still some investigations. For more information
+       look at the code. The main difference is that the motor
+       encoders are taken better into account which fixes the SE 
+       handling on the elevation axis 
+
+   * main/MainLinkDef.h, main/Makefile:
+     - added MPointing
+     - added MTracking
+     
+   * tcpip/MCeCoCom.[h,cc]:  
+     - added alarm counter
+
+   * tcpip/MTcpIpIO.cc:
+     - do not write to output file if stream is locked
+
+   * tpoint/gui.C:
+     - fixed display so that it perfectly shows north, east, ...
+     - added error for residual
+     - simplified residual algorithm
+     - read new files
+     - changed displaying deviations a bit
+     - display result in the display (preliminary)
+     - set gIgnoreLevel to suppress strange color warnings
+
+   * videodev/FilterLed.cc:
+     - use MGMap for drawing...
+
+
+
  2004/05/15 - Thomas Bretz (La Palma)
 
Index: trunk/MagicSoft/Cosy/Makefile
===================================================================
--- trunk/MagicSoft/Cosy/Makefile	(revision 4104)
+++ trunk/MagicSoft/Cosy/Makefile	(revision 4105)
@@ -143,4 +143,6 @@
 	@ln -sf ../../Mars/mbase/MGMap.h  base/MGMap.h
 	@ln -sf ../../Mars/mbase/MGMap.cc base/MGMap.cc
+	@ln -sf ../../Mars/mbase/MGMenu.h  base/MGMenu.h
+	@ln -sf ../../Mars/mbase/MGMenu.cc base/MGMenu.cc
 	@ln -sf ../../Mars/mgeom/MGeomMirror.h  base/MGeomMirror.h
 	@ln -sf ../../Mars/mgeom/MGeomMirror.cc  base/MGeomMirror.cc
Index: trunk/MagicSoft/Cosy/base/BaseLinkDef.h
===================================================================
--- trunk/MagicSoft/Cosy/base/BaseLinkDef.h	(revision 4104)
+++ trunk/MagicSoft/Cosy/base/BaseLinkDef.h	(revision 4105)
@@ -8,8 +8,27 @@
 #pragma link C++ class MLog;
 #pragma link C++ class MStar+;
+#pragma link C++ class MGMap+;
 #pragma link C++ class MGList+;
 #pragma link C++ class MParContainer+;
+
 #pragma link C++ class MObservatory+;
+#pragma link C++ class MVector3+;
+
+#pragma link C++ class MString+;
 #pragma link C++ class MAstro+;
+#pragma link C++ class MAstroSky2Local+;
+#pragma link C++ class MAstroCatalog+;
+#pragma link C++ class MAstroCamera+;
+
+#pragma link C++ class MGeomPix+;
+#pragma link C++ class MGeomCam+;
+#pragma link C++ class MGeomCamMagic+;
+#pragma link C++ class MGeomMirror+;
+
+#pragma link C++ class MHCamera+;
+#pragma link C++ class MH+;
+#pragma link C++ class MBinning+;
+#pragma link C++ class MCamEvent+;
+#pragma link C++ class MHexagon+;
 
 #pragma link C++ class MTime+;
Index: trunk/MagicSoft/Cosy/base/MString.cc
===================================================================
--- trunk/MagicSoft/Cosy/base/MString.cc	(revision 4104)
+++ 	(revision )
@@ -1,4 +1,0 @@
-#include "MString.h"
-
-ClassImp(MString);
-
Index: trunk/MagicSoft/Cosy/base/MString.h
===================================================================
--- trunk/MagicSoft/Cosy/base/MString.h	(revision 4104)
+++ 	(revision )
@@ -1,45 +1,0 @@
-#ifndef MARS_MString
-#define MARS_MString
-
-#ifndef ROOT_TString
-#include <TString.h>
-#endif
-
-#include <stdio.h>
-#include <stdarg.h>
-
-class MString : public TString
-{
-public:
-    MString &Print(const char *fmt, ...)
-    {
-        va_list ap;
-        va_start(ap, fmt);
-
-        Int_t n=256;
-
-        char *ret=0;
-
-        while (1)
-        {
-            ret = new char[n+1];
-            Int_t sz = vsnprintf(ret, n, fmt, ap);
-            if (sz<=n)
-                break;
-
-            n *= 2;
-            delete [] ret;
-        };
-
-        va_end(ap);
-
-        *static_cast<TString*>(this) = ret;
-
-        delete [] ret;
-
-        return *this;
-    }
-    ClassDef(MString, 1)
-};
-
-#endif
Index: trunk/MagicSoft/Cosy/base/MThread.h
===================================================================
--- trunk/MagicSoft/Cosy/base/MThread.h	(revision 4104)
+++ trunk/MagicSoft/Cosy/base/MThread.h	(revision 4105)
@@ -1,4 +1,4 @@
-#ifndef MTHREAD_H
-#define MTHREAD_H
+#ifndef COSY_MThread
+#define COSY_MThread
 
 #ifdef __CINT__
Index: trunk/MagicSoft/Cosy/base/Makefile
===================================================================
--- trunk/MagicSoft/Cosy/base/Makefile	(revision 4104)
+++ trunk/MagicSoft/Cosy/base/Makefile	(revision 4105)
@@ -31,13 +31,27 @@
 .SUFFIXES: .c .cc .cxx .h .hxx .o 
 
-SRCFILES = File.cc \
-	   MStopwatch.cc \
+SRCFILES = MStopwatch.cc \
            MParContainer.cc \
            MThread.cc \
 	   MTimeout.cc \
            MTime.cc \
-           MAstro.cc \
+           MString.cc \
 	   MStar.cc \
 	   MStarList.cc \
+           MAstro.cc \
+           MAstroCatalog.cc \
+           MAstroCamera.cc \
+           MAstroSky2Local.cc \
+           MGeomMirror.cc \
+           MGeomPix.cc \
+           MGeomCam.cc \
+           MGeomCamMagic.cc \
+           MGMap.cc \
+           MGMenu.cc \
+           MH.cc \
+           MBinning.cc \
+           MHexagon.cc \
+           MCamEvent.cc \
+           MHCamera.cc \
            msgqueue.cc \
            MLog.cc \
@@ -49,5 +63,20 @@
 	      MGList.h \
               MTime.h \
+              MString.h \
               MAstro.h \
+              MAstroSky2Local.h \
+              MAstroCatalog.h \
+              MAstroCamera.h \
+	      MGeomMirror.h \
+	      MGeomPix.h \
+	      MGeomCam.h \
+              MGeomCamMagic.h \
+ 	      MHCamera.h \
+              MBinning.h \
+              MH.h \
+              MGMap.h \
+              MGMenu.h \
+              MHexagon.h \
+              MCamEvent.h \
 	      MLog.h \
 	      MLogManip.h \
Index: trunk/MagicSoft/Cosy/bending_magic.txt
===================================================================
--- trunk/MagicSoft/Cosy/bending_magic.txt	(revision 4104)
+++ trunk/MagicSoft/Cosy/bending_magic.txt	(revision 4105)
@@ -1,17 +1,17 @@
-MAGIC1 2003/12/29 19:15:38.433
+MAGIC1 15.05.2004 23:25:21.338
 S   00   000000   000000  0000000
-     IA     502.52368   0.034356796
-     IE    -9.0564239   0.019895878
+     IA     502.51471   0.0072972921
+     IE    -9.0539559   0.0050128431
    FLOP             0             0
      AN             0             0
-     AW             0             0
-   NPAE   0.077561439   0.038824444
+     AW  -0.066794332   0.005947689
+   NPAE             0             0
      CA             0             0
      TF             0             0
      TX             0             0
    ECES             0             0
-   ACES             0             0
+   ACES  -0.021708338   0.0089723026
    ECEC             0             0
-   ACEC             0             0
+   ACEC  -0.072368751   0.011236351
     NRX             0             0
     NRY             0             0
Index: trunk/MagicSoft/Cosy/candrv/network.h
===================================================================
--- trunk/MagicSoft/Cosy/candrv/network.h	(revision 4104)
+++ trunk/MagicSoft/Cosy/candrv/network.h	(revision 4105)
@@ -1,7 +1,11 @@
-#ifndef NETWORK_H
-#define NETWORK_H
+#ifndef COSY_Network
+#define COSY_Network
 
+#ifndef COSY_CanOpen
 #include "canopen.h"
+#endif
+#ifndef COSY_NodeDrv
 #include "nodedrv.h"
+#endif
 
 class Network : public CanOpen
Index: trunk/MagicSoft/Cosy/candrv/nodedrv.cc
===================================================================
--- trunk/MagicSoft/Cosy/candrv/nodedrv.cc	(revision 4104)
+++ trunk/MagicSoft/Cosy/candrv/nodedrv.cc	(revision 4105)
@@ -48,5 +48,5 @@
 #include <iostream.h>
 
-#include <TTimer.h>
+//#include <TTimer.h>
 
 #include "MTime.h"
@@ -530,5 +530,5 @@
             const Double_t t0 = t+fGuardTime;
 
-            while (!HasStopFlag() && t<t0 && t<fTimeoutTime)
+            while (!HasStopFlag() && (double)t<t0 && (double)t<fTimeoutTime)
             {
                 usleep(5);
@@ -540,5 +540,5 @@
             //cout << "-g-> " << (Long_t)((t-t0)*1000)<< endl;
 
-            if (t<fTimeoutTime)
+            if ((double)t<fTimeoutTime)
                 continue;
 
Index: trunk/MagicSoft/Cosy/candrv/nodedrv.h
===================================================================
--- trunk/MagicSoft/Cosy/candrv/nodedrv.h	(revision 4104)
+++ trunk/MagicSoft/Cosy/candrv/nodedrv.h	(revision 4105)
@@ -1,8 +1,12 @@
-#ifndef NODEDRV_H
-#define NODEDRV_H
+#ifndef COSY_NodeDrv
+#define COSY_NodeDrv
 
+#ifndef ROOT_TString
 #include <TString.h>
+#endif
 
+#ifndef COSY_Log
 #include "log.h"
+#endif
 
 #ifdef __CINT__
Index: trunk/MagicSoft/Cosy/candrv/vmodican.cc
===================================================================
--- trunk/MagicSoft/Cosy/candrv/vmodican.cc	(revision 4104)
+++ trunk/MagicSoft/Cosy/candrv/vmodican.cc	(revision 4105)
@@ -934,5 +934,5 @@
 //  and switch the can bus communication on
 //
-VmodIcan::VmodIcan(const char *dev, const int baud, MLog &out) : Log(out), MThread(false, 10)//: CanDriver(dev, baud)
+VmodIcan::VmodIcan(const char *dev, const int baud, MLog &out) : Log(out), MThread(false, 1)//: CanDriver(dev, baud)
 {
     //
Index: trunk/MagicSoft/Cosy/candrv/vmodican.h
===================================================================
--- trunk/MagicSoft/Cosy/candrv/vmodican.h	(revision 4104)
+++ trunk/MagicSoft/Cosy/candrv/vmodican.h	(revision 4105)
@@ -1,4 +1,4 @@
-#ifndef VMODICAN_H
-#define VMODICAN_H
+#ifndef COSY_VmodIcan
+#define COSY_VmodIcan
 
 #include <pthread.h>
@@ -16,5 +16,7 @@
 #endif
 
+#ifndef COSY_MThread
 #include "MThread.h"
+#endif
 
 class Message;
Index: trunk/MagicSoft/Cosy/cosy.cc
===================================================================
--- trunk/MagicSoft/Cosy/cosy.cc	(revision 4104)
+++ trunk/MagicSoft/Cosy/cosy.cc	(revision 4105)
@@ -13,5 +13,4 @@
 
 #define EXPERT
-#define HAVE_CAMERA
 
 #define clog(txt) \
@@ -42,4 +41,6 @@
         if (arg=="-0")
             channel = 0;
+        if (arg=="-c")
+            channel = -1;
     }
 
@@ -96,11 +97,13 @@
     cosy->Start();
 
-    clog("- Starting Camera.");
-#ifdef HAVE_CAMERA
-    MStarguider *client=new MStarguider(MObservatory::kMagic1, channel);
+    MStarguider *client=0;
+    if (channel>=0)
+    {
+        clog("- Starting Camera.");
+        client=new MStarguider(MObservatory::kMagic1, channel);
+        cosy->SetStarguider(client);
+        client->SetCosy(cosy);
+    }
 
-    cosy->SetStarguider(client);
-    client->SetCosy(cosy);
-#endif
     clog("- Starting mainloop.");
 #ifndef EXPERT
@@ -108,11 +111,13 @@
 #endif
     app->Run(kTRUE);
-#ifdef HAVE_CAMERA
-    client->SetCosy(NULL);
-    cosy->SetStarguider(NULL);
 
-    clog("- Stopping starg.");
-    delete client;
-#endif
+    if (channel>=0)
+    {
+        client->SetCosy(NULL);
+        cosy->SetStarguider(NULL);
+        clog("- Stopping starg.");
+        delete client;
+    }
+
     clog("- Stopping cosy.");
     cosy->Stop();
Index: trunk/MagicSoft/Cosy/main/MBending.cc
===================================================================
--- trunk/MagicSoft/Cosy/main/MBending.cc	(revision 4104)
+++ trunk/MagicSoft/Cosy/main/MBending.cc	(revision 4105)
@@ -317,29 +317,93 @@
 
     // Vector in cartesian coordinates
-    TVector3 v(1., 1., 1.); 
+    TVector3 v1;
 
     // Set Azimuth and Elevation
-    v.SetPhi(p.Az());
-    v.SetTheta(TMath::Pi()/2-p.Alt());
+    v1.SetMagThetaPhi(1, TMath::Pi()/2-p.Alt(), p.Az());
+
+
+    TVector3 v2(v1);
+//    cout << sign << endl;
+
+//    cout << "v1: " << v1.Theta()*TMath::RadToDeg() << " " << v1.Phi()*TMath::RadToDeg() << endl;
 
     // Rotate around the x- and y-axis
-    v.RotateY(sign*fAn);
-    v.RotateX(sign*fAw);
+    v1.RotateY(sign*fAn);
+    v1.RotateX(sign*fAw);
+
+//    cout << "v1: " << v1.Theta()*TMath::RadToDeg() << " " << v1.Phi()*TMath::RadToDeg() << endl;
+//    cout << "v2: " << v2.Theta()*TMath::RadToDeg() << " " << v2.Theta()*TMath::RadToDeg() << endl;
+
+   // cout << "dv: " << (v2.Theta()-v1.Theta())*TMath::RadToDeg() << " " << (v2.Phi()-v1.Phi())*TMath::RadToDeg() << endl;
+
+    Double_t dalt = v1.Theta()-v2.Theta();
+    Double_t daz  = v1.Phi()  -v2.Phi();
+
+    //cout << dalt*TMath::RadToDeg() << " " << daz*TMath::RadToDeg() << endl;
+
+    if (daz>TMath::Pi())
+        daz -= TMath::TwoPi();
+    if (daz<-TMath::Pi())
+        daz += TMath::TwoPi();
+
+//    if (daz>TMath::Pi()/2)
+//    {
+//    }
+
+    AltAz d(dalt, daz);
+    return d;
 
     // Calculate Delta Azimuth and Delta Elevation
-    AltAz d(TMath::Pi()/2-v.Theta(), v.Phi());
+    /*
+    AltAz d(TMath::Pi()/2-v1.Theta(), v1.Phi());
+
+    cout << "p :  " << p.Alt()*TMath::RadToDeg() << " " << p.Az()*TMath::RadToDeg() << endl;
+    cout << "d :  " << d.Alt()*TMath::RadToDeg() << " " << d.Az()*TMath::RadToDeg() << endl;
     d -= p;
+    cout << "d-p: " << d.Alt()*TMath::RadToDeg() << " " << d.Az()*TMath::RadToDeg() << endl;
     d *= sign;
-
+    cout << "d* : " << d.Alt()*TMath::RadToDeg() << " " << d.Az()*TMath::RadToDeg() << endl;
+
+
+    cout << "p2:  " << 90-p.Alt()*TMath::RadToDeg() << " " << p.Az()*TMath::RadToDeg() << endl;
+    cout << "d2:  " << 90-d.Alt()*TMath::RadToDeg() << " " << d.Az()*TMath::RadToDeg() << endl;
+
+    Int_t s1 = 90-d.Alt()*TMath::RadToDeg() < 0 ? -1 : 1;
+    Int_t s2 = 90-p.Alt()*TMath::RadToDeg() < 0 ? -1 : 1;
+
+
+    if (s1 != s2)
+    {
+        //90-d.Alt() <-- -90+d.Alt()
+
+        d.Alt(d.Alt()-TMath::Pi());
+        cout << "Alt-" << endl;
+    }
+    cout << "d': " << 90-d.Alt()*TMath::RadToDeg() << " " << d.Az()*TMath::RadToDeg() << endl;
+ /*
     // Fix 'direction' of output depending on input vector
-    if (sign*p.Alt()>TMath::Pi()/2)
+    if (TMath::Pi()/2-sign*p.Alt()<0)
+    {
         d.Alt(d.Alt()-TMath::Pi());
+        cout << "Alt-" << endl;
+    }
+    //if (TMath::Pi()/2-sign*p.Alt()>TMath::Pi())
+    //{
+    //    d.Alt(TMath::Pi()-d.Alt());
+    //    cout << "Alt+" << endl;
+    //}
 
     // Align correction into [-180,180]
     while (d.Az()>TMath::Pi())
+    {
         d.Az(d.Az()-TMath::Pi()*2);
+        cout << "Az-" << endl;
+    }
     while (d.Az()<-TMath::Pi())
+    {
         d.Az(d.Az()+TMath::Pi()*2);
-
+        cout << "Az+" << endl;
+    }
+   */
     return d;
 }
@@ -426,4 +490,7 @@
     p += FLOP;
 
+    //const AltAz MAGIC1(fMagic1*sin(p.Az()), 0);
+    //p += MAGIC1;
+
     const AltAz I(fIe, fIa);
     p += I;
@@ -445,4 +512,7 @@
     const AltAz I(fIe, fIa);
     p -= I;
+
+    //const AltAz MAGIC1(fMagic1*sin(p.Az()), 0);
+    //p -= MAGIC1;
 
     const AltAz FLOP(Sign(fFlop, p.Alt()), 0);
Index: trunk/MagicSoft/Cosy/main/MCaos.cc
===================================================================
--- trunk/MagicSoft/Cosy/main/MCaos.cc	(revision 4104)
+++ trunk/MagicSoft/Cosy/main/MCaos.cc	(revision 4105)
@@ -167,12 +167,12 @@
     fHistallw->SetNameTitle("allw","Rotation angel");
     fHistallw->SetBins(26, -25, 25);
-    fHistallw->SetXTitle("\\Phi [arcmin]");
+    fHistallw->SetXTitle("\\phi [arcmin]");
     fHistallw->SetYTitle("counts");
 
     fHistprxpry = new TH2F;
-    fHistprxpry->SetNameTitle("prx und pry","x- and y-coordniate of the ring-center");
+    fHistprxpry->SetNameTitle("prx und pry","x- and y-coordinate of the ring-center");
     fHistprxpry->SetBins(xbin, xmin, xmax, ybin, ymin, ymax);
-    fHistprxpry->SetXTitle("x [mm]");
-    fHistprxpry->SetYTitle("y [mm]");
+    fHistprxpry->SetXTitle("x [pix]");
+    fHistprxpry->SetYTitle("y [pix]");
     fHistprxpry->SetZTitle("counts");
 
@@ -183,13 +183,6 @@
     fGraphpry->SetTitle("time-developement of the y-coordinate of the ring-center");
 
-    fGraphw = new TGraph*[fPositions.GetEntriesFast()];
-    for (int i=0; i<fPositions.GetEntriesFast(); i++)
-    {
-        TString title = "Time-developement of the angle ";
-        title += i;
-
-        fGraphw[i] = new TGraph;
-        fGraphw[i]->SetTitle(title);
-    }
+    fGraphw = new TGraph;
+    fGraphw->SetTitle("Time-developement of rotation angle");
 
     fHistpr = new TH1F("pr","Radius of the ring", rbin, rmin, rmax);
@@ -211,4 +204,5 @@
     delete fGraphprx;
     delete fGraphpry;
+    delete fGraphr;
 
     for (int i=0; i<6; i++)
@@ -216,5 +210,5 @@
         delete fHistled[i];
         delete fHistw[i];
-        delete fGraphw[i];
+        delete fGraphw;
     }
     delete fHistled;
@@ -265,6 +259,6 @@
     c2->Update();
 
-    c = new TCanvas("ctime", "timedevelopement of center", 800, 800);
-    c->Divide(1,2);
+    c = new TCanvas("ctime", "Timedevelopement of Center", 800, 800);
+    c->Divide(1,3);
     c->cd(1);
     h = fGraphprx->GetHistogram();
@@ -272,5 +266,6 @@
     h->SetYTitle("x [pix]");
     h->DrawCopy();
-    //fGraphprx->DrawClone("LP*")->SetBit(kCanDelete);
+    ((TPad*)gPad)->SetSelected(NULL);
+    fGraphprx->DrawClone("ALP*")->SetBit(kCanDelete);
     c->cd(2);
     h = fGraphpry->GetHistogram();
@@ -278,7 +273,30 @@
     h->SetYTitle("y [pix]");
     h->DrawCopy();
-    //fGraphpry->DrawClone("LP*")->SetBit(kCanDelete);
+    ((TPad*)gPad)->SetSelected(NULL);
+    fGraphpry->DrawClone("ALP*")->SetBit(kCanDelete);
+    c->cd(3);
+    h = fGraphr->GetHistogram();
+    h->SetXTitle("time [s]");
+    h->SetYTitle("r [pix]");
+    h->DrawCopy();
+    ((TPad*)gPad)->SetSelected(NULL);
+    fGraphr->DrawClone("ALP*")->SetBit(kCanDelete);
     c->Modified();
     c->Update();
+
+    c = new TCanvas("crot", "rotation angle", 800, 600);
+    c->Divide(2,1);
+    c->cd(1);
+    fHistallw->SetXTitle("\\phi [arcmin]");
+    fHistallw->SetYTitle("counts");
+    fHistallw->DrawCopy();
+    c->cd(2);
+    h = fGraphw->GetHistogram();
+    h->SetXTitle("time [s]");
+    h->SetYTitle("\\phi [arcmin]");
+    h->DrawCopy();
+    ((TPad*)gPad)->SetSelected(NULL);
+    fGraphw->DrawClone("ALP*")->SetBit(kCanDelete);
+
 
     /* --------------------------------------------------------
@@ -333,4 +351,6 @@
             f.MarkPoint(l1.GetX(), l1.GetY(), l1.GetMag());
 
+            //old
+            /*
             // Fill values into Histogram
             if (!fHistpr)
@@ -339,4 +359,5 @@
             fHistled[i]->Fill(l1.GetX(), l1.GetY());
             fHistw[i]->Fill(l1.GetPhi());
+            */
         }
         first = leds.GetEntries();
@@ -344,5 +365,5 @@
 
     Rings rings;
-    rings.CalcRings(leds, 266, 268);
+    rings.CalcRings(leds, 265, 268);
 
     const Ring &center = rings.GetCenter();
@@ -358,4 +379,34 @@
         fGraphprx->SetPoint(fGraphprx->GetN(), fEvtTime, center.GetX());
         fGraphpry->SetPoint(fGraphpry->GetN(), fEvtTime, center.GetY());
+
+        //new
+        //-----
+        Double_t sum = 0;
+        for (int j=0; j<leds.GetEntries(); j++)
+        {
+            Led &l1 = leds(j);
+
+            fHistled[j]->Fill(l1.GetX(), l1.GetY());
+            //fHistw[j]->Fill(l1.GetPhi());
+
+            Double_t phi[6] =
+            {
+                0,
+                0,
+                0,
+                0,
+                0,
+                0
+            };
+
+            const Double_t w = (leds(j).GetPhi()-phi[j])*60;
+            sum += w;
+
+            fHistw[j]->Fill(w);
+            sum /= leds.GetEntries();
+        }
+        fGraphw->SetPoint(fGraphw->GetN(), fEvtTime, sum);
+        fHistallw->Fill(sum/leds.GetEntries());
+        //-----
     }
 
Index: trunk/MagicSoft/Cosy/main/MCaos.h
===================================================================
--- trunk/MagicSoft/Cosy/main/MCaos.h	(revision 4104)
+++ trunk/MagicSoft/Cosy/main/MCaos.h	(revision 4105)
@@ -42,5 +42,6 @@
     TGraph        *fGraphprx;
     TGraph        *fGraphpry;
-    TGraph       **fGraphw;
+    TGraph        *fGraphw;
+    TGraph        *fGraphr;
 
 public:
Index: trunk/MagicSoft/Cosy/main/MCosy.cc
===================================================================
--- trunk/MagicSoft/Cosy/main/MCosy.cc	(revision 4104)
+++ trunk/MagicSoft/Cosy/main/MCosy.cc	(revision 4105)
@@ -402,4 +402,13 @@
 
     return point.SetPosition(dst, track);
+}
+
+void MCosy::SetTrackingPosRE(ZdAz za)
+{
+    za /= kGearTot;                        // [U_tel]
+    za *= TMath::TwoPi();                  // [rad]
+    //cout << "RE1:  " << za.Zd()*180/3.1415 << " " << za.Az()*180/3.1415 << endl;
+    fTrackingPos = fBending.CorrectBack(za)*TMath::RadToDeg();
+    //cout << "RE2:  " << fTrackingPos.Zd() << " " << fTrackingPos.Az() << endl;
 }
 
@@ -828,6 +837,6 @@
 
     cout << "Reading gear ratios..." << flush;
+    kGear.X(env.GetValue("Zd_GearRatio[U_mot/U_tel]", 1000.0));
     kGear.Y(env.GetValue("Az_GearRatio[U_mot/U_tel]", 1000.0));
-    kGear.X(env.GetValue("Zd_GearRatio[U_mot/U_tel]", 1000.0));
 
     kResRE.Y(0);
@@ -1118,5 +1127,9 @@
         SetStatus(MDriveCom::kError);
 
-    ZdAz bendist = GetPointingPos();
+
+    ZdAz bendist = fStatus&MDriveCom::kTracking ? fTrackingPos : GetPointingPos();
+
+    //cout << (fStatus&MDriveCom::kTracking?"TRA: ":"POS: ") << bendist.Zd() << " " << bendist.Az() << endl;
+
     fCom->SendReport(fStatus, fRaDec, fZdAzSoll, bendist, fTrackingError);
 
@@ -1328,4 +1341,8 @@
     fAz->SetReport(fOutRep);
 
+    fAz->SetMotor(fMac1);
+    fZd1->SetMotor(fMac2);
+    fZd2->SetMotor(fMac2);
+ 
     lout << "- Connecting devices to network." << endl;
 
Index: trunk/MagicSoft/Cosy/main/MCosy.h
===================================================================
--- trunk/MagicSoft/Cosy/main/MCosy.h	(revision 4104)
+++ trunk/MagicSoft/Cosy/main/MCosy.h	(revision 4105)
@@ -1,11 +1,13 @@
-#ifndef MCOSY_H
-#define MCOSY_H
+#ifndef COSY_MCosy
+#define COSY_MCosy
 
 #include "coord.h"
 #include "msgqueue.h"
-#include "network.h"
 #include "MThread.h"
 #include "MBending.h"
 
+#ifndef COSY_Network
+#include "network.h"
+#endif
 #ifndef MARS_MObservatory
 #include "MObservatory.h"
@@ -84,7 +86,8 @@
     MDriveCom *fCom;
 
-    TTimer *fUpdateGui;
-    MTTalk *fTTalk;       // should be outsourced, like the starguider.
+    TTimer    *fUpdateGui;
+    MTTalk    *fTTalk;    // should be outsourced, like the starguider.
                           // with a generic interface to both...
+    ZdAz fTrackingPos;    // [deg] Current tracking position
 
     TMutex fMutexGui;
@@ -185,4 +188,7 @@
     MGCosy *GetWin() { return fWin; }
 
+    ZdAz GetTrackingPosDeg() const { return fTrackingPos; };
+    void SetTrackingPosRE(ZdAz za);
+
     AltAz GetAltAzDeg() const
     {
Index: trunk/MagicSoft/Cosy/main/MPointing.cc
===================================================================
--- trunk/MagicSoft/Cosy/main/MPointing.cc	(revision 4104)
+++ trunk/MagicSoft/Cosy/main/MPointing.cc	(revision 4105)
@@ -151,7 +151,11 @@
         const ZdAz p=fCosy->GetSePos();
 
-        // calculate control deviation and rounded cd
+        // calculate control deviation
         ZdAz rd = dest-p; // [se]
         ZdAz cd = rd;     // [se]
+        // Correct for having two SE available
+        cd.Zd(cd.Zd()*2);
+        // Round to check whether we are as near as possible
+        // to the value we expect
         cd.Round();
 
Index: trunk/MagicSoft/Cosy/main/MStarguider.cc
===================================================================
--- trunk/MagicSoft/Cosy/main/MStarguider.cc	(revision 4104)
+++ trunk/MagicSoft/Cosy/main/MStarguider.cc	(revision 4105)
@@ -8,11 +8,14 @@
 #include <TGraph.h>
 #include <TTimer.h>
+#include <TSystem.h>
 
 #include <TGMenu.h>
 #include <TGLabel.h>
-#include <TSystem.h>
+#include <TGButton.h>
 #include <TGSplitter.h>    // TGHorizontal3DLine
 #include <TGTextEntry.h>
 
+#include "MString.h"
+
 #include "MCosy.h"
 #include "MCaos.h"
@@ -22,4 +25,7 @@
 
 #include "coord.h"
+
+#include "Camera.h"
+#include "PngReader.h"
 
 #include "Led.h"
@@ -29,6 +35,9 @@
 #include "CaosFilter.h"
 #include "StarCatalog.h"
+#include "MGeomCamMagic.h"
+#include "MAstroCamera.h"
 
 #include "MGMenu.h"
+#include "MGCosy.h"
 
 ClassImp(MStarguider);
@@ -36,4 +45,5 @@
 enum {
     IDM_kFilter,
+    IDM_kFindStar,
     IDM_kCaosFilter,
     IDM_kCatalog,
@@ -46,5 +56,7 @@
     IDM_kOnce,
     IDM_kStretch,
-//    IDM_kUseFileRaDec,
+    IDM_kInput,
+    IDM_kChannel1,
+    IDM_kChannel2,
     IDM_kContinous,
     IDM_kRate25ps,
@@ -65,4 +77,5 @@
     IDM_kPixSize,
     IDM_kAngle,
+    IDM_kInterpol250,
     IDM_kInterpol125,
     IDM_kInterpol50,
@@ -83,6 +96,13 @@
 Bool_t MStarguider::HandleTimer(TTimer *t)
 {
-    fImage->DoRedraw();
-    fZoomImage->DoRedraw();
+    if (IsMapped())
+    {
+        fImage->DoRedraw();
+        fZoomImage->DoRedraw();
+    }
+
+    if (fCosy && fCosy->GetWin()->IsMapped())
+        fCosy->GetWin()->GetImage()->DoRedraw();
+
     return kTRUE;
 }
@@ -95,9 +115,16 @@
 }
 
-void MStarguider::InitGui()
+void MStarguider::InitGui(Int_t channel)
 {
     fList = new MGList;
 
     const TGWindow *p=gClient->GetRoot();
+
+    fChannel = new MGPopupMenu(p);
+    fChannel->AddEntry("Channel #1", IDM_kChannel1);
+    fChannel->AddEntry("Channel #2", IDM_kChannel2);
+    fChannel->CheckEntry(channel==0?IDM_kChannel1:IDM_kChannel2);
+    fChannel->Associate(this);
+    fList->Add(fChannel);
 
     //
@@ -106,8 +133,11 @@
     fDisplay = new MGPopupMenu(p);
     fDisplay->AddEntry("&Filter",      IDM_kFilter);
+    fDisplay->AddEntry("Find &Star",   IDM_kFindStar);
     fDisplay->AddEntry("C&aosFilter",  IDM_kCaosFilter);
     fDisplay->AddEntry("Sao &Catalog", IDM_kCatalog);
     fDisplay->AddEntry("Starguider",   IDM_kStarguider);
     fDisplay->AddEntry("Stretch",      IDM_kStretch);
+    if (channel>=0)
+        fDisplay->AddPopup("&Input",   fChannel);
     fDisplay->DisableEntry(IDM_kStarguider);
     fDisplay->CheckEntry(IDM_kStretch);
@@ -169,4 +199,5 @@
 
     fInterpol = new MGPopupMenu(p);
+    fInterpol->AddEntry("250", IDM_kInterpol250);
     fInterpol->AddEntry("125", IDM_kInterpol125);
     fInterpol->AddEntry("50",  IDM_kInterpol50);
@@ -242,5 +273,5 @@
 
     fCRaDec = new MGCoordinates(this, kETypeRaDec);
-    fCRaDec->Move(1, fMenu->GetDefaultHeight()+584);
+    fCRaDec->Move(4, fMenu->GetDefaultHeight()+584);
     AddFrame(fCRaDec);
     fList->Add(fCRaDec);
@@ -255,4 +286,10 @@
     AddFrame(fPZdAz);
     fList->Add(fPZdAz);
+
+    fTPoint = new TGTextButton(this, "TPoint");
+    fTPoint->Move(4, fMenu->GetDefaultHeight()+665);
+    fTPoint->AllowStayDown(kTRUE);
+    AddFrame(fTPoint);
+    fList->Add(fTPoint);
 
     fFps = new TGLabel(this, "---fps");
@@ -294,5 +331,5 @@
     const Double_t pixsize = 23.4;
 
-    fSao->SetPixSize(pixsize/3600);
+    fSao->SetPixSize(pixsize);
     fSao->SetRotationAngle(0);
 
@@ -336,5 +373,8 @@
 
     MapSubwindows();
+    fTPoint->UnmapWindow();
     MapWindow();
+
+    IconifyWindow();
 
     //------------------------------------------------------------
@@ -345,6 +385,6 @@
 }
 
-MStarguider::MStarguider(MObservatory::LocationName_t obs)
-: TGMainFrame(gClient->GetRoot(), 768, 740), fCosy(NULL), fDx((768-kZOOM)/2), fDy((512-kZOOM)/2)
+MStarguider::MStarguider(MObservatory::LocationName_t obs, Int_t channel)
+: TGMainFrame(gClient->GetRoot(), 768, 740), fCosy(NULL), fOutTp(0), fDx((768-kZOOM)/2), fDy((512-kZOOM)/2)
 {
     cout << " #### FIXME: Make MCaos Thread safe!" << endl;
@@ -356,7 +396,5 @@
     fCaos->ReadResources();
 
-    InitGui();
-
-    gVirtualX->GrabButton(fId, kButton2, 0, 0, 0, 0, kTRUE);
+    InitGui(channel);
 
     fTimer=new TTimer(this, 1000/25); // 40ms
@@ -364,8 +402,21 @@
 
     fTime.Now();
+                                             
+    gVirtualX->GrabButton(fId, kButton2, 0, 0, 0, 0, kTRUE);
+
+    if (channel<0)
+        fGetter=new PngReader(*this);
+    else
+    {
+        fGetter = new Camera(*this, channel);
+        ((Camera*)fGetter)->Loop(0);
+    }
 }
 
 MStarguider::~MStarguider()
 {
+    fGetter->ExitLoop();
+    delete fGetter;
+
     gVirtualX->GrabButton(fId, kButton2, 0, 0, 0, 0, kFALSE);
 
@@ -378,4 +429,7 @@
     delete fSao;
     delete fRaDec;
+
+    if (fOutTp)
+        delete fOutTp;
 
     cout << "Camera Display destroyed." << endl;
@@ -416,5 +470,5 @@
                     const Float_t pixsize = atof(fPixSize->GetText());
                     cout << "Pixel Size changed to " << pixsize << "\"/pix" << endl;
-                    fSao->SetPixSize(pixsize/3600);
+                    fSao->SetPixSize(pixsize);
                     return kTRUE;
                 }
@@ -459,4 +513,15 @@
                     fDisplay->UnCheckEntry(IDM_kStarguider);
                     fDisplay->DisableEntry(IDM_kStarguider);
+                }
+                return kTRUE;
+
+            case IDM_kFindStar:
+                Toggle(fDisplay, IDM_kFindStar);
+                if (fDisplay->IsEntryChecked(IDM_kFindStar) && fCosy)
+                    fTPoint->MapWindow();
+                else
+                {
+                    fTPoint->UnmapWindow();
+                    fTPoint->SetDown(kFALSE);
                 }
                 return kTRUE;
@@ -595,4 +660,22 @@
                 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);
+                    delete fGetter;
+                    usleep(150000); // FIX: Device or resource busy.
+                    fGetter = new Camera(*this, ch1);
+                    ((Camera*)fGetter)->Loop(0);
+                }
+                return kTRUE;
+
+            case IDM_kInterpol250:
             case IDM_kInterpol125:
             case IDM_kInterpol50:
@@ -602,5 +685,5 @@
             case IDM_kInterpol2:
             case IDM_kInterpol1:
-                for (int i=IDM_kInterpol125; i<=IDM_kInterpol1; i++)
+                for (int i=IDM_kInterpol250; i<=IDM_kInterpol1; i++)
                     if (mp1==i)
                         fInterpol->CheckEntry(i);
@@ -629,4 +712,7 @@
                 case IDM_kInterpol125:
                     fIntRate = 125;
+                    return kTRUE;
+                case IDM_kInterpol250:
+                    fIntRate = 250;
                     return kTRUE;
                 }
@@ -806,4 +892,107 @@
 }
 
+void MStarguider::FindStar(FilterLed &f, FilterLed &f2, Ring &center, MTime &t)
+{
+    // Set search Paremeters (FIXME: Get them from user input!)
+    f.SetCut(3.0);
+    f.SetBox(70);
+
+    // Try to find Led in this area
+    Leds leds;
+    f.FindStar(leds, center.GetX(), center.GetY());
+
+    // Check wheter star found
+    Led *star = (Led*)leds.At(0);
+    if (!star)
+        return;
+
+    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.SetMirrors("magic.def");
+    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()*360/24, xy.Y()*TMath::DegToRad());
+
+    ac.SetRaDec(rd.Ra(), rd.Dec());
+
+    // Adapt coordinate system (GUI and humans are counting Y in different directions)
+    Double_t x = star->GetX()-center.GetX();
+    Double_t y = center.GetY()-star->GetY();
+
+    // Convert from Pixel to millimeter (1pix=2.9mm)
+    x *= 2.58427;
+    y *= 2.58427;
+
+    // Correct for abberation.
+    x /= 1.0713;
+    y /= 1.0713;
+
+    // Calculate Offset
+    Double_t dzd, daz;
+    ac.GetDiffZdAz(x, y, dzd, daz);
+
+    cout << "STAR-Offset: " << MTime(-1) << " dZd=" << dzd << "d  dAz=" << daz << "d" << endl;
+
+    // Check TPoint data set request
+    if (!fTPoint->IsDown())
+        return;
+    fTPoint->SetDown(kFALSE);
+
+    // If no file open: open new file
+    if (!fOutTp)
+    {
+        //
+        // open tpoint file
+        //
+        const TString name = MCosy::GetFileName("tpoint/starg_%s.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);
+
+    // From the Shaftencoders we get the current 'pointing' position
+    // as it is seen by the drive system (system pointing position)
+    const ZdAz za1 = fCosy->GetTrackingPosDeg();
+
+    // 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 << endl;
+}
+
 bool MStarguider::Interpolate(const unsigned long n, byte *img) const
 {
@@ -844,5 +1033,7 @@
     if (d>1)
     {
-        fFps->SetText(Form("%dfps", (int)((n-n0)/d+.5)));
+        MString txt;
+        txt.Print("%dfps", (int)((n-n0)/d+.5));
+        fFps->SetText(txt);
         fTime = t;
         n0 = n;
@@ -852,5 +1043,9 @@
         return;
 
-    FilterLed f(img, 768, 576, 2.5); // 2.5
+    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))
@@ -874,4 +1069,5 @@
         f.Execute();
 
+    Ring center(768/2, 576/2);
     if (fDisplay->IsEntryChecked(IDM_kCaosFilter))
     {
@@ -882,6 +1078,9 @@
             pos = fCosy->GetPointingPos();
 
-        fCaos->Run(img, printl, printr, pos, t);
-    }
+        center = fCaos->Run(img, printl, printr, pos, t);
+    }
+
+    if (fDisplay->IsEntryChecked(IDM_kFindStar))
+        FindStar(f, f2, center, t);
 
     byte zimg[kZOOM*kZOOM];
@@ -892,4 +1091,14 @@
     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);
+    }
+
     if (fDisplay->IsEntryChecked(IDM_kCatalog))
     {
@@ -901,7 +1110,5 @@
         UpdatePosZoom();
 
-        MStarList stars;
-        fSao->GetStars(stars, time.GetMjd(), *fRaDec);
-
+        /*
         if (fDisplay->IsEntryChecked(IDM_kStarguider))
         {
@@ -913,17 +1120,39 @@
             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);
-
+        */
+
+        // Always call SetMjd first!
+        fSao->SetPointing(time.GetMjd(), *fRaDec);
         fCZdAz->SetCoordinates(fSao->GetZdAz());
 
+        MStarList stars;
+        fSao->CalcStars(stars);
+        fSao->DrawStars(stars, cimg);
+    }
+
+    if (fDisplay->IsEntryChecked(IDM_kCaosFilter))
+    {
+        f2.DrawCircle(center, 0x0a);
+        f2.DrawCircle(center,   5.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_kCatalog))
+    {
+        fSao->PaintImg(cimg, 768, 576);
+
+        const float r = 60*60/fSao->GetPixSize();
+
+        f2.DrawCircle(0.5*r, 0x0a);
+        f2.DrawCircle(1.0*r, 0x0a);
+        f2.DrawCircle(1.5*r, 0x0a);
+    }
+
+    if (fDisplay->IsEntryChecked(IDM_kCaosFilter) ||
+        fDisplay->IsEntryChecked(IDM_kCatalog)    ||
+        fDisplay->IsEntryChecked(IDM_kFindStar))
         fImage->DrawColImg(img, cimg);
-    }
     else
         fImage->DrawImg(img);
@@ -932,4 +1161,5 @@
 void MStarguider::UpdatePosZoom()
 {
+    MString txt;
     if (fDisplay->IsEntryChecked(IDM_kCatalog))
     {
@@ -940,9 +1170,11 @@
         if (aa.Az()<0)
             aa.Az(aa.Az()+360);
-        fPosZoom->SetText(Form("%.1fd/%.1fd (%d, %d)",
-                               -aa.Alt(), aa.Az()-180, fDx, fDy));
+
+        txt.Print("%.1fd/%.1fd (%d, %d)", -aa.Alt(), aa.Az()-180, fDx, fDy);
     }
     else
-        fPosZoom->SetText(Form("(%d, %d)", fDx, fDy));
+        txt.Print("(%d, %d)", fDx, fDy);
+
+    fPosZoom->SetText(txt);
 }
 
Index: trunk/MagicSoft/Cosy/main/MStarguider.h
===================================================================
--- trunk/MagicSoft/Cosy/main/MStarguider.h	(revision 4104)
+++ trunk/MagicSoft/Cosy/main/MStarguider.h	(revision 4105)
@@ -7,20 +7,20 @@
 
 #include "PixClient.h"
+#include "MGImage.h"
+#include "coord.h"
 
 #ifndef MARS_MObservatory
 #include "MObservatory.h"
 #endif
-
 #ifndef MARS_MTime
 #include "MTime.h"
 #endif
-
+#ifndef MARS_MGList
 #include "MGList.h"
-#include "MGImage.h"
-
-#include "coord.h"
+#endif
 
 class TArrayF;
 class TGLabel;
+class TGButton;
 
 class TTimer;
@@ -29,4 +29,6 @@
 class MGPopupMenu;
 class TGTextEntry;
+
+class PixGetter;
 
 class MGImage;
@@ -37,4 +39,6 @@
 class MCosy;
 class MCaos;
+class FilterLed;
+class Ring;
 
 class Leds;
@@ -43,4 +47,6 @@
 {
 private:
+    PixGetter     *fGetter;
+
     MGList        *fList;
 
@@ -57,4 +63,5 @@
     MGPopupMenu   *fSetup;
     MGPopupMenu   *fLimMag;
+    MGPopupMenu   *fChannel;
 
     MGPopupMenu   *fCaosWrite;
@@ -74,4 +81,6 @@
     TGLabel       *fPosZoom;
 
+    TGButton      *fTPoint;
+
     StarCatalog   *fSao;
     MCosy         *fCosy;
@@ -82,4 +91,6 @@
     TTimer *fTimer;
     MTime   fTime;
+
+    ofstream *fOutTp;
 
     Int_t fDx;
@@ -95,8 +106,9 @@
     ZdAz TrackingError(TArrayF &alt, TArrayF &az, TArrayF &mag) const;
     bool Interpolate(const unsigned long n, byte *img) const;
+    void FindStar(FilterLed &f, FilterLed &f2, Ring &center, MTime &t);
 
     //void InitHists();
     //void InitGraphs();
-    void InitGui();
+    void InitGui(Int_t channel);
 
     //void OpenFile();
@@ -110,5 +122,5 @@
 
 public:
-    MStarguider(MObservatory::LocationName_t obs);
+    MStarguider(MObservatory::LocationName_t obs, Int_t channel);
     virtual ~MStarguider();
 
@@ -119,5 +131,7 @@
 
     Bool_t ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2);
+
     Bool_t HandleDoubleClick(Event_t *event);
+    //Bool_t HandleButton(Event_t *);
 
     void SetPointingPosition(RaDec rd);
Index: trunk/MagicSoft/Cosy/main/MTracking.cc
===================================================================
--- trunk/MagicSoft/Cosy/main/MTracking.cc	(revision 4104)
+++ trunk/MagicSoft/Cosy/main/MTracking.cc	(revision 4105)
@@ -73,6 +73,4 @@
         return false;
 
-    fCosy->SetStatus(MDriveCom::kMoving | MDriveCom::kTracking);
-
     fCosy->fMac2->SetRpmMode(TRUE);
     if (fCosy->fMac2->IsZombieNode())
@@ -82,4 +80,6 @@
     if (fCosy->fMac1->IsZombieNode())
         return false;
+
+    fCosy->SetStatus(MDriveCom::kMoving | MDriveCom::kTracking);
 
     return true;
@@ -223,4 +223,51 @@
 
     return kFALSE;
+}
+
+// --------------------------------------------------------------------
+//
+// Return pointing position of the telescope based on the
+// Shaftencoders with interpolation with motor encoders.
+//
+// GetPointingPos [re]
+//
+ZdAz MTracking::GetPointingPosRE(Bool_t pdo) const
+{
+    // Conversion factor from se to re
+    const XY re = fCosy->kGearTot/fCosy->kResSE; //[re/se]
+
+    // Get current shaftencoder position of the telescope
+    Double_t seposzd1 = ((fCosy->fZd1->GetPos()+8192)%16384)*re.X();
+    Double_t seposzd2 = ((fCosy->fZd2->GetPos()+8192)%16384)*re.X();
+    Double_t seposaz  =   fCosy->fAz->GetPos() *re.Y();
+
+    // distance between (To+dt) and To [re]
+    // position time difference < 5usec
+    // fRePos does the synchronization between the
+    // Shaft- and the rotary encoders
+    const ZdAz repos = pdo ? fCosy->GetRePosPdo() : fCosy->GetRePos();
+
+    // Calculate the part of one SE which the motors moved
+    // since the last SE has changed its value
+    const Double_t offzd1 = repos.Zd() - fCosy->fZd1->GetOffset();
+    const Double_t offzd2 = repos.Zd() - fCosy->fZd2->GetOffset();
+    const Double_t offaz  = repos.Az() - fCosy->fAz->GetOffset();
+
+    // Correct for the direction in which the motor is moving
+    // (in which the shaftencoders should change its values)
+    if (offaz<0)
+        seposaz += re.Y();
+    if (offzd1<0)
+        seposzd1 += re.X();
+    if (offzd2<0)
+        seposzd2 += re.X();
+
+    // and interpolate the shaftencoder steps using the motor
+    // encoder positon (Be carefull the minus-sign is important)
+    seposzd1 += offzd1;
+    seposzd2 -= offzd2;
+    seposaz  += offaz;
+
+    return ZdAz((seposzd1-seposzd2)/2, seposaz);
 }
 
@@ -260,18 +307,21 @@
     // calculate offset from present se position
     //
-    const ZdAz sepos = fCosy->GetSePos()*fCosy->kGearTot/fCosy->kResSE; //[re]
+    //const ZdAz sepos = fCosy->GetSePos()*fCosy->kGearTot/fCosy->kResSE; //[re]
     if (!RequestRePos())
         return;
 
-    //
     // Estimate Offset before starting to track
-    //
-    fOffset = sepos-fCosy->GetRePos();
-
-    /*
-     cout << "Sepos:  " << sepos.Zd() << "re, " << sepos.Az() << "re" << endl;
-     cout << "Repos:  " << repos.Zd() << "re, " << repos.Az() << "re" << endl;
-     cout << "Offset: " << fOffset.Zd() << "re, " << fOffset.Az() << "re" << endl;
-     */
+    ZdAz repos = fCosy->GetRePos();
+    fCosy->fZd1->SetOffset(repos.Zd());
+    fCosy->fZd2->SetOffset(repos.Zd());
+    fCosy->fAz->SetOffset(repos.Az());
+
+    fCosy->SetTrackingPosRE(GetPointingPosRE());
+
+    // Initialize Tracker (slalib or starguider)
+    fCosy->fRaDec = dst;
+
+    // StartThread
+    Start();
 
     //
@@ -283,10 +333,4 @@
         return;
     }
-
-    // Initialize Tracker (slalib or starguider)
-    fCosy->fRaDec = dst;
-
-    // StartThread
-    Start();
 
     // Get current nominal local position
@@ -296,5 +340,5 @@
     // Some output
     XY xy(Rad2Deg(dst.Ra())*24/360, Rad2Deg(dst.Dec()));
-    lout << sla.GetTime() << " - Start Tracking: Ra=" <<xy.X() << "h Dec=";
+    lout << sla.GetTime() << " - Start Tracking: Ra=" << xy.X() << "h Dec=";
     lout << xy.Y() << "\xb0 @ Zd=" << pos.Zd()*kRad2Deg <<"deg Az=" << pos.Az()*kRad2Deg <<"deg" << endl;
 
@@ -331,23 +375,29 @@
                 break;
 
+            // Destination position at t+dt in re-units
             dest *= fCosy->kGearTot/TMath::TwoPi();  // [re]
 
-            //*fCosy->fOutRep << "> ReqRePos1 " << endl;
-
-            //
             // Request absolute position of rotary encoder from Macs
-            //
+            // Such that the RE position used in GetPointingPos is
+            // as up-to-date as possible.
+// DO I NEED THIS OR IS THE PDOPOS ENOUGH?
             if (!RequestRePos())
                 break;
 
-            //*fCosy->fOutRep << "> ReqRePos2 " << fOffset.Zd() << " " << fOffset.Az() << endl;
-
-            //
+            // *NEW* offset handling
+            // Get current position of the telescope and
+            // forward this position to MCosy
+            ZdAz sepos = GetPointingPosRE(); //[re]
+            fCosy->SetTrackingPosRE(sepos);
+
             // distance between (To+dt) and To [re]
             // position time difference < 5usec
-            // fOffset does the synchronization between the
+            // fRePos does the synchronization between the
             // Shaft- and the rotary encoders
             repos = fCosy->GetRePos();
-            dest -= repos + fOffset; //[re]
+
+            // Now calculate the distance to move from now
+            // to a time in t+dt.
+            dest -= sepos;
 
             dtime = dt;
@@ -412,7 +462,7 @@
         if (fOut)
         {
-            fOut->Lock();
+            fOut->Lock("MTracking::TrackPosition");
             *fOut << "RE-REPORT " << MTime(-1) << " " << repos.Zd() << " " << repos.Az() <<" " << vt.Zd() << " " << vt.Az() << endl;
-            fOut->UnLock();
+            fOut->UnLock("MTracking::TrackPosition");
         }
 
@@ -455,5 +505,5 @@
     lout << "- Tracking Thread started..." << endl;
 
-    const XY re2se = fCosy->kGearTot/fCosy->kResSE; //[re/se]
+    //const XY re2se = fCosy->kGearTot/fCosy->kResSE; //[re/se]
 
     SlaStars sla(fCosy->fObservatory);
@@ -471,4 +521,7 @@
     bool phcaz=false;
 
+    ZdAz wasse = fCosy->GetSePos();
+    ZdAz oldse = fCosy->GetSePos();
+
     while (!HasStopFlag())
     {
@@ -476,5 +529,5 @@
         // This is the time constant which defines how fast
         // you correct for external influences (like wind)
-        const float weight = 1.; //0.3;
+        //const float weight = 1.; //0.3;
 
         // Check for changes of the shaftencoder values
@@ -492,51 +545,45 @@
         } while (!phca1 && !phca2 && !phcaz && !HasStopFlag());
 
-        //*fCosy->fOutRep << "> Do Calculation" << endl;
-
-        // Get current position of motors (use last automatically sent
-        // position (PDO) - requesting the position results in problems
-        // with thread safty)
-        ZdAz istre = fCosy->GetRePosPdo();
-
-        // get current position of shaftencoders
-        ZdAz istse = fCosy->GetSePos(); // [se]
-
         // Get time from last shaftencoder position change (position: ist)
         // FIXME: Is this correct?
-        if (fCosy->fZd1->GetMjd()>fCosy->fZd2->GetMjd())
-            time.Zd(fCosy->fZd1->GetMjd());
-        else
-            time.Zd(fCosy->fZd2->GetMjd());
-
-        time.Az(fCosy->fAz->GetMjd());
+        //        time.Az(fCosy->fMac1->GetMjd());
+        //        time.Zd(fCosy->fMac2->GetMjd());
+
+        Double_t mjd1 = fCosy->fZd1->GetMjd();
+        Double_t mjd2 = fCosy->fZd2->GetMjd();
+        Double_t mjd0 = fCosy->fAz->GetMjd();
+
+        // get current position of shaftencoders (interpolated
+        // using motor encoders)
+        const ZdAz istse = GetPointingPosRE(kTRUE)/fCosy->kGearTot*TMath::TwoPi();
+        //const ZdAz istse = fCosy->GetSePosPdo();
 
         // calculate offset for both axis (only one is needed)
-        const ZdAz offset = (istse*re2se - istre)*weight + fOffset*(weight-1);
-
+        // *NEW* offset handling
+        //.const ZdAz offset = istre; //(istse*re2se - istre)*weight + fRePos*(weight-1);
         // if Shaftencoder changed position, calculate nominal position
         if (phca1 || phca2)
         {
-            const ZdAz dummy = sla.CalcZdAz(fCosy->fRaDec, time.Zd());
+            ZdAz dummy = sla.CalcZdAz(fCosy->fRaDec, fCosy->fMac2->GetPdoMjd());//TMath::Max(mjd1, mjd2));
+            dummy = fCosy->AlignTrackingPos(dummy);
+            dummy = fCosy->fBending(dummy);
             soll.Zd(dummy.Zd()); // [rad]
-            fOffset.Zd(offset.Zd());
         }
         if (phcaz)
         {
-            const ZdAz dummy = sla.CalcZdAz(fCosy->fRaDec, time.Az());
+            const Double_t mjd = fCosy->fMac1->GetMjd();
+            ZdAz dummy = sla.CalcZdAz(fCosy->fRaDec, fCosy->fMac1->GetPdoMjd());//mjd0);
+            dummy = fCosy->AlignTrackingPos(dummy);
+            dummy = fCosy->fBending(dummy);
             soll.Az(dummy.Az()); // [rad]
-            fOffset.Az(offset.Az());
         }
 
-        // After calculation of fOffset is done we need 'ist' in rad
-        istse /= fCosy->kResSE/TMath::TwoPi(); // [rad]
+        fCosy->fZdAzSoll = soll;
 
         // Calculate the aligned tracking posotion from 'soll'-position
-        fCosy->fZdAzSoll = fCosy->AlignTrackingPos(soll);
-
-        /* --- OLD --- */
-        //fCosy->fTrackingError = istse-fCosy->fBending(fCosy->fZdAzSoll);
-        /* --- NEW --- */
-        fCosy->fTrackingError = fCosy->fBending.CorrectBack(istse)-fCosy->fZdAzSoll;
-        /* --- END --- */
+        if (phca1 || phca2)
+            fCosy->fTrackingError.Zd(soll.Zd()-istse.Zd());
+        if (phcaz)
+            fCosy->fTrackingError.Az(soll.Az()-istse.Az());
     }
 
Index: trunk/MagicSoft/Cosy/main/MTracking.h
===================================================================
--- trunk/MagicSoft/Cosy/main/MTracking.h	(revision 4104)
+++ trunk/MagicSoft/Cosy/main/MTracking.h	(revision 4105)
@@ -20,7 +20,16 @@
     Float_t fTrackDec;
 
-    ZdAz    fOffset; // Offset between se and re coordinate system [re]
+    //Int_t fSePosZd1;
+    //Int_t fSePosZd2;
+    //Int_t fSePosAz;
 
-    MLog *fOut;
+    //Int_t fRePosZd1;
+    //Int_t fRePosZd2;
+    //Int_t fRePosAz;
+
+    //ZdAz    fRePos;  // Offset between se and re coordinate system [re]
+    //ZdAz    fSePos;  // Shaftencoder Position
+
+    MLog   *fOut;
 
     bool RequestRePos();
@@ -28,5 +37,5 @@
     bool LimitSpeed(ZdAz *vt, const SlaStars &sla) const;
     bool InitTracking();
-    //void StopTracking();
+    ZdAz GetPointingPosRE(Bool_t pdo=kFALSE) const;
 
     void *Thread();
@@ -39,6 +48,5 @@
 
     void SetOut(MLog *fout) { fOut = fout; }
-    //void TalkThreadTracking();
-  
+
     ClassDef(MTracking, 0)
 };
Index: trunk/MagicSoft/Cosy/main/MainLinkDef.h
===================================================================
--- trunk/MagicSoft/Cosy/main/MainLinkDef.h	(revision 4104)
+++ trunk/MagicSoft/Cosy/main/MainLinkDef.h	(revision 4105)
@@ -10,3 +10,6 @@
 #pragma link C++ class MBending;
 
+#pragma link C++ class MPointing;
+#pragma link C++ class MTracking;
+
 #endif
Index: trunk/MagicSoft/Cosy/main/Makefile
===================================================================
--- trunk/MagicSoft/Cosy/main/Makefile	(revision 4104)
+++ trunk/MagicSoft/Cosy/main/Makefile	(revision 4105)
@@ -34,4 +34,6 @@
 SRCFILES = MBending.cc \
            MStarguider.cc \
+           MPointing.cc \
+           MTracking.cc \
            MCaos.cc \
 	   MCosy.cc
Index: trunk/MagicSoft/Cosy/tcpip/MCeCoCom.cc
===================================================================
--- trunk/MagicSoft/Cosy/tcpip/MCeCoCom.cc	(revision 4104)
+++ trunk/MagicSoft/Cosy/tcpip/MCeCoCom.cc	(revision 4105)
@@ -59,4 +59,9 @@
     fSolarRadiation = solar;
     fWindSpeed = wind;
+
+    if (fWindSpeed>30)
+        fAlarmCounter++;
+    else
+        fAlarmCounter=0;
 
     cout << "Zd/Az: " << zd << "/" << az << "  ";
@@ -131,10 +136,10 @@
     if (fHumidity>80)
         rc++;
+    if (fWindSpeed>10)
+        rc++;
     if (fWindSpeed>20)
         rc++;
     if (fWindSpeed>30)
         rc++;
-    if (fWindSpeed>50)
-        rc++;
 
     return rc;
Index: trunk/MagicSoft/Cosy/tcpip/MCeCoCom.h
===================================================================
--- trunk/MagicSoft/Cosy/tcpip/MCeCoCom.h	(revision 4104)
+++ trunk/MagicSoft/Cosy/tcpip/MCeCoCom.h	(revision 4105)
@@ -31,8 +31,10 @@
     ComStatus_t fComStat; // communication status
 
-    Float_t fHumidity;       // [%]
-    Float_t fTemperature;    // [deg] celsius
-    Float_t fWindSpeed;      // [km/h]
-    Float_t fSolarRadiation; // [W/m^2] IR-Radiation
+    Float_t fHumidity;         // [%]
+    Float_t fTemperature;      // [deg] celsius
+    Float_t fWindSpeed;        // [km/h]
+    Float_t fSolarRadiation;   // [W/m^2] IR-Radiation
+
+    Int_t   fAlarmCounter;     // Counter for alarm cases
 
     virtual bool InterpreteCmd(TString cmd, TString str);
@@ -56,4 +58,6 @@
     TString GetWeather() const;
     Int_t   GetWeatherStatus() const;
+
+    Bool_t  HasAlarm() const { return fAlarmCounter>3; }
 };
 
Index: trunk/MagicSoft/Cosy/tcpip/MDriveCom.cc
===================================================================
--- trunk/MagicSoft/Cosy/tcpip/MDriveCom.cc	(revision 4104)
+++ trunk/MagicSoft/Cosy/tcpip/MDriveCom.cc	(revision 4105)
@@ -156,5 +156,5 @@
     er *= kRad2Deg;
 
-    rd.Ra(rd.Ra()*24/360);
+    rd.Ra(rd.Ra()/15);
 
     // Set status flag
Index: trunk/MagicSoft/Cosy/tcpip/MTcpIpIO.cc
===================================================================
--- trunk/MagicSoft/Cosy/tcpip/MTcpIpIO.cc	(revision 4104)
+++ trunk/MagicSoft/Cosy/tcpip/MTcpIpIO.cc	(revision 4105)
@@ -74,11 +74,13 @@
         return true;
 
-    const Int_t rc = lout.IsOutputDeviceEnabled(MLog::eGui);
-    lout.DisableOutputDevice(MLog::eGui);
-    lout.Lock();
-    lout << msg << flush;
-    lout.UnLock();
-    if (rc)
-        lout.EnableOutputDevice(MLog::eGui);
+    if (lout.Lock("MTcpIpIO::Send"))
+    {
+        const Int_t rc = lout.IsOutputDeviceEnabled(MLog::eGui);
+        lout.DisableOutputDevice(MLog::eGui);
+        lout << msg << flush;
+        lout.UnLock("MTcpIpIO::Send");
+        if (rc)
+            lout.EnableOutputDevice(MLog::eGui);
+    }
 
     fTime = t;
Index: trunk/MagicSoft/Cosy/videodev/Camera.h
===================================================================
--- trunk/MagicSoft/Cosy/videodev/Camera.h	(revision 4104)
+++ trunk/MagicSoft/Cosy/videodev/Camera.h	(revision 4105)
@@ -1,4 +1,4 @@
-#ifndef CAMERA_H
-#define CAMERA_H
+#ifndef COSY_Camera
+#define COSY_Camera
 
 #ifndef ROOT_TMutex
Index: trunk/MagicSoft/Cosy/videodev/FilterLed.cc
===================================================================
--- trunk/MagicSoft/Cosy/videodev/FilterLed.cc	(revision 4104)
+++ trunk/MagicSoft/Cosy/videodev/FilterLed.cc	(revision 4105)
@@ -8,30 +8,7 @@
 #include "Ring.h"
 
+#include "MGMap.h"
+
 ClassImp(FilterLed);
-
-void FilterLed::DrawCircle(float cx, float cy, float rpix, byte col) const
-{
-    if (cx-rpix<1 || cy-rpix<1 || cx+rpix>fW-2 || cy+rpix>fH-2)
-        return;
-
-    for (int dx=-(int)(rpix*0.7); dx<(int)(rpix*0.7); dx+=2)
-    {
-        const int dy = (int)sqrt(rpix*rpix-dx*dx);
-        fImg[(int)(cx+dx) + (int)(cy-dy)*fW] = col;
-        fImg[(int)(cx+dx) + (int)(cy+dy)*fW] = col;
-        fImg[(int)(cx-dy) + (int)(cy+dx)*fW] = col;
-        fImg[(int)(cx+dy) + (int)(cy+dx)*fW] = col;
-    }
-}
-
-void FilterLed::DrawCircle(const Ring &l, byte col=0x40) const
-{
-    DrawCircle(l.GetX(), l.GetY(), l.GetR(), col);
-}
-
-void FilterLed::DrawCircle(const Ring &l, double r, byte col=0x40) const
-{
-    DrawCircle(l.GetX(), l.GetY(), r, col);
-}
 
 void FilterLed::DrawBox(const int x1, const int y1,
@@ -39,17 +16,5 @@
                         const int col) const
 {
-    for (int x=x1; x<x2+1; x++)
-        for (int y=y1; y<y2+1; y++)
-            if (x>=0 && x<fW-1 && y>=0 && y<fH-1)
-                fImg[y*fW+x] = col;
-}
-
-void FilterLed::MarkPoint(const Led &led) const
-{
-    const int x = (int)(led.GetX()+.5);
-    const int y = (int)(led.GetY()+.5);
-    const int m = (int)(led.GetMag());
-
-    MarkPoint(x, y, m);
+    MGMap::DrawBox(fImg, 768, 576, x1, y1, x2, y2, col);
 }
 
@@ -64,4 +29,28 @@
     DrawBox(x+5, y, x+8, y, m);
     DrawBox(x, y-8, x, y-5, m);
+}
+
+void FilterLed::MarkPoint(const Led &led) const
+{
+    const int x = (int)(led.GetX()+.5);
+    const int y = (int)(led.GetY()+.5);
+    const int m = (int)(led.GetMag());
+
+    MarkPoint(x, y, m);
+}
+
+void FilterLed::DrawCircle(float cx, float cy, float r, byte col) const
+{
+    MGMap::DrawCircle(fImg, 768, 576, cx, cy, r, col);
+}
+
+void FilterLed::DrawCircle(const Ring &l, byte col) const
+{
+    DrawCircle(l.GetX(), l.GetY(), l.GetR(), col);
+}
+
+void FilterLed::DrawCircle(const Ring &l, double r, byte col) const
+{
+    DrawCircle(l.GetX(), l.GetY(), r, col);
 }
 
