fix issue#32, and make the code more clean