Core algorithm