added more error handling (untested)