made algorithm more robust