Updated code: more robust error control. Updated test cases.