PROGRAM TESTE_LPBL
IMPLICIT NONE
   INTEGER, PARAMETER        :: LM  = 50   
   REAL   , PARAMETER        :: EPSQ2  =    0.2
   REAL   , PARAMETER        :: FH     =    1.01
   INTEGER                   :: L
   INTEGER                   :: LPBL 
   INTEGER                   :: LMHK
   REAL                      :: DQ2
   REAL   , DIMENSION(LM)    :: Q2


   READ(10,*) LMHK
   DO L=LM,1,-1
    READ(10,*) Q2(L)
    WRITE(*,*) 'Q2(',L,')',Q2(L)
   ENDDO

!--------------------------- 
! FIND THE HEIGHT OF THE PBL
!---------------------------
!CHOU_GSM    LPBL = LMHK
    LPBL = LMHK-1
!TESTE BUSCA HPBL DE BAIXO P CIMA - JORGE
!DCR    DO 100 L=LMHK/2, LMHK-1, 1   !Chou change the search from half atm to bottom
    DO 100 L=LMHK-1, LMHK/2, -1   !Daniela
!DCR        IF (Q2(L) <= EPSQ2 * FH) THEN
        PRINT*,L,Q2(L),  EPSQ2 * FH    
        IF (Q2(L) <= EPSQ2 * FH) THEN  
            IF (L >= LMHK-3) THEN
	        PRINT*,L,'CYCLE'
                CYCLE
            END IF
            IF (L == LMHK-4) THEN
 	        PRINT*,L,'EXIT'
                EXIT
            ELSE
                LPBL = L
            END IF
            GOTO 110   
        END IF
100 END DO

110 PRINT*,'LPBL = ',LPBL

    LPBL = LMHK-1
    DO 200 L=LMHK-1, LMHK/2, -1   !Daniela
       DQ2= Q2(L-1)- Q2(L)                      ! Vert Dif Q2          
       IF( (ABS(DQ2) <  0.0005)) THEN
          IF  (L > LPBL ) THEN   ! Testar se já foi encontrada camada turbulenta, na camada abaixo 
            CYCLE
          ELSE                             ! está acima da camada turbulenta, e acabou a turbulência.
           EXIT
          ENDIF
       ELSEIF(( DQ2 >= 0. .OR. (DQ2 < 0. .And. ABS(DQ2)>= 0.01))) THEN   ! Estamos na camada turbulenta
            LPBL = L
             Cycle    ! raise L either in decreasing or in increasing tke with height
       ELSE
            EXIT
       END IF
200    END DO
     PRINT*,'LPBL = ',LPBL
END PROGRAM TESTE_LPBL
