Refactor some error code, deal with odd cases better
Remove test code