Refactored the code a bit.
Fixed minor bugs.