finish C port of generation algorithm