I've taken a new approach. This makes the code look much cleaner.