Converted from python to C