      ! SPACE_GEDIIS SIMPLY LOADS THE CURRENT VALUES OF Geom AND Grad INTO
      ! THE ARRAYS GeomSet AND GradSet

      SUBROUTINE SPACE_GEDIIS(MRESET,MSET,Geom,Grad,HEAT,NCoord,GeomSet,GradSet,ESET,FRST)

      IMPLICIT NONE
      integer, parameter :: KINT = kind(1)
      integer, parameter :: KREAL = kind(1.0d0)

      ! MSET=mth iteration, MRESET=Maximum no. of iterations. 
      INTEGER(KINT) :: NCoord, MRESET, MSET 
      ! Geom=geometry with NCoord coordinates. GRAD=gradients.
    REAL(KREAL), INTENT(IN) :: Geom(NCoord)
      REAL(KREAL) :: Grad(NCoord)
    REAL(KREAL) :: Heat
      LOGICAL :: FRST, Print=.TRUE.
      ! GeomSet, GradSet : a long array to store
      REAL(KREAL) :: GeomSet(MRESET*NCoord), GradSet(MRESET*NCoord), ESET(MRESET)
      ! Geom and GRAD for all iterations.

      INTEGER(KINT) :: I, K, NMK, MI, NI
      INTEGER(KINT), SAVE :: NRESET

      ! UPDATE PARAMETER AND GRADIENT SUBSPACE:
      IF (PRINT)  WRITE(*,'(/,''       BEGIN SPACE_GEDIIS  '')')
      IF(FRST)THEN
         NRESET=MIN(NCoord/2,MRESET)
             IF (NCoord .LT. 5 ) THEN ! This condition is imposed for small NCoord,
               ! particularly if NCoord is equal to 2 or 3.
                NRESET = NCoord-1
             END IF
         FRST=.FALSE.
         MSET=0
      ENDIF

      ! IF (PRINT)  WRITE(*,'(/,''       SPACE_GEDIIS 1  '')')
      ! purging the very first Geom and GRAD.
      if (print) WRITE(*,*) "DBG SPACE_GEDIIS MSET, NRESET", MSET,NRESET
      IF (MSET .EQ. NRESET) THEN
         DO I=1,MSET-1
            MI = NCoord*(I-1)
            NI = NCoord*I
            ESET(I)=ESET(I+1)
            DO K=1,NCoord
               GeomSet(MI+K) = GeomSet(NI+K)
               GradSet(MI+K) = GradSet(NI+K)
            END DO
     END DO  
            MSET=NRESET-1
      ENDIF

      ! STORE THE CURRENT POINT:
      !IF (PRINT)  WRITE(*,'(/,''       SPACE_GEDIIS 2  '')')
      DO  K=1,NCoord
         NMK = NCoord*MSET+K ! MSET corresponds mth iteration.
         !IF (PRINT)  WRITE(*,*) 'K,NMK,MSET,NCoord',K,NMK,MSET,NCoord !, &
             !SIZE(GeomSet), SIZE(GradSet),SIZE(Geom),SIZE(GRAD)
         GeomSet(NMK) = Geom(K)
         GradSet(NMK) = Grad(K)
      END DO
    
      MSET=MSET+1
      ESET(MSET)=HEAT
     
      IF (PRINT) WRITE (*,*) "MSET=", MSET
      IF (PRINT)  WRITE(*,'(/,''       END SPACE_GEDIIS   '')')

      END SUBROUTINE SPACE_GEDIIS
