global refactoring and some fixes.