algorithm now works