Working version.
Need to add more tests, comments, and error handleing.