      program extaaapkp
C......................................................................Dec 2019
C Produce ap @ aa @ kp combined annual files  
	dimension iap(366,0:7),kp(366,0:7)
	character*64 infaa,infkp,outfile,rest,txt
	character*3 ap3
c	integer*2 imn,idy,iut
	character*4 AYEAR
	character*2	AYR,AMN,ADY,AUT,kp2
C
CREM!!!		infkp='d:/apkp/kpap/kpYEAR'  !ap
      	infkp='d:/data/kpYEAR.txt'  !new kp/ap data from Potsdam
C   	infaa='d:/apkp/aa/aaYEAR.txt'  !aa
   	infaa='d:/apkp/aa/aaYEAR'  !aa from files ap+aa
C   	infaa='d:/apkp/aa/aaYEAR_P.txt'  !aa
	outfile='d:/apkp/aa/aakpYEAR'
CREM	iyear=1962   !START+++++++++++++++++++++
	iyear=2020
C+	iyear=1952
C+		iyear=1963
C+		iyear=1996
   30 FORMAT(A64)
C start cycle on year: =====================================
c	do 400 KK=1,56	! 1964-2019
C	do 400 KK=1,23	! 1997-2019
C	iyear=2014       ! for 2015
C	do 400 KK=1,11	! 1953-1963
C	do 400 KK=1,9	! 2011-2019
	iyear=iyear+1
	call blet4(iyear,AYEAR)
	ryear=float(iyear)
	AYR=AYEAR(3:4)
	read(ayr,*) ryr
	iyr=int(ryr)
		if(int(ryr/4.)*4.eq.iyr) THEN 
	ndnyr=366
	                          ELSE
	ndnyr=365
	ENDIF
C Reading kpap file for aa-index
   33	format(A31,8(I3))
   37	format(A13,5X,I3)
   34	format(A13,2(1X,I3))
   35	format(A4,3(1X,I2),2(I4))
   36	format(A4,3(1X,A2),1X,I2,2(1X,I3))
C
CREM	infkp(16:19)=AYEAR
	infkp(11:14)=AYEAR
	outfile(16:19)=AYEAR
	OPEN(10,FILE=infkp,action='READ')
C	OPEN(16,FILE=outfile,access='APPEND')
	OPEN(16,FILE=outfile)
c	read(10,*) rest
c	backspace(10)
	do idd=1,ndnyr
c	read(10,33,end=133) title,(iap(idd,k),k=0,7)
	read(10,30,end=133) rest
	do k=0,7
	k2=k*2+13
	k1=k*3+32
	ap3=rest(k1:k1+2)
	kp2=rest(k2:k2+1)
	if (kp2(1:1).eq.' ') kp2(1:1)='0'
	read(kp2,*) rkp
	ikp=int(rkp)
	kp(idd,k)=ikp
	if (ap3(1:1).eq.' ') ap3(1:1)='0'
	if (ap3(2:2).eq.' ') ap3(2:2)='0'
	read(ap3,*) rap3
	iap(idd,k)=int(rap3)
	enddo
C
C  103	write(*,*) title
	enddo
  133	close(unit=10)


C Reading aa file
C
   40 FORMAT(I4,3(1X,I2),5X,I3)
	infaa(14:17)=AYEAR
	outfile(16:19)=AYEAR
	OPEN(11,FILE=infaa,action='READ')
Crem	do i=1,34
Crem	read(11,30) txt ! extra line
Crem	enddo
C
c	do idd=244,ndnyr
	do idd=1,ndnyr
c	read(11,*) iyear,imn,idy,iut,iaaindex
c	backspace(11)

	do ii=0,7
	read(11,40,end=139) iyear,imn,idy,iut,iaaindex
c	iut=iut+3*ii
c?	iut=iut/10000
	call blet2(imn,AMN)
	call blet2(idy,ADY)
	call blet2(iut,AUT)
c	call blet3(iap(idd,ii),RAP)
c	call blet3(iaaindex,RAA)
c	read(11,37,end=139) txt,iaa(idd,ii)
c	write(*,35)	ayear,imn,idy,iut,iap(idd,ii),iaaindex
c	write(16,35)	ayear,imn,idy,iut,iap(idd,ii),iaaindex
	write(*,36)	ayear,amn,ady,aut,kp(idd,ii),iap(idd,ii),iaaindex
	write(16,36)	ayear,amn,ady,aut,kp(idd,ii),iap(idd,ii),iaaindex
	enddo
	enddo
  139	close(unit=10)
	close(unit=16)
  400	continue
	pause ' '
	stop
	END
C
