Fix the a flash write bug (2 lines), lots of cleanup and debug code