Modified program structure for readability purposes. Added more error catching.