rewrite in c. may contain bugs!
result appears a little bit different with the python
version, in which abrupt of transition is not that sharp.