Refactoring. Fixed some bugs and wrote some tests.