final version unless bugs in the algorithms