Removing code duplication by proper templating&specialization.

@sonney2k: It just hurt to see all this code duplication.  Hope you agree.