bug fixing memory leaks and wrong writes