Code cleanup, additional error checks, new testcases.