better error handling, unit tests & code cleanup