made algorithm more efficient