Fixing memory leaks and some cosmetics