very close to working impl I think