      program calobs
      implicit none

c calibrate observed temperature

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

c number of data
      integer NDAT
      parameter (NDAT=121)

c missing
      integer MISS
      parameter (MISS=-999)

c data file IO
      integer IT, ID
      parameter (IT=21)
      parameter (ID=22)

c -----
c calibration table data
      integer nt
      real*8  tTc(NTMAX), tTa(NTMAX)

c time
      character*8  HHMMSS
c temperature
      real*8  Ta, Tc

c loop control
      integer i

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


c open files
      open(ID,file="datafile")
c skip header
      do 210 i = 1, 6
        read(ID,*)
 210  continue
c read, calibrate, and write
      do 240 i = 1, NDAT
        read(ID,*) HHMMSS, Ta
        if (Ta.ne.(MISS*1.0d0)) then
            call calT(nt,tTc,tTa,Ta,Tc)
            write(*,*) HHMMSS, ',', Tc
          else
            write(*,*) HHMMSS, ',', MISS
        end if
 240  continue


      stop
      end



      subroutine calT(nt,tTc,tTa,Ta,Tc)
      implicit none

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

c -----
      integer nt
      real*8  tTc(NTMAX), tTa(NTMAX)

      real*8  Ta

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 = tTc(1) - tTa(1)
          Tc = Ta + dT
        else
          do 110 i = 2, nt
            if (Ta.le.tTa(i)) then
                Tc = ( (tTc(i)-tTc(i-1))/(tTa(i)-tTa(i-1)) )
     &                  *(Ta-tTa(i-1)) + tTc(i-1)
                go to 120
            end if
 110      continue
          Tc = ( (tTc(nt)-tTc(nt-1))/(tTa(nt)-tTa(nt-1)) )
     &            *(Ta-tTa(nt-1)) + tTc(nt-1)
 120      continue
      end if

      return
      end
