Refactor similar code sections into template functions.

Signed-off-by: Rami Ylimäki <rami.ylimaki@vincit.fi>