program main

  use vtype_module
  use fi_module

  use constants0, only : AvogConst
  use cia_module

  implicit none

  character(extstr) :: CtlFN  = 'conv_cia2nc.conf'

  character(extstr) :: CIAFileName
  character(extstr) :: OutputFileName
  character(extstr) :: Src
  character(extstr*4) :: Ref


  ! Local variables
  !

  integer , parameter   :: MaxNmlArySize = 256


  type( CIAParam ) :: CIAP

  integer              :: NWaveNum
  integer              :: NTemp
  REAL(8), allocatable :: w_WaveNum(:)
  REAL(8), allocatable :: t_Temp   (:)
  REAL(8), allocatable :: wt_Coef  (:,:)

  real(8)              :: Abs

  integer            :: FileUnit
  integer            :: iostat

  integer            :: l
  integer            :: t


  namelist /file_nml/ &
    & CIAFileName, &
    & OutputFileName, &
    & Src, &
    & Ref


  CIAFileName    = "../data_hitran/CIA/data/CO2-CO2_2011.cia"
  OutputFileName = "./out"


  ! Explanation

  call fi_open( CtlFN, "read", FileUnit )
  !
  rewind( FileUnit )
  read( FileUnit, nml = file_nml, iostat = iostat )
  if ( iostat > 0 ) then
    stop 'Namelist in file_nml is something wrong.'
  end if
  write( 6, nml = file_nml )
  !
  close( FileUnit )


  write( 6, * ) 'Input  File: ', trim( CIAFileName )
  write( 6, * ) 'Output File: ', trim( OutputFileName )


  NWaveNum = fi_lc( CIAFileName, 2 )
  NTemp    = 2

  allocate( w_WaveNum( NWaveNum ) )
  allocate( t_Temp   ( NTemp    ) )
  allocate( wt_Coef  ( NWaveNum, NTemp ) )

  call fi_open( CIAFileName, "read", FileUnit )
  do l = 1, 2
    read( FileUnit, * )
  end do
  do t = 1, 1
    do l = 1, NWaveNum
      read( FileUnit, * ) w_WaveNum(l), wt_Coef(l,t)
    end do
  end do
  close( FileUnit )

  t_Temp(1) = 100.0d0
  t_Temp(2) = 200.0d0
  do t = 1+1, NTemp
    wt_Coef(:,t) = wt_Coef(:,1)
  end do

  t = 1
  Abs = 0.0d0
!!$  do l = 1, NWaveNum
!!$    Abs = Abs + wt_Coef(l,t) * ( w_WaveNum(2) - w_WaveNum(1) )
!!$  end do
  do l = 1, NWaveNum-1
    Abs = Abs + ( wt_Coef(l,t) + wt_Coef(l+1,t) ) * ( w_WaveNum(2) - w_WaveNum(1) ) / 2.0d0
  end do
!!$  write( 6, * ) Abs

  ! see eq. 2 of Lee et al. (2016), unit is cm-1 (mol cm-3)-2
  wt_Coef = wt_Coef * 7.53d4 / Abs


  ! Unit conversion
  !
  !   conversion from cm-1 to m-1
  w_WaveNum = w_WaveNum * 1.0d2
  !
  !   conversion from cm-1 (mol cm-3)-2 = cm5 mol-2 to m5 molecule-2
  wt_Coef = wt_Coef * 1.0d-10 / AvogConst**2

  call CIAStoreDataInObj( &
    & 2, 2, &
    & NWaveNum, NTemp, w_WaveNum, t_Temp, wt_Coef, &
    & CIAP  &
    & )

!!$  call CIAReadFile( CIAFileName, CIAP )
  call CIAWriteFileNetcdf( OutputFileName, Src, Ref, CIAP )
  call CIAParamFinalize( CIAP )


end program main
