converted algorithm to c