refactored spaghetti function: