Refactor and clean error handling in typechecker. Could still be improved, probably.