improve exceptions
Add unit tests,
Fix memory leak.