!***********************************************************************************
!*                                                                                 *
!*                                 F A M O U S                                     *
!*                                                                                 * 
!*                  Frequency Analysis Mapping On Unusual Sampling                 * 
!*                  -         -        -       -  -       -                        * 
!*                          Program designed and written by                        * 
!*                             F. Mignard   OCA/Cassiopee                          * 
!*                           francois.mignard@obs-nice.fr                          * 
!*                             Version 4.6 - December  2005                        * 
!*                                                                                 *
!*              SEARCH OF A SET OF FREQUENCIES IN A DISCRETE TIMES SERIES          *
!*                                                                                 *
!*                                                                                 *
!*                            TEST PROGRAM WITH REAL DATA                          *
!*                                                                                 *
!***********************************************************************************
! Version : 05/04/05 - replaces previous of 28/03/05
! Version : 08/07/05 - replaces previous of 05/04/05
! No change in the driver in version 4.6 of Famous 
!***************************************************

! This file is the standard driver of the FAMOUS subroutines used to perform a the
! frequency analysis of a time series, non necessarily evenly sampled. It processes
! on data set per run.
!
! This driver is designed to run on real data read on an external file.
!
!     -----------
!     Environment
!     -----------
! 
!     The program environement is provided by the user in a file SETTING.TXT with :
! 
!     - input filename containing 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
!    
!     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                ::  idstar  =  0       ! index for the folded lightcurve

      real(kind=dp)          ::  frbeg, frend, deb, tzero
      integer                ::  icolx, icoly, isprint, iresid, idunif, k, idimsol
      logical                ::  flmulti, flplot, flauto, fltime, flsimul, fldunif
      character*30           ::  file_in, file_out

      real(dp), allocatable  ::  freq(:), ampc(:,:), amps(:,:), rms(:),  snr(:), sol(:)   ! storage allocated after the settings

!*****************   setting file    ******************** 
!
      open(unit =  2, file = 'setting.txt', status = 'old')                               ! settings
!
!*****************   setting file    ******************** 
      
!
!     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,*) numfreq       ! search of at most numfreq lines (will be forced to numfreq = 2 is flmuti = .false.)  
      read(2,*) flmulti       ! .true.: frequency analysis of a multi-periodic signal, .false. : search of a period of a periodic signal (==> numfreq = 2)
      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,*) flplot        ! flag for the auxiliary files (current power spectrum and remaining signal after k lines are found )
      read(2,*) isprint       ! control of printouts (0 : limited to results, 1 : short report, 2 : detailed report)
      read(2,*) iresid        ! control the output of the residuals

      if(.not.flmulti)     numfreq = 2   ! force numfreq = 2 for the search of a periodic signal
!
!     global variables of module famous.lib :  npts, maxdeg, idegf(), tmean, tzero, numfreq
!
!     allocate storage to fundamental arrays
!
      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 all 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
        
!********************************************************************************************

!
!     Nominal mode with input data read in a file
!
      call numobs(idata, npts)                         !npts : number of record in the input file
      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(iout,flsimul,file_in,icolx, icoly,file_out,npts,numfreq,flmulti,flauto,frbeg,frend,fltime,threshold)
      call printsetting(0,   flsimul,file_in,icolx, icoly,file_out,npts,numfreq,flmulti,flauto,frbeg,frend,fltime,threshold)

      deb = seconds(0.0d0)
!
!!    Real stuff starts here
!
      if(flmulti) then      ! frequency analysis
         call freqsearch(npts,xx,yy,numfreq,maxdeg,flplot,flauto,isprint,iout,frbeg,frend, fltime, tzero, freq,snr,ampc,amps)
      else                  ! period search
         call periodsearch(npts,xx,yy,numfreq,maxdeg,flplot,flauto,isprint,iout,frbeg,frend, fltime, tzero, freq,snr,ampc,amps)
      endif

!
!!    Final LS fit and estimate of the standard deviations
!
      call freqsol(npts,xx,yy,isprint,iresid,iout, numfreq,freq,snr,ampc,amps,rms)

      if(flplot.and.(.not.flmulti)) then
         call writefold_lc(idstar,npts,xx,yy,1d0/freq(1))  ! folded data for periodic signal
      endif

      write(iout, 100) seconds(deb)
100   format(//, ' Execution time in seconds : ', F10.2)
      end
!********************************************************************************************
!!
!!                                   END OF TEST PROGRAM
!!
!********************************************************************************************