refactoring and branch conditions bug fix