final refactoring and test for training