Fixed several segmentation faults and memory leaks and bugs in general