factorized code, fixed error