Fixed multiple issues and added some error checking