Added more error handling

Along with some minor bugfixes to make the code more robust.