!# This source file is part of code Pégase.3.0.1 (2019-02-21).
!# Copyright: Michel Fioc (Michel.Fioc@iap.fr), Sorbonne université, 
!# Institut d'astrophysique de Paris/CNRS, France.
!# 
!# Pégase.3.0.1 is governed by the CeCILL license under French law and abides 
!# by the rules of distribution of free software. You can use, modify and/or 
!# redistribute this software under the terms of the CeCILL license as circulated 
!# by CEA, CNRS and INRIA at "http://www.cecill.info". The text of this license
!# is also available in French and in English in directory "doc_dir/" of this
!# code.
!# 
!# As a counterpart to the access to the source code and to the rights to copy,
!# modify and redistribute it granted by the license, users are provided only
!# with a limited warranty, and the software's author, the holder of the
!# economic rights, and the successive licensors have only limited
!# liability. 
!# 
!# The fact that you are presently reading this means that you have had
!# knowledge of the CeCILL license and that you accept its terms.
!#====================================================================== 

module mod_SSPs_ages

  implicit none
  public :: read_SSPs_ages

contains

!#======================================================================
  
  subroutine read_SSPs_ages(SSPs_ages_file, time_step, dim_time_SSP, time_SSP)

    use mod_types
    use mod_linked_list
    use mod_file_access
    use mod_directories, only : ages_dir

    implicit none
    character(len=*), intent(in) :: SSPs_ages_file
    real(CDR), intent(out) :: time_step
    integer, intent(out) :: dim_time_SSP
    real(CDR), dimension(:), pointer :: time_SSP
!#......................................................................
    integer :: unit, ios, factor, tot_factor
    real(CDR) :: time
    type(lk_lst_CDR) :: head_node
    type(lk_lst_CDR), pointer :: current_node => null()
!#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    
    call open_file(unit, file = path_file(ages_dir, SSPs_ages_file))
    read(unit,*) time_step
    dim_time_SSP = 1
    call lk_lst_initialize(head_node)
    call lk_lst_new_node(head_node, current_node)
    current_node % val = 0
    tot_factor = 0
    do
       read(unit,*,iostat=ios) time, factor
       if (ios /= 0) exit
       do 
          if (current_node % val < time) then
             dim_time_SSP = dim_time_SSP+1
             tot_factor = tot_factor+factor
             call lk_lst_new_node(head_node, current_node)
             current_node % val = tot_factor*time_step
          else
             exit
          endif
       enddo
    enddo
    call close_file(unit)

    call lk_lst_to_array(head_node, time_SSP, dim_time_SSP)
    
  end subroutine read_SSPs_ages

end module mod_SSPs_ages
