improved algorithm, added rank