function csf_purify(sd_hilbert_space, total_spin, n_el) result(csfs)
! function to filter out all spin-allowed states from a
! SD Hilbert space
integer(n_int), intent(in) :: sd_hilbert_space(:,:)
integer, intent(in) :: total_spin, n_el
integer(n_int), allocatable :: csfs(:,:)
integer :: i, cnt
integer(n_int), allocatable :: temp_csfs(:,:)
! we have definitely <= sds
allocate(temp_csfs(size(sd_hilbert_space,1),size(sd_hilbert_space,2)), &
source = 0_n_int)
cnt = 0
do i = 1, size(sd_hilbert_space,2)
if (isProperCSF_flexible(sd_hilbert_space(:,i), total_spin, n_el)) then
cnt = cnt + 1
temp_csfs(:,cnt) = sd_hilbert_space(:,i)
end if
end do
allocate(csfs(size(sd_hilbert_space,1), cnt), source = temp_csfs(:,1:cnt))
end function csf_purify