program main

  use vtype_module

  use fi_module
  use cia_module

  implicit none

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

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

  integer :: IMol1
  integer :: IMol2

  ! 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  (:,:)

  integer            :: FileUnit
  integer            :: iostat

  integer            :: l
  integer            :: t


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

  IMol1 = -1
  IMol2 = -1
  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 )


  call fi_open( CIAFileName, "read", FileUnit )
  do l = 1, 2
    read( FileUnit, * )
  end do
  read( FileUnit, * ) NWaveNum, NTemp
  write( 6, * ) 'Number of wavenumber  : ', NWaveNum
  write( 6, * ) 'Number of temperature : ', NTemp

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

  do t = 1, NTemp
    do l = 1, NWaveNum
      read( FileUnit, * ) w_WaveNum(l), t_Temp(t), wt_Coef(l,t)
    end do
  end do
  close( FileUnit )


  ! Unit conversion
  !
  !   conversion from cm-1 to m-1
  w_WaveNum = w_WaveNum * 1.0d2
  !
  !   conversion from cm-1 amagat-2 to cm5 molecule-2 (Richard et al., 2012)
  wt_Coef = wt_Coef * 1.385d-39
  !   conversion from cm5 molecule-2 to m5 molecule-2
  wt_Coef = wt_Coef * 1.0d-10

  call CIAStoreDataInObj( &
    & IMol1, IMol2, &
    & 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
