Added extra error handling

and minor bugfixes.