      program txt2bin
      IMPLICIT NONE
      INTEGER, PARAMETER        :: LM    = 50   
      REAL   , PARAMETER        :: FH    = 1.01
      REAL   , PARAMETER        :: undef = -9999
      REAL                      :: DQ2
      REAL   , DIMENSION(7,LM)  :: Q2
      REAL   , DIMENSION(7,LM)  :: Z
      REAL   , DIMENSION(7)     :: SM
      INTEGER, DIMENSION(7)     :: LMHK
      INTEGER, DIMENSION(7)     :: LPBL
      INTEGER, DIMENSION(7)     :: LPBL2
      REAL   , DIMENSION(7)     :: HPBL
      REAL                      :: EPSQ2
      
      INTEGER                   :: I
      INTEGER                   :: L 
      INTEGER                   :: M 
     
      WRITE(6,'(a,$)') "EPSQ2? : "
      READ(5,*)EPSQ2
             
      open (1,file="variaveis1.txt", form="formatted",status="old")
      open (3,file="variaveis2.txt", form="formatted",status="old")
      do m=1,240
        do I=1,7
	  read(1,*) LMHK(i),sm(i), lpbl(i), hpbl(i)
          do L=LM,1, -1
            read(3,*) Z(I,L), Q2(I,L)	  
          enddo
          IF (LMHK(i) < LM) THEN
	     do l=LM,LMHK(i)+1,-1 
	        z(i,l)=undef
	        q2(i,l)=undef
	     enddo
	   ENDIF
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!	  
	  LPBL2(I) = LMHK(I)/2

          DO 200 L=LMHK(I)-1, LMHK(I)/2, -1   !Daniela
	     if (i == 7) Print*,m,L,Q2(I,L)
             DQ2= Q2(I,L-1)- Q2(I,L)                      ! Vert Dif Q2  
             IF ( (ABS(DQ2) > EPSQ2*0.001 ).AND. Q2(I,L) <= EPSQ2*0.01) THEN
                IF  (L > LPBL2(I) ) CYCLE  ! Testar se já foi encontrada camada turbulenta, na camada abaixo 
              ELSEIF  ((ABS(DQ2)>= EPSQ2*0.25)) THEN
                LPBL2(I) = L-1
                CYCLE   ! raise L either in decreasing or in increasing tke with height
             ELSEIF (L >= LMHK(i)/2) THEN
                CYCLE
             END IF
          200 END DO
          IF ( LPBL2(I) <= LMHK(I)/2) LPBL2(I)=LMHK(I)-1  
	  if (i == 7) print*,"LPBL:", LPBL2(I)
        enddo
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!	
	write(8000) (sm(i),i=1,7)
	write(8000) (float(lmhk(i)),i=1,7)
	write(8000) (float(lpbl(i)),i=1,7)
	write(8000) (float(lpbl2(i)),i=1,7)
	write(8000) (hpbl(i),i=1,7)
	 	
        do l=LM,1,-1
          write(8001) (z(i,l),i=1,7)
        enddo	
        do l=LM,1,-1
          write(8001) (q2(i,l),i=1,7)
        enddo	
       enddo
      end program txt2bin
