cleaned up code a bit and added exception handling