      PROGRAM ADJUST_CF(MRFLAG,CLDCOV,NLAY,CLDFRAC,ADJFRAC)
C
C     Program to scale cloud fractions to give desired cloud cover.
C
C     Input:
C     MRFLAG - 0 if random overlap, 1 if maximum-random
C     CLDCOV - desired cloud cover
C     NLAY - number of layers
C     CLDFRAC(1:NLAY) - input cloud fractions for all layers
C
C     Output:
C     ADJFRAC(1:NLAY) - cloud fractions that give desired cloud cover
C                       for given overlap assumption
C
      PARAMETER (MXLAY=203)
      DIMENSION CLDFRAC(MXLAY),ADJFRAC(MXLAY)
      DIMENSION BLKMAX(MXLAY)

      FRACEPS = 1.E-3
      YEPS = 1.E-3
      NBLK = 0
      IBLK = 0

C     Figure out how many blocks of clouds there are.  If random overlap
C     is assumed, each cloudy layer is a block.
      DO 1000 LAY = 1, NLAY
         IF (CLDFRAC(LAY) .GT. FRACEPS) THEN
            IF (IBLK .EQ. 0) THEN
               IF (MRFLAG .EQ. 1) IBLK = 1
               NBLK = NBLK + 1
               BLKMAX(NBLK) = CLDFRAC(LAY)
            ELSE
               IF (CLDFRAC(LAY) .GT. BLKMAX(NBLK)) 
     &              BLKMAX(NBLK) = CLDFRAC(LAY)      
            ENDIF
         ELSE
            IF (IBLK .EQ. 1) IBLK = 0
         ENDIF
 1000 CONTINUE

C     Compute the factor ADJFAC needed to scale the input cloud fractions
C     in order to yield the given cloud cover.  If the number of cloudy
C     blocks is less than 3, ADJFAC is solved for analytically.
      IF (NBLK .EQ. 1) THEN
         ADJFAC = CLDCOV/BLKMAX(1)
      ELSEIF (NBLK .EQ. 2) THEN
         C1 = BLKMAX(1)
         C2 = BLKMAX(2)
         C12 = C1*C2
         ADJFAC = (C1+C2-SQRT(C1**2+2.*C12+C2**2-4.*C12*CLDCOV)) /
     &        (2.*C12)
      ELSE
         PREVFAC = 0.9
         Y1 = DELCC(NBLK,CLDCOV,PREVFAC,BLKMAX)
         ADJFAC = 1.
         Y2 = DELCC(NBLK,CLDCOV,ADJFAC,BLKMAX)
 2000    CONTINUE
         IF (abs(Y2) .LT. YEPS) GOTO 4000
         SLOPE = (Y2-Y1) / (ADJFAC-PREVFAC)
         PREVFAC = ADJFAC
         Y1 = Y2
         ADJFAC = ADJFAC - Y2 / SLOPE
         Y2 = DELCC(NBLK,CLDCOV,ADJFAC,BLKMAX)
         GOTO 2000
      ENDIF

 4000 CONTINUE
      DO 5000 LAY = 1, NLAY
         ADJFRAC(LAY) = CLDFRAC(LAY) * ADJFAC
 5000 CONTINUE

      STOP
      END

      
      FUNCTION DELCC(N,CLDCOV,FAC,FRACS)
C     Function to compute the difference between the given cloud cover
C     (CLDCOV) and the cloud cover given by the input cloud fractions 
C     scaled by FAC.

      PARAMETER (MXLAY=203)
      DIMENSION FRACS(MXLAY)
      
      PROD = 1.
      DO 1000 I = 1, N
         PROD = PROD * (1. - FAC * FRACS(I))
 1000 CONTINUE
      DELCC = PROD - (1. - CLDCOV)
      
      RETURN
      END
      
               
         
