Further refactoring. Down to 20 lines and easier to understand.