{{- $capitalize := false -}}
{{- $slugs := .Params -}}
{{- if and (gt (len .Params) 0) (eq (index .Params 0) "upper") -}}
{{- $capitalize = true -}}
{{- $slugs = after 1 .Params -}}
{{- end -}}
{{- $links := slice -}}
{{- $firstIsSection := true -}}
{{- $paths := slice -}}
{{- range where $.Site.Pages "Slug" "in" $slugs -}}
{{- if eq (len (where $.Site.Pages "Slug" .Slug)) 1 -}}
{{- $paths = $paths | append .File.Path -}}
{{- else -}}
{{- errorf "Found more than one page with slug '%s'" .Slug -}}
{{- end -}}
{{- end -}}
{{- if ne (len $paths) (len $slugs) -}}
{{- errorf "Found %d pages but %d slugs were provided" (len $paths) (len $slugs) -}}
{{- end -}}
{{- with $.Site.GetPage (index $paths 0) -}}
{{- $firstIsSection = .IsSection -}}
{{- end -}}
{{- range $paths -}}
{{- with $.Site.GetPage . -}}
{{- $isSection := .IsSection -}}
{{- if ne $isSection $firstIsSection -}}
{{- errorf "Cannot mix sections and regular pages in the same reference" -}}
{{- end -}}
{{- $weight := .Weight -}}
{{- $slug := .Slug -}}
{{- if $isSection -}}
{{- $href := cond $.Site.Params.pdfgen (printf "#%s" $slug) .RelPermalink -}}
{{- $link := printf `%d` $href $weight | safeHTML -}}
{{- $links = $links | append $link -}}
{{- else -}}
{{- with .Parent -}}
{{- $parentWeight := .Weight -}}
{{- $href := cond $.Site.Params.pdfgen (printf "#%s" $slug) (printf "%s#%s" .RelPermalink $slug) -}}
{{- $link := printf `%d.%d` $href $parentWeight $weight | safeHTML -}}
{{- $links = $links | append $link -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- $count := len $links -}}
{{- $prefix := "" -}}
{{- if $firstIsSection -}}
{{- if eq $count 1 -}}
{{- $prefix = "chapter " -}}
{{- else -}}
{{- $prefix = "chapters " -}}
{{- end -}}
{{- else -}}
{{- if eq $count 1 -}}
{{- $prefix = "section " -}}
{{- else -}}
{{- $prefix = "sections " -}}
{{- end -}}
{{- end -}}
{{- if $capitalize -}}
{{- $prefix = $prefix | title -}}
{{- end -}}
{{- printf "%s" $prefix | safeHTML -}}
{{- if eq $count 1 -}}
{{- index $links 0 -}}
{{- else if eq $count 2 -}}
{{- index $links 0 -}}{{- print " and " | safeHTML -}}{{- index $links 1 -}}
{{- else -}}
{{- range $i, $link := first (sub $count 1) $links -}}
{{- $link -}}{{- print ", " | safeHTML -}}
{{- end -}}
{{- print "and " | safeHTML -}}{{- index $links (sub $count 1) -}}
{{- end -}}