Complete rewrite to clean up the code a bit