Refactor training function