refactor code and fix some errors

I am pretty sure I forked a branch called rework just this morning. Not sure what happened to that.

If this cant got to master let me know a better place to make these changes.