fix algorythm, found memory error