Really fixed rgen this time. Added some error handling in places.