first finished draft of algorithm