cleaned up code and better exception handling