Code cleanup and better logging