Refoctor the code fix bugs