Code cleanup and added a lot more logging