code cleanup and a lot of fixes