First complete, but ugly, implementation