Working, but needs refactoring and throws exception at the end.