code refactor and bug fixes