re-factoring of main functions, remove duplicated code