Correcting segfaults

This branch corrects a number of segmentation faults and memory leaks in the code. No other segfaults or memory leaks are detected with [valgrind](http://valgrind.org).