```{r setup,eval=TRUE,echo=FALSE}
if (!exists("indent")) {
	indent <- '#'
}
if (exists("testing")) {
	scale <- 1:10
	reliabilities <- list()
	items <- list()
	scale_info <- list(scale_item_names = c("item1", "item2", "item3R"))
}

scale_info <- attributes(scale)
```

`r indent`## Scale: `r scale_name` {#`r scale_name` .tabset}
`r paste0('<a name="', scale_info$scale_item_names, '"></a>', collapse = '', sep = '')`

`r indent`### Reliability {#`r scale_name`_reliability}
```{r reliability, results='asis'}
for (i in seq_along(reliabilities)) {
  rel <- reliabilities[[i]]
  cat(knitr::knit_print(rel, indent = paste0(indent, "####")))
}
```

`r indent`### Likert plot {#`r scale_name`_likert}

```{r likert_setup}
old_height <- knitr::opts_chunk$get("fig.height")
new_height <- length(scale_info$scale_item_names)
new_height <- ifelse(new_height > 20, 20, new_height)
new_height <- ifelse(new_height < 1, 1, new_height)
new_height <- ifelse(is.na(new_height) | is.nan(new_height), 
                     old_height, new_height)
knitr::opts_chunk$set(fig.height = new_height)
```
```{r likert}
likert_plot <- likert_from_items(items)
if (!is.null(likert_plot)) {
  graphics::plot(likert_plot)
}
knitr::opts_chunk$set(fig.height = old_height)
```


`r indent`### Distribution {#`r scale_name`_distribution}
```{r setup_distribution}
binwidth <- mean(diff(sort(unique(scale))))

wrap_at <- knitr::opts_chunk$get("fig.width") * 10
```
```{r distribution}
dist_plot <- plot_labelled(scale, scale_name, wrap_at)

choices <- attributes(items[[1]])$item$choices
breaks <- as.numeric(names(choices))
if (length(breaks)) {
  dist_plot <- dist_plot +
    	ggplot2::scale_x_continuous("Choices", 
	                            breaks = breaks, 
	                            labels = stringr::str_wrap(unlist(choices), 15), 
	                            limits = range(breaks))
}

dist_plot
```

`r indent`### Summary statistics {#`r scale_name`_summary}
```{r summary}
pander::pander(codebook_table(items))
```
