restructure and fix a bug in last commit