      program caldata
      implicit none

c -----
c missing value
      real*8  MISS
      parameter (MISS=-999.0d0)

c data file IO
      integer ID
      parameter (ID=21)

c maximum number of calibration table data
      integer NTMAX
      parameter (NTMAX=100)

c number of obsebservation data
      integer ND
      parameter (ND=121)

c -----
c cal table
      integer nt
      real*8  TCcal(NTMAX), TAcal(NTMAX)

c calibrate observation data
      character*8  timestr
      real*8  TAobs, TCobs

c loop control
      integer i, j

c -----
c open calibration table
      open(ID,file="caltable")
c read table
      do 110 i = 1, NTMAX
        read(ID,*,end=120) TCcal(i), TAcal(i)
 110  continue
      write(*,*) 'data length is too long'
      stop
 120  continue
      nt = i - 1
      close(ID)

c open data file
      open(ID,file="datafile")
c skip header
      do 220 i = 1, 6
        do 210 j = 1, 5
          read(ID,*)
 210    continue
        write(*,*)
 220  continue
c read data, calibrate data, and output data
      do 240 i = 1, ND
        read(ID,*) j, timestr
        read(ID,*) j, TAobs
        read(ID,*)
        read(ID,*)
        read(ID,*)
        if (TAobs.eq.MISS) then
            TCobs = MISS
          else
            call calTs(nt,TCcal,TAcal,TAobs,TCobs)
        end if
        write(*,*) timestr, ',', TCobs
 240  continue
      close(ID)

      stop
      end



      subroutine calTs(nt,Tct,Tst,Ts,Tc)
      implicit none

c -----
c maximum number of calibration table data
      integer NTMAX
      parameter (NTMAX=100)

c -----
      integer nt
      real*8  Tct(NTMAX), Tst(NTMAX)

      real*8  Ts

c -----
      real*8  Tc

c -----
      real*8  dT

      integer i

c -----
      if (nt.eq.0) then
          write(*,*) 'calibration table is empty'
          stop
        else if (nt.eq.1) then
          dT = Tct(1) - Tst(1)
          Tc = Ts + dT
        else
          do 110 i = 2, nt
            if (Ts.le.Tst(i)) then
                Tc = ( (Tct(i)-Tct(i-1))/(Tst(i)-Tst(i-1)) )
     &                  *(Ts-Tst(i-1)) + Tct(i-1)
                go to 120
            end if
 110      continue
          Tc = ( (Tct(nt)-Tct(nt-1))/(Tst(nt)-Tst(nt-1)) )
     &            *(Ts-Tst(nt-1)) + Tct(nt-1)
 120      continue
      end if

      return
      end
