Refactoring trying to fix some logic issues