rewrite the code, improved the comments