!***********************************************************************************
!*                                                                                 *
!*                                 F A M O U S                                     *
!*                                                                                 * 
!*                  Frequency Analysis Mapping On Unusual Sampling                 * 
!*                  -         -        -       -  -       -                        * 
!*                          Program developed and written by                       * 
!*                             F. Mignard   OCA/Cassiopee                          * 
!*                            Version 4.5 - July   2005                            * 
!*                                                                                 *
!*              SEARCH OF A SET OF FREQUENCIES IN DISCRETE TIMES SERIES            *
!*                                                                                 *
!*                                                                                 *
!*                         TEST PROGRAM FOR PHOTOMETRIC DATA                       *
!*                                                                                 *
!***********************************************************************************
! Version : 05/04/05 - replaces previous of 28/03/05
! Version : 11/07/05 - replaces previous of 05/04/05
!***************************************************
!
! This file is the driver of the FAMOUS subroutines  used to perform a the
! frequency analysis of a time series, non necessarily evenly sampled.
!
! The driver and freqsearch subroutines are optimised to search for
! the period of a simply periodic signal, like a variable star or a
! radial velocity signature for extra-solar planet.
!
! This driver is designed to run on real data read on an external file.
! This driver is optimised to run on several independant data sets read on the input file
! Each data set has a header with at least the id, ndata ...
!               followed by ndata records  time(k), value(k)
!
! 
!
!     -----------
!     Environment
!     -----------
! 
!     The program environment is provided by the user in a file SETTING_PHOTOM.TXT with :
! 
!     - input filename containing  the data sets with xx(k), yy(k) in each record
!     - positions of the fields in this file
!     - output filename for the various printouts
!     - number of frequencies to be searched
!     - setting flags for different running options to override defaults
!     - printing options
!
!     The settings are common to all data sets read in the input file
!    
!     By default the unit of time is taken from the sampling in xx(k) as  the increase of
!     xx of one. Then the unit of frequency is just the inverse.
!     
! 
!     The module famouslib contains the common constantes, variables, arrays used by the libray 
!     and all the subroutines called by the driver to run the frequancy mapping
!
! 
!********************************************************************************************

      program teperiod
      use famouslib          ! module with the common specifications and internal subroutines

      implicit none
 
      integer                  ::  idata   =  1       ! external unit for the data
      integer                  ::  iout    =  6       ! external unit for the output
      integer                  ::  isol    =  7       ! external unit for the output
      integer                  ::  iresid  =  0       ! setting to skip the output of the residuals  
      logical                  ::  flmulti = .false.  ! search of a periodic signal

      real(kind=dp)            ::  frbeg, frend, deb, tzero
      real(kind=dp)            ::  xlon, xlat, xmag, period, ston

      integer                  ::  idstar, istar, nstar, icolx, icoly, isprint,  idunif, k, idimsol, numf
      logical                  ::  flauto, fltime, fldunif, flfold
      logical                  ::  flplot = .false.   ! setting to skip the power spectra
      character*30             ::  file_in, file_out
      real(dp), allocatable    ::  freq(:), ampc(:,:), amps(:,:), rms(:),  snr(:), sol(:)   ! storage allocated after the settings
 
      open(unit =  2, file = 'setting_photom.txt', status = 'old')                               ! settings
      
!
!     Settings of the program
!
      read(2,*) file_in       ! Input  filename with the data y(x) as xx, yy  on each record
      read(2,*) icolx         ! index of the column with the time data in file_in
      read(2,*) icoly         ! index of the column with the observations in file_in
      read(2,*) file_out      ! output filename
      read(2,*) flauto        ! automatic (true) or manual(false) search of the max and min frequencies
      read(2,*) frbeg         ! preset min frequency in manual mode
      read(2,*) frend         ! preset max frequency in manual mode
      read(2,*) fltime        ! automatic(true) or preset(false) origin of time in the solution
      read(2,*) tzero         ! force value for the origin of time in preset mode
      read(2,*) threshold     ! threshold in S/N to reject non significant lines (< threshold)
      read(2,*) isprint       ! control of printouts (0 : limited to results, 1 : short report, 2 : detailed report)
      read(2,*) flfold        ! control the output of files with the folded lightcurves
!
!     global variables of module famous.lib :  npts, maxdeg, idegf(), tmean, numfreq
!
!     allocate storage to fundamental arrays
!
      numfreq  = 2            ! forced value for the search of a periodic signal

      allocate(freq(numfreq), idegf(0:numfreq))

!
!     End of the settings for the degrees of the mixed terms
!
      read(2,*) fldunif                    ! flag for the degree of the mixed terms (true : uniform degree for all terms)
      read(2,*) idunif                     ! degree if fldunif = .true.
      if(fldunif) then
         idegf(0:numfreq)  = idunif        ! global assignement of the degree to the array ideg
      else
         read(2,*) (idegf(k), k=0,numfreq) ! degree of each line if fldunif = .false. 
      endif

      maxdeg   = maxval(idegf)             ! highest degree needed for storage allocation

      idimsol  = isize(numfreq,idegf)      ! size of the array sol(1:idimsol). 
!
!     allocate storage to fundamental arrays
!
      allocate(ampc(0:maxdeg,0:numfreq),amps(0:maxdeg,0:numfreq),rms(idimsol),snr(numfreq),sol(idimsol))
      allocate(sig_rel_f(numfreq))

      OPEN(UNIT = idata,  FILE = file_in, status = 'old')      ! input file
!
!     if you comment the next OPEN  the outputs are redirected to the screen (if you keep iout = 6 in the parameter statement)
!
      OPEN(UNIT = iout ,  FILE = file_out,status='unknown')    ! main output file

      OPEN(UNIT = isol ,  FILE = 'summary.txt' ,status='unknown')    ! secondary output file
        
!********************************************************************************************

!
!     Nominal mode with input data read in a file
!
      deb =  seconds(0.0d0)
      nstar  = 100
      do istar = 1, nstar
         numf  = numfreq                                  ! num  can be changed in freqsol
         read(idata, *, end=200)  idstar, npts, xlon, xlat, xmag, period, ston
         allocate (xx(npts), yy(npts), zz(npts))          !storage allocation of global arrays
         call read_signal(idata,npts,icolx,icoly,xx,yy)   !data reading on file_in (unit=idata)
!********************************************************************************************
!
!!    Output of the settings
!
        
         call printsetting_phot(iout,file_in,icolx, icoly, idstar,file_out,npts,numf,flmulti,flauto,frbeg,frend,fltime,threshold)
         call printsetting_phot(0,   file_in,icolx, icoly, idstar,file_out,npts,numf,flmulti,flauto,frbeg,frend,fltime,threshold)
!
!!    Real stuff starts here
!
         flnormal = .true.
         call periodsearch(npts,xx,yy,numf,maxdeg,flplot,flauto,isprint,iout,frbeg,frend,fltime, tzero, freq,snr,ampc,amps)
!
!!    Final LS fit and estimate of the standard deviations
!
         call freqsol(npts,xx,yy,isprint,iresid,iout,numf,freq,snr,ampc,amps,rms)

         if(numf ==1) then
            write(isol, 500)  idstar, npts, xmag, xlat, ston, period, 1d0/freq(1), abs(period -1d0/freq(1))/sig_rel_f(1)/period
         else if(numf >=2) then
            if(flnormal) then                                       ! no inversion of the order of the periods found
               if(flfold) then
                  call writefold_lc(idstar,npts,xx,yy,1d0/freq(1))  ! folded lightcurves
               endif
               write(isol, 510)  idstar, npts, xmag, xlat, ston, period, 1d0/freq(1), (period -1d0/freq(1))/sig_rel_f(1)/period,& 
                               freq(2)/freq(1), sqrt((ampc(0,2)**2+amps(0,2)**2)/(ampc(0,1)**2+amps(0,1)**2)) , flnormal ! to test the adequacy of the period ; more tests to come.
            else
               if(flfold) then
                  call writefold_lc(idstar,npts,xx,yy,1d0/freq(2))  ! folded lightcurves
               endif
               write(isol, 510)  idstar, npts, xmag, xlat, ston, period, 1d0/freq(2), (period -1d0/freq(2))/sig_rel_f(2)/period,& 
                               freq(1)/freq(2), sqrt((ampc(0,1)**2+amps(0,1)**2)/(ampc(0,2)**2+amps(0,2)**2))  , flnormal ! to test the adequacy of the period ; more tests to come.
            endif
         endif
         deallocate (xx, yy, zz)                         !frees the storage of global arrays
      enddo
200   continue 

      write(iout, 100) seconds(deb)
100   format(//, ' Execution time in seconds : ', F7.3)
500   format( i6, i5, 3f10.4, 2f12.5, f10.3, f8.3)
510   format( i6, i5, 3f10.4, 2f12.5, f10.3, f8.3, f10.4, l5)
      end
!********************************************************************************************
!!
!!                                   END OF TEST PROGRAM
!!
!********************************************************************************************

