Nearly done. Still ugly, but functions ok.