Refactor logic error and magical numbers