lab4v2: few bugs, but algorithm correct