Refactoring with fixing potential bugs