refactored logic for maintaining variables