Refined algorithm a bit