      program split2
c F90 
c reads the output from xspl12 and removes duplicates 
c if a month is missing tries to infill using duplicate
c if duplicates both have data, then takes a weighted average, with weights defined 
c  according to inverse of length of record (1/N)
      parameter maxn=50000
      real dat(maxn,27)
      integer iwmo(maxn),index(maxn)
      character*20 name(maxn)
      write(*,*)'Enter start and end years'
      read(*,*) n1,n2
101   format(3f8.2,12f8.1,12f8.4,1x,i7,1x,a20)
102   format(2f8.2,f8.1,f8.4,1x,i7,1x,a20)
c
c * START OF MAIN YEAR LOOP
      do iy=n1,n2
      write(*,*) 'Running for year',iy
c * READ ALL DATA FOR YEAR iy (lat,lon,elv,12*anom,12*rel.var.)
       do i=1,maxn
	read(iy,101,end=9)(dat(i,j),j=1,27),iwmo(i),name(i)
       enddo
       write(*,*) iy,' end of file reached - change maxn'
       stop
9      maxstn=i-1
       write(*,*)'Finished reading:',maxstn,' stations'
       close(iy)
       index=0
c ** LOOP BY STATION
       do i=1,maxstn-1
c *** LOOP BY POTENTIAL MATCHING STATIONS
	do j=i+1,maxstn
	 match=0
c **** TEST FOR 2nd STATION UNTREATED
	 if(index(j).eq.0)then
c **** test for matching WMO codes (irrelevant for .cts files) => match=1
	  if(iwmo(i).eq.iwmo(j))match=1
c **** test for lat/lon within 0.09 degrees => match=1
	  if(abs(dat(i,2)-dat(j,2)).le.0.09.and.abs(dat(i,1)-dat(j,1)).
     &     le.0.09)match=1
c ***** TEST FOR MATCHING STATION
	  if(match.eq.1)then
	   index(j)=1
c ****** LOOP BY MONTH
	   do im=1,12
c ******* if stn1=missing, retain stn2
c ******* if stn1=valid and stn2=valid, weight by relative variance
	    if(dat(i,im+3).eq.-9999.0)then
	     dat(i,im+3)=dat(j,im+3)
	     dat(i,im+12+3)=dat(j,im+12+3)
            else
	     if(dat(j,im+3).ne.-9999.0)then
	      dat(i,im+3)=( dat(j,im+3)*dat(j,im+12+3)+dat(i,im+3)*
     &         dat(i,im+12+3) )/(dat(i,im+12+3)+dat(j,im+12+3))
	     endif
            endif
	   enddo
c ****** END OF LOOP BY MONTH
          endif
c ***** END OF TEST FOR MATCHING STATION
         endif
c **** END OF TEST FOR 2nd STATION UNTREATED
        enddo
c *** END OF LOOP BY POTENTIAL MATCHING STATIONS
19     enddo
c ** END OF LOOP BY STATION
       icount=0
c ** LOOP BY STATION AGAIN
       do i=1,maxstn
        if(index(i).eq.0)then
	 icount=icount+1
	 do im=1,12
	  if(dat(i,im+3).ge.-9998)then
           write(iy*100+im,102)dat(i,1),dat(i,2),dat(i,im+3),
     &      dat(i,im+12+3),
     &      iwmo(i),name(i)
	  endif
         enddo
        endif
       enddo
c ** END OF LOOP BY STATION AGAIN
       write(*,*)'Finished sorting:',icount,'unique stations'
       close(iy*10)
      enddo
c * END OF MAIN YEAR LOOP
      end
