Refactored some code
Another rewrite.