Fixing some bugs. Adding tests.