Heavily improved algorithm