      SUBROUTINE HSCALA5 (Q, ES, IL1, IL2, ILG, ILEV, LEVS, 
     1                    MOIST, LOWBND, SREF, SPOW,
     2                    RMOON,SMIN)
C
C     * MAY 24/2017 - M.LAZARE. FOR CONVERSION TO NEW XC40:
C     *                         - REPLACE IBM INTRINSICS BY GENERIC
C     *                           FOR PORTABILITY.
C     * SEP 13/2007 - M.LAZARE. NEW VERSION FOR GCM15G:
C     *                         - IL1,IL2 PASSED INSTEAD OF "LON".
C     *                         - "FACT" AND "EFACT" NOW INTERNAL.
C     *                         - UNUSED TEMP,PRESPA REMOVED.  
C     * SEP 13/2006 - M.LAZARE/ PREVIOUS VERSION HSCALA4 FOR GCM15F:
C     *               F.MAJAESS.- WORK ARRAYS NOW LOCAL.
C
C     * CALCULATE SPECIFIC HUMIDITY (Q) FROM MODEL MOISTURE 
C     * VARIABLE (ES), AS DEFINED BY SWITCH MOIST.
C
      IMPLICIT REAL (A-H,O-Z),
     +INTEGER (I-N)
  
      LOGICAL LOWBND
  
      REAL  Q (ILG,ILEV) 
      REAL ES (ILG,LEVS)
C  
C     * WORK ARRAYS.
C
      REAL FACT(ILG,ILEV), EFACT(ILG,ILEV)
C
      INTEGER*4 LEN
      INTEGER MACHINE,INTSIZE
C
C     * COMMON BLOCK TO HOLD WORD SIZE.
C
      COMMON /MACHTYP/ MACHINE,INTSIZE
C-----------------------------------------------------------------------
      MSG=ILEV-LEVS
      IF(MSG.GT.0)THEN
        DO L=1,MSG
        DO I=IL1,IL2
          Q(I,L)=0. 
        ENDDO
        ENDDO
      ENDIF 
C
      IF(MOIST.EQ.NC4TO8("   Q") .OR. MOIST.EQ.NC4TO8("SL3D")) THEN 
C
        DO L=MSG+1,ILEV 
          M=L-MSG
          DO I=IL1,IL2
            Q(I,L)=ES(I,M)
          ENDDO
        ENDDO
  
      ELSEIF(MOIST.EQ.NC4TO8("QHYB") .OR. MOIST.EQ.NC4TO8("SLQB")) THEN 
C
        FACT (1:ILG, 1:ILEV)=0.
        EFACT(1:ILG, 1:ILEV)=1.
        DO L=MSG+1,ILEV 
          M=L-MSG
          IF(SPOW.EQ.1.)                     THEN  
            DO I=IL1,IL2
              ESVALX = MAX(ES(I,M),SMIN)
              FACT(I,L)=(1.-(SREF/ESVALX))
              EFACT(I,L) = EXP(FACT(I,L))
            ENDDO
          ELSE
            PINV=1./SPOW
            DO I=IL1,IL2
              ESVALX = MAX(ES(I,M),SMIN)
              FACT(I,L)=PINV*(1.-(SREF/ESVALX)**SPOW)
              EFACT(I,L) = EXP(FACT(I,L))
            ENDDO
          ENDIF   
        ENDDO
C
        DO L=MSG+1,ILEV 
          M=L-MSG
          DO I=IL1,IL2
            IF(ES(I,M).GE.SREF) THEN 
              QVAL=ES(I,M)
            ELSE
C             QVAL = SREF*EFACT(I,L)
C             IF(ES(I,M).LE.SMIN) QVAL=RMOON
              IF(ES(I,M).LE.SMIN) THEN
                QVAL=RMOON
              ELSE
                QVAL = SREF*EFACT(I,L)
              ENDIF
            ENDIF
            Q(I,L) = QVAL
          ENDDO
        ENDDO 
  
      ELSE
                                                  CALL XIT('HSCALA4',-1)
      ENDIF 
C  
      IF(LOWBND)THEN
        DO L=MSG+1,ILEV
        DO I=IL1,IL2
          Q(I,L)=MAX(RMOON,Q(I,L))
        ENDDO
        ENDDO
      ENDIF 
  
      RETURN
      END 
