subroutine write_overlap_state(state, length, index)
implicit none
integer(n_int), intent(in) :: state(0:nIfTot, length)
integer, intent(in) :: index, length
integer :: nOccDets, i, ierr
integer(n_int), allocatable :: buffer(:, :)
real(dp) :: tmp_sign(lenof_sign)
character(*), parameter :: this_routine = "write_overlap_state"
! check how many determinants are stored for this state on this core
allocate(buffer(0:niftot, length), stat=ierr)
nOccDets = 0
do i = 1, length
call extract_sign(state(:, i), tmp_sign)
if (IsUnoccDet(tmp_sign)) then
cycle
end if
nOccDets = nOccDets + 1
buffer(:, nOccDets) = state(:, i)
end do
! copy them to overlap_states
if (allocated(overlap_states(index)%dets)) deallocate(overlap_states(index)%dets)
allocate(overlap_states(index)%dets(0:nIfTot, nOccDets))
overlap_states(index)%dets(:, 1:nOccDets) = buffer(:, 1:nOccDets)
overlap_states(index)%nDets = nOccDets
deallocate(buffer)
end subroutine write_overlap_state