Cleanup permalink generation

Fix permalink generation to not contain various smells. See verbose description in the last commit in this PR.
@dkubb We need an lvar to mutate it below in case of number space exhaustion.