Working version, all functions and tests passing