module base_fftsft_mod
  implicit none


  complex, dimension(:)    , allocatable, private :: tmp1d
  complex, dimension(:,:)  , allocatable, private :: tmp2d
  complex, dimension(:,:,:), allocatable, private :: tmp3d

contains


  subroutine base_fftsft_1d(vec1d, n1)
    complex, dimension(:) :: vec1d
    integer               :: n1

    integer               :: m1

    if (.not.allocated(tmp1d)) allocate(tmp1d(n1))

    m1 = n1/2;

    tmp1d = vec1d
    vec1d(1:n1-m1-1) = tmp1d(m1+2:n1)
    vec1d( n1-m1:n1) = tmp1d( 1:m1+1)

    return
  end subroutine

  subroutine base_fftsft_2d(vec2d, n1, n2)
    complex, dimension(:,:) :: vec2d
    integer                 :: n1, n2

    integer                 :: m1, m2

    if (.not.allocated(tmp2d)) allocate(tmp2d(n1,n2))

    m1 = n1/2; m2 = n2/2

    tmp2d = vec2d
    !!.. flip the 1st dimension
    if (n1>1) then 
       vec2d(1:n1-m1-1,:) = tmp2d(m1+2:n1,:)
       vec2d( n1-m1:n1,:) = tmp2d( 1:m1+1,:)
    end if

    tmp2d = vec2d
    !!.. flip the 2nd dimension
    if (n2>1) then
       vec2d(:,1:n2-m2-1) = tmp2d(:,m2+2:n2)
       vec2d(:, n2-m2:n2) = tmp2d(:, 1:m2+1)
    end if

    return
  end subroutine

  subroutine base_fftsft_3d(vec3d, n1, n2, n3)
    complex, dimension(:,:,:) :: vec3d
    integer                   :: n1, n2, n3

    integer                   :: m1, m2, m3

    if (.not.allocated(tmp3d)) allocate(tmp3d(n1,n2,n3))

    m1 = n1/2; m2 = n2/2; m3 = n3/2
 
    tmp3d = vec3d
    !!.. flip the 1st dimension
    if (n1>1) then
       vec3d(1:n1-m1-1,:,:) = tmp3d(m1+2:n1,:,:)
       vec3d( n1-m1:n1,:,:) = tmp3d( 1:m1+1,:,:)
    end if

    tmp3d = vec3d
    !!.. flip the 2nd dimension
    if (n2>1) then
       vec3d(:,1:n2-m2-1,:) = tmp3d(:,m2+2:n2,:)
       vec3d(:, n2-m2:n2,:) = tmp3d(:, 1:m2+1,:)
    end if

    tmp3d = vec3d
    !!.. flip the 3rd dimension
    if (n3>1) then
       vec3d(:,:,1:n3-m3-1) = tmp3d(:,:,m3+2:n3)
       vec3d(:,:, n3-m3:n3) = tmp3d(:,:, 1:m3+1)
    end if
    return
  end subroutine

end module










