c     Copyright (C)
c     2010-2013 Université Bordeaux 1
c     2010-2013 Ecole des Mines d'Albi
c     2014-2018 - Mesostar
c     
c     This program is free software; you can redistribute it and/or modify
c     it under the terms of the GNU General Public License as published by
c     the Free Software Foundation; either version 2, or (at your option)
c     any later version.

c     This program is distributed in the hope that it will be useful,
c     but WITHOUT ANY WARRANTY; without even the implied warranty of
c     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
c     GNU General Public License for more details.

c     You should have received a copy of the GNU General Public License
c     along with this program; if not, write to the Free Software
c     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
c     USA.
c
      subroutine postcalc(atm_profile,pidx,
     &     Nlay,Nb,Nq,first_band,last_band,
     &     lambda_lo,lambda_hi,z,pres,
     &     si_obs_intensity,si_Tb,si_NER,
     &     si_budget_from_NERs,si_budget_from_net_fluxes,
     &     si_gas_ground,si_gas_space,si_gas_gas,
     &     si_upward_flux,si_downward_flux,si_net_flux,
     &     band_net_flux_toa,band_obs_intensity,band_Tb,
     &     band_NER,band_is_NER,discrete_CF,
     &     band_total_budget,band_gas_ground_budget,
     &     band_gas_space_budget,band_gas_gas_budget,
     &     band_upward_flux,band_downward_flux,band_net_flux)
      implicit none
      include 'max.inc'
      include 'formats.inc'
c
c     Purpose: to perform post-calculation tasks (create result files and gnuplot scripts)
c
c     Input:
c       + atm_profile: 1 for a standard atmospheric profile
c                      2 for a user-defined atmospheric profile
c       + pidx: index of the standard atmospheric profile to use
c       + Nlay: number of atmospheric layers
c       + Nb: number of spectral narrowbands
c       + Nq: quadrature order
c       + first_band: index of the first band spectral integration has to be performed for
c       + last_band: index of the last band spectral integration has to be performed for
c       + lambda_lo: lower limit of each spectral band
c       + lambda_hi: higher limit of each spectral band
c       + z: altitude (m) at the top of each layer
c       + pres: pressure (Pa) at the top of each layer
c       + si_obs_intensity: spectrall integrated observed intensity (W/m^2/sr)
c       + si_Tb: spectrally integrated brightness temperature (K)
c       + si_NER: spectrally integrated NER matrix (W/m^2)
c       + si_budget_from_NERs: spectrally integrated radiative budget (W/m^3) for each gas layer (i=1,Nlay), computed from NERs
c       + si_budget_from_net_fluxes: spectrally integrated radiative budget (W/m^3) for each gas layer (i=1,Nlay), computed from net fluxes
c       + si_gas_ground: spectrally integrated part of the radiative budget (W/m^3) due to gas-ground NERs, for each gas layer (i=1,Nlay)
c       + si_gas_space: spectrally integrated part of the radiative budget (W/m^3) due to gas-space NERs, for each gas layer (i=1,Nlay)
c       + si_gas_gas: spectrally integrated part of the radiative budget (W/m^3) due to gas-gas NERs, for each gas layer (i=1,Nlay)
c       + si_upward_flux: spectrally integrated upward flux (W/m^2) at each interface (i=0,Nlay)
c       + si_downward_flux: spectrally integrated downward flux (W/m^2) at each interface (i=0,Nlay)
c       + si_net_flux: spectrally integrated net flux (W/m^2) at each interface (i=0,Nlay)
c       + band_net_flux_toa: net flux @ TOA, per band (W/m^2 in each band)
c       + band_obs_intensity: observed intensity, per band (W/m^2/sr in each band)
c       + band_Tb: brightness temperature, per band (K)
c       + band_NER: NER matrix, per band (W/m^2 in each band)
c       + band_is_NER: gas-space NERs, per band (W/m^2 in each band)
c       + discrete_CF: contribution function, per band
c       + band_total_budget: total radiative budget, per band (W/m^3 in each band)
c       + band_gas_ground_budget: par of the total radiative budget due to gas-ground NERs, per band (W/m^3 in each band)
c       + band_gas_space_budget: par of the total radiative budget due to gas-space NERs, per band (W/m^3 in each band)
c       + band_gas_gas_budget: par of the total radiative budget due to gas-gas NERs, per band (W/m^3 in each band)
c       + band_upward_flux: upward flux, per band (W/m^2 in each band)
c       + band_downward_flux: downward flux, per band (W/m^2 in each band)
c       + band_net_flux: net flux, per band (W/m^2 in each band)
c
c     I/O
      integer atm_profile,pidx
      integer Nlay,Nb,Nq(1:Nb_mx)
      integer first_band,last_band
      double precision lambda_lo(1:Nb_mx)
      double precision lambda_hi(1:Nb_mx)
      double precision z(0:Nlay_mx)
      double precision pres(0:Nlay_mx)
      double precision si_obs_intensity
      double precision si_Tb
      double precision si_NER(0:Nlay_mx+1,0:Nlay_mx+1)
      double precision si_budget_from_NERs(1:Nlay_mx)
      double precision si_budget_from_net_fluxes(1:Nlay_mx)
      double precision si_gas_ground(1:Nlay_mx)
      double precision si_gas_space(1:Nlay_mx)
      double precision si_gas_gas(1:Nlay_mx)
      double precision si_upward_flux(0:Nlay_mx)
      double precision si_downward_flux(0:Nlay_mx)
      double precision si_net_flux(0:Nlay_mx)
      double precision band_net_flux_toa(1:Nb_mx)
      double precision band_obs_intensity(1:Nb_mx)
      double precision band_Tb(1:Nb_mx)
      double precision band_NER(0:Nlay_mx+1,0:Nlay_mx+1,1:Nb_mx)
      double precision band_is_NER(0:Nlay_mx,1:Nb_mx)
      double precision discrete_cf(0:Nlay_mx,1:Nb_mx)
      double precision band_total_budget(1:Nlay_mx,1:Nb_mx)
      double precision band_gas_ground_budget(1:Nlay_mx,1:Nb_mx)
      double precision band_gas_space_budget(1:Nlay_mx,1:Nb_mx)
      double precision band_gas_gas_budget(1:Nlay_mx,1:Nb_mx)
      double precision band_upward_flux(0:Nlay_mx,1:Nb_mx)
      double precision band_downward_flux(0:Nlay_mx,1:Nb_mx)
      double precision band_net_flux(0:Nlay_mx,1:Nb_mx)
c     temp
      integer i,j,band,quad
      integer err
      double precision band_NER_max(1:Nb_mx),si_NER_max
      double precision band_total_budget_max
      double precision band_gas_ground_budget_max
      double precision band_gas_space_budget_max
      double precision band_gas_gas_budget_max
      double precision band_upward_flux_max
      double precision band_downward_flux_max
      double precision band_net_flux_max
      double precision absolute_band_NER_max
      double precision altitude
      character*1 fband_str1,lband_str1
      character*2 fband_str2,lband_str2
      character*3 fband_str3,lband_str3
      character*3 band_str3,si_Tb_str3
      character*2 Nlay_str2,Nlayp1_str2,Nlayp2_str2
      character*3 Nlay_str3,Nlayp1_str3,Nlayp2_str3
      character*(Nchar_mx) command
      character*(Nchar_mx) Nlay_str,Nlayp1_str,Nlayp2_str
      character*(Nchar_mx) fband_str,lband_str
      character*(Nchar_mx) result_file,filename
      character*(Nchar_mx) gnu_file,gnu_filename
      character*(Nchar_mx) gra_file,gra_filename
      character*(Nchar_mx) gra_file2,gra_filename2
      character*(Nchar_mx) pdf_file
      character*(Nchar_mx) profile_str
      character*(Nchar_mx) band_NER_max_str,si_NER_max_str
      character*(Nchar_mx) lambda_lo_str,lambda_hi_str
      character*(Nchar_mx) band_total_budget_max_str
      character*(Nchar_mx) band_gas_ground_budget_max_str
      character*(Nchar_mx) band_gas_space_budget_max_str
      character*(Nchar_mx) band_gas_gas_budget_max_str
      character*(Nchar_mx) band_upward_flux_max_str
      character*(Nchar_mx) band_downward_flux_max_str
      character*(Nchar_mx) band_net_flux_max_str
      character*(Nchar_mx) title_str
      integer Nelem
      double precision xvalues(1:Nelem_mx)
      double precision marks(1:Nelem_mx)
      integer band_inc,i_inc
      integer nap
      character*(Nchar_mx) band_tics_str
      character*(Nchar_mx) alt_tics_str
      character*(Nchar_mx) pres_tics_str
      integer pres_or_alt
      double precision epsilon_ner,epsilon_flux,epsilon_budget
      parameter(epsilon_ner=1.0D-7)
      parameter(epsilon_flux=1.0D-7)
      parameter(epsilon_budget=1.0D-7)
c     functions
      double precision planck_int_wavlng
c     label
      integer strlen
      character*(Nchar_mx) label
      label='subroutine postcalc'

c     set "pres_or_alt" to 1 if plots have to use pressure
c     set "pres_or_alt" to 2 if plots have to use altitude
      pres_or_alt=1

      if ((pres_or_alt.ne.1).and.(pres_or_alt.ne.2)) then
         call error(label)
         write(*,*) 'pres_or_alt=',pres_or_alt
         write(*,*) 'Allowed values: 1, 2'
         stop
      endif

      write(*,*) 'Recording results and creating gnuplot scripts...'

c      write(*,*) 'Nlay=',Nlay

c     Producing xtics and ytics character strings
      band=first_band
      if (Nb.lt.50) then
         band_inc=2
      else if (Nb.lt.120) then
         band_inc=4
      else
         band_inc=38
      endif
      Nelem=0
      do while (band.lt.last_band)
         Nelem=Nelem+1
         xvalues(Nelem)=band
         marks(Nelem)=(lambda_lo(band)+lambda_hi(band))/2.0D+0
         band=band+band_inc
      enddo
      nap=2
      call make_tics(Nelem,xvalues,marks,nap,band_tics_str)

      i=0
      i_inc=10
      Nelem=0
      do while (i.lt.Nlay+1+i_inc)
         Nelem=Nelem+1
         xvalues(Nelem)=i
         if (i.ge.Nlay+1) then
            marks(Nelem)=z(Nlay)/1.0D+3
         else
            marks(Nelem)=(z(i-1)+z(i))/2.0D+3
         endif
         i=i+i_inc
      enddo
      nap=2
      call make_tics(Nelem,xvalues,marks,nap,alt_tics_str)

      i=0
      i_inc=10
      Nelem=0
      do while (i.lt.Nlay+1+i_inc)
         Nelem=Nelem+1
         xvalues(Nelem)=i
         if (i.le.0) then
            marks(Nelem)=pres(0)/1.0D+2
         else if (i.ge.Nlay) then
            marks(Nelem)=pres(Nlay)/1.0D+2
         else
            marks(Nelem)=(pres(i-1)+pres(i))/1.0D+2
         endif
         i=i+i_inc
      enddo
      nap=2
      call make_tics(Nelem,xvalues,marks,nap,pres_tics_str)

c     Analyzing results for maximum values
c
      band_total_budget_max=0.0D+0
      band_gas_ground_budget_max=0.0D+0
      band_gas_space_budget_max=0.0D+0
      band_gas_gas_budget_max=0.0D+0
      absolute_band_NER_max=0.0D+0
      band_upward_flux_max=0.0D+0
      band_downward_flux_max=0.0D+0
      band_net_flux_max=0.0D+0
      do band=first_band,last_band
c     Looking for max value of NER in current band, only among gas-gas NERs
         band_NER_max(band)=0.0D+0
         do i=1,Nlay
            do j=1,Nlay
               if (band_NER(i,j,band).gt.band_NER_max(band)) then
                  band_NER_max(band)=band_NER(i,j,band)
               endif
            enddo ! j
         enddo ! i
c     Looking for absolute maximum of band NER
         absolute_band_NER_max=absolute_band_NER_max
     &        +band_NER_max(band)
c     Looking for max value of radiative budget (mW/m^3)
         do i=1,Nlay
            if (band_total_budget(i,band)*1.0D+3.gt.
     &           band_total_budget_max) then
               band_total_budget_max=
     &              band_total_budget(i,band)*1.0D+3 ! mW/m^3
            endif
            if (band_gas_ground_budget(i,band)*1.0D+3.gt.
     &           band_gas_ground_budget_max) then
               band_gas_ground_budget_max=
     &              band_gas_ground_budget(i,band)*1.0D+3 ! mW/m^3
            endif
            if (band_gas_space_budget(i,band)*1.0D+3.gt.
     &           band_gas_space_budget_max) then
               band_gas_space_budget_max=
     &              band_gas_space_budget(i,band)*1.0D+3 ! mW/m^3
            endif
            if (band_gas_gas_budget(i,band)*1.0D+3.gt.
     &           band_gas_gas_budget_max) then
               band_gas_gas_budget_max=
     &              band_gas_gas_budget(i,band)*1.0D+3 ! mW/m^3
            endif
         enddo ! i
c     Looking for max value of fluxes (W/m^2)
         do i=0,Nlay
            if (band_upward_flux(i,band).gt.
     &           band_upward_flux_max) then
               band_upward_flux_max=
     &              band_upward_flux(i,band) ! W/m^3
            endif
            if (band_downward_flux(i,band).gt.
     &           band_downward_flux_max) then
               band_downward_flux_max=
     &              band_downward_flux(i,band) ! W/m^3
            endif
            if (band_net_flux(i,band).gt.
     &           band_net_flux_max) then
               band_net_flux_max=
     &              band_net_flux(i,band) ! W/m^3
            endif
         enddo ! i
      enddo ! band
c     absolute_band_NER_max
      absolute_band_NER_max=absolute_band_NER_max
     &     /dble(last_band-first_band+1)/5.0D+0
c     Looking for maximum spectrally integrated NER value (only in gas-gas net exchanges)
      si_NER_max=0.0D+0
      do i=1,Nlay
         do j=1,Nlay
            if (si_NER(i,j).gt.si_NER_max) then
               si_NER_max=si_NER(i,j)
            endif
         enddo ! j
      enddo ! i
c     modification of max. values in order not to print zeroes only
      do band=first_band,last_band
         if (dabs(band_NER_max(band)).lt.epsilon_ner) then
            band_NER_max(band)=epsilon_ner
         endif
         do i=0,Nlay
            if (dabs(band_net_flux(i,band)).lt.epsilon_flux) then
               band_net_flux(i,band)=epsilon_flux
            endif
         enddo ! i
      enddo ! band
      if (dabs(si_NER_max).lt.epsilon_ner) then
         si_NER_max=epsilon_ner
      endif
      if (dabs(absolute_band_NER_max).lt.epsilon_ner) then
         absolute_band_NER_max=epsilon_ner
      endif
      if (dabs(band_upward_flux_max).lt.epsilon_flux) then
         band_upward_flux_max=epsilon_flux
      endif
      if (dabs(band_downward_flux_max).lt.epsilon_flux) then
         band_downward_flux_max=epsilon_flux
      endif
      if (dabs(band_net_flux_max).lt.epsilon_flux) then
         band_net_flux_max=epsilon_flux
      endif
      if (dabs(band_total_budget_max).lt.epsilon_budget) then
         band_total_budget_max=epsilon_budget
      endif
      if (dabs(band_gas_ground_budget_max).lt.epsilon_budget) then
         band_gas_ground_budget_max=epsilon_budget
      endif
      if (dabs(band_gas_space_budget_max).lt.epsilon_budget) then
         band_gas_space_budget_max=epsilon_budget
      endif
      if (dabs(band_gas_gas_budget_max).lt.epsilon_budget) then
         band_gas_gas_budget_max=epsilon_budget
      endif
c
      if (Nlay.lt.10) then
         call error(label)
         write(*,*) 'Cannot convert Nlay to character string'
         write(*,*) 'Nlay=',Nlay
         write(*,*) '< 10'
         stop
      else if (Nlay.lt.100) then
         call num2str2(Nlay,Nlay_str2)
         Nlay_str=Nlay_str2
      else if (Nlay.lt.1000) then
         call num2str3(Nlay,Nlay_str3)
         Nlay_str=Nlay_str3
      else
         call error(label)
         write(*,*) 'Cannot convert Nlay to character string'
         write(*,*) 'Nlay=',Nlay
         write(*,*) '> 1000'
         stop
      endif
c
      if (Nlay+1.lt.10) then
         call error(label)
         write(*,*) 'Cannot convert Nlay+1 to character string'
         write(*,*) 'Nlay+1=',Nlay+1
         write(*,*) '< 10'
         stop
      else if (Nlay+1.lt.100) then
         call num2str2(Nlay+1,Nlayp1_str2)
         Nlayp1_str=Nlayp1_str2
      else if (Nlay+1.lt.1000) then
         call num2str3(Nlay+1,Nlayp1_str3)
         Nlayp1_str=Nlayp1_str3
      else
         call error(label)
         write(*,*) 'Cannot convert Nlay+1 to character string'
         write(*,*) 'Nlay+1=',Nlay+1
         write(*,*) '> 1000'
         stop
      endif
c
      if (Nlay+2.lt.10) then
         call error(label)
         write(*,*) 'Cannot convert Nlay+2 to character string'
         write(*,*) 'Nlay+2=',Nlay+2
         write(*,*) '< 10'
         stop
      else if (Nlay+2.lt.100) then
         call num2str2(Nlay+2,Nlayp2_str2)
         Nlayp2_str=Nlayp2_str2
      else if (Nlay+2.lt.1000) then
         call num2str3(Nlay+2,Nlayp2_str3)
         Nlayp2_str=Nlayp2_str3
      else
         call error(label)
         write(*,*) 'Cannot convert Nlay+2 to character string'
         write(*,*) 'Nlay+2=',Nlay+2
         write(*,*) '> 1000'
         stop
      endif
c
      if (first_band.lt.10) then
         call num2str1(first_band,fband_str1)
         fband_str=fband_str1
      else if (first_band.lt.100) then
         call num2str2(first_band,fband_str2)
         fband_str=fband_str2
      else if (first_band.lt.1000) then
         call num2str3(first_band,fband_str3)
         fband_str=fband_str3
      else
         call error(label)
         write(*,*) 'Cannot convert first_band to character string'
         write(*,*) 'first_band=',first_band
         stop
      endif
c
      if (last_band.lt.10) then
         call num2str1(last_band,lband_str1)
         lband_str=lband_str1
      else if (last_band.lt.100) then
         call num2str2(last_band,lband_str2)
         lband_str=lband_str2
      else if (last_band.lt.1000) then
         call num2str3(last_band,lband_str3)
         lband_str=lband_str3
      else
         call error(label)
         write(*,*) 'Cannot convert last_band to character string'
         write(*,*) 'last_band=',last_band
         stop
      endif
c
      call num2str3(int(si_Tb),si_Tb_str3)
c
c     + band limits
      result_file='narrowband_limits.txt'
      filename='./results/'
     &     //result_file(1:strlen(result_file))
      open(10,file=filename(1:strlen(filename)))
      write(10,*) last_band-first_band+1
      do band=first_band,last_band
         write(10,*) lambda_lo(band),lambda_hi(band)
      enddo ! band
      close(10)

c     + altitude limits
      result_file='atmospheric_layers_limits.txt'
      filename='./results/'
     &     //result_file(1:strlen(result_file))
      open(10,file=filename(1:strlen(filename)))
      write(10,*) Nlay
      do i=1,Nlay
         write(10,*) z(i-1)/1.0D+3,z(i)/1.0D+3
      enddo ! i
      close(10)

c     + NER
      result_file='si_NER.txt'
      filename='./results/'
     &     //result_file(1:strlen(result_file))
      open(11,file=filename(1:strlen(filename)))
      write(11,10) '# Spectrally integrated NER matrix (W/m^2)'
      do i=0,Nlay+1
         write(11,48) (si_NER(i,j),j=0,Nlay+1)
      enddo ! i
      close(11)
      result_file='si_NER.dat'
      filename='./results/'
     &     //result_file(1:strlen(result_file))
      open(11,file=filename(1:strlen(filename)))
      do i=0,Nlay+1
         do j=0,Nlay+1
            write(11,*) i,j,si_NER(i,j)
         enddo ! j
         write(11,*)
      enddo ! i
      close(11)
      gra_file='./results/gra_si_NER'
      open(10,file=gra_file(1:strlen(gra_file)))
      write(10,10) 'set term pdf enhanced color '
     &     //'font "helvetica,20" linewidth 1 size 10,6'
      write(10,10) 'set output "si_NER.pdf"'
      write(10,10) 'set grid layerdefault'
      write(10,10) 'set size square'
c      write(10,10) 'set xlabel "layer index i"'
c      write(10,10) 'set ylabel "layer index j"'
      if (pres_or_alt.eq.1) then
         write(10,10) 'set xlabel "P (hPa)"'
         write(10,10) 'set ylabel "P (hPa)"'
      else
         write(10,10) 'set xlabel "Altitude (km)"'
         write(10,10) 'set ylabel "Altitude (km)"'
      endif
      write(10,10) 'set palette defined (0 "navy", 1 "blue", '
     &     //'2 "skyblue", 3 "turquoise", 4 "white", '
     &     //'5 "khaki", 6 "yellow", 7 "orange", 8 "red")'
      write(10,10) 'set pm3d'
      write(10,10) 'set view map'
      write(10,10) 'set xrange [0:'
     &     //Nlayp1_str(1:strlen(Nlayp1_str))
     &     //']'
      if (pres_or_alt.eq.1) then
         write(10,10) 'set xtics rotate 90 '
     &        //pres_tics_str(1:strlen(pres_tics_str))
      else
         write(10,10) 'set xtics rotate 90 '
     &        //alt_tics_str(1:strlen(alt_tics_str))
      endif
      write(10,10) 'set yrange [0:'
     &     //Nlayp1_str(1:strlen(Nlayp1_str))
     &     //']'
      if (pres_or_alt.eq.1) then
         write(10,10) 'set ytics '
     &        //pres_tics_str(1:strlen(pres_tics_str))
      else
         write(10,10) 'set ytics '
     &        //alt_tics_str(1:strlen(alt_tics_str))
      endif
      call dble2str_noexp(si_NER_max,3,si_NER_max_str,err)
      if (err.ne.0) then
         call error(label)
         write(*,*) 'Error while converting to character string:'
         write(*,*) 'si_NER_max=',si_NER_max
         stop
      endif
      write(10,10) 'set cbrange [-'
     &     //si_NER_max_str(1:strlen(si_NER_max_str))
     &     //':'
     &     //si_NER_max_str(1:strlen(si_NER_max_str))
     &     //']'
      call dble2str_noexp(lambda_lo(first_band),3,lambda_lo_str,err)
      if (err.ne.0) then
         call error(label)
         write(*,*) 'Error while converting to character string:'
         write(*,*) 'lambda_lo(',first_band,')=',lambda_lo(first_band)
         stop
      endif
      call dble2str_noexp(lambda_hi(last_band),3,lambda_hi_str,err)
      if (err.ne.0) then
         call error(label)
         write(*,*) 'Error while converting to character string:'
         write(*,*) 'lambda_hi(',last_band,')=',lambda_hi(last_band)
         stop
      endif
      title_str='spectrally integrated NER matrix (W/m^{2})'
     &     //'\n{/Symbol l}=['
     &        //lambda_lo_str(1:strlen(lambda_lo_str))
     &        //','
     &        //lambda_hi_str(1:strlen(lambda_hi_str))
     &        //'] {/Symbol m}m'
      if (atm_profile.eq.1) then
         if (pidx.eq.1) then
            profile_str='Tropical'
         else if (pidx.eq.2) then
            profile_str='Mid-Latitude Summer'
         else if (pidx.eq.3) then
            profile_str='Mid-Latitude Winter'
         else if (pidx.eq.4) then
            profile_str='Sub-arctic Summer'
         else if (pidx.eq.5) then
            profile_str='Sub-arctic Winter'
         else
            call error(label)
            write(*,*) 'pidx=',pidx
            write(*,*) 'allowed values: 1-5'
            stop
         endif
         title_str=title_str(1:strlen(title_str))
     &        //'\n '
     &        //profile_str(1:strlen(profile_str))
      endif
      write(10,10) 'set title "'
     &     //title_str(1:strlen(title_str))
     &     //'"'
      write(10,10) 'plot "./'
     &     //result_file(1:strlen(result_file))
     &     //'" u 1:2:3 w image notitle'
      write(10,*)
      write(10,10) 'quit'
      close(10)

      gra_file='./results/gra_band_NER'
      open(10,file=gra_file(1:strlen(gra_file)))
      write(10,10) 'set term pdf enhanced color '
     &     //'font "helvetica,20" linewidth 1 size 10,6'
      write(10,10) 'set output "band_NER.pdf"'
      do band=first_band,last_band
         call num2str3(band,band_str3)
         result_file='NER_band'//band_str3(1:strlen(band_str3))//'.dat'
         filename='./results/'
     &        //result_file(1:strlen(result_file))
         open(11,file=filename(1:strlen(filename)))
         do i=0,Nlay+1
            do j=0,Nlay+1
               write(11,*) i,j,band_NER(i,j,band)
            enddo ! j
            write(11,*)
         enddo ! i
         close(11)
         write(10,*)
         write(10,10) 'set grid layerdefault'
         write(10,10) 'set size square'
c         write(10,10) 'set xlabel "layer index i"'
c         write(10,10) 'set ylabel "layer index j"'
         if (pres_or_alt.eq.1) then
            write(10,10) 'set xlabel "P (hPa)"'
            write(10,10) 'set ylabel "P (hPa)"'
         else
            write(10,10) 'set xlabel "Altitude (km)"'
            write(10,10) 'set ylabel "Altitude (km)"'
         endif
         write(10,10) 'set palette defined (0 "navy", 1 "blue", '
     &        //'2 "skyblue", 3 "turquoise", 4 "white", '
     &        //'5 "khaki", 6 "yellow", 7 "orange", 8 "red")'
         write(10,10) 'set pm3d'
         write(10,10) 'set view map'
         write(10,10) 'set xrange [0:'
     &     //Nlayp1_str(1:strlen(Nlayp1_str))
     &     //']'
         if (pres_or_alt.eq.1) then
            write(10,10) 'set xtics rotate 90 '
     &           //pres_tics_str(1:strlen(pres_tics_str))
         else
            write(10,10) 'set xtics rotate 90 '
     &           //alt_tics_str(1:strlen(alt_tics_str))
         endif
         write(10,10) 'set yrange [0:'
     &     //Nlayp1_str(1:strlen(Nlayp1_str))
     &     //']'
         if (pres_or_alt.eq.1) then
            write(10,10) 'set ytics '
     &           //pres_tics_str(1:strlen(pres_tics_str))
         else
            write(10,10) 'set ytics '
     &           //alt_tics_str(1:strlen(alt_tics_str))
         endif
c         if (band_NER_max(band).eq.0.0D+0) then
c            call warning(label)
c            write(*,*) 'band_NER_max(',band,')=',band_NER_max(band)
c         endif
         call dble2str_noexp(band_NER_max(band),3,band_NER_max_str,err)
         if (err.ne.0) then
            call error(label)
            write(*,*) 'Error while converting to character string:'
            write(*,*) 'band_NER_max(',band,')=',band_NER_max(band)
            stop
         endif
         write(10,10) 'set cbrange [-'
     &        //band_NER_max_str(1:strlen(band_NER_max_str))
     &        //':'
     &        //band_NER_max_str(1:strlen(band_NER_max_str))
     &        //']'
         call dble2str_noexp(lambda_lo(band),3,lambda_lo_str,err)
         if (err.ne.0) then
            call error(label)
            write(*,*) 'Error while converting to character string:'
            write(*,*) 'lambda_lo(',band,')=',lambda_lo(band)
            stop
         endif
         call dble2str_noexp(lambda_hi(band),3,lambda_hi_str,err)
         if (err.ne.0) then
            call error(label)
            write(*,*) 'Error while converting to character string:'
            write(*,*) 'lambda_hi(',band,')=',lambda_hi(band)
            stop
         endif
         title_str='NER matrix (W/m^{2}) in band '
     &        //band_str3(1:strlen(band_str3))
     &        //'\n{/Symbol l}=['
     &        //lambda_lo_str(1:strlen(lambda_lo_str))
     &        //','
     &        //lambda_hi_str(1:strlen(lambda_hi_str))
     &        //'] {/Symbol m}m'
         if (atm_profile.eq.1) then
            if (pidx.eq.1) then
               profile_str='Tropical'
            else if (pidx.eq.2) then
               profile_str='Mid-Latitude Summer'
            else if (pidx.eq.3) then
               profile_str='Mid-Latitude Winter'
            else if (pidx.eq.4) then
               profile_str='Sub-arctic Summer'
            else if (pidx.eq.5) then
               profile_str='Sub-arctic Winter'
            else
               call error(label)
               write(*,*) 'pidx=',pidx
               write(*,*) 'allowed values: 1-5'
               stop
            endif
            title_str=title_str(1:strlen(title_str))
     &           //'\n '
     &           //profile_str(1:strlen(profile_str))
         endif
         write(10,10) 'set title "'
     &        //title_str(1:strlen(title_str))
     &        //'"'
         write(10,10) 'plot "./'
     &        //result_file(1:strlen(result_file))
     &        //'" u 1:2:3 w image notitle'
      enddo ! band
      write(10,*)
      write(10,10) 'quit'
      close(10)

c     - for NER animation
      open(10,file='./results/NER_animation/first_band')
      write(10,*) first_band
      close(10)
      open(10,file='./results/NER_animation/last_band')
      write(10,*) last_band
      close(10)
      command='rm -f ./results/NER_animation/NER_band*.dat'
      call exec(command)
      command='rm -f ./results/NER_animation/plot_NER_band*'
      call exec(command)
      command='rm -f ./results/NER_animation/gra_NER_band*'
      call exec(command)
      do band=first_band,last_band
         call num2str3(band,band_str3)
         result_file='NER_band'//band_str3(1:strlen(band_str3))//'.dat'
         filename='./results/NER_animation/'
     &        //result_file(1:strlen(result_file))
         open(11,file=filename(1:strlen(filename)))
         do i=0,Nlay+1
            do j=0,Nlay+1
               write(11,*) i,j,band_NER(i,j,band)
            enddo               ! j
            write(11,*)
         enddo                  ! i
         close(11)
         gnu_file='plot_NER_band'
     &        //band_str3(1:strlen(band_str3))
         gnu_filename='./results/NER_animation/'
     &        //gnu_file(1:strlen(gnu_file))
         gra_file='gra_NER_band'
     &        //band_str3(1:strlen(band_str3))
         gra_filename='./results/NER_animation/'
     &        //gra_file(1:strlen(gra_file))
         pdf_file='NER_band'
     &        //band_str3(1:strlen(band_str3))
     &        //'.pdf'
         open(10,file=gnu_filename(1:strlen(gnu_filename)))
         write(10,10) 'gnuplot '
     &        //gra_file(1:strlen(gra_file))
         write(10,10) '#gv --orientation=LANDSCAPE '
     &        //pdf_file(1:strlen(pdf_file))
     &        //' &'
         close(10)
         open(10,file=gra_filename(1:strlen(gra_filename)))
         write(10,10) 'set term pdf enhanced color '
     &        //'font "helvetica,20" linewidth 1 size 10,6'
         write(10,10) 'set output "'
     &        //pdf_file(1:strlen(pdf_file))
     &        //'"'
         write(10,*)
         write(10,10) 'set grid layerdefault'
         write(10,10) 'set size square'
c         write(10,10) 'set xlabel "layer index i"'
c         write(10,10) 'set ylabel "layer index j"'
         if (pres_or_alt.eq.1) then
            write(10,10) 'set xlabel "P (hPa)"'
            write(10,10) 'set ylabel "P (hPa)"'
         else
            write(10,10) 'set xlabel "Altitude (km)"'
            write(10,10) 'set ylabel "Altitude (km)"'
         endif
         write(10,10) 'set palette defined (0 "navy", 1 "blue", '
     &        //'2 "skyblue", 3 "turquoise", 4 "white", '
     &        //'5 "khaki", 6 "yellow", 7 "orange", 8 "red")'
         write(10,10) 'set pm3d'
         write(10,10) 'set view map'
         write(10,10) 'set xrange [0:'
     &        //Nlayp1_str(1:strlen(Nlayp1_str))
     &        //']'
         if (pres_or_alt.eq.1) then
            write(10,10) 'set xtics rotate 90 '
     &           //pres_tics_str(1:strlen(pres_tics_str))
         else
            write(10,10) 'set xtics rotate 90 '
     &           //alt_tics_str(1:strlen(alt_tics_str))
         endif
         write(10,10) 'set yrange [0:'
     &        //Nlayp1_str(1:strlen(Nlayp1_str))
     &        //']'
         if (pres_or_alt.eq.1) then
            write(10,10) 'set ytics '
     &           //pres_tics_str(1:strlen(pres_tics_str))
         else
            write(10,10) 'set ytics '
     &           //alt_tics_str(1:strlen(alt_tics_str))
         endif
c         if (band_NER_max(band).eq.0.0D+0) then
c            call warning(label)
c            write(*,*) 'band_NER_max(',band,')=',band_NER_max(band)
c         endif
         call dble2str_noexp(absolute_band_NER_max,3,
     &        band_NER_max_str,err)
         if (err.ne.0) then
            call error(label)
            write(*,*) 'Error while converting to character string:'
            write(*,*) 'absolute_band_NER_max=',absolute_band_NER_max
            stop
         endif
         write(10,10) 'set cbrange [-'
     &        //band_NER_max_str(1:strlen(band_NER_max_str))
     &        //':'
     &        //band_NER_max_str(1:strlen(band_NER_max_str))
     &        //']'
         call dble2str_noexp(lambda_lo(band),3,lambda_lo_str,err)
         if (err.ne.0) then
            call error(label)
            write(*,*) 'Error while converting to character string:'
            write(*,*) 'lambda_lo(',band,')=',lambda_lo(band)
            stop
         endif
         call dble2str_noexp(lambda_hi(band),3,lambda_hi_str,err)
         if (err.ne.0) then
            call error(label)
            write(*,*) 'Error while converting to character string:'
            write(*,*) 'lambda_hi(',band,')=',lambda_hi(band)
            stop
         endif
         title_str='NER matrix (W/m^{2}) in band '
     &        //band_str3(1:strlen(band_str3))
     &        //'\n{/Symbol l}=['
     &        //lambda_lo_str(1:strlen(lambda_lo_str))
     &        //','
     &        //lambda_hi_str(1:strlen(lambda_hi_str))
     &        //'] {/Symbol m}m'
         if (atm_profile.eq.1) then
            if (pidx.eq.1) then
               profile_str='Tropical'
            else if (pidx.eq.2) then
               profile_str='Mid-Latitude Summer'
            else if (pidx.eq.3) then
               profile_str='Mid-Latitude Winter'
            else if (pidx.eq.4) then
               profile_str='Sub-arctic Summer'
            else if (pidx.eq.5) then
               profile_str='Sub-arctic Winter'
            else
               call error(label)
               write(*,*) 'pidx=',pidx
               write(*,*) 'allowed values: 1-5'
               stop
            endif
            title_str=title_str(1:strlen(title_str))
     &           //'\n '
     &           //profile_str(1:strlen(profile_str))
         endif
         write(10,10) 'set title "'
     &        //title_str(1:strlen(title_str))
     &        //'"'
         write(10,10) 'plot "./'
     &        //result_file(1:strlen(result_file))
     &        //'" u 1:2:3 w image notitle'
         write(10,*)
         write(10,10) 'quit'
         close(10)
      enddo                     ! band
      
c     + budget
      result_file='si_budget.txt'
      filename='./results/'
     &     //result_file(1:strlen(result_file))
      open(12,file=filename(1:strlen(filename)))
      write(12,10) '# Spectrally integrated radiative budget (W/m^3)'
      write(12,10) '# Lower limit of layer (m) '
     &     //'/ Higher limit of layer (m) '
     &     //'/ Budget from NERs (W/m^3) '
     &     //'/ Budget from net fluxes (W/m^3) '
     &     //'/ Gas-ground budget (W/m^3) '
     &     //'/ Gas-space budget (W/m^3) '
     &     //'/ Gas-gas budget (W/m^3)'
      do i=1,Nlay
         write(12,48) z(i-1),z(i)
     &        ,si_budget_from_NERs(i)
     &        ,si_budget_from_net_fluxes(i)
     &        ,si_gas_ground(i)
     &        ,si_gas_space(i)
     &        ,si_gas_gas(i)
      enddo ! i
      close(12)
c     - total budget, per band
      result_file='total_budget.dat'
      filename='./results/'
     &     //result_file(1:strlen(result_file))
      open(12,file=filename(1:strlen(filename)))
      do band=first_band,last_band
         do i=1,Nlay
            write(12,*) band
     &           ,i
     &           ,(lambda_lo(band)+lambda_hi(band))/2.0D+0 ! microns
     &           ,(z(i-1)+z(i))/2.0D+3 ! km
     &           ,band_total_budget(i,band)*1.0D+3 ! mW/m^3
         enddo ! i
         write(12,*)
      enddo ! band
      close(12)
      gra_file='./results/gra_total_budget'
      open(12,file=gra_file(1:strlen(gra_file)))
      write(12,10) 'set term pdf enhanced color '
     &     //'font "helvetica,20" linewidth 1 size 10,6'
      write(12,10) 'set output "total_budget.pdf"'
      write(12,10) 'set grid layerdefault'
      write(12,10) 'set size square'
c      write(12,10) 'set xlabel "band index"'
c      write(12,10) 'set ylabel "layer index"'
      write(12,10) 'set xlabel "{/Symbol l} ({/Symbol m}m)"'
      if (pres_or_alt.eq.1) then
         write(12,10) 'set ylabel "P (hPa)"'
      else
         write(12,10) 'set ylabel "Altitude (km)"'
      endif
      write(12,10) 'set palette defined (0 "white", 1 "khaki", '
     &     //'2 "yellow", 3 "orange", 4 "red", 5 "brown")'
      write(12,10) 'set pm3d'
      write(12,10) 'set view map'
      write(12,10) 'set xrange ['
     &     //fband_str(1:strlen(fband_str))
     &     //':'
     &     //lband_str(1:strlen(lband_str))
     &     //']'
      write(12,10) 'set xtics rotate 90 '
     &     //band_tics_str(1:strlen(band_tics_str))
      write(12,10) 'set yrange [1:'
     &     //Nlay_str(1:strlen(Nlay_str))
     &     //']'
      if (pres_or_alt.eq.1) then
         write(12,10) 'set ytics '
     &        //pres_tics_str(1:strlen(pres_tics_str))
      else
         write(12,10) 'set ytics '
     &        //alt_tics_str(1:strlen(alt_tics_str))
      endif
      call dble2str_noexp(band_total_budget_max,3,
     &     band_total_budget_max_str,err)
      if (err.ne.0) then
         call error(label)
         write(*,*) 'Error while converting to character string:'
         write(*,*) 'band_total_budget_max=',band_total_budget_max
         stop
      endif
      write(12,10) 'set cbrange [0:'
     &     //band_total_budget_max_str
     &     (1:strlen(band_total_budget_max_str))
     &     //']'
      write(12,10) 'set title "Total radiative budget (mW/m^{3})"'
      write(12,10) 'plot "./'
     &     //result_file(1:strlen(result_file))
     &     //'" u 1:2:5 notitle w image'
      write(12,*)
      write(12,10) 'quit'
      close(12)
c     - gas-ground budget, per band
      result_file='gas_ground_budget.dat'
      filename='./results/'
     &     //result_file(1:strlen(result_file))
      open(12,file=filename(1:strlen(filename)))
      do band=first_band,last_band
         do i=1,Nlay
            write(12,*) band
     &           ,i
     &           ,(lambda_lo(band)+lambda_hi(band))/2.0D+0 ! microns
     &           ,(z(i-1)+z(i))/2.0D+3 ! km
     &           ,band_gas_ground_budget(i,band)*1.0D+3 ! mW/m^3
         enddo ! i
         write(12,*)
      enddo ! band
      close(12)
      gra_file='./results/gra_gas_ground_budget'
      open(12,file=gra_file(1:strlen(gra_file)))
      write(12,10) 'set term pdf enhanced color '
     &     //'font "helvetica,20" linewidth 1 size 10,6'
      write(12,10) 'set output "gas_ground_budget.pdf"'
      write(12,10) 'set grid layerdefault'
      write(12,10) 'set size square'
c      write(12,10) 'set xlabel "band index"'
c      write(12,10) 'set ylabel "layer index"'
      write(12,10) 'set xlabel "{/Symbol l} ({/Symbol m}m)"'
      if (pres_or_alt.eq.1) then
         write(12,10) 'set ylabel "P (hPa)"'
      else
         write(12,10) 'set ylabel "Altitude (km)"'
      endif
      write(12,10) 'set palette defined (0 "white", 1 "khaki", '
     &     //'2 "yellow", 3 "orange", 4 "red", 5 "brown")'
      write(12,10) 'set pm3d'
      write(12,10) 'set view map'
      write(12,10) 'set xrange ['
     &     //fband_str(1:strlen(fband_str))
     &     //':'
     &     //lband_str(1:strlen(lband_str))
     &     //']'
      write(12,10) 'set xtics rotate 90 '
     &     //band_tics_str(1:strlen(band_tics_str))
      write(12,10) 'set yrange [1:'
     &     //Nlay_str(1:strlen(Nlay_str))
     &     //']'
      if (pres_or_alt.eq.1) then
         write(12,10) 'set ytics '
     &        //pres_tics_str(1:strlen(pres_tics_str))
      else
         write(12,10) 'set ytics '
     &        //alt_tics_str(1:strlen(alt_tics_str))
      endif
      call dble2str_noexp(band_gas_ground_budget_max,3,
     &     band_gas_ground_budget_max_str,err)
      if (err.ne.0) then
         call error(label)
         write(*,*) 'Error while converting to character string:'
         write(*,*) 'band_gas_ground_budget_max=',
     &        band_gas_ground_budget_max
         stop
      endif
      write(12,10) 'set cbrange [0:'
     &     //band_gas_ground_budget_max_str
     &     (1:strlen(band_gas_ground_budget_max_str))
     &     //']'
      write(12,10) 'set title "Gas-ground radiative budget (mW/m^{3})"'
      write(12,10) 'plot "./'
     &     //result_file(1:strlen(result_file))
     &     //'" u 1:2:5 notitle w image'
      write(12,*)
      write(12,10) 'quit'
      close(12)
c     - gas-space budget, per band
      result_file='gas_space_budget.dat'
      filename='./results/'
     &     //result_file(1:strlen(result_file))
      open(12,file=filename(1:strlen(filename)))
      do band=first_band,last_band
         do i=1,Nlay
            write(12,*) band
     &           ,i
     &           ,(lambda_lo(band)+lambda_hi(band))/2.0D+0 ! microns
     &           ,(z(i-1)+z(i))/2.0D+3 ! km
     &           ,band_gas_space_budget(i,band)*1.0D+3 ! mW/m^3
         enddo ! i
         write(12,*)
      enddo ! band
      close(12)
      gra_file='./results/gra_gas_space_budget'
      open(12,file=gra_file(1:strlen(gra_file)))
      write(12,10) 'set term pdf enhanced color '
     &     //'font "helvetica,20" linewidth 1 size 10,6'
      write(12,10) 'set output "gas_space_budget.pdf"'
      write(12,10) 'set grid layerdefault'
      write(12,10) 'set size square'
c      write(12,10) 'set xlabel "band index"'
c      write(12,10) 'set ylabel "layer index"'
      write(12,10) 'set xlabel "{/Symbol l} ({/Symbol m}m)"'
      if (pres_or_alt.eq.1) then
         write(12,10) 'set ylabel "P (hPa)"'
      else
         write(12,10) 'set ylabel "Altitude (km)"'
      endif
      write(12,10) 'set palette defined (0 "white", 1 "khaki", '
     &     //'2 "yellow", 3 "orange", 4 "red", 5 "brown")'
      write(12,10) 'set pm3d'
      write(12,10) 'set view map'
      write(12,10) 'set xrange ['
     &     //fband_str(1:strlen(fband_str))
     &     //':'
     &     //lband_str(1:strlen(lband_str))
     &     //']'
      write(12,10) 'set xtics rotate 90 '
     &     //band_tics_str(1:strlen(band_tics_str))
      write(12,10) 'set yrange [1:'
     &     //Nlay_str(1:strlen(Nlay_str))
     &     //']'
      if (pres_or_alt.eq.1) then
         write(12,10) 'set ytics '
     &        //pres_tics_str(1:strlen(pres_tics_str))
      else
         write(12,10) 'set ytics '
     &        //alt_tics_str(1:strlen(alt_tics_str))
      endif
      call dble2str_noexp(band_gas_space_budget_max,3,
     &     band_gas_space_budget_max_str,err)
      if (err.ne.0) then
         call error(label)
         write(*,*) 'Error while converting to character string:'
         write(*,*) 'band_gas_space_budget_max=',
     &        band_gas_space_budget_max
         stop
      endif
      write(12,10) 'set cbrange [0:'
     &     //band_gas_space_budget_max_str
     &     (1:strlen(band_gas_space_budget_max_str))
     &     //']'
      write(12,10) 'set title "Gas-space radiative budget (mW/m^{3})"'
      write(12,10) 'plot "./'
     &     //result_file(1:strlen(result_file))
     &     //'" u 1:2:5 notitle w image'
      write(12,*)
      write(12,10) 'quit'
      close(12)
c     - gas-gas budget, per band
      result_file='gas_gas_budget.dat'
      filename='./results/'
     &     //result_file(1:strlen(result_file))
      open(12,file=filename(1:strlen(filename)))
      do band=first_band,last_band
         do i=1,Nlay
            write(12,*) band
     &           ,i
     &           ,(lambda_lo(band)+lambda_hi(band))/2.0D+0 ! microns
     &           ,(z(i-1)+z(i))/2.0D+3 ! km
     &           ,band_gas_gas_budget(i,band)*1.0D+3 ! mW/m^3
         enddo ! i
         write(12,*)
      enddo ! band
      close(12)
      gra_file='./results/gra_gas_gas_budget'
      open(12,file=gra_file(1:strlen(gra_file)))
      write(12,10) 'set term pdf enhanced color '
     &     //'font "helvetica,20" linewidth 1 size 10,6'
      write(12,10) 'set output "gas_gas_budget.pdf"'
      write(12,10) 'set grid layerdefault'
      write(12,10) 'set size square'
c      write(12,10) 'set xlabel "band index"'
c      write(12,10) 'set ylabel "layer index"'
      write(12,10) 'set xlabel "{/Symbol l} ({/Symbol m}m)"'
      if (pres_or_alt.eq.1) then
         write(12,10) 'set ylabel "P (hPa)"'
      else
         write(12,10) 'set ylabel "Altitude (km)"'
      endif
      write(12,10) 'set palette defined (0 "white", 1 "khaki", '
     &     //'2 "yellow", 3 "orange", 4 "red", 5 "brown")'
      write(12,10) 'set pm3d'
      write(12,10) 'set view map'
      write(12,10) 'set xrange ['
     &     //fband_str(1:strlen(fband_str))
     &     //':'
     &     //lband_str(1:strlen(lband_str))
     &     //']'
      write(12,10) 'set xtics rotate 90 '
     &     //band_tics_str(1:strlen(band_tics_str))
      write(12,10) 'set yrange [1:'
     &     //Nlay_str(1:strlen(Nlay_str))
     &     //']'
      if (pres_or_alt.eq.1) then
         write(12,10) 'set ytics '
     &        //pres_tics_str(1:strlen(pres_tics_str))
      else
         write(12,10) 'set ytics '
     &        //alt_tics_str(1:strlen(alt_tics_str))
      endif
      call dble2str_noexp(band_gas_gas_budget_max,3,
     &     band_gas_gas_budget_max_str,err)
      if (err.ne.0) then
         call error(label)
         write(*,*) 'Error while converting to character string:'
         write(*,*) 'band_gas_gas_budget_max=',
     &        band_gas_gas_budget_max
         stop
      endif
      write(12,10) 'set cbrange [0:'
     &     //band_gas_gas_budget_max_str
     &     (1:strlen(band_gas_gas_budget_max_str))
     &     //']'
      write(12,10) 'set title "Gas-gas radiative budget (mW/m^{3})"'
      write(12,10) 'plot "./'
     &     //result_file(1:strlen(result_file))
     &     //'" u 1:2:5 notitle w image'
      write(12,*)
      write(12,10) 'quit'
      close(12)

c     + flux
      result_file='si_flux.txt'
      filename='./results/'
     &     //result_file(1:strlen(result_file))
      open(13,file=filename(1:strlen(filename)))
      write(13,10) '# Spectrally integrated fluxes (W/m^2)'
      write(13,10) '# Altitude (km) '
     &     //'/ Upward flux (W/m^2) '
     &     //'/ Downward flux (W/m^2) '
     &     //'/ Net flux (W/m^2)'
      do i=0,Nlay
         write(13,48) z(i)/1.0D+3
     &        ,si_upward_flux(i)
     &        ,si_downward_flux(i)
     &        ,si_net_flux(i)
      enddo ! i
      close(13)
c     - upward flux, per band
      result_file='upward_flux.dat'
      filename='./results/'
     &     //result_file(1:strlen(result_file))
      open(13,file=filename(1:strlen(filename)))
      do band=first_band,last_band
         do i=0,Nlay
            write(13,*) band
     &           ,i
     &           ,(lambda_lo(band)+lambda_hi(band))/2.0D+0 ! microns
     &           ,pres(i) ! Pa
     &           ,band_upward_flux(i,band)
     &           /(lambda_hi(band)-lambda_lo(band)) ! W/m^2/micron
         enddo ! i
         write(13,*)
      enddo ! band
      close(13)
      gra_file='./results/gra_upward_flux'
      open(13,file=gra_file(1:strlen(gra_file)))
      write(13,10) 'set term pdf enhanced color '
     &     //'font "helvetica,20" linewidth 1 size 10,6'
      write(13,10) 'set output "upward_flux.pdf"'
      write(13,10) 'set grid layerdefault'
      write(13,10) 'set size square'
c      write(13,10) 'set xlabel "band index"'
      write(13,10) 'set xlabel "{/Symbol l} ({/Symbol m}m)"'
c      write(13,10) 'set ylabel "interface index"'
      if (pres_or_alt.eq.1) then
         write(13,10) 'set ylabel "P (hPa)"'
      else
         write(13,10) 'set ylabel "Altitude (km)"'
      endif
      write(13,10) 'set palette defined (0 "white", 1 "khaki", '
     &     //'2 "yellow", 3 "orange", 4 "red", 5 "brown")'
      write(13,10) 'set pm3d'
      write(13,10) 'set view map'
      write(13,10) 'set xrange ['
     &     //fband_str(1:strlen(fband_str))
     &     //':'
     &     //lband_str(1:strlen(lband_str))
     &     //']'
      write(13,10) 'set xtics rotate 90 '
     &     //band_tics_str(1:strlen(band_tics_str))
      write(13,10) 'set yrange [0:'
     &     //Nlay_str(1:strlen(Nlay_str))
     &     //']'
      if (pres_or_alt.eq.1) then
         write(13,10) 'set ytics '
     &        //pres_tics_str(1:strlen(pres_tics_str))
      else
         write(13,10) 'set ytics '
     &        //alt_tics_str(1:strlen(alt_tics_str))
      endif
      call dble2str_noexp(band_upward_flux_max,3,
     &     band_upward_flux_max_str,err)
      if (err.ne.0) then
         call error(label)
         write(*,*) 'Error while converting to character string:'
         write(*,*) 'band_upward_flux_max=',band_upward_flux_max
         stop
      endif
      write(13,10) 'set cbrange [0:'
     &     //band_upward_flux_max_str
     &     (1:strlen(band_upward_flux_max_str))
     &     //']'
      write(13,10) 'set title "Upward flux (W/m^{2})"'
      write(13,10) 'plot "./'
     &     //result_file(1:strlen(result_file))
     &     //'" u 1:2:5 notitle w image'
      write(13,*)
      write(13,10) 'quit'
      close(13)
c     - downward flux, per band
      result_file='downward_flux.dat'
      filename='./results/'
     &     //result_file(1:strlen(result_file))
      open(13,file=filename(1:strlen(filename)))
      do band=first_band,last_band
         do i=0,Nlay
            write(13,*) band
     &           ,i
     &           ,(lambda_lo(band)+lambda_hi(band))/2.0D+0 ! microns
     &           ,pres(i) ! Pa
     &           ,band_downward_flux(i,band)
     &           /(lambda_hi(band)-lambda_lo(band)) ! W/m^2/micron
         enddo ! i
         write(13,*)
      enddo ! band
      close(13)
      gra_file='./results/gra_downward_flux'
      open(13,file=gra_file(1:strlen(gra_file)))
      write(13,10) 'set term pdf enhanced color '
     &     //'font "helvetica,20" linewidth 1 size 10,6'
      write(13,10) 'set output "downward_flux.pdf"'
      write(13,10) 'set grid layerdefault'
      write(13,10) 'set size square'
c      write(13,10) 'set xlabel "band index"'
      write(13,10) 'set xlabel "{/Symbol l} ({/Symbol m}m)"'
c      write(13,10) 'set ylabel "interface index"'
      if (pres_or_alt.eq.1) then
         write(13,10) 'set ylabel "P (hPa)"'
      else
         write(13,10) 'set ylabel "Altitude (km)"'
      endif
      write(13,10) 'set palette defined (0 "white", 1 "khaki", '
     &     //'2 "yellow", 3 "orange", 4 "red", 5 "brown")'
      write(13,10) 'set pm3d'
      write(13,10) 'set view map'
      write(13,10) 'set xrange ['
     &     //fband_str(1:strlen(fband_str))
     &     //':'
     &     //lband_str(1:strlen(lband_str))
     &     //']'
      write(13,10) 'set xtics rotate 90 '
     &     //band_tics_str(1:strlen(band_tics_str))
      write(13,10) 'set yrange [0:'
     &     //Nlay_str(1:strlen(Nlay_str))
     &     //']'
      if (pres_or_alt.eq.1) then
         write(13,10) 'set ytics '
     &        //pres_tics_str(1:strlen(pres_tics_str))
      else
         write(13,10) 'set ytics '
     &        //alt_tics_str(1:strlen(alt_tics_str))
      endif
      call dble2str_noexp(band_downward_flux_max,3,
     &     band_downward_flux_max_str,err)
      if (err.ne.0) then
         call error(label)
         write(*,*) 'Error while converting to character string:'
         write(*,*) 'band_downward_flux_max=',band_downward_flux_max
         stop
      endif
      write(13,10) 'set cbrange [0:'
     &     //band_downward_flux_max_str
     &     (1:strlen(band_downward_flux_max_str))
     &     //']'
      write(13,10) 'set title "Downward flux (W/m^{2})"'
      write(13,10) 'plot "./'
     &     //result_file(1:strlen(result_file))
     &     //'" u 1:2:5 notitle w image'
      write(13,*)
      write(13,10) 'quit'
      close(13)
c     - net flux, per band
      result_file='net_flux.dat'
      filename='./results/'
     &     //result_file(1:strlen(result_file))
      open(13,file=filename(1:strlen(filename)))
      do band=first_band,last_band
         do i=0,Nlay
            write(13,*) band
     &           ,i
     &           ,(lambda_lo(band)+lambda_hi(band))/2.0D+0 ! microns
     &           ,z(i)/1.0D+3 ! km
     &           ,band_net_flux(i,band) ! W/m^2
         enddo ! i
         write(13,*)
      enddo ! band
      close(13)
      gra_file='./results/gra_net_flux'
      open(13,file=gra_file(1:strlen(gra_file)))
      write(13,10) 'set term pdf enhanced color '
     &     //'font "helvetica,20" linewidth 1 size 10,6'
      write(13,10) 'set output "net_flux.pdf"'
      write(13,10) 'set grid layerdefault'
      write(13,10) 'set size square'
c      write(13,10) 'set xlabel "band index"'
      write(13,10) 'set xlabel "{/Symbol l} ({/Symbol m}m)"'
c      write(13,10) 'set ylabel "interface index"'
      if (pres_or_alt.eq.1) then
         write(13,10) 'set ylabel "P (hPa)"'
      else
         write(13,10) 'set ylabel "Altitude (km)"'
      endif
      write(13,10) 'set palette defined (0 "white", 1 "khaki", '
     &     //'2 "yellow", 3 "orange", 4 "red", 5 "brown")'
      write(13,10) 'set pm3d'
      write(13,10) 'set view map'
      write(13,10) 'set xrange ['
     &     //fband_str(1:strlen(fband_str))
     &     //':'
     &     //lband_str(1:strlen(lband_str))
     &     //']'
      write(13,10) 'set xtics rotate 90 '
     &     //band_tics_str(1:strlen(band_tics_str))
      write(13,10) 'set yrange [0:'
     &     //Nlay_str(1:strlen(Nlay_str))
     &     //']'
      if (pres_or_alt.eq.1) then
         write(13,10) 'set ytics '
     &        //pres_tics_str(1:strlen(pres_tics_str))
      else
         write(13,10) 'set ytics '
     &        //alt_tics_str(1:strlen(alt_tics_str))
      endif
      call dble2str_noexp(band_net_flux_max,3,
     &     band_net_flux_max_str,err)
      if (err.ne.0) then
         call error(label)
         write(*,*) 'Error while converting to character string:'
         write(*,*) 'band_net_flux_max=',band_net_flux_max
         stop
      endif
      write(13,10) 'set cbrange [0:'
     &     //band_net_flux_max_str
     &     (1:strlen(band_net_flux_max_str))
     &     //']'
      write(13,10) 'set title "Net flux (W/m^{2})"'
      write(13,10) 'plot "./'
     &     //result_file(1:strlen(result_file))
     &     //'" u 1:2:5 notitle w image'
      write(13,*)
      write(13,10) 'quit'
      close(13)

c     + Observed intensity
      result_file='obs_intensity.txt'
      filename='./results/'
     &     //result_file(1:strlen(result_file))
      open(14,file=filename(1:strlen(filename)))
      write(14,10) '# Observed intensity'
      write(14,10) '# lower wavelength (Âµm) '
     &     //'/ higher wavelength (Âµm) '
     &     //'/ intensity (W/m^2/sr) in band '
     &     //'/ intensity (W/m^2/sr) '
     &     //'at global brightness temperature '
     &     //'/ intensity (W/m^2/sr/Âµm) in band'
     &     //'/ intensity (W/m^2/sr/Âµm) '
     &     //'at global brightness temperature'
      do band=first_band,last_band
         write(14,48) lambda_lo(band)
     &        ,lambda_hi(band)
     &        ,band_obs_intensity(band)
     &        ,planck_int_wavlng(lambda_lo(band),lambda_hi(band),si_Tb)
     &        ,band_obs_intensity(band)
     &        /(lambda_hi(band)-lambda_lo(band))
     &        ,planck_int_wavlng(lambda_lo(band),lambda_hi(band),si_Tb)
     &        /(lambda_hi(band)-lambda_lo(band))
      enddo ! band
      close(14)
      gra_file='./results/gra_int1'
      open(14,file=gra_file(1:strlen(gra_file)))
      write(14,10) 'set xlabel "{/Symbol l} ({/Symbol m}m)"'
      write(14,10) 'set ylabel "Specific intensity (W/m^{2}/sr)"'
      write(14,10) 'set key bottom'
      write(14,10) 'plot \'
      write(14,10) '     "./'
     &     //result_file(1:strlen(result_file))
     &     //'" u (($1+$2)/2):3 title "observed" w lines lt -1 lw 1 \'
      write(14,10) '    ,"./'
     &     //result_file(1:strlen(result_file))
     &     //'" u (($1+$2)/2):4 title "Planck('
     &     //si_Tb_str3(1:strlen(si_Tb_str3))
     &     //' K)" w lines lt 0 lw 1 \'
      close(14)
      gra_file='./results/gra_int2'
      open(14,file=gra_file(1:strlen(gra_file)))
      write(14,10) 'set xlabel "{/Symbol l} ({/Symbol m}m)"'
      write(14,10) 'set ylabel "Specific intensity '
     &     //'(W/m^{2}/sr/{/Symbol m}m)"'
      write(14,10) 'set key bottom'
      write(14,10) 'plot \'
      write(14,10) '     "./'
     &     //result_file(1:strlen(result_file))
     &     //'" u (($1+$2)/2):5 title "observed" w lines lt -1 lw 1 \'
      write(14,10) '    ,"./'
     &     //result_file(1:strlen(result_file))
     &     //'" u (($1+$2)/2):6 title "Planck('
     &     //si_Tb_str3(1:strlen(si_Tb_str3))
     &     //' K)" w lines lt 0 lw 1 \'
      close(14)
     
c     + Brightness temperature
      result_file='Tb.txt'
      filename='./results/'
     &     //result_file(1:strlen(result_file))
      open(15,file=filename(1:strlen(filename)))
      write(15,10) '# Observed brightness temperature (K)'
      write(15,10) '# lower wavelength (Âµm) '
     &     //'/ higher wavelength (Âµm) '
     &     //'/ brightness temperature (K) in band '
     &     //'/ total brightness temperature (K)'
      do band=first_band,last_band
         write(15,48) lambda_lo(band)
     &        ,lambda_hi(band)
     &        ,band_Tb(band)
     &        ,si_Tb
      enddo ! band
      close(15)
      gra_file='./results/gra_Tb'
      open(15,file=gra_file(1:strlen(gra_file)))
      write(15,10) 'set term pdf enhanced color '
     &     //'font "helvetica,20" linewidth 1 size 10,6'
      write(15,10) 'set output "Tb.pdf"'
      write(15,10) 'set xrange[0:20]'
      write(15,10) 'set xlabel "{/Symbol l} ({/Symbol m}m)"'
      write(15,10) 'set ylabel "Brightness temperature (K)"'
      write(15,10) 'set key top'
      write(15,10) 'plot \'
      write(15,10) '     "./'
     &     //result_file(1:strlen(result_file))
     &     //'" u (($1+$2)/2):3 title "signal" w lines lt -1 lw 1 \'
      write(15,10) '    ,"./'
     &     //result_file(1:strlen(result_file))
     &     //'" u (($1+$2)/2):4 title "average Tb='
     &     //si_Tb_str3(1:strlen(si_Tb_str3))
     &     //' K" w lines lt 0 lw 1 \'
      write(15,*)
      write(15,10) 'quit'
      close(15)

c     + Discrete contribution function
      result_file='discrete_contribution_function.txt'
      filename='./results/'
     &     //result_file(1:strlen(result_file))
      open(16,file=filename(1:strlen(filename)))
      write(16,10) '# Discrete contribution function (from each layer)'
      do band=first_band,last_band
         write(16,10) 'narrowband index:'
         write(16,*) band
         write(16,10) 'lower wavelength (Âµm):'
         write(16,48) lambda_lo(band)
         write(16,10) 'higher wavelength (Âµm):'
         write(16,48) lambda_hi(band)
         write(16,10) 'Lower limit of the layer (km) '
     &        //'/ Higher limit of the layer (km) '
     &        //'/ discrete Contribution Function'
         write(16,48) z(0)/1.0D+3
     &        ,z(0)/1.0D+3
     &        ,discrete_cf(0,band)
         do i=1,Nlay
            write(16,48) z(i-1)/1.0D+3
     &           ,z(i)/1.0D+3
     &           ,discrete_cf(i,band)
         enddo ! i
      enddo ! band
      close(16)
      result_file='discrete_CF.dat'
      filename='./results/'
     &     //result_file(1:strlen(result_file))
      open(16,file=filename(1:strlen(filename)))
      do band=first_band,last_band
         do i=0,Nlay
            if (i.eq.0) then
               altitude=0.0D+0
            else
               altitude=(z(i-1)+z(i))/2.0D+3 ! km
            endif
            write(16,*) band
     &           ,i
     &           ,(lambda_lo(band)+lambda_hi(band))/2.0D+0 ! microns
     &           ,altitude ! km
     &           ,discrete_cf(i,band)
         enddo ! i
         write(16,*)
      enddo ! band
      close(16)
      gra_file='./results/gra_CF'
      open(16,file=gra_file(1:strlen(gra_file)))
      write(16,10) 'set term pdf enhanced color '
     &     //'font "helvetica,20" linewidth 1 size 10,6'
      write(16,10) 'set output "discrete_CF.pdf"'
      write(16,10) 'set grid layerdefault'
      write(16,10) 'set size square'
c      write(16,10) 'set xlabel "band index"'
      write(16,10) 'set xlabel "{/Symbol l} ({/Symbol m}m)"'
c      write(16,10) 'set ylabel "layer index"'
      if (pres_or_alt.eq.1) then
         write(16,10) 'set ylabel "P (hPa)"'
      else
         write(16,10) 'set ylabel "Altitude (km)"'
      endif
      write(16,10) 'set palette defined (0 "white", 1 "khaki", '
     &     //'2 "yellow", 3 "red", 4 "black")'
c      write(16,10) 'set palette defined (0 "white", 1 "khaki", '
c     &     //'2 "yellow", 3 "orange", 4 "red", 5 "brown")'
      write(16,10) 'set pm3d'
      write(16,10) 'set view map'
      write(16,10) 'set xrange ['
     &     //fband_str(1:strlen(fband_str))
     &     //':'
     &     //lband_str(1:strlen(lband_str))
     &     //']'
      write(16,10) 'set xtics rotate 90 '
     &     //band_tics_str(1:strlen(band_tics_str))
      write(16,10) 'set yrange [0:'
     &     //Nlay_str(1:strlen(Nlay_str))
     &     //']'
      if (pres_or_alt.eq.1) then
         write(16,10) 'set ytics '
     &        //pres_tics_str(1:strlen(pres_tics_str))
      else
         write(16,10) 'set ytics '
     &        //alt_tics_str(1:strlen(alt_tics_str))
      endif
      
      write(16,10) 'set log cb'
      write(16,10) 'set cbrange [0.0001:1]'
c      write(16,10) 'set cbrange [0:1]'
      write(16,10) 'set title "Contribution function"'
      write(16,10) 'plot "./'
     &     //result_file(1:strlen(result_file))
     &     //'" u 1:2:5 notitle w image'
      write(16,*)
      write(16,10) 'quit'
      close(16)

      return
      end


      subroutine make_tics(Nelem,xvalues,marks,nap,tics_str)
      implicit none
      include 'max.inc'
c
c     Purpose: to produce a tics string for gnuplot labeling
c
c     Input:
c       + Nelem: number of elements
c       + xvalues: the "Nelem" values of the variable
c       + marks: the corresponding "Nelem" values that must be displayed (instead of the values of the variable)
c       + nap: number of digits after the decimal separator that must be printed
c     
c     Output:
c       + tics_str: tics string
c
c     I/O
      integer Nelem
      double precision xvalues(1:Nelem_mx)
      double precision marks(1:Nelem_mx)
      integer nap
      character*(Nchar_mx) tics_str
c     temp
      integer i
      integer conv_err
      character*(Nchar_mx) dble_str
c     label
      integer strlen
      character*(Nchar_mx) label
      label='subroutine make_tics'

      if (Nelem.gt.Nelem_mx) then
         call error(label)
         write(*,*) 'Nelem=',Nelem
         write(*,*) 'while Nelem_mx=',Nelem_mx
         stop
      endif
      if (nap.lt.0) then
         call error(label)
         write(*,*) 'nap=',nap
         stop
      endif

      tics_str='('

      do i=1,Nelem
         call dble2str_noexp(marks(i),nap,dble_str,conv_err)
c     Debug
c         write(*,*) marks(i),dble_str(1:strlen(dble_str))
c     Debug
         if (conv_err.ne.0) then
            call error(label)
            write(*,*) 'could not convert to character string:'
            write(*,*) 'marks(',i,')=',marks(i)
            stop
         else
            tics_str=tics_str(1:strlen(tics_str))
     &           //'"'
     &           //dble_str(1:strlen(dble_str))
     &           //'" '
         endif
         call dble2str_noexp(xvalues(i),nap,dble_str,conv_err)
         if (conv_err.ne.0) then
            call error(label)
            write(*,*) 'could not convert to character string:'
            write(*,*) 'xvalues(',i,')=',xvalues(i)
            stop
         else
            tics_str=tics_str(1:strlen(tics_str))
     &           //' '
     &           //dble_str(1:strlen(dble_str))
         endif
         if (i.lt.Nelem) then
            tics_str=tics_str(1:strlen(tics_str))
     &           //', '
         endif
         if (strlen(tics_str).ge.Nchar_mx) then
            call error(label)
            write(*,*) 'tics_str exceeds maximum length'
            write(*,*) 'Nelem=',Nelem
            stop
         endif
      enddo ! i

      tics_str=tics_str(1:strlen(tics_str))
     &     //')'

      return
      end

