cleaned up a bit and fixed a segfault