Fixed several bugs, including a memory leak