Refined algorithm