rewrite most of parts in pure c