fix many bugs, add many testcases