Refactoring, various fixes and tweaks