Fixed segfaults, memory leaks, etc