Final commit with working code. May need more test cases.