Improve error message, plug memory leak and simplify code