Cleaned the code, added tests