Bug fixes and cleanup

Add more error handling and fix bugs and memoryleaks