working but for segfaults and hangs at the end