Added some error detection

This hasn't been tested yet.