Refactoring.

Signed-off-by: Ben Corlett <bencorlett@me.com>
Complete rewrite and simplification.

Signed-off-by: Ben Corlett <bencorlett@me.com>