Refactoring code for readability, getting consistent failures