refactor and correcting logic bugs.