Original algorithm complete version 1