modularized core functions. verified two simple cases.