improved algorithm dramatically