More refactoring, better error handling, test cases for MA