More code cleanup. Added better error handling