alanoe/refactoring1

A lot of improvements and some bug fixes. I may break in more pull requests if you guys prefer.