      program corrplot_prepare
      implicit none
  
      integer*4 imxrec
      parameter(imxrec=100000)
      character cf1*50,cf2*50,cfout*50
      integer*4 idate1(imxrec),idate2(imxrec),i,j,nrec1,nrec2,
     &          nmatch,ngm
      real*8 ftime1(imxrec),ftime2(imxrec),t1(imxrec),t2(imxrec),
     &       r5,r3,r4

      
      call getarg(1,cf1)   ! Reads 1st argument, input file 1
      call getarg(2,cf2)   ! Reads 2nd argument, input file 2
      call getarg(3,cfout) ! Reads 3rd argument, output file

! Reads input file 1:
      open(1,file=cf1,status='old')
      read(1,*)
      do i=1,imxrec
        read(1,*,end=108) idate1(i),ftime1(i),r3,r4,r5,t1(i)
      end do
      stop'F-ERR: imxrec too small to read 1st file !'
 108  close(1)
      nrec1=i-1
     
! Reads input file 2:
      open(1,file=cf2,status='old')
      read(1,*)
      do i=1,imxrec
        read(1,*,end=118) idate2(i),ftime2(i),r3,r4,r5,t2(i)
      end do
      stop'F-ERR: imxrec too small to read 2nd file !'
 118  close(1)
      nrec2=i-1
    
! For each record in the input file 1, finds the corresponding record (if any)
! in the input file 2, writes out the matching records:
      open(1,file=cfout,status='unknown')
      write(1,'(a34)')'#  date, time, t1(degC),  t2(degC)'
      nmatch = 0
      ngm = 0
      do i=1,nrec1
        do j=1,nrec2
          if( (idate2(j).eq.idate1(i)) .AND.
     &        (dabs(ftime2(j)-ftime1(i)).lt.1.d-3) ) then ! records matching
              nmatch = nmatch + 1
              if((t1(i).gt.-25.d0.AND.t1(i).lt.50.d0) .AND.
     &           (t2(j).gt.-25.d0.AND.t2(j).lt.50.d0) ) then 
                  ngm = ngm + 1
                  write(1,111) idate1(i),ftime1(i),t1(i),t2(j)
              end if
          end if
        end do ! end loop j=1,nrec2
      end do ! end loop i=1,nrec1 
      close(1)

      write(*,*)'NREC1, NREC2, NMATCH = ',nrec1,nrec2,nmatch
      write(*,*)'N. of MATCHING and GOOD records = ',ngm
      

111   FORMAT(i8,f6.2,2f10.2)

      stop ' ==== NORMAL COMPLETION ==== ' 
      end
