Fixed a lot of bugs, as well as some small code optimizations.
Closes #2.