copy algorithm from slides