code enhancement and fixed #43 (split function into smaller functions)