Working verison. Lacks test cases