Added logging and some error checking, also fixed a couple of small bugs.