First complete implementation, untested