dimanche 26 août 2018

V442 And ATEL & BeSS spectra

On august 14th, 2018, I found that V442 And Be star went into a new outburst. I published an ATEL (Astronomical Telegram) with the help of Steve Shore:

http://www.astronomerstelegram.org/?read=11966


Here is copy of that telegram:

A new outburst of the Be star V442 And = HD6226

ATel #11966; Olivier Thizy (Observatoire de la Belle Etoile, Revel, France)
on 18 Aug 2018; 14:22 UT

Credential Certification: S. N. Shore (shore@df.unipi.it)

Subjects: Optical, Request for Observations, Star, Variables

V442 And (= HD6226) has been monitored as part of an ongoing effort to understand its activity cycles. Since Jun. 2018 the star has been under scrutiny in an attempt to detect the initiation of an outburst. This Be star has undergone several spectroscopically active intervals in the past few years. Equipment used is a T0.28m telescope with R=10000 echelle spectrograph, Atik 460ex CCD camera, PRISM v10 software for acquisition and ISIS v5.8.0 for spectra reduction. No substantial spectral changes were detected between Jun 27.089 and Aug 11.009 (33 spectra). However, the Halpha line showed a very significant increase in emission on Aug 14.997 (exposure time of 4800 sec, S/N > 50). Halpha line has shown drastic V/R changes every night since then. Emission was not visible on Hbeta line on Aug 14.997 spectrum but was detected in emission with a 6000 sec spectrum taken on Aug t 15.966 as a single emission on the blueward of the absorption line. The Aug 15.966 spectrum is also showing a broad, weak blueshifted emission on Hgamma. Further spectroscopic observations are strongly encouraged, especially across a broad wavelength range and at high resolution. Spectra are available at the BeSS Be Star Spectra database and further spectra submitted there as well.

BeSS Be Star Spectra database: http://basebe.obspm.fr/basebe/Accueil.php?flag_lang=en



For a dozen days, this outburst has been followed by several members of the BeSS database and I plotted all spectra after resampling them (0.05A/pixel), cropping them (6520-6600A) in ISIS and removing the telluric lines in VisualSpec. Then I used my MAtLab 3D graph script to do several plots below.

 3D graph of all spectra since I'm monitoring V442 And in 2018


 Same as above but with the first spectrum (as reference) substracted


2D spectrogram


Same as above but forst spectrum (reference) substracted


 Same as above with Parula colormap - great for a smartphone's background! :-)


vendredi 17 août 2018

V442 And in outburst again!

I have been observing V442 And since I could in june. I saw small changes in its spectrum but then suddently a drastic change occured between the 11th and the 14th of august - an outburst!

I wrote an ATEL about it - thanks to Steve Shore for helping me out:
http://www.astronomerstelegram.org/?read=1196


Here are my own spectra (all in BeSS database) and I encourage everyone to follow this target, specially during such outburst.




Using MatLab 3D script, I was able to do some 3D graphs as well as spectrogram (here they are spectra with the first one substracted, to better show the emission).

The emission is very bright on Halpha, well visible on Hbeta and can be detected on Hgamma. The He I 5876 and line at 4820A do not show emission but clear periodic behaviour (stellar rotation) and at the time of emission I seem to detect  a change in the spectrum too.



















Code for the MatLab Graph3D.m

%
% Graph2D
%
% Plot a graph from a serie of spectra
% X axis: wavelength (in radial velocity)
% Y axis: time, interpolated, in JD
%

% TODO
% ****
% 1/ fold date into phase using Period & HJD0
% 2/ move from JD to HJD
% 3/ correct wavelength from heliocentric RV
% 4/ dsplay dual labels on date axis: HJD-2457000 *and* Year
%

clear

% Create list of FITS files in the directpry & subdirectories
ds = datastore('.\','Type','image','IncludeSubfolders',false,'FileExtensions',{'.fit','.fits','.FIT','.FITS'});

% Global variables
c=300000.0; % light speed in km/s
JD0=2457000.0;

% Key data from target (V442 And) from CDS & litterature
Name='V442 And';
Author='(c) O.Thizy';
RATxt = '01 03 53.3583';
RA = 0.2788;
DecTxt = '+47 38 32.260';
Dec = 0.8315;
SpectralType = 'Be star';
MagB = 6.7900;
MagV = 6.8200;
MagR = 6.8200;
RV = -55.00;
HJD0=2457987.85;
Period=2.61507;

% Select the wavelength to display
Lambda0=4920.0; % Line near Hbeta
%=6678.0; % HeI singlet
%=6563.8; % Halpha
%=6678.0; % HeI singlet
%=4920.0; % Line near Hbeta
%=4861.0; % Hbeta
%=4340.0; % Hgamma
%=5876.0; % HeI triplet
%=4921.0; %HeI singlet

% Define which is the reference spectrum (usually the first one)
REFNum=1;

Titre=[Name ' / ' num2str(Lambda0) 'A / ' Author];

% Define the spectral domain to display
v1=-500.0; % in km/s
v2=+500.0; % in km/s
% Define the beginning of the spectral domain for all your spectra
% and the dispersion
%CRVAL=6507.5; % Valid for my echelle spectra only - Halpha!!!
CRVAL=4825.5; % Valid for my echelle spectra only - Hbeta!!!
%CRVAL=4277.5; % Valid for my echelle spectra only - Hgamma!!!
%CRVAL=5831.5; % Valid for my echelle spectra only - Na doublet!!!
CDELT=0.05; % idem

% Calculate the index position of the spectral domain within the
% interpolated spectrum
x1 = int32((Lambda0 + v1*Lambda0/c - CRVAL)/CDELT);
x2 = int32((Lambda0 + v2*Lambda0/c - CRVAL)/CDELT);
dX=int32(x2-x1)+1; % Spectrum now will go through (1:dX)
nX = int32(1000);
nY = 100;


REF = fitsread(ds.Files{REFNum}); % Reference spectrum vector (for substrated graph)

% NAXIS=63281; % Nb of Elements
MATRIX=zeros(length(ds.Files),dX);
MATRIX_SUB=zeros(length(ds.Files),dX);
MATRIX_PHASE=zeros(length(ds.Files),dX);
%OBS_DATE=zeros(length(ds.Files));

for i = 1:length(ds.Files)
    fName = char(ds.Files(i));
    H=fitsinfo(ds.Files{i});
    Data = fitsread(ds.Files{i}); % spectrum vector
       
    % searching for key header values
    if max(size(H.Contents)) == 1
        kwd = H.PrimaryData.Keywords ;
    elseif max(size(H.Contents)) > 3
        kwd = [H.PrimaryData.Keywords;H.Image(max(size(H.Contents))-2).Keywords];
    else
        kwd = H.PrimaryData.Keywords ;
    end

    HeaderMax = max(size(kwd));

    for L=1:HeaderMax
        k = kwd {L,1};
        kc = kwd {L,2};
        kt = kwd {L,3};
   
        switch k
            % CALIBRATION & REDUCTION data
            case 'NAXIS1'
                NAXIS1 = kwd {L,2};
            case 'CRVAL1'
                CRVAL1 = kwd {L,2};
            case 'CDELT1'
                CDELT1 = kwd {L,2};

            case 'JD-MID'
                JD = kwd {L,2};
               
            case 'EXPTIME2' % Total exposure duration (including in-between read-out time)
                ExpTimeTotal = kwd {L,2};
           
            case 'DATE-OBS'
                if length(kwd {L,2}) == 17
                    ObsDate = datetime(kwd {L,2},'InputFormat','uuuuMMdd''T''HH:mm:ss','TimeZone','UTC');
                elseif length(kwd {L,2}) == 18
                    ObsDate = datetime(kwd {L,2},'InputFormat','uuuuMMdd''T:''HH:mm:ss','TimeZone','UTC');
                elseif length(kwd {L,2}) == 19
                    if strcmp(kwd {L,2}(14),'-')
                        ObsDate = datetime(kwd {L,2},'InputFormat','uuuu-MM-dd''T''HH-mm:ss','TimeZone','UTC');
                    else
                        ObsDate = datetime(kwd {L,2},'InputFormat','uuuu-MM-dd''T''HH:mm:ss','TimeZone','UTC');
                    end
                elseif  length(kwd {L,2}) == 20
                    ObsDate = datetime(kwd {L,2},'InputFormat','uuuu-MM-dd''T''HH:mm:ss.','TimeZone','UTC');
                elseif  length(kwd {L,2}) == 21
                    ObsDate = datetime(kwd {L,2},'InputFormat','uuuu-MM-dd''T''HH:mm:ss.S','TimeZone','UTC');
                elseif  length(kwd {L,2}) == 22
                    ObsDate = datetime(kwd {L,2},'InputFormat','uuuu-MM-dd''T''HH:mm:ss.SS','TimeZone','UTC');
                elseif  length(kwd {L,2}) == 30
                    ObsDate = datetime(kwd {L,2},'InputFormat','uuuu-MM-dd''T''HH:mm:ss.SSSSSSSSSS','TimeZone','UTC');
                elseif  length(kwd {L,2}) == 31
                    ObsDate = datetime(kwd {L,2},'InputFormat','uuuu-MM-dd''T''HH:mm:ss.SSSSSSSSSSS','TimeZone','UTC');
                elseif  length(kwd {L,2}) == 32
                    ObsDate = datetime(kwd {L,2},'InputFormat','uuuu-MM-dd''T''HH:mm:ss.SSSSSSSSSSSS','TimeZone','UTC');
                elseif  length(kwd {L,2}) >= 23
                    ObsDate = datetime(kwd {L,2},'InputFormat','uuuu-MM-dd''T''HH:mm:ss.SSS','TimeZone','UTC');
                elseif  isempty(kwd {L,2})
                    ObsDate = kwd {L,2};
             end           
        end
  
    end
    % Lambda = CRVAL1 + CDELT1 * x
    % x = (Lambda - CRVAL1)/CDELT1
    % v = (Lambda-Lambda0)/Lambda0*c
    % Lambda = Lambda0 + v*Lambda0/c

    %Xx1 = int32((Lambda0 + v1*Lambda0/c - CRVAL1)/CDELT1);
    %Xx2 = int32((Lambda0 + v2*Lambda0/c - CRVAL1)/CDELT1);
    % dXx = int32(Xx2-Xx1)+1;
    % Xnew=linspace(1,dXx,nX);

    OBS_DATE(i)=(JD-JD0);
    % CalcJD = juliandate(ObsDate + seconds(ExpTimeTotal / 2))
    [HJD,ObjVel]=otz_hjd(JD,[RA Dec]);
    OBS_PHASE(i)=(HJD-JD0)/Period-fix((HJD-JD0)/Period);

    %    MATRIX(i,1:dX)=Data(x1:x2);
    MATRIX_SUB(i,1:dX)=Data(x1:x2)/mean(Data(x2-50:x2-40))-REF(x1:x2)/mean(REF(x2-50:x2-40));
    MATRIX(i,1:dX)=Data(x1:x2)/mean(Data(x2-50:x2-40));

end % end of loop for each file/spectrum

% pcolor(MATRIX), shading interp;
   
T=1:length(ds.Files);
Tnew=linspace(1,length(ds.Files),nY);
%X=double(1:dX);
%Vnew=linspace(double(1),double(dX),double(nX));

Lambda=CRVAL1+double((x1:x2))*CDELT1;
Velocity=(Lambda-Lambda0)/Lambda0*c;
   
Y=linspace(OBS_DATE(1),OBS_DATE(length(ds.Files)),nY);
Y_PHASE=linspace(0,1,nY);

IMAGE=interp1(T,MATRIX,Tnew);
IMAGE_SUB=interp1(T,MATRIX_SUB,Tnew);

%IMAGE2=interp2(T,X,MATRIX(:,x1:x2),Tnew,Vnew);

T=1:length(ds.Files);
Tnew=linspace(0,1,nY);

IMAGE_PHASE=interp1(T,MATRIX,Tnew);


% At the end, create & display:
%
% 2D image in Velocity Vs JD-JD0
% 2D image in Velocity Vs Phase [0:1]
% 2D image + 3D graph (spectra) in Velocity Vs JD-JD0
% 2D image + 3D graph (spectra) in Velocity Vs Phase [0:1]
% Same with REF spectra substracted
%

%pcolor(Velocity,Y,IMAGE),shading interp,colormap gray;
%pcolor(IMAGE),shading interp,colormap gray;
%figure;
%surf(Velocity,Y,IMAGE),shading interp,colormap parula,colorbar,ylabel('JD-2458000'),xlabel('velocity (km/s)');
% colormap jet, colormap gray, colormap parula
% Use plot for 1D, pcolor for 2D and surf for 3D, contourf for art !
%contourf(Velocity,Y,IMAGE),shading interp,colormap gray,colorbar,ylabel('JD-2458000'),xlabel('velocity (km/s)');

% Note: whos VARIABLE gives structure information on the variable !

% 2D image in Velocity Vs JD-JD0
figure
pcolor(Velocity,Y,IMAGE),shading interp,colormap gray,colorbar,ylabel(['JD-' num2str(JD0)]),xlabel('velocity (km/s)'),title(Titre);

% 2D image in Velocity Vs JD-JD0 with REF spectrum substracted
figure
pcolor(Velocity,Y,IMAGE_SUB),shading interp,colormap gray,colorbar,ylabel(['JD-' num2str(JD0)]),xlabel('velocity (km/s)'),title(Titre);

% Graph 2D with all spectra (surface plot & 3D plot, time shifted
figure;
hold on
pcolor(Velocity,Y,IMAGE),shading interp,colormap parula,colorbar,ylabel(['JD-' num2str(JD0)]),xlabel('velocity (km/s)'),title(Titre);
for i=1:length(OBS_DATE)
    plot3(Velocity,ones(size(Velocity))*OBS_DATE(i),MATRIX(i,:))
end

% Graph 2D with all spectra (surface plot & 3D plot, folded in phased time
%figure
% hold on
% pcolor(Velocity,Y_PHASE,IMAGE_PHASE),shading interp,colormap parula,colorbar,ylabel('Phase'),xlabel('velocity (km/s)'),title(Titre);
%for i=1:length(OBS_DATE)
%    plot3(Velocity,ones(size(Velocity))*OBS_PHASE(i),MATRIX(i,:))
%end





dimanche 12 août 2018

Be Star Spectra call for observations

I recently read a very interesting review article on Be stars dated from 2013 that mention our work: "highly motivated amateur astronomers have begun to contribute to the field with spectroscopic observations of increasing quality, comparable to that ofsmall professional instruments. Spectra are made available to the community via the Be Star Spectra Database".

If you are interested in learning more about those very insteresting stars, check out this detailed review which explains very well the definition of Be stars (and what are NOT Be stars) as well as recent (past decade) learning on those objects:

There is also a more recent article (2017) on 28 Cygni that use several spectra from dozen of amateur taken back in 2015-2016 and while the star has not strongly active, spectra are showing some ineresting feature specially in 2016 with some changes seen. The article decribes very well what can be seen on Halpha spectra (EW, V/R, RV) and their meaning:


During the month of june, more than a hundred spectra were taken by 18 different observers. If you are also interested in helping acquiring Be stars spectra, specially with high resolution spectrograph (R>5000), I would recommend you to start practicing the BeSS file format and spectra acquisition/reduction with some bright targets. gamma Cassiopae is usually a good choice to start with, well visible in the sky. You can also start with beta Lyrae, whose Halpha spectrum is always changing.

Once you have a spectrum in BeSS format, you can contact one of the database administrator to check everything is okay. You can also submit it on BeSS databas (submission of a spectrum is actually your registration). There, your spectrum will be checked in terms of quality and compared to other's in the database:

Then, go to slightly fainter targets. Why not 28 Cygni for exemple, whose behavior is always of interest (see article above!). You can also pick lambda Cygni, omicron Andromedae or phi Andromedae as those three stars are under a special scrutiny at the moment, looking for drastic changes in their Halpha profile, sign of an outburst!

Again, simply submit your spectra on BeSS database whre it will be checked. You can also do some prep analysis by downloading a recent spectrum from BeSS - a fully public access - and comparing to yours. Check specifically for telluric lines which should be at the same position (wavelength calibration quality control!) and shape of the line similar (good check on instrumental response for exemple).
Look for spectra taken with similar equipment than yours and compare acquisition time and overall noise on the continuum - are they similar, better or maybe some hints of improvement?

Then, there are plenty of other Be stars to look at. ARASBeAm provides a list, every night, on Be stars to observe by comparing the last spectrum date and the expected observation period. Targets are displayed in red when they should abolutely be observed, yellow when it is recommended to observe them and green when they are not a priority (but you can still observe them). Check out ARASBeAm website:


Be Star Spectra is not only interesting from a scientific point of view (cf the two proposed articles - and more!) but they also help you to progress in general stellar specrocopy. So do not hesitate to join in.

There is just one warning... once you get hooked, you will love it! :-)

samedi 11 août 2018

reading Note: classical Be stars

I have been reading some articles on Be stars and I found out an excellent review by Thomas Rivinius , Alex C. Carciofi & Christophe Martayan: Classical Be Stars, Rapidly Rotating B Stars with Viscous Keplerian Decretion Disks. It was published in 2013.

I also liked the more recent article (2017) by Baader et al: Short-term variability and mass loss in Be stars - III - BRITE and SMEI satellite photometry of 28 Cygni - a very nice review of the non radial pulsations seen in this Be star.

Here are some of my notes taken from the article read - of course all mistakes would be mine! But this explains why I have such interest in Be stars: they are bright but still very mysterious, even if some veils were lifted in the past decade... :-)


Ten years after the excellent review by Porter & Rivinius published in 2003, the authors first clarifies the definition of Be stars: a non-supergiant B star whose spectrum has, or had at some time, one or
more Balmer lines in emission.

This is actually the first time that this definition is clarified as they list stars that are NOT Be stars while they could look like from the definition above:
-Herbig Ae/Be: young object with acretion disk, while classical Be stars have actually decretion disks;-mass transfering binaries: typical Algol or W UMa binaries sometimes show emission lines but this comes from the mass transfered from one star to the other one, different mechanism than classical Be stars;
-B[e] stars also show forbidden lines. There are different types of B[e] stars, some could say that thre is almost one category for each B[e] star! But their mechanism is also different than classical Be stars even if they could show a disk shape circum stellar material;
-magnetic B stars can sometimes show emission line. Circum stellar environment shows variability with exactly the same period as the photosphere, thus making them different to classical Be stars;
-Oe stars can sometimes be considered as the blue extension of Be stars but some spectropolarimetry observation tend to show otherwise;
-A & F shell stars could also be considered as the red extension of Be stars group within the HR diagram but some study show that they could be closer to Herbig Ae/Be stars thus they should not included in the classical Be stars group.

Of course, supergiant B stars such as P Cygni while considered originally as part of the same group were quickly look as different mechanism to eject mass (winds typically), are clearly not Be stars as the definition states.


Variability on all time scale is a clear characteristic of classical Be stars. One can see variations over several decades, with for exemple period of quiescence and no emission at all is mixed with period with visible emission line. But variation of several days, hours or even minutes can also be seen, leading to a wide variety of astrohysical phenomena!

Be star spectra (typically Halpha) can lead to different measurements:
-EW (Equivalent Width) is a measurement of the line strength. Some times, emission can lead to tens of Angstroems of EW.
-V/R is the ratio, when the emission line is double peak, of the Violet peak intensity by the Red peak intensity. Sometimes the continuum is substracted, sometimes even the photospheric absorption profile. So if you do similar measurements, make sure to always detail the definition of your V & R measurements.
Usully variable within weeks to decade, short time variation are usually binarity driven and longuer ones linked to the disk itself.
Variations within few days are closer to the photosphere. Transportation of material from the star to the disk usually takes days or weeks at most. Stellar rotation and typical pulsations period fall into that range too.
Variation of less than half a day are often beta Cep pulsations modes, specially in early type Be stars.

Cyclic asymetry of the emission lines can also be linked to global waves over the disk, very similar to acretion disk phenomenon seen in young objects. But remember that for Be stars, disk are decretion ones.


Of course, Be stars are observed with other technics than spectroscopy, such as:
-(spectro)Polarimetry: light emitted from the star isn't polarized but when the light is scattered by the free electrons in the ionized disk, it becomes polarized. Spectropolarimetry is also a powerful tool to measure magnetifc field, even if those are very weak in massive stars such as Be stars.
-Interferometry had been developped in recent years and both stars and disk have been observed with this technics, only available for large and/or close stars.
-Spectroastrometry
-Photometry, specially space based high frequency precise photometry (BRITE, SMEI, CoRoT, Kelper...), leading to very fine study of the pulsations modes of the Be stars. Ground based photometry are also important as geometry changes in how we see the Be star system (in case of binarity) lead to variation of the absolute flux received to us.

Anyway, check out those two articles, they are very interesting to read:
https://arxiv.org/abs/1310.3962
https://arxiv.org/abs/1708.07360



Reading in the pool... :-)

dimanche 5 août 2018

OTZ_Auto : finally some automatic observations !

For the last 12 nights, I have been working on a script under PRISM v10 to automate my observations.

First, I groupes together my starting sequence and add some lines to handle the GemBird Power Manager USB and LAN multiple plugs. I have been able to automate completely the sequence except telescope equipment connexion (for some reason, it doesn't work but I haven't spend too much time on this yet), the Power Manager USB connexion (it fails very often) and the telescope resynch at the beginning.
Then I added a way to point to a target with some trick to take care of my strong DEC backlash of my Losmandy Titan mount.




Last, I added the end of night code to close all the equipment and switch off the Power Managers plugs.

Of course it doesn't run always as I wanted, mostly because my coding is "quick & dirty" but I have been able to acquire around 60 spectra (Halpha alone) during 12 nights. I have been able to reach 6-7 targets per night while previous method (run a sequence, go to sleep, wake up, change target, etc...) was running 3 targets usually per night!



What a pleasure to read "DONE" when I wake up, with telescope & cameras stopped and dome closed. I can quickly check with TeamViewer that the script went okay...


I can also quickly look at the guiding image fields (to check the target is the right one) and then reduce all spectra in ISIS and post them on BeSS. I completed the script with a DOS batch to clean up all the temporary files and sort my raw/reduced data in proper directories at the end.

So the script is now at its first version and works fine for me even if some steps at the beginning are manual and I sometimes have trouble with the first autoguiding. It is based on brightest star in the field and tere are LOT of improvement to be added: include a true scheduler, handle weather management, star hopping GoTo for large telescope movements, astrometry, etc... But it does the job for now.

Here is the code for those wanting to play with it, it is delivered "as is" of course.

/////////////////////////////////////////////////////////////////////////////////
//                                                                                                                                                                             //
//                                   OTZ_Auto - Script to observe automatically (c) Olivier Thizy                              //
//                                                                                                                                                                             //
/////////////////////////////////////////////////////////////////////////////////
//
// Some specificities to equipment used:
// -Losmandy Titan mount with strong backlash in Delta
// -echelle spectrograph with Velmann board to control calibration lamps
// -observing bright Be star as primary focus
// -Atik 460ex for spectra acquisition
// -Atik Titan for guiding
// -Dome (controled by Dome TRacker)
// -RoboFocus
//
// BUGS / ROBUSTNESS
// ------------------
// -if object$ is not recognize: skip target
// -end of night, dome disconnected?
// -improve how brighteststar works + error management
// -replace USB by LN gembird
// -pb with telescope connexion (hardware?)
// -sometimes fails at first autoguiding, root cause not found yet
//
// WEATHER MANAGEMENT
// -------------------
// -calibrate Sentinel cloud sensor
// -wait for good weather
// -check weather: pause
// -multiple pause: close equipment
// -rain detection -> wiring to dome tracker
// -sentinel relay script activation
//
// IMPROVEMENTS
// -------------
// -create at the end a clean list at the end of targets acquired + Exp Time + Nb of exposures + Max(kADU) + Elevation (copy/paste in Excel ObsLog)
// -automatic guiding exposure based on Vmag
// -catalog of Be stars with Vmag, ra, dec, HD #, exposure time & nbExposures
// -automatic scheduling based on priority & time allocation
// -catalog of bright isolated stars
// -goto with star hopping
// -improve simulator mode to estimate the total time of a session
// -add management of star to Synch at the end of a session to "park" scope
// -stop telescope tracking while waiting for next target
// -use external text file for the list of targets, read it every loop to allow change during the night/session
//
// REVISION HISTORY
// ----------------
// -05/08/2018: first "stable version", target list inside script, some bugs (telescope connexion, USB Gembird, first autoguiding).
//    Lack weather management, good target catalog, star hopping method for large GoTo, etc... some comments in french.
//    Based on brightest star in the field, very specific to my own equipment. 60 Be stars spectra (Halpha) acquired so far with the script.
//
/////////////////////////////////////////////////////////////////////////////////

print "OTZ_Auto: automatic observation script (c) Olivier Thizy"
print "Version of 05/08/2018"

// Key debug/temporary parameters to control manual interventions...
//     OpenDomeManually: Set to 1 if you want to open dome manually (to wait for better sky conditions for exemple)
//     RequestManualInitialSynch: set to 1 if you want to manually synch telescope to first star
//     CheckIfPowerManagerIsOK: set to 1 to make a double check of the Power Manager as USB isn't always working properly
//     ConnectTelescopeManually: set to 1 if you want to connect manually telescope/equipment in prism
//   Simulation: set to 1 to estimate the ability to run the night with the given targets
// Note: for full automated observations all parameters should be to 0
OpenDomeManually=1
CheckIfPowerManagerIsOK=0
ConnectTelescopeManually=1
RequestManualInitialSynch=1
Simulation=0

//
// General parameters
//
// do not point telescope past meridian
AngleHorMin=0
// do not observe below... (in °)
HauteurMin=40
// fiber position
GuidePosX=291.0
GuidePosY=213.0
// For Atik 460ex camera, cooling in 15 minutes to -10°C (winter) or 0°C (summer) seems enough
minutestogodowntotemp=20
Detectortemperature=0.0
// Elevation of the sun at which we start the instrumentation (degrees converted to radians)
// I usually start equipment when Sun is below 0°, start calibration when below 4° in order to start observing when below -8°
elevsunstartinitnight_Deg=-1.0
elevsunstartbegnight_Deg=-4.0
elevsunstartobservations_Deg=-7.0
elevsunstopobservations_Deg=-7.0
// CCD numbers
GuidingCamNumber=1
AcqCamNumber=2
// difference between local time and UT
deltaUT=-1
// time (in milliseconds) to wait after GoTo so dome can be synch' with telescope
WaitForDomeTime=60000
// Sentinel weather station parameters
LimitTempCiel=-100.0
LimitMagnitudeCiel=-100.0
ValMinBelleMeteo=5
// for simulation purposes
TotalExpTimeForSession=0


if Simulation=0 then
    Now Date
    Datetostr Date Date$
    print "[" Date$ "] Starting Calibration sequence"

//    GoSub Start_and_Calib:

    Now Date
    Datetostr Date Date$
    print "[" Date$ "] Calibration sequence done"
endif



// Just to test it...
//GoSub BoucleAttendBeauTemp:

if Simulation=0 then
    // Resynch telescope on delta Her
    if RequestManualInitialSynch=1 then
        Input "TEST: ensure telescope is synch (& focused ?) near to first target - then press ENTER" Dummy$
    else
    goto SkipThisSynch:
        // Synch sequence for the beginning of the bight
        // bet Oph
        objet$="hd161096"
        GExpTime=0.1
        GoSub StarHopping:
        // zet Aql
        objet$="hd177724"
        GExpTime=0.1
        GoSub StarHopping:
        // nu Oph
        objet$="hd163917"
        GExpTime=0.1
        GoSub StarHopping:
        // eta Ser
        objet$="hd68723"
        GExpTime=0.1
        GoSub StarHopping:
    SkipThisSynch:
    endif
endif

Target[1]$="QRVul"
Target[2]$="lamCyg"
Target[3]$="omiAnd"
Target[4]$="V442And"
Target[5]$="phiAnd"
Target[6]$="V549Per"
NbTargets=6

for NumeroObject=1 to NbTargets
    Object$=Target[NumeroObject]$
    if Simulation=0 then
        GoSub TakeObject:
    else
        GoSub LookUpObject:
        TotalExpTimeForSession=TotalExpTimeForSession+ExpSec*NbExposure
    endif
next NumeroObject


if Simulation=1 then
    str TotalExpTimeForSession TotalExpTimeForSession$
    TotalExpTimeForSessionMin=(TotalExpTimeForSession/60)
    round TotalExpTimeForSessionMin TotalExpTimeForSessionMin
    str TotalExpTimeForSessionMin TotalExpTimeForSessionMin$
    TotalExpTimeForSessionHours=(TotalExpTimeForSession/3660)
    round TotalExpTimeForSessionHours TotalExpTimeForSessionHours
    str TotalExpTimeForSessionHours TotalExpTimeForSessionHours$
    print "Total Exposure should be: " TotalExpTimeForSession$ " sec., " TotalExpTimeForSessionMin$ " min., " TotalExpTimeForSessionHours$ " hours."
    end
endif

GoTo FinishScriptHere:

EndOfSession:
// END OF SESSION
print "-----------------------------------------------------------"
EquipmentClosed=0
// Synch on bet And first
GoSub IsSunStillBelow:
if SunStillBelow=1 then
    objet$="hd6860"
    GExpTime=0.1
    GoSub StarHopping:
else
    GoSub endnight:
    GoTo EndOfMainSequence:
endif
// Synch on eta Psc then
GoSub IsSunStillBelow:
if SunStillBelow=1 then
    objet$="hd9270"
    GExpTime=0.1
    GoSub StarHopping:
else
    GoSub endnight:
    GoTo EndOfMainSequence:
endif


FinishScriptHere:
GoSub endnight:

EndOfMainSequence:

// Et message de fin...
Now Date
Datetostr Date Date$
print "[" Date$ "] That's all folks..."

sOutput$=" "
Print sOutput$

sOutput$="DDD     OOO  N    N EEEEE"
Print sOutput$
sOutput$="D  D   O   O N N  N E    "
Print sOutput$
sOutput$="D   D  O   O N  N N EEE  "
Print sOutput$
sOutput$="D  D   O   O N   NN E    "
Print sOutput$
sOutput$="DDD     OOO  N    N EEEEE"
Print sOutput$

sOutput$=" "
Print sOutput$


END



/////////////////////////////////////////////////////////////////////////////////
//
// Goto a target, center object, run autoguiding and acquire spectra
//
/////////////////////////////////////////////////////////////////////////////////
GoToTargetAndAcquisition:


print "-----------------------------------------------------------"

REM Coordonnées équatoriales de l'objet en radians
GETOBJECTCOORD objet$ alpha delta

if alpha=-100
  Now Date
  Datetostr Date Date$
  print "[" Date$ "] L'objet " objet$ " n'est pas reconnu par PRISM !"
  return
endif

str alpha alphaRad$
str delta deltaRad$
RAD_TO_RA  alpha alpha$
RAD_TO_DEC delta delta$

Now Date
Datetostr Date Date$
PRINT "[" Date$ "] " Object$ " (" objet$ ") is at coordinates :"
PRINT "[" Date$ "] RA  : " alpha$ " (" alphaRad$ " radians)"
PRINT "[" Date$ "] DEC : " delta$ " (" deltaRad$ " radians)"

//Longitude du lieu = celle du site par défaut
GETSTDRLONGITUDE Longitude
// Latitude du lieu
GETSTDRLATITUDE Latitude
// Loop to wait for the target to reach proper altitude in the sky
LoopWaitHauteur:
// Date du moment :
NOW Date
// Hauteur de l'objet en radian :
GETHEIGHT alpha delta Date Longitude Latitude Hauteur
// Hauteur en degrés
Hauteur=Hauteur*TODEG

if Hauteur<HauteurMin then
   stoptelescope
   DelayBlock 60000
   Goto LoopWaitHauteur:
endif


// Look for telescope position at the end of acquisition to check if not past meridian+limit / give 50% margin to allow half exposure...
// TSL pour calculer angle horaire
SIDERALTIME Date Longitude TSL
// Angle horaire objet en radian :
COMPUTEANGLEHOR TSL alpha AngleHor
//Angle horaire en heures décimales:
AngleHor=AngleHor*12/PI
AngleHorEndOfExposure=AngleHor+((ExpSec*NbExposure)/3600.0)/2.0

AngleHorLimit=0.0
// si DEC<45°: 10min supplémentaires
if delta<(45.0/180.*3.1415) then
    AngleHorLimit=10.0/60.0
endif
// si DEC<30°: 20min supplémentaires
if delta<(30.0/180.*3.1415) then
    AngleHorLimit=20.0/60.0
endif
// si DEC<25°: 1h10 supplémentaires
if delta<(25.0/180.*3.1415) then
    AngleHorLimit=70.0/60.0
endif
// si DEC<6°: 1h45 supplémentaires
if delta>(6.0/180.*3.1415) then
    AngleHorLimit=105.0/60.0
endif

if AngleHorEndOfExposure>AngleHorLimit
   Now Date
   Datetostr Date Date$
   print "[" Date$ "] Target at the end of the sequence will be at hour angle: " AngleHorEndOfExposure " so target skipped"
   return
endif


// Pointage ou non ?
If AngleHor<AngleHorMin then
    If Hauteur>HauteurMin then
        str Hauteur Hauteur$
        Now Date
        Datetostr Date Date$
        print "[" Date$ "] GoTo Target at Elevation : " Hauteur$ "°"
        MoveTelescope alpha delta
        WaitForEndMoveTelescope
        DelayBlock 20000
        deltaplus=delta+0.003
        MoveTelescope alpha deltaplus
        WaitForEndMoveTelescope
        DelayBlock 10000
        // Je pointe un peu en dessous de la fibre pour toujours arriver par ce côté pour le centrage/guidage
        deltaplus=delta+0.00015
        MoveTelescope alpha deltaplus
        WaitForEndMoveTelescope
        DelayBlock 10000
    Else
        Now Date
        Datetostr Date Date$
        print "[" Date$ "] Target too low"
        return
    EndIf
Else
    Now Date
    Datetostr Date Date$
    print "[" Date$ "] Target too close to meridian"
    return
EndIf

Now Date
Datetostr Date Date$
print "[" Date$ "] Telescope at target position now"


// Wait for the dome
Now Date
Datetostr Date Date$
print "[" Date$ "] Waiting for the dome"
DelayBlock WaitForDomeTime
Now Date
Datetostr Date Date$
print "[" Date$ "] Dome should be at telescope position now"


REM *** calculating night's date

NOW year month day hour minute second MS

lengthmonth[1]=31
REM bissextile years
yearfrac=year/4
frac yearfrac bissextile
if bissextile=0 then
   lengthmonth[2]=29
else
   lengthmonth[2]=28
endif
lengthmonth[3]=31
lengthmonth[4]=30
lengthmonth[5]=31
lengthmonth[6]=30
lengthmonth[7]=31
lengthmonth[8]=31
lengthmonth[9]=30
lengthmonth[10]=31
lengthmonth[11]=30
lengthmonth[12]=31

if hour<12 then
   if day=1 then
      if month=1 then
         year=year-1
         month=12
         day=31
      else
         month=month-1
      endif
      day=lengthmonth[month]
   else
      day=day-1
   endif
endif

str year year$

str month month$
if month<10 then
   month$="0"+month$
endif

str day day$
if day<10 then
   day$="0"+day$
endif

CurrentDate$=year$+month$+day$

// set directory to save file and copy CALIB files in
sDirSave$="C:\Users\ObsBE\Documents\Acquisitions\"+CurrentDate$+"_eShel101_Atik460-1x1_38420_Revel\"


// Centrage étoile la plus brillante sur la consigne
GExpTimeMilSec=GExpTime*1000
GExpTimeChamp=GExpTimeMilSec*10
StartExposure_EX 1 GExpTimeMilSec
WaitForEndExposure_EX 1
GetLastImageExposure_EX 1 ImgChampToCenter
sFullPath$=sDirSave$+"ATIK HS "+Object$+"_center.fits"
SAVEFIT ImgChampToCenter sFullPath$
MinDynamiqueAutoguidage=500
MaxDynamique=55000
MaxOmC=900
PSFMin=3
DemLargFenCentro=32
ZoneRecherche=26
BRIGHTEST_STAR ImgChampToCenter MinDynamiqueAutoguidage MaxDynamique MaxOmC PSFMin DemLargFenCentro ZoneRecherche XGuideCentro YGuideCentro
if XGuideCentro<0 then
   Now Date
   Datetostr Date Date$
   print "[" Date$ "] Star not found, skipping target"
   return
endif
if YGuideCentro<0 then
   Now Date
   Datetostr Date Date$
   print "[" Date$ "] Star not found, skipping target"
   return
endif
str XGuideCentro XStar$
str YGuideCentro YStar$
Now Date
Datetostr Date Date$
print "[" Date$ "] Star found at position " XStar$ ", " YStar$
// Je centre un peu en dessous de la fente pour que l'autoguidage fonctionne toujours dans ce sens (tube à l'Ouest)
GuidePosYDecale=GuidePosY-5
str GuidePosX GuidePosX$
str GuidePosY GuidePosY$
str GuidePosYDecale GuidePosYDecale$
Now Date
Datetostr Date Date$
print "[" Date$ "] Centering at position " GuidePosX$ ", " GuidePosYDecale$ "; Fiber at " GuidePosX$ ", " GuidePosY$
OFFSET_TELESCOPE ImgChampToCenter XGuideCentro YGuideCentro GuidePosX GuidePosYDecale
WAITFORENDMOVETELESCOPE
DelayBlock 2000
CLOSE ImgChampToCenter

GExpTimeChamp=GExpTimeMilSec*40
StartExposure_EX 1 GExpTimeChamp
WaitForEndExposure_EX 1
GetLastImageExposure_EX 1 ImgChamp


// Sauvegarde de l'image de guidage surexposée (FITS et JPG)
sFullPath$=sDirSave$+"ATIK HS "+Object$+".fits"
SAVEFIT ImgChamp sFullPath$
sFullPath$=sDirSave$+"ATIK HS "+Object$+".jpg"
SAVEJPG ImgChamp sFullPath$
CLOSE ImgChamp

DelayBlock 5000
   

// Run autoguiding
NumCam=1
CCDNum=1
DelayACQSec=5
WindowSize=200
CentroSize=25
StarThresADU=200
RaMin=5.0
RaMax=210
DecMin=5.0
DecMax=210
Backlash=0
CurrentDEC=0
AlarmEnabled=0
GuidePosX=291.0
GuidePosY=213.0
DeltaMoveFashion=0
SaveImagettes=0
DirSaveImg$="c:\ccd"
AllFrame=1
AgressRA=0.4
AgressDEC=0.4
WindowAllFrame=400

Now Date
Datetostr Date Date$
print "[" Date$ "] Autoguidage ON"
STARTGUIDECONSIGNE NumCam CCDNum GExpTime DelayACQSec WindowSize CentroSize StarThresADU AgressRA AgressDEC RaMin RaMax DecMin DecMax Backlash CurrentDEC AlarmEnabled DeltaMoveFashion GuidePosX GuidePosY SaveImagettes DirSaveImg$ AllFrame WindowAllFrame Valid message$

DelayBlock 5000

str Valid Valid$
Now Date
Datetostr Date Date$
print "[" Date$ "] Valid: " Valid$ " / Status: " message$

/////////////////////
// Acquiring Target
/////////////////////
ExpTime=ExpSec*1000


REM StatWindow Img  X1  Y1  X2  Y2  Mean  Quadratic_mean  Stddev  Max  Min  Flux  Median
HaX1=864
HaY1=1710
HaX2=984
HaY2=1722
ContX1=1543
ContY1=1640
ContX2=1588
ContY2=1189

WinPosX=500
WinPosY=100
WinSizeX=1000
WinSizeY=1000



str ExpSec ExpSec$
str NbExposure NbExposure$

sOutput$="Starting sequence for Target: "+Object$+" ("+NbExposure$+" x "+ExpSec$+" seconds)"
    Now Date
    Datetostr Date Date$
    print "[" Date$ "] " sOutput$
sOutput$="Target filename: "+Object$
Now Date
Datetostr Date Date$
print "[" Date$ "] " sOutput$

GetStdrLongitude Longitude
GetStdrLatitude Latitude
    Now Date
    Datetostr Date Date$
    print "[" Date$ "] Longitude = " Longitude*TODEG " Latitude = " Latitude*TODEG
Now Date
GETRADECSUN  Date  AlphaS  DeltaS  sunelevation
Datetostr Date Date$
RAD_TO_DEC sunelevation ElevationS$
GET_TELESCOPE_POSITION Alpha2000 Delta2000 Hauteur Azimuth AngleHor
Hauteur=Hauteur*TODEG
AngleHor=AngleHor*TODEG/15.0
round Hauteur Hauteur
AngleHor=AngleHor*10.0
round AngleHor AngleHor
AngleHor=AngleHor/10.0
str Hauteur Hauteur$
str AngleHor AngleHor$
print "[" Date$ "] Sun at " ElevationS$ "°, Telescope at " Hauteur$ "° & Hour Angle: " AngleHor "h"

MaxHaAvg=0
MaxContAvg=0
NbMeasures=0

For i=1 NbExposure
  // Ensure proper Dome tracking - just to make sure...
  DOME_SET_CONTROL 1 1

  GoSub CanIContontinueToObserve:

  if ContinueObservations=0 then
    Now Date
    Datetostr Date Date$
    print "[" Date$ "] Sun too high, stopping observations"
    GoTo EndOfGoToTargetAndAcquisition:
  endif
 
  StartExposure_EX 2 ExpTime
  WaitForEndExposure_EX 2
  GetLastImageExposure_EX 2 img

  STR i i$
  sFullPath$=sDirSave$+Object$+"-"+i$+".fits"
  SAVEFIT img sFullPath$


  StatWindow Img  HaX1  HaY1  HaX2  HaY2  Mean  Quadratic_mean  Stddev  Max  Min  Flux  Median
  MaxHa=Max-Min
  MaxHaAvg=MaxHaAvg+MaxHa
  NbMeasures=NbMeasures+1
  str MaxHa MaxHa$
  StatWindow Img  ContX1  ContY1  ContX2  ContY2  Mean  Quadratic_mean  Stddev  Max  Min  Flux  Median
  MaxCont=Max-Min
  MaxContAvg=MaxContAvg+MaxCont
  str MaxCont MaxCont$
  sOutput$=">>> "+i$+" <<< : Max. Ha="+MaxHa$+" / Continuum="+MaxCont$
  Now Date
  Datetostr Date Date$
  print "[" Date$ "] " sOutput$
  GetStdrLongitude Longitude
  GetStdrLatitude Latitude
  Now Date
  GETRADECSUN  Date  AlphaS  DeltaS  sunelevation
  Datetostr Date Date$
  RAD_TO_DEC sunelevation ElevationS$
  GET_TELESCOPE_POSITION Alpha2000 Delta2000 Hauteur Azimuth AngleHor
  Hauteur=Hauteur*TODEG
  AngleHor=AngleHor*TODEG/15.0
  round Hauteur Hauteur
  AngleHor=AngleHor*10.0
  round AngleHor AngleHor
  AngleHor=AngleHor/10.0
  str Hauteur Hauteur$
  str AngleHor AngleHor$
  print "[" Date$ "] Sun at " ElevationS$ "°, Telescope at " Hauteur$ "° & Hour Angle: " AngleHor "h"

  SetWindowPos img WinPosX WinPosY
  SizeWindowX img WinSizeX
  SizeWindowY img WinSizeY

  Close img
  DelayBlock 3000

Next i

EndOfGoToTargetAndAcquisition:

if NbMeasures>0 then
  MaxHaAvg=MaxHaAvg/NbMeasures
  round MaxHaAvg MaxHaAvg
  MaxContAvg=MaxContAvg/NbMeasures 
  round MaxContAvg MaxContAvg
  str MaxHaAvg MaxHaAvg$
  str MaxContAvg MaxContAvg$
  Now Date
  Datetostr Date Date$
  print "[" Date$ "] STATISTICS: Halpha at " MaxHaAvg$ ", continuum at: " MaxContAvg$
endif

Now Date
Datetostr Date Date$
print "[" Date$ "] Stopping autoguiding"
StopGuide_Ex 1 1

// Synchronise télescope sur la cible pointée (car ça a bougé pendant l'autoguidage)
Now Date
Datetostr Date Date$
print "[" Date$ "] Resynch telescope on position"
CALIBRATE_TELESCOPE alpha delta


return


/////////////////////////////////////////////////////////////////////////////////
//
// Start_and_Calib - Routine to beign the night: connecting equipment, spectral calibration, opening dome...
//
/////////////////////////////////////////////////////////////////////////////////

Start_and_Calib:


// Switch ON Gembird USB & LAN multiplug
if CheckIfPowerManagerIsOK=1 then
    Input "Please check Power Manager is ON, OK and connect to USB socket - then press ENTER" Dummy$
else
    ExecExternal "C:\Program Files\Power Manager\pm.exe" ""
    delayBlock 3000
    Now Date
    Datetostr Date Date$
    print "[" Date$ "] Power Manager started"
endif

REM Switch ON the power for the mount, dome & focuser
Now Date
Datetostr Date Date$
print "[" Date$ "] Switching mount, dome & robofocus ON"
ExecExternal "C:\Program Files\Power Manager\pm.exe" "-on -Device3 -Mount"
delayBlock 1000
ExecExternal "C:\Program Files\Power Manager\pm.exe" "-on -Device3 -DomeTracker"
delayBlock 1000
ExecExternal "C:\Program Files\Power Manager\pm.exe" "-on -Device3 -RoboFocus"
if ConnectTelescopeManually=1 then
    Input "Please connect Telescope/Dome/Focuser in PRISM... and press ENTER" Dummy$
else
    delayBlock 15000
    Now Date
    Datetostr Date Date$
    print "[" Date$ "] Connecting to Telescope/Dome/Focuser"
    CONNECT_OBSERVATORY Valid
    delayBlock 30000
endif
Now Date
Datetostr Date Date$
print "[" Date$ "] Stopping the sidereal tracking"
stoptelescope
Now Date
Datetostr Date Date$
print "[" Date$ "] Set dome moving on telescope tracking & GoTo"
DOME_SET_CONTROL 1 1
delayBlock 3000


REM *** calculating night's date

NOW year month day hour minute second MS

lengthmonth[1]=31
REM bissextile years
yearfrac=year/4
frac yearfrac bissextile
if bissextile=0 then
   lengthmonth[2]=29
else
   lengthmonth[2]=28
endif
lengthmonth[3]=31
lengthmonth[4]=30
lengthmonth[5]=31
lengthmonth[6]=30
lengthmonth[7]=31
lengthmonth[8]=31
lengthmonth[9]=30
lengthmonth[10]=31
lengthmonth[11]=30
lengthmonth[12]=31

if hour<12 then
   if day=1 then
      if month=1 then
         year=year-1
         month=12
         day=31
      else
         month=month-1
      endif
      day=lengthmonth[month]
   else
      day=day-1
   endif
endif

str year year$

str month month$
if month<10 then
   month$="0"+month$
endif

str day day$
if day<10 then
   day$="0"+day$
endif

CurrentDate$=year$+month$+day$


REM *** set directory to save file and copy CALIB files in
sDirSave$="C:\Users\ObsBE\Documents\Acquisitions\"+CurrentDate$+"_eShel101_Atik460-1x1_38420_Revel\"
createdir sDirSave$
createdir sDirSave$+"CALIB"
ExecExternal "C:\Users\ObsBE\Documents\Acquisitions\CALIB\CopyDirs.bat" sDirSave$+"CALIB"
createdir sDirSave$+"Poubelle"
createdir sDirSave$+"Raw"
createdir sDirSave$+"Resultats"
Now Date
Datetostr Date Date$
print "[" Date$ "] Tonight directory is: "+sDirSave$




REM *** Waiting for the Sun to be below "elevsunstartinitnight" to start initialising CCD
GetStdrLongitude Longitude
GetStdrLatitude Latitude
REM print "Longitude = " Longitude*TODEG " Latitude = " Latitude*TODEG

elevsunstartinitnight=elevsunstartinitnight_Deg/TODEG

beginnighttime:
Now Date
Datetostr Date Date$
GETRADECSUN  Date  AlphaS  DeltaS  sunelevation
RAD_TO_DEC sunelevation ElevationS$
if sunelevation>0
   position$="above"
else
   position$="below"
endif
print "[" Date$ "] Sun at " ElevationS$ position$ " horizon (Tgt: " elevsunstartinitnight_Deg "°)"
if sunelevation>elevsunstartinitnight
   delayBlock 60000
   goto beginnighttime:
endif
Now Date
Datetostr Date Date$
print "[" Date$ "] The sun is now " ElevationS$ " degrees below horizon, starting up camera and mount"


REM Switch ON Gembird LAN multiplug: calibration unit & Atik460 CCD camera
ExecExternal "C:\Program Files\Power Manager\pm.exe" "-on -GemBirdLAN -Atik460"
Now Date
Datetostr Date Date$
print "[" Date$ "] Atik 460 camera power ON now"

delayBlock 10000
  

REM *** Initialisations CCDs
Now Date
Datetostr Date Date$
print "[" Date$ "] Connect/Initialise guiding (#1) & acquisition (#2) cameras; cooling the main one"
GoSub init_camera:


elevsunstartbegnight=elevsunstartbegnight_Deg/TODEG

REM *** Waiting for the sun to be below "elevsunstartbegnight", then start telescope & open dome
waittillstarttime:
Now Date
GETRADECSUN  Date  AlphaS  DeltaS  sunelevation
Datetostr Date Date$
RAD_TO_DEC sunelevation ElevationS$
if sunelevation>0
   position$="above"
else
   position$="below"
endif
print "[" Date$ "] Sun at " ElevationS$ position$ " horizon (Tgt: " elevsunstartbegnight_Deg "°)"
if sunelevation>elevsunstartbegnight
   delayBlock 60000
   goto waittillstarttime:
endif
Now Date
Datetostr Date Date$
print "[" Date$ "] The sun is now " ElevationS$ " degrees below horizon, starting the observations"


REM echelle calibration
REM Switch ON Gembird LAN multiplug: calibration unit
Now Date
Datetostr Date Date$
print "[" Date$ "] Switch calibration unit ON & start spectral calibration"
ExecExternal "C:\Program Files\Power Manager\pm.exe" "-on -GemBirdLAN -Calib"

delayBlock 3000
GoSub AcquireCalibration:

REM Switch OFF Gembird LAN multiplug: calibration unit
delayBlock 3000
Now Date
Datetostr Date Date$
print "[" Date$ "] Switch calibration unit OFF"
ExecExternal "C:\Program Files\Power Manager\pm.exe" "-off -GemBirdLAN -Calib"


REM *** Waiting for the Sun to be below "elevsunstartobservations" to start observations
GetStdrLongitude Longitude
GetStdrLatitude Latitude
REM print "Longitude = " Longitude*TODEG " Latitude = " Latitude*TODEG

elevsunstartobservations=elevsunstartobservations_Deg/TODEG

beginobservationtime:
Now Date
GETRADECSUN  Date  AlphaS  DeltaS  sunelevation
Datetostr Date Date$
RAD_TO_DEC sunelevation ElevationS$
if sunelevation>0
   position$="above"
else
   position$="below"
endif
Now Date
Datetostr Date Date$
print "[" Date$ "] Sun at " ElevationS$ position$ " horizon (Tgt: " elevsunstartobservations_Deg "°)"
if sunelevation>elevsunstartobservations
   delayBlock 60000
   goto beginobservationtime:
endif
Now Date
Datetostr Date Date$
print "[" Date$ "] The sun is now " ElevationS$ " degrees below horizon, starting up observations"


// Open DOME and start observations !


if OpenDomeManually=1 then
    Input "Please open Dome when ready - then press ENTER" Dummy$
else
    Open_Dome
    DelayBlock 30000
endif
Now Date
Datetostr Date Date$
print "[" Date$ "] Dome is now open"


Now Date
Datetostr Date Date$
print "[" Date$ "] Starting observing sequence..."


return




/////////////////////////////////////////////////////////////////////////////////
//
// Subroutine to initialize the camera, contains informations and settings of the camera
//
/////////////////////////////////////////////////////////////////////////////////

init_camera:

Now Date
Datetostr Date Date$
print "[" Date$ "] Connecting the Atik Titan guiding camera (1)"
cameraerror$=""
INIT_CCD_CAMERA_EX  GuidingCamNumber Valid  cameraerror$
if Valid=2 then
   nbinning=1
   SetBinningX_Ex GuidingCamNumber nBinning
   SetBinningY_Ex GuidingCamNumber nBinning
else
   Now Date
   Datetostr Date Date$
   print "[" Date$ "] ERREUR initialisation camera 1: Atik Titan"
   print cameraerror$
   EXIT
endif  

REM We start the camera
Now Date
Datetostr Date Date$
print "[" Date$ "] Connecting the Atik 460ex camera (2)"
Detector_number=2
CameraChannel=1
cameraerror$=""
INIT_CCD_CAMERA_EX  AcqCamNumber Valid  cameraerror$
if Valid=2 then
   nbinning=1
   SetBinningX_Ex AcqCamNumber nBinning
   SetBinningY_Ex AcqCamNumber nBinning
   for i=1 to minutestogodowntotemp
      GetCCDTemperature_Ex  AcqCamNumber CameraChannel Starttemperature
      deltaT=Detectortemperature-Starttemperature
      deltaTperminute=deltaT/minutestogodowntotemp
      Now Date
      Datetostr Date Date$
      print "[" Date$ "] Going from " Starttemperature " to " Detectortemperature " we need to cool " deltaTperminute " degrees per minute"
      Currenttemperature=Starttemperature+(deltaTperminute*i)
      round Currenttemperature Currenttemperature
      if Currenttemperature<Detectortemperature+0.2 then
         goto endcooling1:
      else
      SetCCDTemperature_Ex AcqCamNumber CameraChannel Currenttemperature
      Now Date
      Datetostr Date Date$
      print "[" Date$ "] " i " minute, CCD going down to " Currenttemperature " degrees"
      delayBlock 60000
      endif
   next i
else
   REM The camera didn't initialize correctly
   Now Date
   Datetostr Date Date$
   print "[" Date$ "] ERREUR initialisation camera 2: Atik 460ex"
   print cameraerror$
   EXIT
endif  

endcooling1:
Now Date
Datetostr Date Date$
print "[" Date$ "] END COOLING"
SetCCDTemperature_Ex AcqCamNumber CameraChannel Detectortemperature  
return


/////////////////////////////////////////////////////////////////////////////////
//
// Initializing the telescope / NOT USED...
//
/////////////////////////////////////////////////////////////////////////////////
init_telescope:
print "Connecting to the telescope"
OPEN_TELESCOPE_DEVICES 0 0
print "Connected"
print "stopping the sidereal tracking..."
stoptelescope
return



/////////////////////////////////////////////////////////////////////////////////
//
// End of night, closing telescope, camera, etc...
//
/////////////////////////////////////////////////////////////////////////////////
endnight:
REM We have to see how to bring the camera back to ambient temperature before closing it.
Now Date
Datetostr Date Date$
print "[" Date$ "] Observing is finished, so closing the telescope..."



REM Closing the telescope
//CLOSE_TELESCOPE_DEVICES
close_dome
delayBlock 20000
stoptelescope
delayBlock 4000
CLOSE_TELESCOPE_DEVICES
Now Date
Datetostr Date Date$
print "[" Date$ "] Telescope tracking stopped & dome closed, equipment closed"

REM Switch OFF the power for the mount, dome & focuser
ExecExternal "C:\Program Files\Power Manager\pm.exe" "-off -Device3 -Mount"
ExecExternal "C:\Program Files\Power Manager\pm.exe" "-off -Device3 -DomeTracker"
ExecExternal "C:\Program Files\Power Manager\pm.exe" "-off -Device3 -RoboFocus"
delayBlock 3000

Now Date
Datetostr Date Date$
print "[" Date$ "] Setting main camera temperature to positive (10°C) & wait 5 minutes"
Currenttemperature=20
CameraChannel=1
SetCCDTemperature_Ex AcqCamNumber CameraChannel Currenttemperature
delayBlock 300000

Now Date
Datetostr Date Date$
print "[" Date$ "] Closing cameras connexion"
CLOSE_CCD_CAMERA_EX 1
CLOSE_CCD_CAMERA_EX 2

Now Date
Datetostr Date Date$
print "[" Date$ "] Switching OFF mount, dome, robofocus and CCD cameras"

REM Switch OFF Gembird LAN multiplug: calibration unit & Atik460 CCD camera
ExecExternal "C:\Program Files\Power Manager\pm.exe" "-off -GemBirdLAN -Calib"
ExecExternal "C:\Program Files\Power Manager\pm.exe" "-off -GemBirdLAN -Atik460"
delayBlock 3000

Now Date
Datetostr Date Date$
print "[" Date$ "] End of night sequence done"

return


/////////////////////////////////////////////////////////////////////////////////
//
// Acquire calibration for the echelle spectrograph
//
/////////////////////////////////////////////////////////////////////////////////

AcquireCalibration:
REM Penser à enlever la sauvegarde automatique dans PRISM avant de lancer le script!

Object$="ref"

PoseThAr=60000
PoseTung=2800
PoseLEDs=2800
ON=1
OFF=0
Port1=1
Port2=2
Port3=3
Port4=4


Switchdesired=1
// Recupere l'etat des swiches d'un coup dans une table
GETSWITCH Switchdesired nbSwitches ArrayName ArrayState

sOutput$="Dir: "+sDirSave$
Now Date
Datetostr Date Date$
print "[" Date$ "]" sOutput$
sOutput$="Object: "+Object$
print "[" Date$ "]" sOutput$


REM =================
REM Miroir + Tungsten
REM =================
SETSWITCH Port1 ON
DelayBlock 1000
SETSWITCH Port4 ON
DelayBlock 1000

For i=1 33
  STR i i$
  StartExposure_EX AcqCamNumber PoseTung
  sFullPath$=sDirSave$+Object$+"_tung-"+i$+".fits"
  sOutput$="Tungsten: "+Object$+"_tung-"+i$+".fits"
  Now Date
  Datetostr Date Date$
  print "[" Date$ "]" sOutput$
  WaitForEndExposure_EX AcqCamNumber
  GetLastImageExposure_EX AcqCamNumber img
  SAVEFIT img sFullPath$
  Close img
Next i


REM =================
REM LEDs + Tungsten
REM =================
SETSWITCH Port2 ON
DelayBlock 1000

For i=1 3
  STR i i$
  StartExposure_EX AcqCamNumber PoseLEDs
  sFullPath$=sDirSave$+Object$+"_led-"+i$+".fits"
  sOutput$="Flat: "+Object$+"_led-"+i$+".fits"
  Now Date
  Datetostr Date Date$
  print "[" Date$ "]" sOutput$
  WaitForEndExposure_EX AcqCamNumber
  GetLastImageExposure_EX AcqCamNumber img
  SAVEFIT img sFullPath$
  Close img
Next i

DelayBlock 2000

SETSWITCH Port2 OFF
DelayBlock 2000

SETSWITCH Port4 OFF
DelayBlock 2000


REM =================
REM ThAr
REM =================
SETSWITCH Port3 ON
DelayBlock 3000

For i=1 3
  STR i i$
  StartExposure_EX AcqCamNumber PoseThAr
  sFullPath$=sDirSave$+Object$+"_thor-"+i$+".fits"
  sOutput$="ThAr: "+Object$+"_thor-"+i$+".fits"
  Now Date
  Datetostr Date Date$
  print "[" Date$ "]" sOutput$
  WaitForEndExposure_EX AcqCamNumber
  DelayBlock 1000
  GetLastImageExposure_EX AcqCamNumber img
  DelayBlock 1000
  SAVEFIT img sFullPath$
  Close img
  DelayBlock 1000
Next i

DelayBlock 3000

SETSWITCH Port3 OFF
DelayBlock 1000

SETSWITCH Port1 OFF
DelayBlock 1000

REM sOutput$="That's all folks"
REM Print sOutput$

return


/////////////////////////////////////////////////////////////////////////////////
//
// Star Hopping: Goto a target, center object, resynch telescope
//
/////////////////////////////////////////////////////////////////////////////////
StarHopping:

REM Coordonnées équatoriales de l'objet en radians
GETOBJECTCOORD objet$ alpha delta

if alpha=-100
  Now Date
  Datetostr Date Date$
  print "[" Date$ "] L'étoile " objet$ " n'est pas reconnu par PRISM !"
  return
endif

str alpha alphaRad$
str delta deltaRad$
RAD_TO_RA  alpha alpha$
RAD_TO_DEC delta delta$

Now Date
Datetostr Date Date$
PRINT "[" Date$ "] Utilisation de l'étoile " objet$ " pour du 'star hopping'"
PRINT "[" Date$ "] RA  : " alpha$ " (" alphaRad$ " radians)"
PRINT "[" Date$ "] DEC : " delta$ " (" deltaRad$ " radians)"

//Longitude du lieu = celle du site par défaut
GETSTDRLONGITUDE Longitude
// Latitude du lieu
GETSTDRLATITUDE Latitude
// Loop to wait for the target to reach proper altitude in the sky
LoopWaitHauteur:
// Date du moment :
NOW Date
// Hauteur de l'objet en radian :
GETHEIGHT alpha delta Date Longitude Latitude Hauteur
// Hauteur en degrés
Hauteur=Hauteur*TODEG

if Hauteur<HauteurMin then
   stoptelescope
   DelayBlock 60000
   Goto LoopWaitHauteur:
endif

// TSL pour calculer angle horaire
SIDERALTIME Date Longitude TSL
// Angle horaire objet en radian :
COMPUTEANGLEHOR TSL alpha AngleHor
//Angle horaire en heures décimales:
AngleHor=AngleHor*12/PI

// Pointage ou non ?
If AngleHor<AngleHorMin then
    If Hauteur>HauteurMin then
        Now Date
        Datetostr Date Date$
        print "[" Date$ "] Ca pointe !"
        MoveTelescope alpha delta
        str Hauteur Hauteur$
        Now Date
        Datetostr Date Date$
        print "[" Date$ "] Hauteur cible : " Hauteur$ "°"
        WaitForEndMoveTelescope
        Delay 10000
        WaitForEndDelay
        deltaplus=delta+0.003
        MoveTelescope alpha deltaplus
        WaitForEndMoveTelescope
        Delay 5000
        WaitForEndDelay
        // Je pointe un peu en dessous de la fibre pour toujours arriver par ce côté pour le centrage/guidage
        deltaplus=delta+0.00015
        MoveTelescope alpha deltaplus
        WaitForEndMoveTelescope
    Else
        Now Date
        Datetostr Date Date$
        print "[" Date$ "] Hauteur cible trop basse"
        return
    EndIf
Else
    Now Date
    Datetostr Date Date$
    print "[" Date$ "] Angle Horaire cible trop proche du méridien"
    return
EndIf

Now Date
Datetostr Date Date$
print "[" Date$ "] Pointage fini"


// Wait for the dome
Now Date
Datetostr Date Date$
print "[" Date$ "] Waiting for the dome"
Delay 60000
WaitForEndDelay
Now Date
Datetostr Date Date$
print "[" Date$ "] Dome should be at telescope position now"


// Centrage étoile la plus brillante sur la consigne
//OPEN ImgChamp "C:\Users\ObsBE\Documents\Acquisitions\20180719_eShel101_Atik460-1x1_38420_Revel\ATIK HS V442 And.fits"
GExpTimeMilSec=GExpTime*1000
GExpTimeChamp=GExpTimeMilSec*1
StartExposure_EX 1 GExpTimeMilSec
WaitForEndExposure_EX 1
GetLastImageExposure_EX 1 ImgChamp
MinDynamiqueAutoguidage=500
MaxDynamique=55000
MaxOmC=900
PSFMin=3
DemLargFenCentro=32
ZoneRecherche=26
BRIGHTEST_STAR ImgChamp MinDynamiqueAutoguidage MaxDynamique MaxOmC PSFMin DemLargFenCentro ZoneRecherche XGuideCentro YGuideCentro
if XGuideCentro<0 then
   Now Date
   Datetostr Date Date$
   print "[" Date$ "] Star not found, skipping target"
   return
endif
if YGuideCentro<0 then
   Now Date
   Datetostr Date Date$
   print "[" Date$ "] Star not found, skipping target"
   return
endif
str XGuideCentro XStar$
str YGuideCentro YStar$
Now Date
Datetostr Date Date$
print "[" Date$ "] Star found at position " XStar$ ", " YStar$
// Je centre un peu en dessous de la fente pour que l'autoguidage fonctionne toujours dans ce sens (tube à l'Ouest)
GuidePosYDecale=GuidePosY-5
str GuidePosX GuidePosX$
str GuidePosY GuidePosY$
str GuidePosYDecale GuidePosYDecale$
Now Date
Datetostr Date Date$
print "[" Date$ "] Centering at position " GuidePosX$ ", " GuidePosYDecale$ "; Fiber at " GuidePosX$ ", " GuidePosY$
OFFSET_TELESCOPE ImgChamp XGuideCentro YGuideCentro GuidePosX GuidePosYDecale
WAITFORENDMOVETELESCOPE
Delay 2000
WaitForEndDelay
CLOSE ImgChamp

Now Date
Datetostr Date Date$
print "[" Date$ "] Resynch telescope on position"
CALIBRATE_TELESCOPE alpha delta

return


/////////////////////////////////////////////////////////////////////////////////
//
// Check if I can continue to observe another 20min based on Sun position & telescope Vs meridian
//
/////////////////////////////////////////////////////////////////////////////////
CanIContontinueToObserve:
NOW Date
GET_TELESCOPE_POSITION RA2000 DEC2000 Haut Azi AHor
GETSTDRLONGITUDE Longitude
GETSTDRLATITUDE Latitude
GETHEIGHT RA2000 DEC2000 Date Longitude Latitude Hauteur
// Hauteur en degrés
Hauteur=Hauteur*TODEG

if Hauteur<HauteurMin then
   Now Date
   Datetostr Date Date$
   print "[" Date$ "] Target too low"
   ContinueObservations=0
   return
endif

// TSL pour calculer angle horaire
SIDERALTIME Date Longitude TSL
// Angle horaire objet en radian :
COMPUTEANGLEHOR TSL RA2000 AngleHor
//Angle horaire en heures décimales:
AngleHor=AngleHor*12/PI

AngleHorLimit=0.0
// si DEC<45°: 10min supplémentaires
if DEC2000<0.75 then
    AngleHorLimit=0.2
endif
// si DEC<30°: 20min supplémentaires
if DEC2000<0.5 then
    AngleHorLimit=0.4
endif
// si DEC<25°: 1h10 supplémentaires
if DEC2000<0.44 then
    AngleHorLimit=1.2
endif
// si DEC<6°: 1h45 supplémentaires
if DEC2000>0.1 then
    AngleHorLimit=1.75
endif

if AngleHor>AngleHorLimit
   Now Date
   Datetostr Date Date$
   print "[" Date$ "] Target too close to meridian (telescope too close to pier)"
   ContinueObservations=0
   return
endif

// Check Sun elevation
GetStdrLongitude Longitude
GetStdrLatitude Latitude

elevsunstopobservations=elevsunstopobservations_Deg/TODEG

Now Date
GETRADECSUN  Date  AlphaS  DeltaS  sunelevation
Datetostr Date Date$
RAD_TO_DEC sunelevation ElevationS$
if sunelevation>elevsunstopobservations
   Now Date
   Datetostr Date Date$
   print "[" Date$ "] Sun too high to continue observing"
   ContinueObservations=0
   return
endif

ContinueObservations=1

return


/////////////////////////////////////////////////////////////////////////////////
//
// Check if Sun is still below horizon limit, check if observations can continu...
//
/////////////////////////////////////////////////////////////////////////////////
IsSunStillBelow:

// Check Sun elevation
GetStdrLongitude Longitude
GetStdrLatitude Latitude

elevsunstopobservations=elevsunstopobservations_Deg/TODEG

Now Date
GETRADECSUN  Date  AlphaS  DeltaS  sunelevation
Datetostr Date Date$
RAD_TO_DEC sunelevation ElevationS$
if sunelevation>elevsunstopobservations
   Now Date
   Datetostr Date Date$
   print "[" Date$ "] Sun too high to continue observing"
   SunStillBelow=1
   ContinueObservations=0
   return
endif

SunStillBelow=1
ContinueObservations=1

return



/////////////////////////////////////////////////////////////////////////////////
//
// Wait several minutes (for long waiting time)...
//
/////////////////////////////////////////////////////////////////////////////////
WaitForMinutes:
//MinutesToWait=5

str MinutesToWait MinutesToWait$

Now Date
Datetostr Date Date$
print "[" Date$ "] Start waiting for " MinutesToWait$ " minutes"

Now DateBegin

WaitForMinutesLoop:
Now Date
Ecart=(Date-DateBegin)*24.0*60.0
if Ecart<MinutesToWait then
goto WaitForMinutesLoop:
endif

Now Date
Datetostr Date Date$

print "[" Date$ "] Fin (MinutesToWait=" MinutesToWait ")"

return

/////////////////////////////////////////////////////////////////////////////////
//
// Look up for Object$ parameters in terms of single exposure time, Nb of exposures...
//
/////////////////////////////////////////////////////////////////////////////////
LookUpObject:

if Object$="64Ser" then
    objet$="hd175869"
    GExpTime=0.1
    ExpSec=1200
    NbExposure=3
endif

if Object$="QTSer" then
    objet$="hd170783"
    GExpTime=0.4
    ExpSec=1200
    NbExposure=3
endif

//iot Lyr / hd178475 / Mag 5.1
if Object$="iotLyr" then
    objet$="hd178475"
    GExpTime=0.1
    ExpSec=1200
    NbExposure=3
endif

//V558 Lyr / hd183362 / Mag 6.4
if Object$="V558Lyr" then
    objet$="hd183362"
    GExpTime=0.25
    ExpSec=1200
    NbExposure=4
endif

//11 Cyg / hd185037 / Mag 5.9
if Object$="11Cyg" then
    objet$="hd185037"
    GExpTime=0.25
    ExpSec=1200
    NbExposure=3
endif

if Object$="12Vul" then
    objet$="hd187811"
    GExpTime=0.25
    ExpSec=1200
    NbExposure=3
endif

//25 Cyg / hd189687 / Mag 5.2
if Object$="25Cyg" then
    objet$="hd189687"
    GExpTime=0.1
    ExpSec=1200
    NbExposure=3
endif

if Object$="28Cyg" then
    objet$="hd191610"
    GExpTime=0.1
    ExpSec=1200
    NbExposure=3
endif

if Object$="QRVul" then
    objet$="hd192685"
    GExpTime=0.5
    ExpSec=1200
    NbExposure=3
endif

if Object$="lamCyg" then
    objet$="hd198183"
    GExpTime=0.2
    ExpSec=1200
    NbExposure=3
endif

//ups Cyg / hd202904 / Mag 4.4
if Object$="upsCyg" then
    objet$="hd202904"
    GExpTime=0.1
    ExpSec=600
    NbExposure=3
endif

if Object$="16Peg" then
    objet$="hd208057"
    GExpTime=0.1
    ExpSec=1200
    NbExposure=3
endif

//31Peg / hd212076 / Mag4.9
if Object$="31Peg" then
    objet$="hd212076"
    GExpTime=0.2
    ExpSec=1200
    NbExposure=3
endif

//14 Lac / hd216200 / Mag 5.8
if Object$="14Lac" then
    objet$="hd216200"
    GExpTime=0.2
    ExpSec=1200
    NbExposure=3
endif

//18 And / hd222304 / Mag 5.3
if Object$="18And" then
    objet$="hd222304"
    GExpTime=0.1
    ExpSec=1200
    NbExposure=3
endif

if Object$="omiAnd" then
    objet$="hd217675"
    GExpTime=0.1
    ExpSec=900
    NbExposure=3
endif

//omi Cas / hd4180 / mag 4.5
if Object$="omiCas" then
    objet$="hd4180"
    GExpTime=0.1
    ExpSec=600
    NbExposure=5
endif

if Object$="V442And" then
    objet$="hd6226"
    GExpTime=0.25
    ExpSec=1200
    NbExposure=4
endif

//phi And / hd6811 / mag 4.3
if Object$="phiAnd" then
    objet$="hd6811"
    GExpTime=0.1
    ExpSec=600
    NbExposure=3
endif

if Object$="V764Cas" then
    objet$="hd7636"
    GExpTime=0.3
    ExpSec=1200
    NbExposure=4
endif
//hd9709 / mag 7.4
if Object$="hd9709" then
    objet$="hd9709"
    GExpTime=0.4
    ExpSec=1200
    NbExposure=4
endif

if Object$="phiPer" then
    objet$="hd10516"
    GExpTime=0.1
    ExpSec=900
    NbExposure=3
endif

if Object$="V549Per" then
    objet$="hd3661"
    GExpTime=1.0
    ExpSec=1200
    NbExposure=6
endif

if Object$="hd13867" then
    objet$="hd13867"
    GExpTime=0.3
    ExpSec=1200
    NbExposure=4
endif

return

/////////////////////////////////////////////////////////////////////////////////
//
// TakeObject: acquire spectra of Object$
//
/////////////////////////////////////////////////////////////////////////////////
TakeObject:

GoSub LookUpObject:

GoSub GoToTargetAndAcquisition:
GoSub IsSunStillBelow:
if SunStillBelow=0 then
    if StarToSynchForObject$="" then
        //objet$="hd886"
        //GExpTime=0.1
        //GoSub StarHopping:
    endif
    GoTo EndOfSession:
endif


return


/////////////////////////////////////////////////////////////////////////////////
//
// Meteo.pgm: gestion station Sentinel (T.Lemoult)
//
/////////////////////////////////////////////////////////////////////////////////
// lecture des parametres de la station meteo Sentinel
ReadMeteo:

//Print "Donnees de la station meteo Sentinel:"
pathSentinel$="C:\Users\ObsBE\Documents\Sentinel\Datas\infodata.txt"
Open_FileTxt_For_Read fichier pathSentinel$

for i=1 7
    ReadFileTXT fichier ligneDummy$
next i

ReadFileTXT fichier ligneTempExt$
CUTSTR ligneTempExt$ "=" 2 out$
val out$ TempExt

ReadFileTXT fichier ligneHumidity$
CUTSTR ligneHumidity$ "=" 2 out$
val out$ Humidity
//print "Humidity=" out$

ReadFileTXT fichier ligneDummy$
ReadFileTXT fichier ligneDummy$

ReadFileTXT fichier ligneTempSkyIR$
CUTSTR  ligneTempSkyIR$  "="  2  out$
val out$ TempskyIR
//print "TempskyIR=" out$

ReadFileTXT fichier ligneTempDetectorIR$
CUTSTR ligneTempDetectorIR$ "=" 2 out$
val out$ TempDetectorIR
//print "TempDetectorIR=" out$

ReadFileTXT fichier ligneRainFall$
CUTSTR ligneRainFall$ "=" 2 out$
if Out$="No" then
        RainFall=0
        RainFall$="N"
ELSE
        RainFall=1
        RainFall$="Y"
ENDIF
//print "RainFall=" out$

ReadFileTXT fichier ligneWindSpeedGust$
CUTSTR ligneWindSpeedGust$ "=" 2 out$
val out$ WindSpeedGust
//print "WindSpeedGust=" out$

ReadFileTXT fichier ligneDummy$
ReadFileTXT fichier ligneDummy$
ReadFileTXT fichier ligneDummy$
ReadFileTXT fichier ligneDummy$

ReadFileTXT fichier ligneLightLevel$
CUTSTR ligneLightLevel$ "=" 2 out$
val out$ LightLevel
//print "LightLevel=" out$

tempCiel=TempSkyIR-TempExt
STR tempCiel tempCiel$
//print "calcul temperature ciel =" tempCiel$

////////////////////////
if (tempCiel<LimitTempCiel) then
    if RainFall=0 then
        if LightLevel>LimitMagnitudeCiel
            BeauTemp=1
        ELSE
            BeauTemp=0
        ENDIF
    ELSE
        BeauTemp=0
    ENDIF
ELSE
    BeauTemp=0
ENDIF   

// Beautemp est obtenus en regardant que la derniere valeur du  Sentinel.
if BeauTemp=1 then
    CompteurBeauTemp=CompteurBeauTemp+1
ELSE
    CompteurBeauTemp=0
ENDIF

// MeteoOK donne un résultat filtree..
if CompteurBeauTemp>ValMinBelleMeteo then
//    Print "Il fait beau depuis un moment.. On va pouvoir observer"
    MeteoOK=1
else
    MeteoOK=0
    IF (BeauTemp=1) then
//        Print "Si le beau temps se maintien, on pourra observer"
    ELSE
//        Print "Il ne fait pas assez beau pour observer"
    ENDIF
ENDIF

CLOSEFILETXT  fichier
return

BoucleAttendBeauTemp:
    Now Date
    Datetostr Date Date$
    print "[" Date$ "] Waiting for good weather. Sky temp=" tempCiel$ " (" LimitTempCiel "), Rain=" RainFall$

    GOSUB ReadMeteo:
    DELAYBLOCK 60000
    if MeteoOK=0 THEN
        GOTO BoucleAttendBeauTemp:
    ENDIF

return


/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
//                                                                             END OF SCRIPT                                                                     //
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////