      INTEGER FUNCTION NEWUNIT(IUIN)

C     * MAY 12/2004 - L.SOLHEIM
C     *
C     * RETURN THE FIRST UNIT NUMBER .GE. IUIN THAT IS NOT ATTACHED
C     * TO A FILE. UNIT NUMBERS IN THE EXCLUSION LIST (IUXCLD) WILL
C     * NEVER BE RETURNED. THIS EXCLUSION LIST MAY BE APPENDED TO BY
C     * PASSING IN A NEGATIVE IUIN, IN WHICH CASE THE VALUE RETURNED IS
C     * APPENDED TO THE EXCLUSION LIST.
C-----------------------------------------------------------------------
C
      IMPLICIT REAL (A-H,O-Z),
     +INTEGER (I-N)

C     * IUMAX IS THE LARGEST UNIT NUMBER THAT WILL BE RETURNED
C     * F90 ALLOWS UNIT NUMBER IN THE RANGE 0 TO 2147483647
C     * THIS RANGE (EXCLUDING END POINTS) IS ALLOWED HERE

      INTEGER, PARAMETER :: IUMAX=2147483647

      INTEGER IUIN

C     * LOCAL
      LOGICAL UEXIST,UOPEN,FOUND
      INTEGER IU

C     * THE UNIT NUMBERS IN THE IUXCLD LIST WILL NEVER BE USED
      INTEGER, PARAMETER :: LXCLD_MAX=100
      INTEGER, SAVE :: IUXCLD(LXCLD_MAX)

      DATA IUXCLD /0,5,6,7,8,95*-1/
C-----------------------------------------------------------------------

C     * FIND THE FIRST AVAILABLE UNIT NUMBER NOT ATTACHED TO A FILE

      IF (IUIN.LT.1) THEN
        IF (IUIN.EQ.0) THEN
          IU=0
        ELSE
C         * WHEN IUIN IS NEGATIVE WE RESERVE THE FIRST AVAILABLE
C         * UNIT .GE. IABS(IUIN) BY SAVING IT IN IUXCLD
          IU=IABS(IUIN)-1
        ENDIF
      ELSE IF (IUIN.LT.IUMAX) THEN
        IU=IUIN-1
      ELSE
        WRITE(6,*)'NEWUNIT: IUIN=',IUIN,' IS OUT OF RANGE.'
        WRITE(6,*)'         STARTING FROM UNIT 1'
        IU=0
      ENDIF
      UEXIST=.TRUE.
      UOPEN=.TRUE.
      DO WHILE (UEXIST .AND. UOPEN .AND. IU.LT.IUMAX)
        IU=IU+1
        IF (.NOT.ANY(IU.EQ.IUXCLD(:))) THEN
          INQUIRE(IU,EXIST=UEXIST,OPENED=UOPEN)
        ENDIF
      ENDDO
      IF (IU.GE.IUMAX) THEN
        WRITE(6,*)'NEWUNIT: UNABLE TO FIND AN AVAILABLE UNIT NUMBER'
        WRITE(6,*)'       UEXIST,UOPEN,IU: ',UEXIST,UOPEN,IU
        CALL                                         XIT("NEWUNIT",-1)
      ENDIF
      NEWUNIT=IU

      IF (IUIN.LT.0) THEN

C       * RESERVE THIS UNIT NUMBER BY SAVING IT IN IUXCLD

        I=0
        FOUND=.FALSE.
        DO WHILE(.NOT.FOUND .AND. I.LT.LXCLD_MAX)
          I=I+1
          IF (IUXCLD(I).LT.0) THEN
            IUXCLD(I)=IU
            LXCLD=I
            FOUND=.TRUE.
          ENDIF
        ENDDO
        IF (FOUND) THEN
          WRITE(6,'(A)')'NEWUNIT: ADDING TO EXCLUDE LIST'
          WRITE(6,'(A)')'         NEW EXCLUDE LIST: '
          WRITE(6,'(10I6)')(IUXCLD(I),I=1,LXCLD)
        ELSE
          WRITE(6,'(A)')'NEWUNIT: ***WARNING*** EXCLUDE LIST OVERFLOW.'
        ENDIF
      ENDIF

      RETURN
      END
