      implicit none

      integer,parameter :: mx=180
      integer,parameter :: my=89

      real :: values(mx*my),results(5000),dis(5000,4)
      real :: d(4),tmp(1500),dall
      integer :: i,j,iyear,imonth,iday,ihour,valid
      integer :: loc(1500),num(5000,4),steps
      character(len=70) :: snd(3),sno(3),snm(3),sns(3),input,model,a
      character(len=4) :: sea,area

      data snd /'_Pt_Standardized_','_','.txt'/
      data snm /'locations/','180x89_','.txt'/
      data sns /'locations/Surroundings4ERAint_','180x89_','.txt'/
      data sno /'_PtonHs_','_','.txt'/

      call get_command_argument(1,input)
      read(input,*) model
      call get_command_argument(2,input)
      read(input,*) sea
      call get_command_argument(3,input)
      read(input,*) area

      open(20,file=trim(snm(1))//trim(area)//
     & trim(snm(2))//trim(sea)//trim(snm(3)))
      do i=1,1500
         read(20,*,end=97) loc(i)
      enddo
97    close(20)

      valid=0
      open(40,file=trim(sns(1))//trim(area)//
     & trim(sns(2))//trim(sea)//trim(sns(3)))
      read(40,*) a
      do i=1,5000
         read(40,*,end=98) a,num(i,1),num(i,2),num(i,3),num(i,4),
     & dis(i,1),dis(i,2),dis(i,3),dis(i,4)
         valid=valid+1
      enddo
98    close(40)

      open(30,file=trim(model)//trim(sno(1))//trim(area)//
     & trim(sno(2))//trim(sea)//trim(sno(3)))

      open(3,file=trim(model)//trim(snd(1))//trim(area)//
     & trim(snd(2))//trim(sea)//trim(snd(3)))

      print*,trim(model)//trim(sno(1))//trim(area)//
     & trim(sno(2))//trim(sea)//trim(sno(3))

      do
         read(3,'(i6,3i4.2,i6)',end=99) iyear,imonth,iday,ihour,steps
         read(3,'(10f9.3)')(tmp(i),i=1,steps)
         do i=1,steps
            values(loc(i))=tmp(i)
         enddo

         do i=1,valid
            do j=1,4
               d(j)=dis(i,j)
               if(abs(d(j)).lt.1e-8) d(j)=1e-8
               d(j)=1./d(j)
            enddo
            dall=d(1)+d(2)+d(3)+d(4)
            do j=1,4
               d(j)=d(j)/dall
            enddo
         results(i)=values(num(i,1))*d(1)+values(num(i,2))*d(2)+
     & values(num(i,3))*d(3)+values(num(i,4))*d(4)
         enddo

         write(30,'(i6,3i4.2,i6)') iyear,imonth,iday,ihour,valid
         write(30,'(10f9.3)')(results(i),i=1,valid)
      enddo

99    close(30)
      close(3)
      end
