adjusted to Boris suggestions for algorithm