fix many bugs, add new testcases