Trimmed down and cleaned up the code from Claudio. Added some basic unit tests.