!***********************************************************************************
!*                                                                                 *
!*                                 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 A DISCRETE TIMES SERIES          *
!*                                                                                 *
!*                                                                                 *
!*                         TEST PROGRAM WITH SIMULATED DATA                        *
!*                                                                                 *
!***********************************************************************************
! Version : 05/04/05 - replaces previous of 28/03/05
! Version : 08/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.
!
! This driver is designed to run on simulated data.
! Data simulator  is included in the fortran module simul_famous.f90
!
!     -----------
!     Environment
!     -----------
! 
!     The program environment is provided by the user in a file SETTING_SIMUL.TXT with :
! 
!     - number of data point
!     - 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
!
!     The module simul_famous contains the subroutines for the three different simulation modes
!
!     signal_nominal(n,x,y)        :  generates n data points sampled at x(k) with values y(k)
!     signal_lines  (n,x,y)        :  reads a list of amplitudes and frequencies in a file
!     signal_time   (n,x,y)        :  reads a time sampling in a file (x(k)) and samples the signal accordingly
!
!
!     THE USER MUST INCLUDE FILE NAMES AND FEW OTHER THINGS IN THE CODE 
!     THE USER MUST DEFINE  HIS OWN SIGNAL IN THE CODE
!
!     see the introduction in the module and search for the string 'user_defined'
!
!********************************************************************************************

      program teperiod
      use famouslib          ! module with the common specifications and internal subroutines
      use simul_famous

      implicit none

      integer                ::  iout    =  6       ! external unit for the output

      real(kind=dp)          ::  frbeg, frend, deb, tzero
      integer                ::  icolx, icoly, isprint, iresid, idunif, k, idimsol
      logical                ::  flplot, flauto, fldunif
      logical                ::  flsimul = .true.  ! simulation mode
      logical                ::  fltime  = .true.  ! data centered about the mean
      logical                ::  flmulti = .true.  ! multiperiodic search 
      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_simul.txt', status = 'old')                ! settings
      
!
!!    Settings of the program
!
      read(2,*) npts          ! number of data points in the simulation
      read(2,*) file_out      ! output filename
      read(2,*) numfreq       ! search of at most numfreq lines  
      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,*) 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 printout (0 : limited to results, 1 : short report, 2 : detailed report)
      read(2,*) iresid        ! control the output of the residuals

!
!     global variables of module famous.lib :  npts, maxdeg, idegf(), tmean, 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))
 

!      
!     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
        
!********************************************************************************************

!     Data simulation
!       
!     Uncheck your simulator and update your setting in the relevant subroutine in the module simul_famous
!
      allocate (xx(npts), yy(npts), zz(npts))
      call signal_nominal(npts,xx,yy)                 !simulated data with an analytical formula
!      call signal_lines (npts,xx,yy)                  !simulated data with external list of lines
!      call signal_time  (npts,xx,yy)                  !simulated data with external time sampling  npts can be changed by the routine
!********************************************************************************************
!
!!    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
!
      call freqsearch(npts,xx,yy,numfreq,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, numfreq,freq,snr,ampc,amps,rms)

      write(iout, 100) seconds(deb)
100   format(//, ' Execution time in seconds : ', F6.2)
      end
!********************************************************************************************
!!
!!                                   END OF TEST PROGRAM
!!
!********************************************************************************************