Functional optimized version. Needs refactoring and clean up, but the main
idea works.