second attempt at algo