Refactor bugfix to a more streamline code