Make the code work, add some error checking