Fixed a few small bugs and refactored the code.