Added more logging, corrected logic and fixed mem leaks.