PROGRAM toasciiprec

!Programa para preparar as datas para os dados de entrada para o programa FCLIMDEX lendo pr, tx e tn binarios 

 IMPLICIT NONE

 INTEGER, PARAMETER :: nXPoint=355 
 INTEGER, PARAMETER :: nYPoint=390
 INTEGER, PARAMETER :: nMonths=12 !Número de meses
 INTEGER, PARAMETER :: YearInit=1961
 INTEGER, PARAMETER :: YearEND=2005
 INTEGER, PARAMETER :: nDaysTot=366*(YearEND-YearInit+1)
 
 REAL               :: Var_prec(1,nYPoint,nDaysTot),Var_tmax(1,nYPoint,nDaysTot),Var_tmin(1,nYPoint,nDaysTot)	
 REAL,ALLOCATABLE   :: Var_prec_mon(:,:,:),Var_tmax_mon(:,:,:),Var_tmin_mon(:,:,:)
 CHARACTER(LEN=255) :: DATEy
 CHARACTER(LEN=255) :: DATEm
 CHARACTER(LEN=255) :: PATH
 CHARACTER(LEN=255) :: FILENAME1,FILENAME2
 CHARACTER(LEN=255) :: PATH_out
 CHARACTER(LEN=255) :: FILENAME_out
 CHARACTER(LEN=3)   :: xpoint 
 CHARACTER(LEN=3)   :: ypoint 
 LOGICAL            :: existfile
 REAL               :: rindex
 INTEGER            :: year, month, nDays, day, irec
 INTEGER            :: dd_prec, dd_temp, dd
 INTEGER            :: j 
 INTEGER            :: i,x,y
 INTEGER            :: it,t
 INTEGER            :: lrec
 INTEGER(4)         :: MON(12),MONLEAP(12)

 INTEGER            :: ierr,num_procs,mype,js_x,je_x
 INTEGER, ALLOCATABLE :: myXs(:),myXe(:)

 DATA MON/31,28,31,30,31,30,31,31,30,31,30,31/
 DATA MONLEAP/31,29,31,30,31,30,31,31,30,31,30,31/


! Edit:  PATH_out directories

       PATH_out='/scratchout/grupos/grpetamc//home/andre.lyra/'//   &
       & +'CORDEX_Group1/Eta_SAM20/CanESM2/'

       FILENAME_out='dates.txt'
		
!       DO i=1,nXPoint
       
!          WRITE(xpoint,'(I3.3)')i


          OPEN(10,FILE=TRIM(PATH_out)//TRIM(FILENAME_out),STATUS='unknown',FORM='formatted',POSITION='append')
					
          DO j=1,nYPoint
	     WRITE(ypoint,'(I3.3)')j
             
	     dd=1
             DO year=YearInit,YearEnd
                WRITE(DATEy,'(I4)') year 

		DO month=1,nMonths
                   WRITE(DATEm,'(I2)') month
	           
		   IF (leapyear(year).eq.1) THEN
             	      nDays=MONLEAP(month)
	              ELSE
             	         nDays=MON(month)
                   ENDIF 
		   
		   DO day=1,nDays

                      write(10,'(I4,x,I2,x,I2,x,F9.3,x,F7.3,x,F7.3)') year,month,day

		      dd=dd+1
		   ENDDO !day

	        ENDDO !month

	     ENDDO !year
 
          ENDDO
	 
          CLOSE (10)
	 
!       ENDDO			
	
	
 CONTAINS 
 RECURSIVE integer function leapyear(iyear)
 
 integer iyear

!      if(mod(iyear,400).eq.0) then
!        leapyear=1
!      else
!        if(mod(iyear,100).eq.0) then
!          leapyear=0
!        else
          if(mod(iyear,4).eq.0) then
           leapyear=1
          else
            leapyear=0
        endif
!       endif
!      endif
      end function leapyear
 
END PROGRAM 


