simplify code and add a parameter to train function