Updated a lot of the code, added some error checking