---
title: "{{title}}"
author: "{{author}}"
date: "`r format(Sys.time(), '%d %B, %Y')`"
urlcolor: blue
output: 
  pdf_document:
  toc: true
---

```{r, echo=FALSE}
library("exams.forge")
library("rjson")
library("knitr")
# read JSON file
exams   <- fromJSON(file="{{json}}")[[1]]
# based on students last and first name create an order
name    <- order(sapply(exams, function(v) {paste(v[1], v[2], sep=", ")}))
# create data frame with name, points and grades for overview
student <- data.frame(Name=rep(NA_character_, length(name)), 
                      Punkte=rep(NA_character_, length(name)), 
                      Note=rep('      ', length(name)),
                      stringsAsFactors = FALSE)
```

```{r student, results="asis", echo=FALSE}  
k   <- 1
txt <- NULL
for (i in name) {
  # get exam for one student
  exam <- exams[[i]]
  txt <- c(txt, sprintf("\\newpage\n## %s, %s\n", exam[1], exam[2]))
  student$Name[k]   <- sprintf("%s, %s", exam[1], exam[2])  
  student$Punkte[k] <- exam[7]
  tab <- data.frame(Status=exam[3], Beginn=exam[4], Ende=exam[5],
                    Dauer=exam[6], Bewertung=exam[7], stringsAsFactors = FALSE)
  txt <- c(txt, kable(tab))
  # take the exam questions and answers
  j <- 8
  while(j<length(exam)) {
    txt <- c(txt, sprintf ("### Aufgabe %.0f", (j-5)%/%3))
    txt <- c(txt, toRMarkdown(exam[j]), "\n")
    tab <- data.frame("Richtige Antwort"=exam[j+2], "Gegebene Antwort"=exam[j+1], 
                      stringsAsFactors = FALSE)
    txt <- c(txt, kable(tab), "\n")
    j <- j+3
  }    
  k <- k+1
}
cat(paste0(txt, collapse="\n"))
```

```{r uebersicht, results="asis", echo=FALSE}
txt <- ''
# compute grades from points
student$Note <- grade(student$Punkte, maxpts=7, fixed=FALSE)
# create overview table
gpts <- ceiling(100*attr(student$Note, "gradebreaks"))/100
gpts <- rbind(gpts[-12], gpts[-1])
tab  <- table(student$Note)
gpts <- rbind(gpts, tab, prop.table(tab)) 
colnames(gpts) <- c("5.0", "4.0", "3.7", "3.3", "3.0", "2.7", "2.3", "2.0", "1.7", "1.3", "1.0")
rownames(gpts) <- c("Von", "Bis unter", "Anzahl", "Anteil")
txt  <- c(txt, '\\newpage\n# Noten\n', kable(gpts, align='rrrrrrrrrrr'), "\n\n")
# creat table for each students points and grades
txt  <- c(txt, kable(student, align="lrr"), "\n")
cat(paste0(txt, collapse="\n"))
```

