! Module   : make_passband
! Purpose  : create passband files from ASCII tables
!
! Copyright 2021-2022 Rich Townsend & The MSG Team
!
! This file is part of MSG. MSG is free software: you can redistribute
! it and/or modify it under the terms of the GNU General Public
! License as published by the Free Software Foundation, version 3.
!
! MSG is distributed in the hope that it will be useful, but WITHOUT
! ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
! or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
! License for more details.
!
! You should have received a copy of the GNU General Public License
! along with this program.  If not, see <http://www.gnu.org/licenses/>.

#:include 'forum.inc'

program make_passband

   ! Uses

   use forum_m
   use msg_m

   use ISO_FORTRAN_ENV

   ! No implicit typing

   implicit none

   ! Variables

   character(:), allocatable :: table_file_name
   real(RD)                  :: F_0
   character(:), allocatable :: passband_file_name

   integer               :: unit
   integer               :: n
   real(RD), allocatable :: lam(:)
   real(RD), allocatable :: S(:)
   integer               :: i
   type(passband_t)      :: passband
   type(hdf5io_t)        :: hdf5io

   ! Read command-line arguments

   @:ASSERT(n_arg() == 3, 'Syntax: make_passband table_file_name F_0 passband_file_name')

   call get_arg(1, table_file_name)
   call get_arg(2, F_0)
   call get_arg(3, passband_file_name)

   ! Read the table data

   open(NEWUNIT=unit, STATUS='OLD', FILE=table_file_name)

   n = 0

   count_loop : do
      read(unit, *, END=100)
      n = n + 1
   end do count_loop

100 continue

   rewind(unit)

   allocate(lam(n))
   allocate(S(n))

   read_loop : do i = 1, n
      read(unit, *) lam(i), S(i)
   end do read_loop

   close(unit)

   ! Create the passband

   passband = passband_t(S, lam, F_0)

   ! Write the passband_t

   hdf5io = hdf5io_t(passband_file_name, CREATE_FILE)
   call passband%write(hdf5io)
   call hdf5io%final()

   ! Finish

end program make_passband
