Refactored and added error checking.
Better names for a couple of functions.
Surround with a self invoking function.