Fixed bugs, and added error checking