!C
!C  SPACE SIMPLY LOADS THE CURRENT VALUES OF Geom AND GRAD INTO
!C  THE ARRAYS GeomSet AND GradSet
!C
      SUBROUTINE Space_all(NGeomF,IGeom,MRESET,MSET,Geom,GRAD,HEAT,NCoord,GeomSet,GradSet,ESET,FRST)

!      IMPLICIT DOUBLE PRECISION (A-H,O-Z)
!      INCLUDE 'SIZES'
    
      IMPLICIT NONE
      integer, parameter :: KINT = kind(1)
      integer, parameter :: KREAL = kind(1.0d0)

!      INCLUDE 'SIZES'

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

      INTEGER(KINT) :: I,J,K,NMK,MI,NI
      INTEGER(KINT), SAVE :: NRESET
!C
!C     UPDATE PARAMETER AND GRADIENT SUBSPACE
!C
      IF (PRINT)  WRITE(*,'(/,''       BEGIN SPACE  '')')
      IF(FRST(IGeom))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
         ENDIF
         FRST(IGeom)=.FALSE.
         MSET(IGeom)=0
      ENDIF
!C
      !IF (PRINT)  WRITE(*,'(/,''       SPACE 1  '')')
        ! purging the very first Geom and GRAD.
       if (print) WRITE(*,*) "DBG Space MSET(",IGeom,"), NRESET",MSET(IGeom),NRESET
       IF (MSET(IGeom) .EQ. NRESET) THEN
         DO 10 I=1,MSET(IGeom)-1
            MI = NCoord*(I-1)
            NI = NCoord*I
            ESET(I)=ESET(I+1)
            DO 10 K=1,NCoord
               GeomSet(IGeom,MI+K) = GeomSet(IGeom,NI+K)
   10    GradSet(IGeom,MI+K) = GradSet(IGeom,NI+K)
            MSET(IGeom)=NRESET-1
       ENDIF
!C
!C     STORE THE CURRENT POINT
!C
      !IF (PRINT)  WRITE(*,'(/,''       SPACE 2  '')')
      DO  K=1,NCoord
         NMK = NCoord*MSET(IGeom)+K ! MSET(IGeom) corresponds the mth iteration.
         IF (PRINT)  WRITE(*,*) 'K,NMK,MSET(',IGeom,'),NCoord',K,NMK,MSET(IGeom),NCoord, &
                     SIZE(GeomSet(IGeom,:)), SIZE(GradSet(IGeom,:)),SIZE(Geom),SIZE(GRAD)
         GeomSet(IGeom,NMK) = Geom(K)
         GradSet(IGeom,NMK) = Grad(K)
      END DO
      MSET(IGeom)=MSET(IGeom)+1
      ESET(MSET(IGeom))=HEAT

      IF (PRINT) WRITE (*,*) "MSET(",IGeom,")=", MSET(IGeom)
      IF (PRINT)  WRITE(*,'(/,''       END SPACE   '')')
    
      END SUBROUTINE Space_all
