Fix bugs and added tests from Eli.