General code clean up, various fixes