Refactoring: remove global variables and long conditions