Cleaned up implementation some, and fixed a couple of bugs