Reworked algorithm