Fixed a bug which could cause an infinite loop. Added better exception
handling, and appropriate tests