Improved error handling and device handling

Removed some bugs. Added better error handling.