finalized algorithm