Cleared up the code a bit - better error handling now