refactor train code