Improve on the template function robustness and speed.

Signed-off-by: hajee <hajee@moretIA.com>