Handle malformed input
More refactoring, comments