finally fixed the algorithms