Very rough code, but mostly works