Cleanup permalink generation

Fix permalink generation to not contain various smells. See verbose description in the last commit in this PR.
@dkubb Yeah. I did not spotted this one and stuck to close with what upstream did initially. This is a nice effect of code reviews. My brain was just "locked in" from its previous achievements with reducing the code.