SUBROUTINE Expand(List,Idx,Dim)

  ! This subroutine expands a list entered in a compacted form
  ! ie 1 -10 => 1 2 3  4 5 6 7 8 9 10

  use VarTypes

  INTEGER(KINT), INTENT(IN) :: Dim
  INTEGER(KINT), INTENT(INOUT) :: List(Dim)
  INTEGER(KINT), INTENT(INOUT) :: Idx

  LOGICAL, ALLOCATABLE :: FTmp(:) ! Dim
  LOGICAL :: Debug
  INTEGER(KINT) :: i

  INTERFACE
     function valid(string) result (isValid)
       CHARACTER(*), intent(in) :: string
       logical                  :: isValid
     END function VALID

  END INTERFACE

  Debug=valid('Expand')

  Allocate(FTmp(Dim))
  FTmp=.FALSE.

  Idx=1

  DO WHILE (List(Idx).NE.0)
     If (List(Idx).LT.0) THEN
        DO I=List(Idx-1),abs(List(Idx))
           IF (.NOT.FTmp(I)) THEN
              FTmp(I)=.TRUE.
           END IF
        END DO
     ELSEIF (.NOT.FTmp(List(Idx))) THEN
        FTmp(List(Idx))=.TRUE.
     END IF
     Idx=Idx+1
  END DO

  if (debug) WRITE(*,*) "DBG Expand,  List",List

  ! We convert List into non compacted form
  Idx=1
  DO I=1,Dim
     If(Ftmp(I)) THEN
        List(Idx)=I
        Idx=Idx+1
     END IF
  END DO
  List(Idx)=0
  Idx=Idx-1

 DEALLOCATE(Ftmp)

END SUBROUTINE Expand
