Major cleanup, and added logging