move algorithm into function, initial pass at alg2