What a mess. Fixed some problem in template function core.