finished C implementation