      program lagsw3hkp0jm
C..Add Sw peak -24h +24h.............................................May 2022
C JPL 3h indices based on monthly-median
C WUmax from -24h:tkp:+24h
C WLmin from -24h:tkp:+24h
C WEmax from -24h:tkp:+24h
C
      CHARACTER*64 infile,outfile,infileq,txt
	CHARACTER*2 AYR
	CHARACTER*4 AYEAR
	DIMENSION sw(0:71)
C
      infile='wulessn0kp3jm.out'
	outfile='wulessw0kp3jm.txt'
	infileq='d:\Apkp\OMNI\swYEAR.txt'
C
       OPEN(10,file=infile,action='READ')
       OPEN(11,file=outfile)
   30 format(1X,F8.3,1X,I3,3(1X,I2),1X,F4.1,4(1X,I3,1X,F6.2),1X,I3
     +,1X,I4)
   33 format(3I2,24(1X,F4.1))
C
	DO k=0,71
	sw(k)=0.
	ENDDO
	ndy=0
C
	DO 41 iev=1,563
    	read(10,30,end=50) ryear,lda,imn,idy,itkp,xkpmax,jtwu,wumax
     +,jtwl,wlmin,jtwe,wemax,jtwp,wpmax,isumkp,nn
C
C
C
C 	 produce lag for day 
C++ READ 1h Sw
      iyear=int(ryear)
	iyr=iyear-iyear/100*100
	call blet4(iyear,AYEAR)
C
	lda=ndoy(iyr,imn,idy)
	call blet2(iyr,AYR)
	infileq(16:19)=AYEAR
	OPEN(12,file=infileq,action='READ')
	do k=1,13
	read(12,*) txt
	if (txt(1:4).eq.'YEAR') exit
	enddo
C
      lda1=lda+1
	do kk=1,lda1            !1
C++ move data up to keep for d-1,d0,d+1 days
	 do k=0,23				  !2
	sw(k)=sw(k+24)
	sw(k+24)=sw(k+48)
	 enddo					  !2
	DO j=0,23					!3
	read(12,*,end=55) kyear,klda,kut,bt,bz,pt,pn,sw(j+48)
	if (sw(j+48).gt.9990.) sw(j+48)=0. ! missed data
	 ENDDO						!3
	 enddo					  !1
   55	close(12)
      nitkp=itkp+24
C fill missed data with Vsw-aver
       ncnt=0
	swav=0.
      do k=0,71
	if (sw(k).gt.0.) then
	ncnt=ncnt+1
	swav=swav+sw(k)
	endif
	enddo
	if (ncnt.gt.0) then
	swav=swav/ncnt
	            else
	swav=300.
	endif
C Replase missed Vsw:
      do k=0,71
	if (sw(k).eq.0.) then
	sw(k)=swav
	endif
	enddo

C swmax
      swmax=0.
	itsw=0
C-	n1sw=nitkp-24 !tkp-24h
C-	n2sw=nitkp+24 !tkp+24h ! new
C-	do k=n1sw,n2sw  !new
	do k=0,71
	if (sw(k).gt.swmax) then
	swmax=sw(k)
	itsw=k-24
	endif
	enddo
	jtsw=itsw-itkp
C
C Output
      ndy=ndy+1
      write(*,32) ryear,lda,imn,idy,itkp,xkpmax,jtwu,wumax,jtwl,wlmin
	+,jtwe,wemax,jtwp,wpmax,jtsw,swmax,isumkp,ndy
	write(11,32) ryear,lda,imn,idy,itkp,xkpmax,jtwu,wumax,jtwl,wlmin
	+,jtwe,wemax,jtwp,wpmax,jtsw,swmax,isumkp,ndy
C
   41 continue
   32 format(1X,F8.3,1X,I3,3(1X,I2),1X,F4.1,4(1X,I3,1X,F6.2),1X,I3
     +,1X,F6.1,1X,I3,1X,I4)
   50	close(unit=10)
	close(unit=11)
	pause ' '
	STOP
	END