further refactoring and corrections