Code cleanup and various fixes