trying a more readable algorithm - still to be validated