Memory fix

Hi,

These are a set of patches that I made after running valgrind against the code to find memory and file descriptor leaks

cheers