refactor and bug fixing