Added debug function and error handling

(and minor improvements)