Added error checking and fixed a couple bugs.