diff --git a/.gitignore b/.gitignore
index 20f245e3dca3b11f428faab14eb7a8181616aaf4..f681c2b69d80bfe19973abf84b6ea48353e155e5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,8 +2,3 @@
 .Rhistory
 .RData
 .~lock.*#
-R/Companies/
-Formulas_Reference/2013*.xls*
-LifeInsuranceContracts.Rproj
-Vergleichsrechnung_Excel
-inst/doc
diff --git a/DESCRIPTION b/DESCRIPTION
index bbd7461fcb997c0ffcac5069e11083fa38761c55..65a53fc148f28c1acf769580a306eb7635957a81 100644
--- a/DESCRIPTION
+++ b/DESCRIPTION
@@ -1,61 +1,21 @@
 Package: LifeInsuranceContracts
 Type: Package
-Version: 0.0.5
-Date: 2023-10-18
+Version: 0.0.6
+Date: 2023-10-20
 Title: Framework for Traditional Life Insurance Contracts
-Description: R6 classes to model traditional life insurance
-    contracts like annuities, whole life insurances or endowments. Such life
-    insurance contracts provide a guaranteed interest and are not directly linked
-    to the performance of a particular investment vehicle. However, they typically
-    provide (discretionary) profit participation. This package provides a framework
-    to model such contracts in a very generic (cash-flow-based) way and includes
-    modelling profit participation schemes, dynamic increases or more general
-    contract layers, as well as contract changes (like sum increases or premium
-    waivers). All relevant quantities like premium decomposition, reserves and 
-    benefits over the whole contract period are calculated and potentially 
-    exported to excel. Mortalities are given using the 'MortalityTables' package.
+Description: This package has been renamed to LifeInsureR, please use that package.
 Authors@R: c(person("Reinhold", "Kainhofer", role=c("aut", "cre"), email="reinhold@kainhofer.com"))
 Author: Reinhold Kainhofer [aut, cre]
 Maintainer: Reinhold Kainhofer <reinhold@kainhofer.com>
 Encoding: UTF-8
 Imports:
-    R6,
-    MortalityTables,
-    objectProperties,
-    lubridate,
-    openxlsx,
-    dplyr,
-    scales,
-    abind,
-    stringr,
-    methods,
-    rlang,
-    rmarkdown,
-    kableExtra,
-    pander,
-    tidyr
+    LifeInsureR,
+    rmarkdown
 License: GPL (>= 2)
-RoxygenNote: 7.2.3
-Collate:
-    'HelperFunctions.R'
-    'InsuranceParameters.R'
-    'ProfitParticipation_Functions.R'
-    'ProfitParticipation.R'
-    'InsuranceTarif.R'
-    'InsuranceContract.R'
-    'addDataTableWorksheet.R'
-    'contractGrid.R'
-    'create_LIC_project.R'
-    'exportInsuranceContract_xlsx.R'
-    'showVmGlgExamples.R'
-    'exportInsuranceContractExample.R'
 Suggests:
-    knitr,
-    magrittr,
-    tibble,
-    testthat,
-    fs
+    knitr
 VignetteBuilder: knitr
 Roxygen: list(markdown = TRUE)
-URL: https://gitlab.open-tools.net/R/r-life-insurance-contracts
-BugReports: https://gitlab.open-tools.net/R/r-life-insurance-contracts/-/issues
+URL: https://gitlab.open-tools.net/R/LifeInsureR
+BugReports: https://gitlab.open-tools.net/R/LifeInsureR/-/issues
+RoxygenNote: 7.2.3
diff --git a/Examples/Beispiel_Vortrag.R b/Examples/Beispiel_Vortrag.R
deleted file mode 100644
index 7031d533675417a7446435ce94ed222845606b29..0000000000000000000000000000000000000000
--- a/Examples/Beispiel_Vortrag.R
+++ /dev/null
@@ -1,146 +0,0 @@
-# 2.2 Tariff implementation (InsuranceTarif)
-
-library(magrittr)
-library(MortalityTables)
-library(lubridate)
-library(LifeInsuranceContracts)
-mortalityTables.load("Austria_Census")
-
-mort.AT.census.2011.male
-
-Tarif.L71U = InsuranceTarif$new(
-    name = "L71-U",
-    type = "wholelife",
-    tarif = "DeathPlus - Short Term Life Insurance",
-    desc = "Term Life insurance (5 years) with constant sum insured and regular premiums",
-    policyPeriod = 5, premiumPeriod = 5,  # premiumPeriod not needed, defaults to maturity
-
-    mortalityTable = mortalityTable.mixed(
-        table1 = mort.AT.census.2011.male, weight1 = 0.65,
-        table2 = mort.AT.census.2011.female, weight2 = 0.35
-    ),
-    i = 0.005,
-    tax = 0.04,
-    costs = initializeCosts(alpha = 0.05, gamma = 0.01, gamma.paidUp = 0.01, unitcosts = 10),
-    surrenderValueCalculation = function(surrenderReserve, params, values) {
-        surrenderReserve * 0.9
-    }
-);
-
-
-
-# 2.3 Creating a contract
-
-contract.L71U  = InsuranceContract$new(
-    Tarif.L71U,
-    age = 35,
-    contractClosing = as.Date("2020-08-18"),
-    sumInsured = 100000);
-contract.L71U.1996R  = InsuranceContract$new(
-    Tarif.L71U,
-    age = 35,
-    contractClosing = as.Date("2020-08-18"),
-    mortalityTable = AVOe1996R.male,
-    sumInsured = 100000);
-
-contract.L71U$Values$premiums
-contract.L71U.1996R$Values$premiums
-
-library(openxlsx)
-exportInsuranceContract.xlsx(contract.L71U, "L71U.xlsx")
-openXL("L71U.xlsx")
-
-
-contract.L71U$Values$premiums
-contract.L71U$Values$reserves
-
-
-contract.L71U$Values$cashFlows
-contract.L71U$Values$cashFlowsCosts[,,,"survival"]
-contract.L71U$Parameters$Costs %>% costsDisplayTable()
-
-contract.L71U$Values$presentValues
-contract.L71U$Values$presentValuesCosts
-
-
-VMGL.contract = InsuranceContract$new(
-    Tarif.L71U,
-    age = 35, policyPeriod = 5, premiumPeriod
-    sumInsured = 100000,
-    contractClosing = as.Date("2020-07-01")
-)
-
-showVmGlgExamples(VMGL.contract, t_prf = 3, t = 3)
-
-
-
-
-
-
-library(MortalityTables)
-mortalityTables.load("Austria_Census")
-mortalityTables.load("Austria_Annuities_AVOe2005R")
-# Costs: 4% acquisition, where 2.5% are zillmered, 5\% of each premium as beta costs,
-#        1%o acquisition costs of the sum insured over the whole contract period
-example.Costs = initializeCosts(
-    alpha = 0.04, Zillmer = 0.025,
-    beta = 0.05,
-    gamma.contract = 0.001, gamma.paidUp = 0.001
-)
-example.Surrender = function(surrenderReserve, params, values) {
-    n = params$ContractData$policyPeriod
-    # Surrender Penalty is 10% at the beginning and decreases linearly to 0%
-    surrenderReserve * (0.9 + 0.1 * (0:n)/n)
-}
-Tarif.Endowment = InsuranceTarif$new(
-    name = "Example Tariff - Endowment",
-    type = "endowment",
-    tarif = "EN1",
-    desc = "An endowment with regular premiums",
-
-    mortalityTable = mort.AT.census.2011.unisex,
-    i = 0.005,
-    costs = example.Costs,
-    unitcosts = 10,
-    tax = 0.04,         # 4% insurance tax
-    surrenderValueCalculation = example.Surrender
-)
-
-contract.Endowment.Dynamics = InsuranceContract$new(
-    tarif = Tarif.Endowment,
-    sumInsured = 10000,
-    age = 40,
-    policyPeriod = 10,
-    contractClosing = as.Date("2020-09-01"),
-    id = "Initial contract"
-)$
-    addDynamics(t = 5, NewSumInsured = 11000, id = "Dynamic at 5")$
-    addDynamics(t = 7, NewSumInsured = 12000, id = "Dynamic at 7")$
-    addDynamics(t = 8, NewSumInsured = 13500, id = "Dynamic at 8")
-
-contract.Endowment.Dynamics
-exportInsuranceContract.xlsx(contract.Endowment.Dynamics, "dyn.xlsx")
-openXL("dyn.xlsx")
-
-
-contract.Endowment.Dynamics = InsuranceContract$new(
-    tarif = Tarif.Endowment,
-    sumInsured = 10000,
-    age = 40,
-    policyPeriod = 10,
-    contractClosing = as.Date("2020-09-01"),
-    id = "Initial contract"
-)$addBlock(t = 3, tarif = Tarif.Endowment, age = 43, policyPeriod = 7,
-           sumInsured = 1000, premiumPeriod = 1, id = "Einmalzuzahlung at 5")
-
-contract.L71U.prf = contract.L71U$premiumWaiver(t = 3)
-contract.L71U.prf$Values$reservesBalanceSheet
-
-contract.L71U.prf$Values$cashFlows
-
-grd = contractGridPremium(
-    axes = list(mortalityTable = mort.AT.census["m", ], age = seq(20, 80, 10)),
-    tarif = Tarif.L71U,
-    sumInsured = 100000,
-    contractClosing = as.Date("2020-08-18")
-)
diff --git a/Examples/Example_Endowment_Dynamics.xlsx b/Examples/Example_Endowment_Dynamics.xlsx
deleted file mode 100644
index a6b68ff2f5bb0fcb7f8a5ff3056e3dd0cd3820de..0000000000000000000000000000000000000000
Binary files a/Examples/Example_Endowment_Dynamics.xlsx and /dev/null differ
diff --git a/Examples/Example_Endowment_Dynamics_CODE.R b/Examples/Example_Endowment_Dynamics_CODE.R
deleted file mode 100644
index 7ccb9ae3e82329e6772e388d2982ff88635c6502..0000000000000000000000000000000000000000
--- a/Examples/Example_Endowment_Dynamics_CODE.R
+++ /dev/null
@@ -1,46 +0,0 @@
-library(magrittr)
-library(MortalityTables)
-library(LifeInsuranceContracts)
-mortalityTables.load("Austria_Census")
-
-# Costs: 4% acquisition, where 2.5% are zillmered, 5\% of each premium as beta costs,
-#        1%o acquisition costs of the sum insured over the whole contract period
-example.Costs = initializeCosts(
-    alpha = 0.04, Zillmer = 0.025,
-    beta = 0.05,
-    gamma.contract = 0.001, gamma.paidUp = 0.001
-)
-example.Surrender = function(surrenderReserve, params, values) {
-    n = params$ContractData$policyPeriod
-    # Surrender Penalty is 10% at the beginning and decreases linearly to 0%
-    surrenderReserve * (0.9 + 0.1 * (0:n)/n)
-}
-
-Tarif.Endowment = InsuranceTarif$new(
-    name = "Example Tariff - Endowment",
-    type = "endowment",
-    tarif = "EN1",
-    desc = "An endowment with regular premiums",
-
-    mortalityTable = mort.AT.census.2011.unisex,
-    i = 0.005,
-    costs = example.Costs,
-    unitcosts = 10,
-    tax = 0.04,         # 4% insurance tax
-    surrenderValueCalculation = example.Surrender
-)
-
-contract.Endowment = InsuranceContract$new(
-    Tarif.Endowment,
-    age = 50, policyPeriod = 35,
-    premiumFrequency = 12,
-    sumInsured = 100000,
-    contractClosing = as.Date("2020-07-01")
-)
-contract.exportExample = contract.Endowment$clone()$
-    addDynamics(t = 3, SumInsuredDelta = 10000)$
-    addDynamics(t = 5, SumInsuredDelta = 15000)$
-    addDynamics(t = 10, SumInsuredDelta = 15000)$
-    addDynamics(t = 14, SumInsuredDelta = 10000)
-exportInsuranceContract.xlsx(contract.exportExample, filename = "Example_Endowment_Dynamics.xlsx")
-openxlsx::openXL("Example_Endowment_Dynamics.xlsx")
diff --git a/Formulas_Reference/.gitignore b/Formulas_Reference/.gitignore
deleted file mode 100644
index 1663ebea4eb69ff65a73bc92b1b64fd27efb1138..0000000000000000000000000000000000000000
--- a/Formulas_Reference/.gitignore
+++ /dev/null
@@ -1,10 +0,0 @@
-*.aux
-*.dvi
-*.log
-*.synctex.gz
-*.backup
-*.kilepr
-Bernkopf Max
-Formelsammlung_Beispielrechnung.toc
-Formelsammlung_Beispielrechnung.out
-.gitignore
diff --git a/Formulas_Reference/Formelsammlung_Beispielrechnung.pdf b/Formulas_Reference/Formelsammlung_Beispielrechnung.pdf
deleted file mode 100644
index b516030319141b056f7ae74c7809d4b9d3ea2ad3..0000000000000000000000000000000000000000
Binary files a/Formulas_Reference/Formelsammlung_Beispielrechnung.pdf and /dev/null differ
diff --git a/Formulas_Reference/Formelsammlung_Beispielrechnung.tex b/Formulas_Reference/Formelsammlung_Beispielrechnung.tex
deleted file mode 100644
index 158f1569d3e3f762e58404d959ac1baf70f56963..0000000000000000000000000000000000000000
--- a/Formulas_Reference/Formelsammlung_Beispielrechnung.tex
+++ /dev/null
@@ -1,1168 +0,0 @@
-\documentclass[a4paper,10pt]{article}
-\usepackage[T1]{fontenc}
-\usepackage[utf8]{inputenc}
-\usepackage{geometry}
-\usepackage{tabularx, longtable}
-\usepackage{amsmath}
-\usepackage[ngerman]{babel}
-\usepackage[usenames,dvipsnames]{xcolor}
-\usepackage{enumerate}
-\usepackage{enumitem}
-\setlist{nolistsep}
-\usepackage{multirow}
-%\usepackage{itemize}
-% \usepackage{sans}
-\usepackage{array}
-\newcolumntype{C}[1]{>{\centering\arraybackslash$}p{#1}<{$}}
-\usepackage{rotating}
-\usepackage{pdflscape}
-\usepackage{hyperref}
-
-% \usepackage{mathpazo}% Palatino mit mathematischen Zeichen
-\hyphenation{Prä-mi-en-frei-stel-lung}
-
-%opening
-\title{\textbf{Formelsammlung Tarif Lebensversicherung}}
-\author{Reinhold Kainhofer (reinhold@kainhofer.com)}
-
-\geometry{bottom=2cm,top=2cm,left=1.5cm,right=1.5cm}
-
-\newcommand{\PreserveBackslash}[1]{\let\temp=\\#1\let\\=\temp}
-\newcolumntype{v}[1]{>{\PreserveBackslash\centering\hspace{0pt}}p{#1}}
-
-\newcommand{\markiert}[1]{{\setlength{\fboxsep}{0pt}\colorbox{Goldenrod}{\textcolor{red}{#1}}}}
-\newcommand{\orZero}[1]{\mathit{\left[#1\right]}}
-\newcommand{\xn}{{\act[x]{n}}}
-
-
-\setlength{\parindent}{0em}
-
-\makeatletter
-\DeclareRobustCommand{\act}[2][]{%
-\def\arraystretch{0}%
-\setlength\arraycolsep{0.5pt}%
-\setlength\arrayrulewidth{0.5pt}%
-\setbox0=\hbox{$\scriptstyle#1\ifx#1\empty{asdf}\else:\fi#2$}%
-\begin{array}[b]{*2{@{}>{\scriptstyle}c}|}
-\cline{2-2}%
-\rule[1.25pt]{0pt}{\ht0}%
-#1\ifx#1\empty\else:\fi & #2%
-\end{array}%
-}
-\makeatother
-
-\renewcommand{\labelitemi}{-)}
-% \renewcommand[\itemsep}{0cm}
-% \renewcommand{\labelitemsep}{0cm}
-\itemsep0em
-
-
-\begin{document}
-
-\maketitle
-
-% \begin{abstract}
-%
-% \end{abstract}
-
-Bemerkung: Sämtliche Barwerte werden rekursiv bestimmt, daher werden alle Formeln in ihrer rekursiven Form angegeben. Teilweise wird aus informativen Gründen davor die entsprechende Summenformel angegeben, diese wird jedoch nicht zur tatsächlichen Berechnung benutzt.
-
-\tableofcontents
-
-
-\begin{landscape}
-\section{Definitionen sämtlicher Variablen}
-
-\subsection{Vertragsdetails (vertragsspezifische Werte)}
-
-\newenvironment{deftab}{\begin{longtable}{p{1.7cm}p{13cm}p{9cm}}}{\end{longtable}}
-
-\begin{deftab}
- $VS$ & Versicherungssumme & \texttt{contract\$params\$sumInsured}\\
- $\widetilde{VS}$ & Versicherungssumme nach außerplanmäßiger Prä"-mi"-en"-frei"-stel"-lung\\[0.5em]
- $x$ & Eintrittsalter der versicherten Person & \texttt{contract\$params\$age}\\
- $n$ & Versicherungsdauer & \texttt{contract\$params\$policyPeriod}\\
- $l$ & Aufschubdauer des Versicherungsschutzes & \texttt{contract\$params\$deferral}\\
- $m$ & Prämienzahlungsdauer & \texttt{contract\$params\$premiumPeriod}\\
- $k$ & Prämienzahlungsweise ($k$-tel jährlich) & \texttt{contract\$params\$premiumFrequency}\\
- $g$ & Garantiedauer (für Renten)  & \texttt{contract\$params\$guaranteed}\\
- $f$ & Prämienfreistellungszeitpunkt\\[0.5em]
-
- $YOB$ & Geburtsjahr der versicherten Person (bei Benutzung von Generationentafeln) & \texttt{contract\$params\$YOB}\\
- $Beg$ & Versicherungsbeginn (Datum, TODO)\\[0.5em]
-
- $q_{x+t}$ & einjährige Sterbewahrscheinlichkeit der versicherten Person (aus $YOB$ und $x$ bestimmt) & \texttt{contract\$params\$transitionProbabilities\$q}\\
- $i_{x+t}$ & einjährige Erkrankungswahrscheinlichkeit (z.B. Dread Disease, Krebs, etc.) & \texttt{contract\$params\$transitionProbabilities\$i} \\
- $p_{x+t}$ & einjährige Überlebenswahrscheinlichkeit als Aktiver, $p_{x+t} = 1-q_{x+t}-i_{x+1}$ & \texttt{contract\$params\$transitionProbabilities\$p} \\
- $\omega$  & Höchstalter gemäß der benutzten Sterbetafel  & \texttt{getOmega(tarif\$mortalityTable)} \\[0.5em]
-
-
- $k_{Ausz}$ & unterjährige Auszahlung der Erlebensleistungen (nur Renten) & \texttt{contract\$params\$benefitFrequency}\\
- $y$ & Eintrittsalter der 2. versicherten Person (TODO)\\
-
-
-\end{deftab}
-
-\subsection{Tarifdetails (identisch für alle Verträge)}
-\begin{deftab}
- $i$ & Rechnungszins & \texttt{tarif\$i}\\[0.5em]
- $v$ & Diskontierungsfaktor $v=\frac1{1+i}$ & \texttt{tarif\$v}\\[0.5em]
-
- $\rho$ & Sicherheitszuschlag auf die Prämie & \texttt{tarif\$loadings\$security} \\
- $\rho^{RG}$ & Risikosumme (relativ zu DK) im Ablebensfall bei Prämienrückgewähr & \texttt{tarif\$premiumRefundLoading} \\
- $uz(k)$ & Unterjährigkeitszuschlag bei $k$-tel jährlicher Prämienzahlung (in \% der Prämie) & \texttt{tarif\$premiumFrequencyLoading}\\
- $O(k)$ & Ordnung der Unterjährigkeitsrechnung der Erlebenszahlungen (0./""1./""1,5./""2. Ordnung) & \texttt{tarif\$benefitFrequencyOrder}\\[0.5em]
-
-\end{deftab}
-
-\subsection{Leistungen}
-
-\begin{deftab}
- $\Pi_t$ & (Netto-)Prämie zum Zeitpunkt $t$ (vorschüssig), $\Pi^{nachsch.}_t$ für nachschüssige Prämienzahlungsweise, normiert auf 1 & \texttt{contract\$cashFlows\$premiums\_advance}\\
- $\Pi^{nachsch.}_t$ & (Netto-)Prämie zum Zeitpunkt $t$ (nachschüssig), normiert auf 1 & \texttt{contract\$cashFlows\$premiums\_arrears}\\
- $PS_t$ &Bruttoprämiensumme bis zum Zeitpunkt $t$: $PS_t=\sum_{j=0}^t \Pi^a_t$\\
- $PS$ & Bruttoprämiensumme über die gesamte Vertragslaufzeit  & \texttt{contract\$premiumSum}\\[0.5em]
-
- $\ddot{e}_t$ & vorschüssige Erlebenszahlung zum Zeitpunkt $t$ (normiert auf 1) & \texttt{contract\$cashFlows\$survival\_advance}\\
- $e_t$ & nachschüssige Erlebenszahlung zum Zeitpunkt $t$ (normiert auf 1) & \texttt{contract\$cashFlows\$survival\_arrears}\\[0.5em]
-
- $\ddot{e}_t^*$ & vorschüssige garantierte Zahlung zum Zeitpunkt $t$ (normiert auf 1) & \texttt{contract\$cashFlows\$guaranteed\_advance}\\
- $e_t^*$ & nachschüssige garantierte Zahlung zum Zeitpunkt $t$ (normiert auf 1) & \texttt{contract\$cashFlows\$guaranteed\_arrears}\\[0.5em]
-
- $a_t$ & Ablebensleistung proportional zur Versicherungssumme (nachschüssig) & \texttt{contract\$cashFlows\$death\_sumInsured}\\
- $a_t^{(RG)}$ & Ablebensleistung für Prämienrückgewähr (normiert auf Prämie 1, relativ zu Prämienzumme $PS$) & \texttt{contract\$cashFlows\$death\_GrossPremium}\\[0.5em]
- $\widetilde{a}_t$ & Ablebensleistung nach außerplanmäßiger Prämienfreistellung proportional zur Versicherungssumme (nachschüssig) & \texttt{contract\$cashFlows\$death\_PremiumFree}\\
-
- $\overrightarrow{CF}^B_t$ & Leistungscashflow (relativ zur jeweiligen Basis, sowie vor"~/""nachschüssig) als Matrix dargestellt
-\end{deftab}
-
-\subsection{Kosten}
-Mögliche Basen für die Kostenfestsetzung sind:
-\begin{align*}
- \text{Basis} &= \begin{cases}\text{VS ... Versicherungssumme (\texttt{"{}SumInsured"})}\\\text{PS ... gesamte Prämiensumme  (\texttt{"{}SumPremiums"})}\\\text{BP ... Bruttojahresprämie  (\texttt{"{}GrossPremium"})}\end{cases} &
- \text{Dauer} &= \begin{cases}\text{1 ... einmalig bei Abschluss (\texttt{"{}once"})}\\\text{PD ... Prämienzahlungsdauer (\texttt{"{}PremiumPeriod"})}\\\text{Prf ... Nach Ablauf der Prämienzahlungsdauer (\texttt{"{}PremiumFree"})}\\\text{LZ ... gesamte Laufzeit (\texttt{"{}PolicyPeriod"})}\end{cases}
-\end{align*}
-
-
-\begin{deftab}
- $\alpha_t^{\text{Basis},\text{Dauer}}$ & Abschlusskostensatz relativ zu Basis über die angegebene Dauer & \texttt{tarif\$costs["{}alpha",,]}\\
- $Z_t^{\text{Basis},\text{Dauer}}$ & Zillmerkostensatz relativ zu Basis über die angegebene Dauer & \texttt{tarif\$costs["{}Zillmer",,]}\\
- $\beta_t^{\text{Basis},\text{Dauer}}$ & Inkassokostensatz relativ zu Basis über die angegebene Dauer & \texttt{tarif\$costs["{}beta",,]}\\
- $\gamma_t^{\text{Basis},\text{Dauer}}$ & Verwaltungskostensatz relativ zu Basis über die angegebene Dauer & \texttt{tarif\$costs["{}gamma",,]}\\
- $\widetilde{\gamma}_t^{\text{Basis},\text{Dauer}}$ & Verwaltungskostensatz nach außerplanmäßiger Prämienfreistellung relativ zu Basis über die angegebene Dauer & \texttt{tarif\$costs["{}gamma\_nopremiums",,]}\\[0.5em]
-
- $\alpha_t^{\text{Basis}}$ & Abschlusskosten-Cash Flow relativ zu Basis zu $t$ & \texttt{contract\$cashFlowsCosts[,"{}alpha", Basis]}\\
- $Z_t^{\text{Basis}}$ & Zillmerkosten-Cash Flow relativ zu Basis zu $t$  & \texttt{contract\$cashFlowsCosts[,"{}Zillmer", Basis]}\\
- $\beta_t^{\text{Basis}}$ & Inkassokosten-Cash Flow relativ zu Basis zu $t$  & \texttt{contract\$cashFlowsCosts[,"{}beta", Basis]}\\
- $\gamma_t^{\text{Basis}}$ & Verwaltungskosten-Cash Flow relativ zu Basis zu $t$  & \texttt{contract\$cashFlowsCosts[,"{}gamma", Basis]}\\
- $\widetilde{\gamma}_t^{\text{Basis}}$ & Verwaltungskosten-Cash Flow nach außerplanmäßiger Prämienfreistellung relativ zu Basis zu $t$  & \texttt{contract\$cashFlowsCosts[,"{}gamma\_nopremiums", Basis]}\\[0.5em]
-
- $\overrightarrow{CF}^C_t$ & Kostencashflows (relativ zur jeweiligen Basis) als Matrix dargestellt & \texttt{contract\$cashFlowsCosts["{}t",,]}
-\end{deftab}
-
-\subsection{Barwerte}
-
-\begin{deftab}
- $P_\xn(t)$ & BW der zuk. Prämienzahlungen (mit Prämie 1) zum Zeitpunkt $t$ & \texttt{contract\$presentValues\$premiums}\\
- $E^*_\xn(t)$ & BW der zuk.  garantierten Zahlungen (mit VS 1) zum Zeitpunkt $t$ & \texttt{contract\$presentValues\$guaranteed}\\
- $E_\xn(t)$ & BW der zuk.  Erlebenszahlungen (mit VS 1) zum Zeitpunkt $t$ & \texttt{contract\$presentValues\$survival}\\
- $E^{(k)}_\xn(t)$ & BW der zuk.  Erlebenszahlungen (mit VS 1) bei $k$-tel jährlicher Auszahlung zum Zeitpunkt $t$ & \texttt{contract\$presentValues\$survival}\\
- $\alpha(k)$, $\beta(k)$ & Unterjährigkeitskorrektur bei $k$-tel jährlicher Auszahlung\\
- $A_\xn(t)$ & BW der zuk.  Ablebensleistungen (mit VS 1) zum Zeitpunkt $t$ & \texttt{contract\$presentValues\$death\_SumInsured}\\
- $A_\xn^{prf}(t)$  & BW der zuk.  Ablebensleistungen (mit VS 1) zum Zeitpunkt $t$ nach Prämienfreistellung & \texttt{contract\$presentValues\$death\_GrossPremium}\\
- $A^{(RG)}_\xn(t)$ & BW der zuk.  Ablebensleistungen aus Prämienrückgewähr (mit BP 1) zum Zeitpunkt $t$ & \texttt{contract\$presentValues\$death\_PremiumFree}\\[0.5em]
-
- $PV^{B1}_\xn(t)$ & BW aller zuk.  Leistungen (ohne Prämienrückgewähr) zum Zeitpunkt $t$ & \texttt{contract\$presentValues\$benefits}\\[1em]
- $PV^B_\xn(t)$ & BW aller zuk.  Leistungen (inkl. Prämienrückgewähr) zum Zeitpunkt $t$ & \texttt{contract\$presentValues\$benefitsAndRefund}\\[1em]
-
-\end{deftab}
- KOSTEN (TODO)
-
-\subsection{Prämien und Prämienzerlegung}
-
-\begin{deftab}
- $\Pi^1_\xn$ & Nettoprämie auf VS 1 & \texttt{contract\$premiums[["{}unit.net"]]}\\
- $\Pi_\xn^{1,Z}$ & Zillmerprämie auf VS 1 & \texttt{contract\$premiums[["{}unit.Zillmer"]]}\\
- $\Pi_\xn^{1,a}$ & Bruttoprämie (``adequate'' bzw. ``expense-load premium'') auf VS 1 & \texttt{contract\$premiums[["{}unit.gross"]]}\\[0.5em]
- $\Pi_\xn$ & Nettoprämie & \texttt{contract\$premiums[["{}net"]]}\\
- $\Pi_\xn^Z$ & Zillmerprämie & \texttt{contract\$premiums[["{}Zillmer"]]}\\
- $\Pi_\xn^a$ & Bruttoprämie (``adequate'' bzw. ``expense-load premium'') & \texttt{contract\$premiums[["{}gross"]]}\\[0.5em]
-
- $\Pi_\xn^\alpha$ & $\alpha$-Kostenprämie (Abschlusskostenprämie)\\
- $\Pi_\xn^\beta$ & $\beta$-Kostenprämie (Inkassokostenprämie)\\
- $\Pi_\xn^\gamma$ & $\gamma$-Kostenprämie (Verwaltungskostenprämie)\\[0.5em]
-
-
- $\Pi_\xn^\text{inv.}$ & Inventarprämie (Netto- plus Verwaltungskostenprämie)\\[1em]
-
- $\Pi_\xn^s$ & Sparprämie (zum Aufbau des Nettodeckungskapitals investierter Teil der Prämie)\\
- $\Pi_\xn^r$ & Risikoprämie (zur Deckung des einjährigen Ablebensrisikos benutzter Teil der Prämie)\\[0.5em]
-
- $\Pi_\xn^v$ & verrechnete Prämie (Bruttoprämie inkl. Rabatte, Zuschläge, Stück"-kosten und Steuer) & \texttt{contract\$premiums[["{}written"]]}\\
- $\Pi_\xn^\text{tax}$ & Versicherungssteuer & \texttt{contract\$premiums[["{}tax"]]}\\
-\end{deftab}
-
-\subsection{Absolutwerte der Cashflows und Barwerte}
-
-TODO
-
-\subsection{Rückstellungen}
-
-\begin{deftab}
- $_{t}V_\xn$ & Nettodeckungskapital zum Zeitpunkt $t$  & \texttt{contract\$reserves[,"net"]}\\
- $_{t}V^a_\xn$ & Brutto-Deckungskapital (``adequate'' bzw. ``expense-loaded reserve'') & \texttt{contract\$reserves[,"adequate"]}\\
- $_{t}V^Z_\xn$ & Zillmerreserve bei Zillmerung & \texttt{contract\$reserves[,"Zillmer"]}\\
- $_{t}V^\alpha_\xn$ & Abschlusskostenreserve & \texttt{contract\$reserves[,"TODO"]}\\
- $_{t}V^\beta_\xn$ & Inkassokostenreserve (typischerweise $=0$)& \texttt{contract\$reserves[,"TODO"]}\\
- $_{t}V^\gamma_\xn$ & Verwaltungskostenreserve & \texttt{contract\$reserves[,"gamma"]}\\
- $_{t}V^{Umr}_\xn$ & Umrechnungsreserve (Basis für Vertragskonvertierungen und Prämienfreistellung), inkl. anteiliger Abschlusskostenrückerstattung bei Beendigung innerhalb von fünf Jahren& \texttt{contract\$reserves[,"reduction"]}\\
- $AbskErh(t)$ & Anteilsmäßige Rückerstattung der Abschlusskosten bei Kündigung innerhalb von fünf Jahren& \texttt{contract\$reserves[,"alphaRefund"]}\\[1em]
-
- $BilRes_{t+u}$  & Bilanzreserve (Interpolation aus  $_{t}V^{x}_\xn$ und $_{t+1}V^{x}_\xn$)
-\end{deftab}
-
-\subsection{Werte nach außerplanmäßiger Prämienfreistellung}
-
-Werte nach außerplanmäßiger Prämienfreistellung werden durch ein $\widetilde{\quad}$ über dem jeweiligen Symbol angezeigt.
-
-
-
-
-
-\end{landscape}
-\pagebreak
-
-\section{Kosten}
-
-\subsection{Abschlusskosten (\texorpdfstring{$\alpha$}{alpha}-Kosten) / Zillmerkosten (Z-Kosten)}
-\begin{itemize}
- \item Einmalig (bei Vertragsabschluss)
- \begin{itemize}
-   \item \markiert{an Versicherungssumme}
-   \item \markiert{an Brutto-Prämiensumme}\footnote{Entspricht Einmalprämie bei Einmalerlag}
-   \item an Barwert der Versicherungsleistungen (z.B. Rentenbarwert) % HP PV5F & PV6F
- \end{itemize}
- \item Laufend (während Prämienzahlungsdauer)\footnote{Bei Einmalerlag sind einmalige $\alpha$-Kosten und laufende $\alpha$-Kosten auf die Prämie während der Prämienzahlungsdauer ident.}
- \begin{itemize}
-   \item \markiert{an Bruttoprämie}
-   \item an Brutto-Prämiensumme
- \end{itemize}
- \item Laufend (über gesamte Laufzeit des Vertrags)
- \begin{itemize}
-   \item an Bruttoprämie
-   \item an Brutto-Prämiensumme
- \end{itemize}
-
-\end{itemize}
-
-% TODO: Check the following tariffs:
-%   - GW PV5F & PV6F
-
-\subsection{Inkassokosten (\texorpdfstring{$\beta$}{beta}-Kosten)}
-
-\begin{itemize}
- \item Laufend an Bruttoprämie während Prämienzahlungsdauer (einmalig bei Einmalerlag)
-\end{itemize}
-
-
-\subsection{Verwaltungskosten (\texorpdfstring{$\gamma$}{gamma}-Kosten)}
-
-Laufend während der gesamten Laufzeit verrechnet:
-
-\begin{itemize}
- \item \markiert{an Versicherungssumme (prämienpflichtig)}
- \item \markiert{an Versicherungssumme (planmäßig/außerplanmäßig prämienfrei)}
- \item an Leistungsbarwert / Rentenbarwert (=Deckungskapital) (prämienfrei) % GW PS0-9 & PV0-9
- \item an Prämiensumme (prämienpflichtig) (=am Rentenbarwert zu Vertragsbeginn bei sof.beg.LR mit EE)
- \item an Prämiensumme (planmäßig/außerplanmäßig prämienfrei)
-
- \item am Ablösekapital während Aufschubzeit % ER III B-PZV Single
- \item \markiert{an jeder Erlebenszahlung/Rente (während Liquiditätsphase)} % ER III B-PZV Single
- \item am Deckungskapital % SV I5U
-\end{itemize}
-
-% TODO: Check the following tariffs:
-%   - GW PS0-9 & PV0-9
-%   - ER III B-PZV Single
-
-\subsection{Stückkosten \textit{StkK}}
-
-\begin{itemize}
- \item Stückkosten (Absolutbetrag) $StkK$ pro Jahr während Prämienzahlungsdauer (bzw. einmalig bei Einmalprämie)
-\end{itemize}
-
-
-\subsection{Übersicht}
-
-Die häufigsten Kostentypen sind \markiert{markiert}.
-
-% % \begin{longtable}{||l|v{3cm}|v{3cm}|v{3cm}|v{3cm}||}\hline\hline
-% %  & an VS & an PS & an JBP\footnote{während der gesamten Prämienzahlungsdauer} & \\ \hline
-% %
-% % Abschluss $\alpha$ & \markiert{$\alpha^{VS}_{j}$ (einmalig)} & $\alpha^{PS}_{j}$ (LZ)\footnote{evt. mit jährlicher faktorieller Aufwertung (evt. mit Obergrenze)} & $\alpha^{BP}_{j}$ (LZ)\linebreak \markiert{$\alpha_{3a,j}$ (PrD)} & \\ \hline
-% % Zillmer $z$ & \markiert{$z^{VS}_{j}$} & \markiert{$z^{PS}_{j}$} & & \\ \hline
-% % Inkasso $\beta$ & & & \markiert{$\beta_{j}$ (PrD)} & \\ \hline
-% % Verwaltung $\gamma$ & \markiert{$\gamma^{VS}_{j}$ (PrD)}\linebreak \markiert{$\gamma^{VS,fr}_{j}$ (nach PrD)}\linebreak \markiert{$\gamma^{frei}_{j}$ (PrFrei)} & $\gamma^{PS}_{j}$ (LZ/PrD) & & $\gamma^{BP,PrD}_{j}$ (an ErlZ, LZ) \\\hline\hline
-% % % \\[-0.9em]\hline
-% % %
-% % % Stückkosten $K$ &
-% % % \\\hline\hline
-% % %
-% % %
-% % \end{longtable}
-% %
-
-\begin{longtable}{||lr|v{1.5cm}|v{1.5cm}|v{1.5cm}|v{1.5cm}|v{1.5cm}|v{1.5cm}||}\hline\hline
-Typ & Dauer & an VS & an PS & an JBP\footnote{während der gesamten Prämienzahlungsdauer} & an NP & konstant & \\ \hline
-
-
-Abschluss $\alpha$ & einmalig      & \markiert{$\alpha^{VS,once}$} &                                                                                                    &                            & $\alpha^{NP,once}$ & & \\
-                   & Prämiendauer  &                              &                                                                                                    & \markiert{$\alpha^{BP,PrD}$} & & & \\
-                   & Prämienfrei   &                              &                                                                                                    &                            & & & \\
-                   & Vertragsdauer &                              & $\alpha^{PS,LZ}$\footnote{evt. mit jährlicher faktorieller Aufwertung, evt. mit Obergrenze)} & $\alpha^{BP,LZ}$          & & & \\ \hline
-Zillmer $z$ & einmalig      & \markiert{$z^{VS,once}$} & \markiert{$z^{PS,once}$} & & & & \\
-            & Prämiendauer  &                         &                         & & & & \\
-            & Prämienfrei   &                         &                         & & & & \\
-            & Vertragsdauer &                         & $z^{PS,LZ}$ & & & & \\ \hline
-Inkasso $\beta$ & einmalig      & & &                              & & & \\
-                & Prämiendauer  & & & \markiert{$\beta^{BP,PrD}$} & & & \\
-                & Prämienfrei   & & &                              & & & \\
-                & Vertragsdauer & & &                              & & & \\ \hline
-Verwaltung $\gamma$ & einmalig      &  & & & & & \\
-                    & Prämiendauer  & \markiert{$\gamma^{VS,PrD}$}    & $\gamma^{PS,PrD}$ & & & & \\
-                    & Prämienfrei   & \markiert{$\gamma^{VS,fr}$} &                   & & & & $\gamma^{BP,Erl}$ (an ErlZ) \\
-                    & Vertragsdauer & $\gamma^{VS,LZ}$           & $\gamma^{PS,LZ}$ & &  & & \\\hline
-
-\multirow{4}{2.5cm}{{Verwaltung $\tilde{\gamma}$ (außerplanm. prämienfrei)}} & einmalig      & & & & & & \\
-                    & Prämiendauer  & & & & & & \\
-                    & Prämienfrei   & & & & & & \\
-                    & Vertragsdauer & \markiert{$\tilde{\gamma}^{VS,LZ}$} & & & & & \\
-\hline\hline
-\end{longtable}
-
-\subsection{Kosten-Cashflows}
-Jede Kostenart ($\alpha$/Zillmer/$\beta$/$\gamma$/$\tilde{\gamma}$) und Bemessungsgrundlage (VS/{}PS/{}JBP) erzeugt aus den verschiedenen Kostendauern einen Cash-Flow-Vektor in folgender Art, der diskontiert den gesamten Kostenbarwert der jeweiligen Kostenart und Bmgl. liefert:
-\begin{equation*}
- X_t^{Bmgl} =
- \begin{cases}
- X^{Bmgl,once} + X^{Bmgl,PrD} + X^{Bmgl,LZ} & \text{für $t=0$} \\
- \hphantom{X^{Bmgl,once} + \;\,} X^{Bmgl,PrD} + X^{Bmgl,LZ} & \text{für $0<t\leq m$} \\
- \hphantom{X^{Bmgl,once} + \;\,} X^{Bmgl,fr} \;\;\; + X^{Bmgl,LZ} & \text{für $m<t\leq n$}
- \end{cases}
-\end{equation*}
-
-
-
-% \subsubsection{Stückkosten:}
-% \begin{longtable}{lp{13cm}}
-% $K_1$\dots & Stückkosten einmalig bei Vertragsabschluss\\
-% $K$\dots & Stückkosten jährlich während Prämienzahlungsdauer\\
-% $K_{LZ}$\dots & Stückkosten jährlich während der gesamten Laufzeit\\
-% \end{longtable}
-
-\pagebreak
-
-\section{Normierte Cashflows (auf Einheitswerte)}
-
-% \begin{sidewaystable}
-\begin{center}
-
-
-% \rotatebox{90}{
-\begin{tabular}{lp{6.5cm}v{1.6cm}v{1.5cm}v{1.5cm}v{1cm}v{1cm}}
-& Beschreibung & LR & ALV & ELV & T-F & DD\\\hline\\[0.01em]
-$pr_t$  \dots          & Prämienzahlungen (vorschüssig) zu $t$ & $t<m$ & $t<m$ & $t<m$ & $t<m$ & $t<m$ \\
-$PS$                   & Prämiensumme, $PS=\sum_{t=0}^n pr_t$\\[0.5em]\hline\\[0em]
-
-$\ddot{e}_t$  \dots    & Erlebenszahlungen vorschüssig zu $t$ & $(l+g)...n$ & 0 & $t=n$ & 0 & 0 \\
-$e_t$  \dots           & Erlebenszahlungen nachschüssig zu $t+1$& $(l+g)...n$ & 0 & $t=n$ & 0 & 0 \\
-$\ddot{e}_t^{*}$ \dots & garantierte Zahlungen vorschüssig zu $t$ & $(l+g)...n$ & 0 & 0  & $t=n$ & 0 \\
-$e_t^{*}$  \dots       & garant. Zahlungen nachschüssig zu $t+1$ & $(l+g)...n$ & 0 & 0  & 0 & 0 \\[0.5em]\hline\\[0em]
-
-$a_t$  \dots           & Ablebenszahlung zu $t+1$ & 0 & $l...n$ & 0 & 0 & 0 \\
-$d_t$  \dots           & Zahlung zu $t+1$ bei Eintritt der Erkrankung zwischen $t$ und $t+1$ & 0 & 0 & 0 & 0& $l...n$ \\[0.5em]\hline\\[0em]
-$a_t^{(RG)}$           & Ablebenszahlungen für PRG zu $t+1$ (Ableben im Jahr $t$) & $\min(t+1, m, f)$ & 0 & $\min(t+1,m,f)$ & 0 & 0 \\[0.5em]\hline
-
-\end{tabular}
-% }
-\end{center}
-% \end{sidewaystable}
-
-Die Cash-Flows können auch in Matrixform dargestellt werden:
-\begin{align*}
-%
- \overrightarrow{CF}^L_t &= \left(
- \begin{matrix} % TODO: Add an indication that the first row is in advance, the second in arrears
-pr_t & \ddot{e}_t^{*} & \ddot{e}_t & 0 & 0 & 0 \\
-pr^{(nachsch)}_t & e_t^{*} & e_t & a_t & d_t & a_t^{(RG)}\\
-\end{matrix}
- \right)
-%
-&
- \overrightarrow{CF}^K_t &= \left(
- \begin{matrix}
-\alpha^{(VS)}_t & \alpha^{(PS)}_t  & \alpha^{(BP)}_t & \alpha^{(NP)}_t & \alpha^{(1)}_t\\
-z^{(VS)}_t & z^{(PS)}_t  & - & z^{(NP)}_t & z^{(1)}_t\\
-- & - & \beta_t & - & - \\
-\gamma^{(VS)}_t & \gamma^{(PS)}_t & -  & \gamma^{(NP)}_t & \gamma^{(1)}_t\\
-\widetilde{\gamma}^{(VS)}_t & - & - & \widetilde{\gamma}^{(NP)}_t & \widetilde{\gamma}^{(1)}_t\\
- \end{matrix}
- \right)
-\end{align*}
-
-
-\pagebreak
-
-\section{Barwerte}
-
-\subsection{Prämienbarwert}
-
-\begin{align*}
-P_\xn(t) &= \sum_{j=t}^n pr_{t+j} \cdot v^{j-t}  \cdot {}_{j-t}p_{x+t}\\
-	  &= pr_{t} + v \cdot p_{x+t} \cdot P_\xn(t+1)
-\end{align*}
-
-\subsection{Barwert garantierter Zahlungen:}
-Garantierte Erlebensleistungen (wenn Aufschubzeit überlebt wurde):
-% TODO!
-\begin{align*}
- E^{*}_\xn(t) &= \begin{cases}
-		    {}_{l-t}p_{x+t} \cdot v^{l-t} \cdot \sum_{j=l}^{n} \left\{\ddot{e}^{*}_{j-t}+ v\cdot e^*_{j-t}\right\} v^{j-t} & \text{für $t<l$ (Aufschubzeit)}\\
-		    \sum_{j=t}^{n} \left\{\ddot{e}^{*}_{j-t}+ v\cdot e^*_{j-t}\right\} v^{j-t} & \text{für $t\ge l$ (Liquiditätsphase)}
-                 \end{cases}\\
-   &= \ddot{e}_t^{*} + \left\{E^{*}_\xn(t+1) + e_t^*\right\}\cdot v \cdot \begin{cases}
-	    1 & \text{für $t<l$ (Aufschubzeit)}\\
-            p_{x+t} & \text{für $t\ge l$ (Liquiditätsphase)}
-       \end{cases}
-\end{align*}
-
-
-\subsection{Erlebensleistungsbarwert:}
-% 1. Person:
-\begin{align*}
-E_\xn(t) &= \sum_{j=t}^n \left(\ddot{e}_{t+j} \cdot v^{j-t}  {}_{j-t}p_{x+t} + e_{t+j} \cdot v^{j+1-t} {}_{j+1-t}p_{x+t} \right)\\
-	  &= \ddot{e}_{t} + v \cdot p_{x+t} \cdot \left\{ e_t + E_\xn(t+1)\right\}\\
-% \intertext{2. Person:}
-% E2_{\act[y]{n}}(t) &= \ddot{e}_{t} + v \cdot p_{y+t} \cdot \left\{ e_t + E2_{\act[y]{n}}(t+1)\right\}\\
-% \intertext{gemeinsam:}
-% E12_{\act[x,y]{n}}(t) &= \ddot{e}_{t} + v \cdot p_{x+t} \cdot p_{y+t} \cdot \left\{ e_t + E12_{\act[x,y]{n}}(n,t+1)\right\}\\
-\end{align*}
-
-% \intertext{Garantierte Erlebensleistungen (wenn Aufschubzeit überlebt wurde):}
-% % \begin{align*}
-%  E^{*}_\xn(t) &= \begin{cases}
-% 		    {}_{l-t}p_{x+t} \cdot v^{l-t} \cdot \sum_{j=l}^{n} \left\{\ddot{e}^{*}_{j-t}+ v\cdot e^*_{j-t}\right\} v^{j-t} & \text{für $t<l$ (Aufschubzeit)}\\
-% 		    \sum_{j=t}^{n} \left\{\ddot{e}^{*}_{j-t}+ v\cdot e^*_{j-t}\right\} v^{j-t} & \text{für $t\ge l$ (Liquiditätsphase)}
-%                  \end{cases}\\
-%    &= \ddot{e}_t^{*} + \left\{E^{*}_\xn(t+1) + e_t^*\right\}\cdot v \cdot \begin{cases}
-% 	    1 & \text{für $t<l$ (Aufschubzeit)}\\
-%             p_{x+t} & \text{für $t\ge l$ (Liquiditätsphase)}
-%        \end{cases}
-% \end{align*}
-\subsection{Unterjährige Auszahlung der Erlebenszahlungen}
-
-Analog zu (bei konstanter Rente)
-\begin{align*}
- \ddot{a}^{(m)}_\xn &= \ddot{a}_x^{(m)} - {}_np_x \cdot v^n \cdot \ddot{a}_{x+n}^{(m)}\\
- \ddot{a}_x^{(m)} &= \alpha(m) \ddot{a}_x - \beta(m)
-\end{align*}
-mit
-\begin{align*}
- \alpha(m)&= \frac{d \cdot i}{d^{(m)} \cdot i^{(m)}} & \beta(m) &= \frac{i-i^{(m)}}{d^{(m)} \cdot i^{(m)}}
-\end{align*}
-und $d = \frac{i}{1+i}$, $i^{(m)} = m \cdot \left((1+i)^{1/m} -1\right)$ und $d^{(m)} = i^{(m)} / \left(1+i^{(m)}/m\right)$ bzw. approximativ mit
-\begin{center}
-\begin{tabular}{rccccc}
-& 0.Ord. & 1.Ord. & 1,5-te Ord. & 2.Ord. & \\\hline
-$\alpha(m)$ = & 1 &  & & $+\frac{m^2-1}{12 m^2} i^2$ & ...\\
-$\beta(m)$ = & $\frac{m-1}{2m}$ & $+ \frac{m^2-1}{6 m^2}i$ & $\left[+ \frac{1-m^2}{12\cdot m^2}\cdot i^2\right]$ &$+ \frac{1-m^2}{24 m^2}i^2$ & ...\\[0.3em]\hline
-\end{tabular}
-\end{center}
-
-ergibt sich auch für allgemeine unterjährige Erlebenszahlungen $\ddot{e}_t$ eine Rekursionsgleichung.
-
-\subsubsection{Vorschüssige \textit{m}-tel jährliche Auszahlung der Erlebensleistungen}
-
-
-\begin{align*}
-E^{(m)}_\xn(t) &= \ddot{e}_t \cdot \ddot{a}_{\act[x+t]{1}}^{(m)} + v \cdot p_{x+1} \cdot E^{(m)}_\xn(t+1)\\
-  &= \ddot{e}_t \cdot \left\{\alpha(m)  - \beta(m) \cdot \left(1-p_{x+t} \cdot v\right)\right\} + v\cdot p_{x+t} \cdot E^{(m)}_\xn(t+1)
-\end{align*}
-
-
-\subsubsection{Nachschüssige \textit{m}-tel jährliche Auszahlung der Erlebensleistungen}
-
-\begin{align*}
-E^{(m)}_\xn(t) &= e_t \cdot a_{\act[x+t]{1}}^{(m)} + v \cdot p_{x+t} \cdot E^{(m)}_\xn(t+1)\\
-   &= e_t\cdot\left\{\alpha(m) - \left(\beta(m)+\frac1m\right)\cdot\left(1-p_{x+t} v\right)\right\} + v\cdot p_{x+t} \cdot E^{(m)}_\xn(t+1)
-\end{align*}
-
-\subsubsection{Allgemeine \textit{m}-tel jährliche Auszahlung der Erlebensleistungen}
-
-
-\begin{align*}
-E^{(m)}_\xn(t) = &\ddot{e}_t \cdot \left\{\alpha(m)  - \beta(m) \cdot \left(1-p_{x+t} \cdot v\right)\right\} +  \\
- &e_t\cdot\left\{\alpha(m) - \left(\beta(m)+\frac1m\right)\cdot\left(1-p_{x+t} v\right)\right\} + \\
- &v\cdot p_{x+t} \cdot E^{(m)}_\xn(t+1)
-\end{align*}
-
-
-
-
-\subsection{Ablebensbarwert}
-
-
-\begin{align*}
-\intertext{\subsubsection*{Prämienpflichtiger Ablebensbarwert}}
-A_\xn(t) &= \sum_{j=t}^n {}_{j-t}p_{x+t} \cdot q_{x+j} \cdot v^{j-t+1} \cdot a_{j} \\
-         &= q_{x+t} \cdot v \cdot a_t + p_{x+t} \cdot v \cdot A_\xn(t+1)\\
-%
-\intertext{\subsubsection*{Prämienfreier Ablebensbarwert}}
-A^{(prf)}_\xn(t) &= q_{x+t} \cdot v \cdot a^{(prf.)}_t + p_{x+t} \cdot v \cdot A^{(prf.)}_\xn(t+1)\\
-%
-\intertext{\subsubsection*{Barwert der gesamten Prämienrückgewähr (an BP)}}
-A^{(RG)}_\xn(t) &= q_{x+t} \cdot v \cdot a^{(RG)}_t + p_{x+t} \cdot v \cdot A^{(RG)}_\xn(t+1)\\
-%
-\intertext{\subsubsection*{Barwert der bisher bereits erworbenen Prämienrückgewähr (an BP)}}
-A^{(RG-)}_\xn(t) &= a^{(RG)}_{t-1} \cdot A^{(RG-,1)}_\xn(t)\\
-A^{(RG-,1)}_\xn(t) &= q_{x+t} \cdot v \cdot 1 + p_{x+t} \cdot v \cdot A^{(RG-,1)}_\xn(t+1)\\
-%
-\intertext{\subsubsection{Barwert der künftig noch zu erwerbenden Prämienrückgewähr (an BP)}}
-A^{(RG+)}_\xn(t) &= A^{(RG)}_\xn(t) - A^{(RG-)}_\xn(t)
-\intertext{Dieser Wert ist rekursiv nicht darstellbar.}
-\end{align*}
-
-\subsection{Disease-Barwert}
-\begin{align*}
-A^d_\xn(t) &= i_{x+t} \cdot v \cdot d_t + p_{x+t} \cdot v \cdot A^d_\xn(t+1)\\
-\end{align*}
-
-\subsection{Leistungsbarwert}
-
-\begin{align*}
-BW^L_\xn(t) &= E_\xn(t) + A_\xn(t) + A^d_\xn(t) &\text{ohne Prämienrückgewähr}\\
-BW^{L,RG}_\xn(t) &= BW^L_\xn(t) + (1+\rho^{RG}) \cdot A^{(RG)}_\xn(t)\cdot BP_\xn &\text{inkl. Prämienrückgewähr}
-\end{align*}
-
-
-
-\subsection{Kostenbarwerte}
-
-\begin{align*}
-\intertext{Abschlusskostenbarwerte:}
-AK^{(VS)}_\xn(t) &= \alpha^{VS}_{t} + v \cdot p_{x+t} \cdot AK^{(VS)}_\xn(t+1) \\
-AK^{(PS)}_\xn(t) &= \alpha^{PS}_{t} + v \cdot p_{x+t} \cdot AK^{(PS)}_\xn(t+1) \\
-AK^{(BP)}_\xn(t) &= \alpha^{BP}_{t} + v \cdot p_{x+t} \cdot AK^{(BP)}_\xn(t+1) \\
-AK^{(NP)}_\xn(t) &= \alpha^{NP}_{t} + v \cdot p_{x+t} \cdot AK^{(NP)}_\xn(t+1) \\
-AK^{(1)}_\xn(t)  &= \alpha^{1}_{t}  + v \cdot p_{x+t} \cdot AK^{(1)}_\xn(t+1) \\
-\intertext{Zillmerkostenbarwerte:}
-ZK^{(VS)}_\xn(t) &= z^{VS}_{t} + v \cdot p_{x+t} \cdot ZK^{(VS)}_\xn(t+1) \\
-ZK^{(PS)}_\xn(t) &= z^{PS}_{t} + v \cdot p_{x+t} \cdot ZK^{(PS)}_\xn(t+1) \\
-\intertext{Inkassokostenbarwerte:}
-IK^{(BP)}_\xn(t) &= \beta^{BP}_{t} + v \cdot p_{x+t} \cdot IK^{(BP)}_\xn(t+1) \\
-\intertext{Verwaltungskostenbarwerte:}
-VK^{(VS)}_\xn(t) &= \gamma^{VS}_{t} + v \cdot p_{x+t} \cdot VK^{(VS)}_\xn(t+1) \\
-VK^{(PS)}_\xn(t) &= \gamma^{PS}_{t} + v \cdot p_{x+t} \cdot VK^{(PS)}_\xn(t+1) \\
-VK^{(NP)}_\xn(t) &= \gamma^{NP}_{t} + v \cdot p_{x+t} \cdot VK^{(NP)}_\xn(t+1) \\
-VK^{(1)}_\xn(t)  &= \gamma^{1}_{t}  + v \cdot p_{x+t} \cdot VK^{(1)}_\xn(t+1) \\
-\widetilde{VK}^{(VS)}_\xn(t) &= \widetilde{\gamma}^{VS}_{t} + v \cdot p_{x+t} \cdot \widetilde{VK}^{(VS)}_\xn(t+1) \\
-\intertext{Gesamte Kostenbarwerte:}
-K^{(VS)}_\xn(t) &= AK^{(VS)}_\xn(t) + IK^{(VS)}_\xn(t) + VK^{(VS)}_\xn(t)\\
-K^{(PS)}_\xn(t) &= AK^{(PS)}_\xn(t) + IK^{(PS)}_\xn(t) + VK^{(PS)}_\xn(t)\\
-K^{(BP)}_\xn(t) &= AK^{(BP)}_\xn(t) + IK^{(BP)}_\xn(t) + VK^{(BP)}_\xn(t)\\
-K^{(NP)}_\xn(t) &= AK^{(NP)}_\xn(t) + IK^{(NP)}_\xn(t) + VK^{(NP)}_\xn(t)\\
-K^{(1)}_\xn(t) &= AK^{(1)}_\xn(t) + IK^{(1)}_\xn(t) + VK^{(1)}_\xn(t)\\
-\end{align*}
-
-
-\subsection{Darstellung der Barwerte in Vektor-/Matrixform}
-Die Leistungs- und Kostenbarwerte können (wie auch die Cashflows zu einem Zeitpunkt)
-in Matrixform dargestellt werden (aus Gründen der Übersichtlichkeit wird hier bei
-allen Termen der Subscript $\xn$ unterlassen):
-\begin{align*}
-  \overrightarrow{BW}^L(t) &= \left(
- \begin{matrix}
-    P(t), & %E^{Gar}(t), & E(t), & A(t),
-    BW^L(t), & A^{(RG)}(t)
- \end{matrix}
- \right)
-%
- &
-%
- \overrightarrow{BW}^K(t) &= \left(
- \begin{matrix}
-AK^{(VS)}(t) & AK^{(PS)}(t)  & AK^{(BP)}(t) & AK^{(NP)}(t) & AK^{(1)}(t)\\
-%
-ZK^{(VS)}(t) & ZK^{(PS)}(t)  & - & ZK^{(NP)}(t) & ZK^{(1)}(t)\\
-%
-- & - & IK^{(BP)}(t)  & IK^{(NP)}(t) & IK^{(1)}(t)\\
-%
-VK^{(VS)}(t) & VK^{(PS)}(t) & - & VK^{(NP)}(t) & VK^{(1)}(t)\\
-\widetilde{VK}^{(VS)}(t) & - & - & \widetilde{VK}^{(NP)}(t) & \widetilde{VK}^{(1)}(t)\\
- \end{matrix}
- \right)
-%
-\end{align*}
-
-
-
-\pagebreak
-
-\section{Prämien}
-
-Da die Prämienrückgewähr auf die Bruttoprämie gewährt wird, wird für die Bestimmung der Netto- und Zillmerprämie die Bruttoprämie benötigt. Es wird daher die Formel für unabhängige Bestimmung der Bruttoprämie hergeleitet, aus der dann die Netto- und Zillmerprämie berechnet werden können.
-
-\subsection{Nettoprämie:}
-\begin{align*}
-NP_\xn &= \frac{%E_\xn(0) + A_\xn(0) + \left(1+\rho^{RG}\right) \cdot A^{(RG)}_\xn(0) \cdot BP_\xn}
-BW^{L}_\xn(0) + \left(1+\rho^{RG}\right) \cdot A^{(RG)}_\xn(0) \cdot BP_\xn}
-{P_\xn(0)} \cdot \left(1+\rho\right)
-\end{align*}
-
-
-\subsection{Zillmerprämie (gezillmerte Nettoprämie):}
-% TODO: Sind die beta-Kosten proportional zu BP oder zur ZP??? I.e. ist \beta im Nenner mit BP oder im Zähler?
-\begin{align*}
-ZP_\xn &=
-\frac{%
-%   NP_\xn\cdot P_\xn(0) +
-  \overbrace{\left(BW^{L}_\xn(0) + \left(1+\rho^{RG}\right) \cdot A^{(RG)}_\xn(0) \cdot BP_\xn\right) \cdot (1+\rho)}^{=NP_\xn\cdot P_\xn(0)} +
-  ZK_\xn(0)
-%
-}{P_\xn(0)}\\
-&= NP_\xn + \frac{ZK_\xn(0)}{P_\xn(0)}
-\end{align*}
-mit dem gesamten Barwert der Zillmerkosten:
-\begin{align*}
- ZK_\xn(t) &=  ZK^{(VS)}_\xn(t) +
-  ZK^{(PS)}_\xn(t) \cdot BP_\xn \cdot PS +
-  ZK^{(BP)}_\xn(t) \cdot BP_\xn\,.
-\end{align*}
-
-
-Varianten:
-\begin{itemize}
- \item % REFERENCE: GE Tarife!
-     $\beta$- und $\gamma$-Kosten auch in die Zillmerprämie eingerechnet. Einziger Unterschied zur Bruttoprämie ist dann, dass nur die Zillmerkosten statt der $\alpha$-Kosten aufgeteilt werden.
-\begin{align*}
-ZP_\xn &=
-\left[%
-%   NP_\xn\cdot P_\xn(0) +
-  BW^{L,RG}_\xn(0) \cdot (1+\rho) +
-  \left(ZK^{(VS)}_\xn(0) + IK^{(VS)}_\xn(0) + VK^{(VS)}_\xn(0)\right) +  \right.\\
-  &\qquad\left.\left(ZK^{(PS)}_\xn(0) + IK^{(PS)}_\xn(0) + VK^{(PS)}_\xn(0)\right) \cdot BP_\xn \cdot PS + \right.\\
-  &\qquad\left.\left(ZK^{(BP)}_\xn(0) + IK^{(BP)}_\xn(0) + VK^{(BP)}_\xn(0)\right) \cdot BP_\xn
-%
-\right] / %
-\left(P_\xn(0)\right)
-\end{align*}
-
- \item % REFERENCE: ME
-    Prämienrückgewähr proportional zu Zillmerprämie (für Berechnung der Zillmerprämie):
-\begin{align*}
-ZP_\xn &= \frac{BW^L_\xn(0) + \left(1+\rho^{RG}\right) \cdot A^{(RG)}_\xn(0) \cdot ZP_\xn}{P_\xn(0)} \cdot \left(1+\rho\right)\\
-ZP_\xn &= \frac{BW^L_\xn(0)}{P_\xn(0) - \left(1+\rho^{RG}\right)\cdot A^{(RG)}_\xn(0)\cdot \left(1+\rho\right)} \cdot \left(1+\rho\right)
-\end{align*}
-
-\end{itemize}
-
-
-\subsection{Bruttoprämie:}
-\begin{align*}
-BP_\xn &= \frac%
-{
-   BW^L_\xn(0)\cdot\left(1+\rho\right)\cdot\left(1 + \frac{K^{(NP)}_\xn(0)}{P_\xn(0)}\right) +
-   \left( AK^{(VS)}_\xn(0) + IK^{(VS)}_\xn(0) + VK^{(VS)}_\xn(0) \right) + \frac{K_\xn^{(1)}}{VS}
-}%
-{
-   P_\xn(0) -
-   A^{(RG)}_\xn \left(1+\rho^{RG}\right) \left(1+\rho\right)\cdot\left(1 + \frac{K^{(NP)}_\xn(0)}{P_\xn(0)}\right) -
-         (AK^{(BP)}_\xn + IK^{(BP)}_\xn + VK^{(BP)}_\xn) -
-   \left(K^{(PS)}_\xn\right) PS
-}
-\end{align*}
-Wie man deutlich sehen kann, ist die Kostenursache ($\alpha$, $\beta$ oder $\gamma$) für die Prämienbestimmung irrelevant. Es werden die Barwerte aller drei Kostenarten jeweils bei der entsprechenden Bemessungsgrundlage aufaddiert ($K^{(PS)}_\xn = AK^{(PS)}_\xn + IK^{(PS)}_\xn + VK^{(PS)}_\xn)$).
-
-Die obige Formel ergibt sich direkt aus dem Äquivalenzprinzip durch Umformung. Die auf die Nettoprämie bezogenen Kostensätze erfordern dabei das Einsetzen der Formel für die Nettoprämie, da bei der Berechnung der BP die NP noch nicht bestimmt ist (da die Prämienrückgewähr in der NP auf dem Wert der BP basiert!).
-\begin{multline*}
-   BP_\xn \cdot P_\xn(0) = 
-   BW_\xn^{L}\cdot(1+\rho) + A_\xn^{(RG)} \left(1+\rho^{RG}\right)\left(1+\rho\right)\cdot BP_\xn + \\
-   K_\xn^{(BP)}\cdot BP_\xn + K_\xn^{(PS)} \cdot PS \cdot BP_\xn +
-   K_\xn^{(VS)} + K_\xn^{(NP)} \cdot NP + \frac{K_\xn^{(1)}}{VS}
-\end{multline*}
-
-
-%
-\subsection{Ablebensleistung im Jahr \textit{t}:}
-\begin{align*}
-Abl(t) &= \left\{a_t + a^{(RG)}_t \cdot BP_\xn\right\} \cdot VS
-\end{align*}
-
-\subsection{Koeffizienten in Vektorschreibweise}
-Für die Berechnung der Prämien können die Koeffizienten der jeweiligen Barwerte auch mittels der Vektor-/Ma\-trix\-schreib\-wei\-se dargestellt werden (siehe Tabelle \ref{PVCoeff}).
-\begin{sidewaystable}
-\centering
-
-% \newenvironment{benarray}{\big(\begin{array}{*4{C{3.4em}}C{12em}}}{\end{array}\big)}
-\newenvironment{benarray}{\big(\begin{array}{C{4em}C{8em}C{12em}}}{\end{array}\big)}
-\newenvironment{costarray}{\left(\begin{array}{*5{C{4.7em}}}}{\end{array}\right)}
-% TODO: laufende alpha-Kosten
-\begin{tabular}{||ll|c|c||}\hline\hline
- & & Leistungen & Kosten \\ \hline\hline
- Terme & &
-%   $\begin{benarray}P_\xn(t) & E^{Gar}_\xn(t) & E_\xn(t) & A_\xn(t)  & A_\xn^{(RG)}(t)\end{benarray}$
-  $\begin{benarray}P_\xn(t) & BW^L_\xn(t)  & A_\xn^{(RG)}(t)\end{benarray}$
- &
- $\begin{costarray}
-AK^{(VS)}_\xn(t) & AK^{(PS)}_\xn(t)  & AK^{(BP)}_\xn(t) & AK^{(NP)}_\xn(t) & AK^{(1)}_\xn(t)\\
-ZK^{(VS)}_\xn(t) & ZK^{(PS)}_\xn(t)  & -  & ZK^{(NP)}_\xn(t) & ZK^{(1)}_\xn(t)\\
-- & - & IK_\xn(t)  & IK^{(NP)}_\xn(t) & IK^{(1)}_\xn(t)\\
-VK^{(VS)}_\xn(t) & VK^{(PS)}_\xn(t) & - & VK^{(NP)}_\xn(t) & VK^{(1)}_\xn(t)\\
-VK^{frei}_\xn(t) & - & - & VK^{(fr,NP)}_\xn & VK^{fr,(1)}_\xn\\
- \end{costarray}$
-\\\hline\hline
-
-
-Nettoprämie & Zähler &
-  $\begin{benarray}0 & 1+\rho & \left(1+\rho^{RG}\right)\cdot BP_\xn \cdot \left(1+\rho\right)\end{benarray}$
- & -
-\\
-
- & Nenner &
-  $\begin{benarray} 1 & 0 & 0 \end{benarray}$
- & -
-\\\hline
-
-
-Zillmerprämie & Zähler &
-  $\begin{benarray}0 & 1+\rho & \left(1+\rho^{RG}\right)\cdot BP_\xn \cdot \left(1+\rho\right)\end{benarray}$
- &
- % TODO: Include costs depending on NetPremium and constant costs
- $\begin{costarray}
-0 & 0 & 0 \\
-1 & BP_\xn\cdot PS & BP_\xn & TODO & TODO\\
-\orZero{1} & \orZero{BP_\xn\cdot PS} & \orZero{BP_\xn} & TODO & TODO\\
-\orZero{1} & \orZero{BP_\xn\cdot PS} & \orZero{BP_\xn} & TODO & TODO\\
-0 & 0 & 0 & 0 & 0\\
- \end{costarray}$
-\\
-
- & Nenner &
-  $\begin{benarray} 1 & 0 & 0\end{benarray}$
- &
--
-\\\hline
-
-Bruttoprämie & Zähler &
-   $\begin{benarray}0 & \left(1+\rho\right)\cdot\left(1+\frac{K^{(NP)}_\xn(t)}{P_\xn(t)}\right) & 0\end{benarray}$
- &
- $\begin{costarray}
-1 & 0 & 0 & 0 & \frac{1}{VS} \\
-0 & 0 & 0 & 0 & 0 \\
-1 & 0 & 0 & 0 & \frac{1}{VS} \\
-1 & 0 & 0 & 0 & \frac{1}{VS} \\
-0 & 0 & 0 & 0 & 0 \\
- \end{costarray}$
-\\
-
- & Nenner &
-  $\begin{benarray}1 & 0 & -(1+\rho)\cdot(1+\rho^{RG})\cdot\left(1+\frac{K^{(NP)}_\xn(t)}{P_\xn(t)}\right) \end{benarray}$
- &
- $\begin{costarray}
-0 & -PS & -1 & 0 & 0 \\
-0 & 0   & 0 & 0 & 0\\
-0 & -PS & -1 & 0 & 0 \\
-0 & -PS & -1 & 0 & 0\\
-0 & 0   & 0 & 0 & 0\\
- \end{costarray}$
-\\
-
-\hline\hline
-
-\end{tabular}
-\label{PVCoeff}
-\caption{Koeffizienten der einzelnen Barwerte zur Berechnung der Prämien}
-\end{sidewaystable}
-
-
-
-\section{Zuschläge und Abschläge, Vorgeschriebene Prämie}
-
-\begin{longtable}{p{4cm}p{11cm}}
- $oUZu$ \dots & Zuschlag für Vertrag ohne ärztliche Untersuchung\\
- $SuRa=SuRa(VS)$ \dots & Summenrabatt (von Höhe der VS abhängig)\\
- $VwGew$ \dots & Vorweggewinnbeteiligung in Form eines \%-uellen Rabattes auf die Bruttoprämie\\
- $StkK$ \dots & Stückkosten pro Jahr (während Prämienzahlungsdauer, einmalig bei Einmalprämien)\\
- $PrRa=PrRa(BP)$ \dots & Prämienrabatt (von Höhe der Bruttoprämie abhängig)\\
- $VwGew_{StkK}$ \dots & Vorweggewinnbeteiligung in Form eines Rabattes auf die Prämie nach Zu-/Abschlägen (insbesondere nach Stückkosten)\\
- $PartnerRa$ \dots & Partnerrabatt auf Prämie nach Zu-/Abschlägen (z.B. bei Abschluss mehrerer Verträge), additiv zu $VwGew_{StkK}$\\
-
- $uz(k)$ \dots & Zuschlag für unterjährige Prämienzahlung ($k$ mal pro Jahr)
- \begin{equation*}
-  uz(k)=\left.\begin{cases}uk_1 & \text {für jährliche}\\uk_2 & \text {für halbjährliche} \\ uk_4 & \text{für quartalsweise}\\uk_{12} & \text{für monatliche}\end{cases}\right\} \text{Prämienzahlung}
- \end{equation*}\\
-
-
- $VSt$ \dots & Versicherungssteuer (in Österreich 4\% oder 11\%) \\
-
-\end{longtable}
-
-
-Vorgeschriebene Prämie (jährlich):
-\begin{multline*}
-PV_\xn = \left\{ (BP_\xn + oUZu - SuRa) \cdot VS \cdot (1-VwGew) + StkK\right\} \cdot \\ \left(1-PrRa-VwGew_{StkK}-PartnerRa\right)\cdot \left(1+uz(k)\right) \cdot (1+VSt)
-%
-\end{multline*}
-
-Vorgeschriebene Prämie (pro Zahlungsperiode):
-\begin{equation*}
- PV^{(k)}_\xn = \frac{PV_\xn}{k}
-\end{equation*}
-
-\section{Prämienzerlegung}
-Für die Prämienzerlegung (nach Bestimmung der Höhe der Bruttoprämie) kann man die Formel zur Bruttoprämie auch umformen zu
-\begin{align*}
- BP_\xn &= \frac{BW^L_\xn(0)\cdot\left(1+\rho\right) + BP_\xn \cdot A^{(RG)}_\xn \left(1+\rho^{RG}\right) \left(1+\rho\right)}{P_\xn(0)} \\
-  &\quad + \frac{AK^{(VS)}_\xn(0) + BP_\xn \cdot AK^{(BP)}_\xn + BP_\xn \cdot PS \cdot AK^{(PS)}_\xn + NP_\xn \cdot AK^{(NP)}_\xn + AK^{(1)}_\xn}{P_\xn(0)}\\
-  &\quad + \frac{IK^{(VS)}_\xn(0) + BP_\xn \cdot IK^{(BP)}_\xn + BP_\xn \cdot PS \cdot IK^{(PS)}_\xn + NP_\xn \cdot IK^{(NP)_\xn} + IK^{(1)}_\xn}{P_\xn(0)}\\
-  &\quad + \frac{VK^{(VS)}_\xn(0) + BP_\xn \cdot VK^{(BP)}_\xn + BP_\xn \cdot PS \cdot VK^{(PS)}_\xn + NP_\xn \cdot VK^{(NP)_\xn} + VK^{(1)}_\xn}{P_\xn(0)}\\
-  &= NP_\xn + \underbrace{\frac{AK_\xn(0)}{P_\xn(0)}}_{=\Pi_\xn^\alpha} + \underbrace{\frac{IK_\xn(0)}{P_\xn(0)}}_{=\Pi_\xn^\beta} + \underbrace{\frac{VK_\xn(0)}{P_\xn(0)}}_{=\Pi_\xn^\gamma} \\
-  &= \underbrace{NP_\xn + \underbrace{\frac{ZK_\xn(0)}{P_\xn(0)}}_{=\Pi_\xn^{\alpha,Z}}}_{=\Pi_\xn^Z} +  \underbrace{\frac{AK_\xn(0)-ZK_\xn(0)}{P_\xn(0)}}_{=\Pi_\xn^{\alpha,noZ}} + \Pi_\xn^\beta + \Pi_\xn^\gamma
-\end{align*}
-und damit die Bruttoprämie in die einzelnen Kostenprämien zerlegen.\vspace{1em}
-
-Es ergibt sich somit folgende Zerlegung der verrechneten Prämie:
-
-\renewlist{itemize}{itemize}{10}
-\setlist[itemize]{label=\textbullet}
-
-\setlistdepth{9}
-\begin{itemize}
-  \item verrechnete Prämie (jährlich) $\Pi_\xn^v$
-  \begin{itemize}
-    \item[+] Versicherungssteuer $\Pi_\xn^{tax}$
-    \item[+] Unterjährigkeitszuschlag
-    \item[$-$] Prämienrabatt
-    \item[$-$] Vorweggewinnbeteiligung (inkl. Stückkosten)
-    \item[$-$] Partnerrabatt
-    \item[+] Stückkosten
-    \item[$-$] Vorweggewinnbeteiligung (vor Stückkosten)
-    \item[$-$] Summenrabatt
-    \item[+] Zuschlag ohne ärztliche Untersuchung
-    \item[+] Bruttoprämie $\Pi_\xn^a$
-    \begin{itemize}
-      \item[+] Nettoprämie $\Pi_\xn$
-      \begin{itemize}
-        \item[+] Risikoprämie (netto) $\Pi_\xn^r$
-        \item[+] Sparprämie (netto) $\Pi_\xn^s$
-      \end{itemize}
-      \item[+] gezillmerter Teil der $\alpha$-Prämie $\Pi_\xn^{\alpha,Z}$
-      \item[+] ungezillmerter Teil der $\alpha$-Prämie $\Pi_\xn^{\alpha,noZ}$
-      \item[+] $\beta$-Prämie $\Pi_\xn^\beta$
-      \item[+] $\gamma$-Prämie $\Pi_\xn^\gamma$
-    \end{itemize}
-  \end{itemize}
-\end{itemize}
-\vspace{1em}
-
-Die Zillmerprämie (Nettoprämie $\Pi_\xn$ + gezillmerter Teil der $\alpha$-Prämie $\Pi_\xn^{\alpha,Z}$) kann wie die Nettoprämie in Spar- und Risikoprämie zerlegt werden:
-\begin{itemize}
-  \item Zillmerprämie $\Pi_\xn^Z$
-  \begin{itemize}
-    \item[+] gezillmerte Risikoprämie
-    \item[+] gezillmerte Sparprämie
-    \begin{itemize}
-      \item[+] $\alpha$-Tilgung (Tilgung der Zillmerkosten)
-      \item[+] echte Sparprämie (zum Aufbau des nicht-negativen Deckungskapitals)
-    \end{itemize}
-  \end{itemize}
-\end{itemize}
-
-
-
-
-\pagebreak
-\section{Absolute Cash-Flows und Barwerte}
-
-TODO
-
-
-\pagebreak
-
-\section{Rückstellungen und Reserven}
-
-\subsection{Deckungskapital / Reserve}
-
-\subsubsection{Nettodeckungskapital prämienpflichtig:}
-\begin{align*}
-V_\xn(t) &= \left\{BW^L_\xn(t)\cdot(1+\rho) - NP_\xn\cdot P_\xn(t)\right\} \cdot VS
-\end{align*}
-
-\subsubsection{Zillmerreserve prämienpflichtig:}
-TODO!
-\begin{align*}
-V_\xn(t) &= \left\{BW^L_\xn(t)\cdot(1+\rho) - ZP_\xn\cdot P_\xn(t)\right\} \cdot VS =\\
- &= \left\{BW^L_\xn(t)\cdot(1+\rho) - NP_\xn\cdot P_\xn(t) - ZK_\xn(0) \cdot BP_\xn(t) \cdot \frac{P_\xn(t)}{P_\xn(0)}\right\} \cdot VS \\
-\end{align*}
-
-\subsubsection{Reserve prämienpflichtig:}
-Entspricht bei Zillmerung der Zillmerreserve
-\begin{align*}
-V_\xn(t) &= \left\{BW^L_\xn(t)\cdot(1+\rho) - ZP_\xn\cdot P_\xn(t)\right\} \cdot VS \\
-\end{align*}
-
-\subsubsection{Bruttoreserve prämienpflichtig:}
-
-\begin{align*}
-V^{(b)}_\xn(t) &= \left\{BW^L_\xn(t)\cdot(1+\rho) +  - ZP_\xn\cdot P_\xn(t)\right\} \cdot VS \\
-\end{align*}
-
-\subsection{Verwaltungskostenreserve:}
-\begin{align*}
-V^{VwK}_\xn(t) &= \left\{ VK^{(VS)}_\xn(t) - \left(\frac{VK^{(VS)}_\xn(0)}{P_\xn(0)}\right) \cdot P_\xn(t)\right\} \cdot VS\\
-\end{align*}
-
-\subsection{Reserve prämienfrei:}
-\begin{align*}
-V^{frei}_\xn(t) &= \left\{(E_\xn(t) + A1_\xn(t))\cdot\widetilde{VW} + TODO \cdot \min(f,m) \cdot BP_\xn(x,n)\cdot VS\right\} \cdot (1+\rho) \\
-\end{align*}
-
-\subsection{Verwaltungskostenreserve prämienfrei:}
-\begin{align*}
-V^{WvK,frei}_\xn(t) &= VK4_\xn(t) \cdot \widetilde{VS}
-\end{align*}
-
-\section{Spar- und Risikoprämie}
-
-
-\begin{equation*}
- P_\xn(t) = SP_\xn(t) + RP_\xn(t)
-\end{equation*}
-
-
-\subsection{Sparprämie}
-
-\begin{align*}
-SP_\xn(t) &= V_\xn(t+1) \cdot v - V_\xn(t) + \left(\ddot{e}_t + v\cdot e_t\right)\cdot VS
-\end{align*}
-
-gezillmert:
-\begin{align*}
-SP^Z_\xn(t) &= V^Z_\xn(t+1) \cdot v - V^Z_\xn(t) + \left(\ddot{e}_t + v\cdot e_t\right)\cdot VS
-\end{align*}
-
-\subsection{Risikoprämie}
-\begin{align*}
-RP_\xn(t) &= v\cdot q_{x+t} \cdot \left\{Abl(t) - V_\xn(t+1)\right\}
-\end{align*}
-
-gezillmert:
-\begin{align*}
-RP^Z_\xn(t) &= v\cdot q_{x+t} \cdot \left\{Abl(t) - V^Z_\xn(t+1)\right\}
-\end{align*}
-
-
-
-\section{Bilanzreserve}
-
-\begin{tabular}{lp{14cm}}
-$BegDatum$ \dots & Beginndatum des Vertrags\\
-$BilDatum$ \dots & Bilanzstichtag  des Unternehmens\\
-$baf$ \dots & Bilanzabgrenzungsfaktor (Jahresanteil zwischen Abschlussdatum und Bilanzstichtag)
-\begin{itemize}
- \item 30/360: $baf=\frac{Monat(BilDatum+1)-Monat(BegDatum)+1}{12} \mod 1$
- \item Taggenau: $baf=\frac{BilDatum-BegDatum+1}{TageImJahr(BilDatum)} \mod 1$
- \item etc.
-\end{itemize}
-\\
-\end{tabular}
-
-
-\subsection{prämienpflichtig}
-% Bilanzabgrenzungsfaktor
-Bilanzreserve für Versicherungsleistungen:
-\begin{align*}
-BilRes^{(L)}_\xn(t) &= (1-baf)\cdot V_\xn(t) + baf \cdot V_\xn(t+1)\\
-\intertext{Verwaltungskosten-Bilanzreserve:}
-BilRes^{(VwK)}_\xn(t) &= (1-baf)\cdot V^{(VwK)}_\xn(t) + baf \cdot V^{(VwK)}_\xn(t+1)\\
-\intertext{Gesamte Bilanzreserve:}
-BilRes_\xn(t) &= BilRes^{(L)}_\xn(t) + BilRes^{(VwK)}_\xn(t)\\
-\intertext{\subsection{prämienfrei}
-Bilanzreserve für Versicherungsleistungen, prämienfrei:}
-BilRes^{(L),frei}_\xn(t) &= (1-baf)\cdot V^{frei}_\xn(t) + baf \cdot V^{frei}_\xn(t+1)\\
-\intertext{Verwaltungskosten-Bilanzreserve, prämienfrei:}
-BilRes^{(VwK),frei}_\xn(t) &= (1-baf)\cdot V^{VwK,frei}_\xn(t) + baf \cdot V^{VwK,frei}_\xn(t+1)\\
-\intertext{Gesamte Bilanzreserve, prämienfrei:}
-BilRes^{frei}_\xn(t) &= BilRes^{(L),frei}_\xn(t) + BilRes^{(VwK),frei}_\xn(t)\\\
-\end{align*}
-
-
-\pagebreak
-
-\section{Prämienfreistellung und Rückkauf}
-
-Verteilung der $\alpha$-Kosten auf $r$ Jahre für den Rückkauf bzw. die Vertragskonversion
-ist nicht bei allen Tarifen oder in allen Jurisdiktionen vorgesehen. => FLAG
-
-\subsection{Umrechnungsreserve}
-Sowohl Prämienfreistellung als auch Rückkauf starten von der Umrechnungsreserve, die sich aus der
-Zillmerreserve, den Kostenrückstellungen sowie der Verteilung der $\alpha$-Kosten auf 5 Jahre ergibt:
-\begin{align*}
- V_\xn^{Umr} &= \left(V_\xn(t) + V^{VwK}_\xn(t) + AbsKErh(t)\right)\cdot (1-VwGew(TODO))
-\end{align*}
-wobei $AbsKErh(t)$ die anteilsmäßige Rückzahlung der Abschlusskosten bei Rückkauf innerhalb der ersten
-$n(=5)$ Jahre gemäß \S 176 öVersVG bezeichnet:
-\begin{align*}
-AbskErh(t) &= \max\left(\sum_{j=0}^t Zillm(j) - \frac{t}{5} \sum_{j=0}^n Zillm(j), 0\right)&& \text{(Abschlusskostenerhöhungsbetrag)}\\
-Zillm(t) &= z^{(VS)}_t + z^{(BP)} \cdot BP_\xn + z^{(PS)}_t \cdot BP_\xn \cdot \sum_{j=0}^n pr_j &&\text{(Zillmerprämienanteil/-cashflow im Jahr $j$)}
-\end{align*}
-
-Varianten:
-\begin{itemize}
- \item Verteilung auf 5 Jahre nicht linear ($t/5$), sondern als 5-jährige Leibrente bewertet, deren Rest noch ausständig ist.
- \begin{align*}
-   AbskErh(t) &= \max\left(\sum_{j=0}^t Zillm(j) - \left(1-\frac{\ddot{a}_{\act[x+t]{r-t}}}{\ddot{a}_{\act[x]{r}}}\right) \frac{t}{5} \sum_{j=0}^n Zillm(j), 0\right)
- \end{align*}
- \item Bei zahlreichen Tarifen wird die Abschlusskostenerhöhung erst NACH dem Rückkaufsabschlag addidiert,
-    sodass diese Erhöhung nicht vom Abschlag betroffen ist => FLAG
-\end{itemize}
-
-\subsection{Rückkaufswert (prämienpflichtig)}
-
-Zahlreiche Tarife sind NICHT rückkaufsfähig => FLAG
-
-\begin{align*}
- Rkf(t) &= f(V_\xn^{Umr}, ...)
-\end{align*}
-
-Die Abschläge von der Umrechnungsreserve auf den Rückkaufswert sind im Allgemeinen nicht
-standardisiert, sondern variieren je nach Versicherungsunternehmen stark. Mögliche
-Abschläge sind:
-
-\subsubsection*{Prozentualer Rückkaufsabschlag}
-Prozentualer Abschlag auf die Umrechnungsreserve, z.B. $2\%$ oder $5\%$:
-$RkfFakt=0.95$
-\begin{align*}
-f(V_\xn^{Umr}, ...) = RkfFakt \cdot V_\xn^{Umr} \text{\quad mit $RkfFakt=0.98$ oder $0.95$}
-\end{align*}
-
-\subsubsection*{Lineare Erhöhung des prozentualen Rückkaufsabschlags}
-\begin{align*}
-f(V_\xn^{Umr}, ...) &= RkfFakt(t) \cdot V_\xn^{Umr} \\
-RkfFakt(t) &= min(k_1 + t \cdot \delta k; k_2) \text{\quad mit z.B. $k_1=0.9$, $\delta k = 0.005$ und $k_2=0.98$}
-\end{align*}
-Alternativ:
-\begin{equation*}% ME L12PLK3Z
- RkfFakt(t) = \begin{cases}
-0.95 & 1\leq t \leq 3\\
-0.95 + 0.003\cdot(t-3) & 3<t\leq 13\\
-0.98 & 13<t
-\end{cases}
-\end{equation*}
-
-
-\subsubsection*{Prozentualer Abschlag mit Mindestabschlag}
-% GW GDV1
-\begin{align*}
-f(V_\xn^{Umr}, ...) &= min\left(0.95 \cdot V_\xn^{Umr}, Abl(t), V_\xn^{Umr}-0.15 \cdot BP_\xn \cdot VS\cdot (1-VwGew)\right)
-\end{align*}
-
-% GW ER11
-\begin{align*}
-f(V_\xn^{Umr}, ...) &= min\left(0.95 \cdot V_\xn^{Umr}, Abl(t)\right)
-\end{align*}
-
-
-\subsubsection*{Prozentualer Abschlag mit Mindestabschlag (Mindesttodesfallsumme als Grenze)}
-% HP/GW:
-\begin{align*}
-f(V_\xn^{Umr}, ...) &= min(0.95 \cdot V_\xn^{Umr}, MTS(m,t)) \\
-MTS(m,t) &= ...
-\end{align*}
-
-
-\subsubsection*{Abschlag proportional zum Deckungskapital}
-% GE
-\begin{align*}
-f(V_\xn^{Umr}, ...) &= V_\xn^{Umr}\cdot \left(s_f + \max(0.97-s_f, 0) \cdot \frac{V_\xn^{Umr}}{VS}\right) \\
-s_f &=\begin{cases}0.92 & \text{ für $t<\max(10, n-5)$}\\ 1 & \text{sonst}\end{cases}
-\end{align*}
-
-
-TODO: Weitere mögliche Rückkaufsabschläge rausfinden
-
-\subsection{Stornogebühr bei Rückkauf}
-
-Manche Tarife sehen eine fixe Stornogebühr bei Rückkauf (z.B. nur in den ersten 24 Monaten) vor:
-% GW
-\begin{equation*}
- StoGeb = \min\left(\max\left(0.15 \cdot PV(x,n) \cdot\frac{pz}{1-uz(pz)} \cdot\frac1{1+VSt}, 30 \right), 300\right)
-\end{equation*}
-Ansonsten: $StoGeb=0$.
-
-
-
-\subsection{Prämienfreistellung}
-
-Der Vertrag wird zum Zeitpunkt $f$ prämienfrei gestellt, d.h. ab $f$ wird keine Prämie mehr bezahlt,
-die Höhe des Versicherungsschutzes bestimmt sich aus dem zu $f$ vorhandenen Deckungskapital und den
-Kostenreserven (Umrechnungsreserve). Bei Prämienrückgewähr wird nur die tatsächlich bezahlte Prämiensumme rückgewährt.
-
-Aus
-\begin{align*}
- V_\xn^{Umr}(f) - StoGeb %= \\
- = \underbrace{BW^L_\xn(f)\cdot\left(1+\rho\right)\cdot \widetilde{VS} + BW^{RG,frei}_\xn(f)\cdot \left(1+\rho\right) \cdot BP_\xn \cdot VS}_{=V^{frei}_\xn(f)} + \underbrace{VK^{frei}_\xn(f)}_{=V_\xn^{VwK,frei}(f)}
-%  =  V^{frei}_\xn(f) + V_\xn^{VwK,frei}(f)
-\end{align*}
-mit
-\begin{align*}
-BW^{RG,frei}_\xn(f) &= A^{(RG)}_\xn(t) \cdot \underbrace{\sum_{j=0}^{f-1} pr_j}_{\substack{=\min\left(f,m\right)\text{ bei }\\\text{lfd. konst. Prämie}}} && \text{(BW zukünftiger Prämienrückgewähr)}
-\end{align*}
-ergibt sich die neue Versicherungssumme $\widetilde{VS}(f)$ nach Prämienfreistellung zum Zeitpunkt $f$:
-\begin{equation*}
-\widetilde{VS}(f) = \frac
-  { V_\xn^{Umr}(f) - BW^{RG,frei}_\xn(f)\cdot (1+\rho)\cdot BP_\xn \cdot VS - StoGeb}
-  {BW^L_\xn(f)\cdot(1+\rho) + VK^{frei}_\xn(f)}
-\end{equation*}
-
-\subsection{Reserven nach außerplanmäßiger Prämienfreistellung}
-
-\subsubsection*{Nettodeckungskapital außerplanmäßig Prämienfrei zu $f$}
-
-\begin{align*}
-V^{(n),prf,f}_\xn(t) &= \left\{BW^{L,prf}_\xn(t)\cdot(1+\rho)\right\} \cdot \widetilde{VS(f)}
-\end{align*}
-
-\subsubsection{Reserve außerplanmäßig prämienfrei:}
-
-\begin{align*}
-V_\xn^{prf,f}(t) &= \left\{BW^{L,pr}_\xn(t)\cdot(1+\rho) + BW^{RG,frei,f}_{\act[x]{x}}(t)\right\} \cdot \widetilde{VS(f)} \\
-\end{align*}
-
-\subsection{Verwaltungskostenreserve außerplanmäßig prämienfrei:}
-\begin{align*}
-V^{VwK,prf,f}_\xn(t) &= \left\{ VK^{(VS), prf.}_\xn(t) + VK^{(PS),prf.}_\xn(t)\cdot PS(f)\right\} \cdot \widetilde{VS(f)}\\
-\end{align*}
-
-
-TOCHECK:
-\subsection{Reserve prämienfrei:}
-\begin{align*}
-V^{frei}_\xn(t) &= \left\{(E_\xn(t) + A1_\xn(t))\cdot\widetilde{VW} + TODO \cdot \min(f,m) \cdot BP_\xn(x,n)\cdot VS\right\} \cdot (1+\rho) \\
-\end{align*}
-
-\subsection{Verwaltungskostenreserve prämienfrei:}
-\begin{align*}
-V^{WvK,frei}_\xn(t) &= VK4_\xn(t) \cdot \widetilde{VS}
-\end{align*}
-
-\subsection{Umrechnungsreserve außerplanmäßig prämienfrei}
-\begin{align*}
- V_\xn^{Umr, prf, f}(t) &= \left(V^{prf,f}_\xn(t) + V^{VwK,prf,f}_\xn(t)\right)\cdot (1-VwGew(TODO))
-\end{align*}
-
-
-
-
-
-\end{document}
diff --git a/NAMESPACE b/NAMESPACE
index 1588dbffacfa04548e63b4c79bc6f6635d35b78c..982e4b7cd408bcfd2d932bda1411c3321263d255 100644
--- a/NAMESPACE
+++ b/NAMESPACE
@@ -1,122 +1,4 @@
 # Generated by roxygen2: do not edit by hand
 
-S3method(makeContractGridDimname,InsuranceTarif)
-S3method(makeContractGridDimname,R6)
-S3method(makeContractGridDimname,default)
-S3method(makeContractGridDimname,double)
-S3method(makeContractGridDimname,mortalityTable)
-S3method(makeContractGridDimname,numeric)
-export(CalculationEnum)
-export(InsuranceContract)
-export(InsuranceContract.ParameterDefaults)
-export(InsuranceContract.ParameterStructure)
-export(InsuranceContract.ParametersFallback)
-export(InsuranceContract.ParametersFill)
-export(InsuranceContract.Values)
-export(InsuranceTarif)
-export(PP.base.NULL)
-export(PP.base.PreviousZillmerReserve)
-export(PP.base.ZillmerReserveT2)
-export(PP.base.ZillmerRiskPremium)
-export(PP.base.contractualReserve)
-export(PP.base.meanContractualReserve)
-export(PP.base.previousContractualReserve)
-export(PP.base.sumInsured)
-export(PP.base.totalProfitAssignment)
-export(PP.benefit.None)
-export(PP.benefit.Profit)
-export(PP.benefit.ProfitGuaranteeSupporting)
-export(PP.benefit.ProfitPlusGuaranteedInterest)
-export(PP.benefit.ProfitPlusHalfGuaranteedInterest)
-export(PP.benefit.ProfitPlusHalfInterestMinGuaranteeTotal)
-export(PP.benefit.ProfitPlusHalfTotalInterest)
-export(PP.benefit.ProfitPlusInterestMinGuaranteeTotal)
-export(PP.benefit.ProfitPlusTerminalBonusReserve)
-export(PP.benefit.ProfitPlusTotalInterest)
-export(PP.benefit.TerminalBonus)
-export(PP.benefit.TerminalBonus5Years)
-export(PP.benefit.TerminalBonus5YearsProRata)
-export(PP.calculate.RateOnBase)
-export(PP.calculate.RateOnBaseMin0)
-export(PP.calculate.RateOnBaseSGFFactor)
-export(PP.calculate.RatePlusGuaranteeOnBase)
-export(PP.rate.expenseProfit)
-export(PP.rate.interestProfit)
-export(PP.rate.interestProfit2)
-export(PP.rate.interestProfit2PlusGuarantee)
-export(PP.rate.interestProfitPlusGuarantee)
-export(PP.rate.riskProfit)
-export(PP.rate.sumProfit)
-export(PP.rate.terminalBonus)
-export(PP.rate.terminalBonusFund)
-export(PP.rate.totalInterest)
-export(PP.rate.totalInterest2)
-export(PVfactory)
-export(PaymentTimeEnum)
-export(ProfitComponentsEnum)
-export(ProfitParticipation)
-export(SexEnum)
-export(TariffTypeEnum)
-export(age.exactRounded)
-export(age.yearDifference)
-export(applyHook)
-export(contractGrid)
-export(contractGridPremium)
-export(costs.baseAlpha)
-export(costs.scaleAlpha)
-export(costsDisplayTable)
-export(deathBenefit.annuityDecreasing)
-export(deathBenefit.linearDecreasing)
-export(exportInsuranceContract.xlsx)
-export(exportInsuranceContractExample)
-export(fallbackFields)
-export(fillFields)
-export(fillNAgaps)
-export(filterProfitRates)
-export(freqCharge)
-export(head0)
-export(initializeCosts)
-export(isRegularPremiumContract)
-export(isSinglePremiumContract)
-export(makeContractGridDimname)
-export(makeContractGridDimnames)
-export(pad0)
-export(padLast)
-export(premiumRefundPeriod.default)
-export(rollingmean)
-export(setCost)
-export(showVmGlgExamples)
-export(sumProfits)
-export(testVmGlgExample)
-export(valueOrFunction)
-export(vmGlgExample.generateTest)
-exportClasses(CalculationSingleEnum)
-exportClasses(PaymentTimeSingleEnum)
-exportClasses(ProfitComponentsMultipleEnum)
-exportClasses(SexSingleEnum)
-exportClasses(TariffTypeSingleEnum)
-import(MortalityTables)
-import(R6)
-import(dplyr)
-import(lubridate)
-import(openxlsx)
-import(scales)
-import(stringr)
-import(tidyr)
-importFrom(abind,abind)
-importFrom(kableExtra,kable)
-importFrom(lubridate,"year<-")
-importFrom(lubridate,days)
-importFrom(lubridate,interval)
-importFrom(lubridate,month)
-importFrom(lubridate,time_length)
-importFrom(lubridate,year)
-importFrom(lubridate,years)
-importFrom(methods,is)
-importFrom(methods,new)
-importFrom(objectProperties,setSingleEnum)
-importFrom(pander,pander)
-importFrom(rlang,.data)
+import(LifeInsureR)
 importFrom(rmarkdown,render)
-importFrom(utils,head)
-importFrom(utils,tail)
diff --git a/R/.gitignore b/R/.gitignore
deleted file mode 100644
index f90d1a18e6d64d251f905fc276e6a67c137c4aa0..0000000000000000000000000000000000000000
--- a/R/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-dummy.R
-*.R.bak
diff --git a/R/HelperFunctions.R b/R/HelperFunctions.R
index 9184fbaa187b13df519bebf371d47a3699ddc4f5..68bbc4e684bc7bdedf557f43662695e75b8d7084 100644
--- a/R/HelperFunctions.R
+++ b/R/HelperFunctions.R
@@ -1,956 +1,4 @@
-#' @importFrom abind abind
-#' @importFrom objectProperties setSingleEnum
-#' @importFrom utils head tail
-#' @importFrom methods new
-#' @importFrom lubridate time_length interval
+#' @import LifeInsureR
+#  Prevent spurious imports warnings in CRAN checks:
+#' @importFrom rmarkdown render
 NULL
-
-
-
-#' Enum to describe when a benefit or premium payment is due (in advance or in arrears)
-#'
-#' @details Currently, only two values are allowed;
-#' \itemize{
-#'     \item "in advance"
-#'     \item "in arrears"
-#' }
-#'
-#' @export
-PaymentTimeEnum = objectProperties::setSingleEnum("PaymentTime", levels = c("in advance", "in arrears"));
-
-#' Enum to describe possible sexes in an insurance contract or tariff.
-#'
-#' @details
-#' Currently, the only possible values are:
-#' * "unisex"
-#' * "male"
-#' * "female"
-#'
-#' @export
-SexEnum = objectProperties::setSingleEnum("Sex", levels = c("unisex", "male", "female"));
-
-#' Enum to define how much of a contract needs to be calculated automatically.
-#'
-#' @details
-#' When an [InsuranceContract] object is created, all time series are immediately
-#' calculated. However, sometimes, one only needs part of the values, so it
-#' would be a waste of resources to calculate e.g. all future reserves and
-#' profit participation, if only premiums are of interest.
-#'
-#' Possible values are:
-#' * "all"
-#' * "probabilities"
-#' * "cashflows"
-#' * "presentvalues"
-#' * "premiums"
-#' * "absvalues"
-#' * "reserves"
-#' * "premiumcomposition"
-#' * "profitparticipation"
-#' * "history"
-#'
-#' @export
-CalculationEnum = objectProperties::setSingleEnum("Calculation",
-    levels = c(
-      "all",
-      "probabilities",
-      "cashflows",
-      "presentvalues",
-      "premiums",
-      "absvalues",
-      "reserves",
-      "premiumcomposition",
-      "profitparticipation",
-      "history"
-    )
-)
-
-
-#' Enum to define the different components of profit participation.
-#'
-#' @details
-#' Profit participation schemes typically consist of different components,
-#' which are calculated independently. Typical components are interest profit
-#' to distribute investment gains to the customer, risk profit and expense profit
-#' to return security margins in the biometric risk and the expenses to the customer
-#' and sum profit, which aplies to contracts with higher sums insured, where
-#' charged expenses are calculated from the sum insured, while the actual
-#' expenses are more or less constant. Thus, high contracts are charged more,
-#' which causes profits that are returned as sum profit.
-#'
-#' As a special case, part of the profits can be stored in a terminal bonus
-#' reserve and only distributed on maturity (or potentially on death), but
-#' not on surrender. Some (older) profit participation schemes add an independently
-#' calculated bonus on maturity (e.g. twice the total profit assignment of the
-#' last year) at maturity to give customers an additional incentive not to
-#' surrender a contract.
-#'
-#' Possible values are (multiple can be given):
-#' * "interest"
-#' * "risk"
-#' * "expense"
-#' * "sum"
-#' * "terminal"
-#' * "TBF"
-#'
-#' @export
-ProfitComponentsEnum = objectProperties::setMultipleEnum("ProfitComponents",
-    levels = c(
-      "advance",
-      "interest",
-      "risk",
-      "expense",
-      "sum",
-      "terminal",
-      "TBF"
-    )
-)
-
-#' Determine whether a contract (given all parameters) is a single-premium contract or with regular premiums
-#'
-#' Single premium contracts are identified by the parameter \code{premiumPeriod = 1}.
-#'
-#' @param params The parameters of the contract.
-#' @param values Unused by default (already calculated values of the contract)
-#'
-#' @export
-isSinglePremiumContract = function(params, values) { params$ContractData$premiumPeriod <= 1 }
-
-
-#' Determine whether a contract (given all parameters) is a contract with regular premiums
-#'
-#' Regular premium contracts are identified by the parameter \code{premiumPeriod > 1}.
-#'
-#' @param params The parameters of the contract.
-#' @param values Unused by default (already calculated values of the contract)
-#'
-#' @export
-isRegularPremiumContract = function(params, values) { params$ContractData$premiumPeriod > 1 }
-
-
-#' Describes the death benefit of a linearly decreasing whole life insurance (after a possible deferall period)
-#'
-#' The death benefit will be the full sumInsured for the first year after the
-#' deferral period and then decrease linearly to 0 at the end of the policyPeriod.
-#' This can be used with the \code{deathBenefit} parameter for insurance
-#' contracts, but should not be called directly.
-#'
-#' @param len The desired length of the Cash flow vector (can be shorter than
-#'            the policyPeriod, if q_x=1 before the end of the contract, e.g.
-#'            for life-long insurances)
-#' @param params The full parameter set of the insurance contract (including
-#'               all inherited values from the tariff and the profit participation)
-#' @param values The values calculated from the insurance contract so far
-#'
-#' @export
-deathBenefit.linearDecreasing = function(len, params, values) {
-  protectionPeriod = params$ContractData$policyPeriod - params$ContractData$deferralPeriod;
-  pad0((protectionPeriod:0) / protectionPeriod, l = len)
-}
-
-
-#' Default premium refund period: for deferred contracts the deferral period, otherwise the whole contract
-#'
-#' If a premium refund is set for the tariff, the default is the full contract
-#' period, except for deferred contracts (typically deferred life annuities),
-#' for which the deferral period is the refund period.
-#'
-#' @param params The full parameter set of the insurance contract (including
-#'               all inherited values from the tariff and the profit participation)
-#' @param values The values calculated from the insurance contract so far
-#'
-#' @export
-premiumRefundPeriod.default = function(params, values) {
-  ifelse(params$ContractData$deferralPeriod > 0, params$ContractData$deferralPeriod, params$ContractData$policyPeriod)
-}
-
-
-#' Describes the death benefit of a decreasing whole life insurance (after a possible deferall period)
-#'
-#' The death benefit will be the full sumInsured for the first year after the
-#' deferral period and then decrease like an annuity to 0 at the end of the policyPeriod.
-#' This can be used with the \code{deathBenefit} parameter for insurance
-#' contracts, but should not be called directly.
-#'
-#' This function is a mere generator function, which takes the interest rate and
-#' generates a function that describes a decreasing annuity.
-#'
-#' The generated function has the following parameters:
-#' \describe{
-#'     \item{len}{The desired length of the Cash flow vector (can be shorter than
-#'            the policyPeriod, if q_x=1 before the end of the contract, e.g.
-#'            for life-long insurances)}
-#'     \item{params}{The full parameter set of the insurance contract (including
-#'               all inherited values from the tariff and the profit participation)}
-#'     \item{values}{The values calculated from the insurance contract so far}
-#' }
-#'
-#'
-#' @param interest The interest rate of the loan, which is underlying the insurance.
-#'
-#'
-#' @export
-deathBenefit.annuityDecreasing = function(interest) {
-  function(len, params, values) {
-    protectionPeriod = params$ContractData$policyPeriod - params$ContractData$deferralPeriod;
-    vk = 1/(1 + interest);
-    if (interest == 0) {
-      benefit = (protectionPeriod:0) / protectionPeriod
-    } else {
-      benefit = (vk ^ (protectionPeriod:0) - 1) / (vk ^ protectionPeriod - 1)
-    }
-    pad0(benefit, l = len)
-  }
-}
-
-
-#' Calculate the age of the insured based on exact age at contract closing, rounded
-#' to the nearest birthday.
-#'
-#' @param params The parameters of the contract.
-#' @param values Unused by default (already calculated values of the contract)
-#'
-#' @export
-age.exactRounded = function(params, values) {
-  round(time_length(
-    interval(params$ContractData$birthDate, params$ContractData$contractClosing),
-  "years"))
-}
-
-#' Calculate the age of the insured based on the difference of the bith year and
-#' contract closing year.
-#'
-#' @param params The parameters of the contract.
-#' @param values Unused by default (already calculated values of the contract)
-#'
-#' @export
-age.yearDifference = function(params, values) {
-  year(params$ContractData$contractClosing) - year(params$ContractData$birthDate)
-}
-
-
-#' Defines a frequency charge (surcharge for monthly/quarterly/semiannual) premium payments
-#'
-#' @description Tariffs are typically calculated with yearly premium installments. When
-#' premiums are paid more often then one a year (in advance), the insurance
-#' receives part of the premium later (or not at all in case of death), so a
-#' surcharge for premium payment frequencies higher than yearly is applied to
-#' the  premium, typically in the form of a percentage of the premium.
-#'
-#' This function generates the internal data structure to define surcharges for
-#' monthly, quarterly and semiannual premium payments. The given surcharges can
-#' be either given as percentage points (e.g. 1.5 means 1.5% = 0.015) or as
-#' fractions of 1 (i.e. 0.015 also means 1.5% surcharge). The heuristics applied
-#' to distinguish percentage points and fractions is that all values larger than 0.1
-#' are understood as percentage points and values 0.1 and lower are understood
-#' as fractions of 1.
-#' As a consequence, a frequency charge of 10% or more MUST be given as percentage points.
-#'
-#' Currently, the frequency charges are internally represented as a named list,
-#' \code{list("1" = 0, "2" = 0.01, "4" = 0.02, "12" = 0.03)}, but that might
-#' change in the future, so it is advised to use this function rather than
-#' explicitly using the named list in your code.
-#'
-#' @param monthly Surcharge for monthly premium payments
-#' @param quarterly Surcharge for quarterly premium payments
-#' @param semiannually Surcharge for semi-annual premium payments
-#' @param yearly Surcharge for yearly premium payments (optiona, default is no surcharge)
-#'
-#' @export
-freqCharge = function(monthly = 0, quarterly = 0, semiannually = 0, yearly = 0) {
-  # Apply the heuristics to allow percentage points given
-  if (monthly > 0.1) monthly = monthly / 100;
-  if (quarterly > 0.1) quarterly = quarterly / 100;
-  if (semiannually > 0.1) semiannually = semiannually / 100;
-  if (yearly > 0.1) yearly = yearly / 100;
-
-  # internal representation for now is a named list:
-  list("1" = yearly, "2" = semiannually, "4" = quarterly, "12" = monthly)
-}
-
-
-
-mergeValues = function(starting, ending, t) {
-  # if either starting or ending is missing, always use the other, irrespective of t:
-  if (missing(ending) || is.null(ending)) {
-    starting
-  } else if (missing(starting) || is.null(starting)) {
-    ending
-  } else if (t == 0) {
-    ending
-  } else {
-    rbind(starting[1:t,], ending[-1:-t,])
-  }
-}
-mergeValues3D = function(starting, ending, t) {
-  # if either starting or ending is missing, always use the other, irrespective of t:
-  if (missing(ending) || is.null(ending)) {
-    starting
-  } else if (missing(starting) || is.null(starting)) {
-    ending
-  } else if (t == 0) {
-    ending
-  } else {
-    abind::abind(starting[1:t,,,], ending[-1:-t,,,], along = 1)
-  }
-}
-
-#' PVfactory (R6Class for present values with arbitrary dimensions)
-#'
-#' provides functions to calculate present values for survival, death, dread
-#' disease, invalidity and guaranteed benefits in various dimensions
-#' @param qx the vector of mortality / death probabilities
-#' @param m the number of yearly payments
-#' @param mCorrection the list of alpha/beta to correct present values for multiple payments per year
-#' @param v the discount factor (1 / (1+i))
-#' @param advance the payment cashflows in advance
-#' @param arrears the payment cashflows in arrears
-#' @param start the time index, where the PV calculation should be based
-#' @param benefits the vector of death / invalidity / disease benefits
-#' @param ... other parameters (currently not used, for future use)
-#' @export
-#'
-PVfactory = R6Class(
-  "PVfactory",
-
-  ######################### PUBLIC METHODS ################################# #
-  public  = list(
-    #' @description Initialize the present value factory with defaults for qx, interest and multiple payments per year
-    initialize = function(qx, m = 1, mCorrection = list(alpha = 1, beta = 0), v = 1) {
-      private$qx = qx;
-      private$m = m;
-      private$mCorrection = mCorrection;
-      private$v = v;
-    },
-    #' @description Present values of guaranteed benefits (paid in advance or arrears, possible multiple times per year)
-    guaranteed = function(advance = NULL, arrears = NULL, start = 0, ..., m = private$m, mCorrection = private$mCorrection, v = private$v) {
-      # General Note: Since the CF vectors can have an arbitrary number of
-      # dimensions, we cannot directly access them via advance[1,..]. Rather,
-      # we have to construct the `[` function manually as a quoted expression,
-      # inserting the required number of dimensions and then evaluating that
-      # expression. This makes this function a little harder to read, but the
-      # performance should not take a hit and it is implemented in a very
-      # general way.
-
-      cfs = list(advance, arrears)
-      # https://stackoverflow.com/a/16896422/920231
-      deflt = cfs[!unlist(lapply(cfs, is.null))][[1]] * 0
-
-      if (missing(advance)     || is.null(advance))     advance = deflt
-      if (missing(arrears)     || is.null(arrears))     arrears = deflt
-
-      l = max(unlist(lapply(cfs, function(cf) if(!is.null(dim(cf))) dim(cf)[[1]] else length(cf))))
-
-      # TODO: Make sure all CF tensors have the same number of dimensions
-      dms = if (is.null(dim(advance))) length(advance + 1) else dim(advance);
-
-      # Resulting PV tensor has one timestep more than the CF tensors!
-      dms[1] = dms[1] + 1
-      dmNr = if (is.null(dim(advance))) 1 else length(dim(advance))
-
-      # To be able to access the CF tensors in arbitrary dimensions, we
-      # construct the [..] operator manually by quoting it and then inserting
-      # arguments matching the number of dimensions
-      Qadv     = Quote(advance[]    )[c(1,2,rep(3, dmNr))];
-      Qarr     = Quote(arrears[]    )[c(1,2,rep(3, dmNr))];
-      Qres     = Quote(res[])[c(1,2,rep(3, dmNr))]; # Access the correct number of dimensions
-      QresAss  = Quote(res <- tmp)
-
-      VL = function(quoted, time) {
-        eval(quoted %>% `[<-`(3, time))
-      }
-
-      init = VL(Qadv, 1) * 0;
-
-      # assuming advance and arrears have the same dimensions...
-      # TODO: Pad to length l
-      # advance = pad0(advance, l, value = init);
-      # arrears = pad0(arrears, l, value = init);
-
-      # TODO: Replace loop by better way (using Reduce?)
-      res = array(0, dim = dms)
-
-      # Starting value for the recursion:
-      tmp = init
-      QresAss[[2]] = Qres %>% `[<-`(3, dms[[1]])
-      eval(QresAss)
-
-      advcoeff = mCorrection$alpha - mCorrection$beta * (1 - v);
-      arrcoeff = mCorrection$alpha - (mCorrection$beta + 1/m) * ( 1 - v);
-      for (i in l:(start + 1)) {
-        # coefficients for the payments (including corrections for payments during the year (using the alpha(m) and beta(m)):
-        # The actual recursion:
-        tmp = VL(Qadv, i) * advcoeff + VL(Qarr, i) * arrcoeff + v * VL(Qres, i+1);
-        # Assign tmp to the slice res[i, ....]
-        QresAss[[2]] = Qres %>% `[<-`(3, i)
-        eval(QresAss)
-      }
-      VL(Qres, list(1:l))
-    },
-
-    #' @description Present values of survival benefits (paid in advance or arrears, possible multiple times per year)
-    survival = function(advance = NULL, arrears = NULL, start = 0, ..., m = private$m, mCorrection = private$mCorrection, v = private$v) {
-      # General Note: Since the CF vectors can have an arbitrary number of
-      # dimensions, we cannot directly access them via advance[1,..]. Rather,
-      # we have to construct the `[` function manually as a quoted expression,
-      # inserting the required number of dimensions and then evaluating that
-      # expression. This makes this function a little harder to read, but the
-      # performance should not take a hit and it is implemented in a very
-      # general way.
-
-      cfs = list(advance, arrears)
-      # https://stackoverflow.com/a/16896422/920231
-      deflt = cfs[!unlist(lapply(cfs, is.null))][[1]] * 0
-
-      if (missing(advance)     || is.null(advance))     advance = deflt
-      if (missing(arrears)     || is.null(arrears))     arrears = deflt
-
-      l = max(unlist(lapply(cfs, function(cf) if(!is.null(dim(cf))) dim(cf)[[1]] else length(cf))))
-
-      # TODO: Make sure all CF tensors have the same number of dimensions
-      dms = if (is.null(dim(advance))) length(advance) else dim(advance);
-
-      # Resulting PV tensor has one timestep more than the CF tensors!
-      dms[1] = dms[1] + 1
-      dmNr = if (is.null(dim(advance))) 1 else length(dim(advance))
-
-      # To be able to access the CF tensors in arbitrary dimensions, we
-      # construct the [..] operator manually by quoting it and then inserting
-      # arguments matching the number of dimensions
-      Qadv     = Quote(advance[]    )[c(1,2,rep(3, dmNr))];
-      Qarr     = Quote(arrears[]    )[c(1,2,rep(3, dmNr))];
-      Qres     = Quote(res[])[c(1,2,rep(3, dmNr))]; # Access the correct number of dimensions
-      QresAss  = Quote(res <- tmp)
-
-      VL = function(quoted, time) {
-        eval(quoted %>% `[<-`(3, time))
-      }
-
-      init = VL(Qadv, 1) * 0;
-
-      # assuming advance and arrears have the same dimensions...
-      p = pad0(private$qx$px, l, value=0);
-      # TODO: Pad to length l
-      # advance = pad0(advance, l, value = init);
-      # arrears = pad0(arrears, l, value = init);
-
-      # TODO: Replace loop by better way (using Reduce?)
-      res = array(0, dim = dms)
-
-      # Starting value for the recursion:
-      tmp = init
-      QresAss[[2]] = Qres %>% `[<-`(3, dms[[1]])
-      eval(QresAss)
-
-      advcoeff = mCorrection$alpha - mCorrection$beta * (1 - p * v);
-      arrcoeff = mCorrection$alpha - (mCorrection$beta + 1/m) * (1 - p * v);
-      for (i in l:(start + 1)) {
-        # coefficients for the payments (including corrections for payments during the year (using the alpha(m) and beta(m)):
-        # The actual recursion:
-        tmp = VL(Qadv, i) * advcoeff[i] + VL(Qarr, i) * arrcoeff[i] + v * p[i] * VL(Qres, i+1);
-        # Assign tmp to the slice res[i, ....]
-        QresAss[[2]] = Qres %>% `[<-`(3, i)
-        eval(QresAss)
-      }
-      VL(Qres, list(1:l))
-    },
-
-    #' @description Present values of death benefits
-    death = function(benefits, start = 0, ..., v = private$v) {
-      # General Note: Since the CF vectors can have an arbitrary number of
-      # dimensions, we cannot directly access them via advance[1,..]. Rather,
-      # we have to construct the `[` function manually as a quoted expression,
-      # inserting the required number of dimensions and then evaluating that
-      # expression. This makes this function a little harder to read, but the
-      # performance should not take a hit and it is implemented in a very
-      # general way.
-
-      cfs = list(benefits)
-      if (missing(benefits) || is.null(benefits)) return(0);
-
-      l = max(unlist(lapply(cfs, function(cf) if(!is.null(dim(cf))) dim(cf)[[1]] else length(cf))))
-
-      # TODO: Make sure all CF tensors have the same number of dimensions
-      dms = if (is.null(dim(benefits))) length(benefits) else dim(benefits);
-
-      # Resulting PV tensor has one timestep more than the CF tensors!
-      dms[1] = dms[1] + 1
-      dmNr = if (is.null(dim(benefits))) 1 else length(dim(benefits))
-
-      # To be able to access the CF tensors in arbitrary dimensions, we
-      # construct the [..] operator manually by quoting it and then inserting
-      # arguments matching the number of dimensions
-      Qben     = Quote(benefits[]    )[c(1,2,rep(3, dmNr))];
-      Qres     = Quote(res[])[c(1,2,rep(3, dmNr))]; # Access the correct number of dimensions
-      QresAss  = Quote(res <- tmp)
-
-      VL = function(quoted, time) {
-        eval(quoted %>% `[<-`(3, time))
-      }
-
-      init = VL(Qben, 1) * 0;
-
-      # assuming advance and arrears have the same dimensions...
-      p = pad0(private$qx$px, l, value = 0);
-      q = pad0(private$qx$qx, l, value = 1);
-      # TODO: Pad to length l
-      # benefits = pad0(benefits, l, value = init);
-
-      # TODO: Replace loop by better way (using Reduce?)
-      res = array(0, dim = dms)
-
-      # Starting value for the recursion:
-      tmp = init
-      QresAss[[2]] = Qres %>% `[<-`(3, dms[[1]])
-      eval(QresAss)
-
-      for (i in l:(start + 1)) {
-        # coefficients for the payments (including corrections for payments during the year (using the alpha(m) and beta(m)):
-        # The actual recursion:
-        tmp = v * q[i] * VL(Qben, i) + v * p[i] * VL(Qres, i+1);
-        # Assign tmp to the slice res[i, ....]
-        QresAss[[2]] = Qres %>% `[<-`(3, i)
-        eval(QresAss)
-      }
-      VL(Qres, list(1:l))
-    },
-    #' @description Present values of disease benefits
-    disease = function(benefits, start = 0, ..., v = private$v) {
-      # General Note: Since the CF vectors can have an arbitrary number of
-      # dimensions, we cannot directly access them via advance[1,..]. Rather,
-      # we have to construct the `[` function manually as a quoted expression,
-      # inserting the required number of dimensions and then evaluating that
-      # expression. This makes this function a little harder to read, but the
-      # performance should not take a hit and it is implemented in a very
-      # general way.
-
-      cfs = list(benefits)
-      if (missing(benefits) || is.null(benefits)) return(0);
-
-      l = max(unlist(lapply(cfs, function(cf) if(!is.null(dim(cf))) dim(cf)[[1]] else length(cf))))
-
-      # TODO: Make sure all CF tensors have the same number of dimensions
-      dms = if (is.null(dim(benefits))) length(benefits) else dim(benefits);
-
-      # Resulting PV tensor has one timestep more than the CF tensors!
-      dms[1] = dms[1] + 1
-      dmNr = if (is.null(dim(benefits))) 1 else length(dim(benefits))
-
-      # To be able to access the CF tensors in arbitrary dimensions, we
-      # construct the [..] operator manually by quoting it and then inserting
-      # arguments matching the number of dimensions
-      Qben     = Quote(benefits[]    )[c(1,2,rep(3, dmNr))];
-      Qres     = Quote(res[])[c(1,2,rep(3, dmNr))]; # Access the correct number of dimensions
-      QresAss  = Quote(res <- tmp)
-
-      VL = function(quoted, time) {
-        eval(quoted %>% `[<-`(3, time))
-      }
-
-      init = VL(Qben, 1) * 0;
-
-      # assuming advance and arrears have the same dimensions...
-      p = pad0(private$qx$px, l, value = 0);
-      ix = pad0(private$qx$ix, l, value = 0);
-      # TODO: Pad to length l
-      # benefits = pad0(benefits, l, value = init);
-
-      # TODO: Replace loop by better way (using Reduce?)
-      res = array(0, dim = dms)
-
-      # Starting value for the recursion:
-      tmp = init
-      QresAss[[2]] = Qres %>% `[<-`(3, dms[[1]])
-      eval(QresAss)
-
-      for (i in l:(start + 1)) {
-        # coefficients for the payments (including corrections for payments during the year (using the alpha(m) and beta(m)):
-        # The actual recursion:
-        tmp = v * ix[i] * VL(Qben, i) + v * p[i] * VL(Qres, i+1);
-        # Assign tmp to the slice res[i, ....]
-        QresAss[[2]] = Qres %>% `[<-`(3, i)
-        eval(QresAss)
-      }
-      VL(Qres, list(1:l))
-    },
-    # Cash flows only after death
-    # This case is more complicated, as we have two possible states of
-    # payments (present value conditional on active, but payments only when
-    # dead => need to write the Thiele difference equations as a pair of
-    # recursive equations rather than a single recursive formula...)
-    #' @description Present values of guaranteed benefits after death (paid in advance or arrears, possible multiple times per year)
-    afterDeath = function(advance = NULL, arrears = NULL, start = 0, ..., m = private$m, mCorrection = private$mCorrection, v = private$v) {
-      # General Note: Since the CF vectors can have an arbitrary number of
-      # dimensions, we cannot directly access them via advance[1,..]. Rather,
-      # we have to construct the `[` function manually as a quoted expression,
-      # inserting the required number of dimensions and then evaluating that
-      # expression. This makes this function a little harder to read, but the
-      # performance should not take a hit and it is implemented in a very
-      # general way.
-
-      cfs = list(advance, arrears)
-      # https://stackoverflow.com/a/16896422/920231
-      deflt = cfs[!unlist(lapply(cfs, is.null))][[1]] * 0
-
-      if (missing(advance)     || is.null(advance))     advance = deflt
-      if (missing(arrears)     || is.null(arrears))     arrears = deflt
-
-      l = max(unlist(lapply(cfs, function(cf) if(!is.null(dim(cf))) dim(cf)[[1]] else length(cf))))
-
-      # TODO: Make sure all CF tensors have the same number of dimensions
-      dms = if (is.null(dim(advance))) length(advance) else dim(advance);
-
-      # Resulting PV tensor has one timestep more than the CF tensors!
-      dms[1] = dms[1] + 1
-      dmNr = if (is.null(dim(advance))) 1 else length(dim(advance))
-
-      # To be able to access the CF tensors in arbitrary dimensions, we
-      # construct the [..] operator manually by quoting it and then inserting
-      # arguments matching the number of dimensions
-      Qadv     = Quote(advance[]    )[c(1,2,rep(3, dmNr))];
-      Qarr     = Quote(arrears[]    )[c(1,2,rep(3, dmNr))];
-      Qres     = Quote(res[])[c(1,2,rep(3, dmNr))]; # Access the correct number of dimensions
-      QresAss  = Quote(res <- tmp)
-
-      VL = function(quoted, time) {
-        eval(quoted %>% `[<-`(3, time))
-      }
-
-      init = VL(Qadv, 1) * 0;
-
-      # assuming advance and arrears have the same dimensions...
-      p = pad0(private$qx$px, l, value=0);
-      q = pad0(private$qx$qx, l, value=0);
-      # TODO: Pad to length l
-      # advance = pad0(advance, l, value = init);
-      # arrears = pad0(arrears, l, value = init);
-
-      # TODO: Replace loop by better way (using Reduce?)
-      res = array(0, dim = dms)
-
-      # Starting value for the recursion:
-      prev = init;
-      prev.dead = init;
-      QresAss[[2]] = Qres %>% `[<-`(3, dms[[1]])
-      eval(QresAss)
-
-      advcoeff = mCorrection$alpha - mCorrection$beta * (1 - v);
-      arrcoeff = mCorrection$alpha - (mCorrection$beta + 1/m) * (1 - v);
-      for (i in l:(start + 1)) {
-        # The actual recursion:
-        tmp = p[i] * v * prev + q[i] * v * prev.dead;
-        # Assign tmp to the slice res[i, ....]
-        QresAss[[2]] = Qres %>% `[<-`(3, i)
-        eval(QresAss)
-        prev = tmp
-        prev.dead = VL(Qadv, i) * advcoeff[i] + VL(Qarr, i) * arrcoeff[i] + v * prev.dead;
-      }
-      VL(Qres, list(1:l))
-    }
-  ),
-  private = list(
-    qx = data.frame(Alter = c(), qx = c(), ix = c(), px = c()),
-    m = 1,
-    mCorrection = list(alpha = 1, beta = 0),
-    v = 1
-  )
-);
-
-
-
-getSavingsPremium = function(reserves, v=1, survival_advance=c(0), survival_arrears=c(0)) {
-  pad0(reserves[-1], length(reserves))*v - reserves + survival_advance + survival_arrears*v
-}
-
-correctionPaymentFrequency = function(i, m = 1, order = 0) {
-  # 0th-order approximation
-  alpha = 1;
-  beta = 0;
-  # negative orders mean that NO correction is done, e.g. because other means of
-  # correction are used like an explicit premium frequency loading on the premium.
-  if (order >= 0 ) beta = beta + (m - 1) / (2 * m);
-  # For higher orders, simply add one term after the other!
-  if (order >= 1)     beta = beta + (m ^ 2 - 1) / (6 * m ^ 2) * i; # S-Versicherung: *(1-i/2)
-  # order 1.5 has a special term that should NOT be used for higher-order approximations!
-  if (order == 1.5)   beta = beta + (1 - m ^ 2) / (12 * m ^ 2) * i ^ 2;
-
-  if (order >= 2) {
-    beta = beta + (1 - m ^ 2) / (24 * m ^ 2) * i ^ 2;
-    alpha = alpha + (m ^ 2 - 1) / (12 * m ^ 2) * i ^ 2;
-  }
-  # Exact value
-  if (order == Inf) {
-    d = i / (1 + i);
-    im = m * ((1 + i) ^ (1/m) - 1);
-    dm = im / (1 + im/m);
-
-    alpha = d*i / (dm*im);
-    beta = (i - im) / (dm * im);
-  }
-  list(alpha = alpha, beta = beta);
-}
-
-#' Pad a vector with 0 to a desired length
-#'
-#' @param v the vector to pad with 0
-#' @param l the desired (resulting) length of the vector
-#' @param value the value to pad with (if padding is needed). Default to 0, but
-#'     can be overridden to pad with any other value.
-#' @param start the first \code{start} values are always set to 0 (default is 0,
-#'     can be changed using the \code{value.start} argument),
-#'     the vector \code{v} starts only after these leading zeroes. The number of
-#'     leading zeroes counts towards the desired length
-#' @param value.start the value to insert before the start index.
-#'
-#' @return returns the vector \code{v} padded to length \code{l} with value \code{value} (default 0).
-#'
-#' @examples
-#' pad0(1:5, 7)   # Pad to length 7 with zeroes
-#' pad0(1:5, 3)   # no padding, but cut at length 3
-#'
-#' # 3 leading zeroes, then the vector start (10 elements of vector, no additional padding needed):
-#' pad0(1:10, 13, start = 3)
-#'
-#' # padding with value other than zero:
-#' pad0(1:5, 7, value = "pad")
-#' @export
-pad0 = function(v, l, value = 0, start = 0, value.start = 0) {
-  # 3 cases: desired length<=start => only 0/value.start
-  #          desired length within start+v => cut v
-  #          desired length longer than start+v => pad with 0/value
-  if (l <= start) {
-    rep(value.start, l)
-  } else if (start <= l && l <= start + length(v)) {
-    c(rep(value.start, start), v[0:(l - start)])
-  } else {
-    # Need padding
-    c(rep(value.start, start), v, rep(value, l - length(v) - start))
-  }
-}
-
-
-
-#' Set all entries of the given vector to 0 up until index 'start'
-#'
-#' @param v the vector to modify
-#' @param start how many leading elements to zero out
-#' @param value.start the value to insert before the start index.
-#'
-#' @return the vector \code{v} with the first \code{start} elements replaced by 0.
-#'
-#' @examples
-#' head0(1:10, 3)
-#' @export
-head0 = function(v, start = 0, value.start = 0) {
-  if (start == 0) {
-    v
-  } else {
-    c(rep(value.start, start), tail(v, -start))
-  }
-}
-
-#' Pad the vector \code{v} to length \code{l} by repeating the last entry of the
-#' vector.
-#'
-#' This function is just a trivial wrapper around \code{pad0} and only calls [pad0()]
-#' with the last element of the vector as padding value instead of the default 0.
-#'
-#' @param v the vector to pad by repeating the last element
-#' @param ... arguments passed through to \code{pad0}
-#'
-#' @examples
-#' padLast(1:5, 7) # 5 is repeated twice
-#' padLast(1:5, 3) # no padding needed
-#'
-#' @export
-padLast = function(v, ...) {
-    pad0(v, value = tail(v, n = 1), ...)
-}
-
-#' Replace all \code{NA} entries of a vector with the previous non-NA value
-#'
-#' Sometimes one has a vector with some gaps (\code{NA}) values, which cause
-#' problems for several numeric functions. This function \code{fillNAgaps} fills
-#' these missing values by inserting the last preceeding non-NA-value. Leading
-#' NA values (at the start of the vector will not be modified). If the
-#' argument \code{firstBack = TRUE}, leading \code{NA}-values are replaced by
-#' the first non-NA value.
-#' Trailing NAs are always replaced by the last previous NA-value.
-#'
-#' This code was taken from the R Cookbook:
-#' http://www.cookbook-r.com/Manipulating_data/Filling_in_NAs_with_last_non-NA_value/
-#' LICENSE (from that page): The R code is freely available for use without any restrictions.
-#' In other words: you may reuse the R code for any purpose (and under any license).
-#'
-#' @param x The vector where NA-values should be filled by repeating the last preceeding non-NA value
-#' @param firstBack if \code{TRUE}, leading NAs are replaced by the first non-NA
-#'     value in the vector, otherwise leading NAs are left untouched.
-#'
-#' @export
-fillNAgaps <- function(x, firstBack=FALSE) {
-    ## NA's in a vector or factor are replaced with last non-NA values
-    ## If firstBack is TRUE, it will fill in leading NA's with the first
-    ## non-NA value. If FALSE, it will not change leading NA's.
-
-    # If it's a factor, store the level labels and convert to integer
-    lvls <- NULL
-    if (is.factor(x)) {
-        lvls <- levels(x)
-        x    <- as.integer(x)
-    }
-
-    goodIdx <- !is.na(x)
-
-    # These are the non-NA values from x only
-    # Add a leading NA or take the first good value, depending on firstBack
-    if (firstBack)   goodVals <- c(x[goodIdx][1], x[goodIdx])
-    else             goodVals <- c(NA,            x[goodIdx])
-
-    # Fill the indices of the output vector with the indices pulled from
-    # these offsets of goodVals. Add 1 to avoid indexing to zero.
-    fillIdx <- cumsum(goodIdx) + 1
-
-    x <- goodVals[fillIdx]
-
-    # If it was originally a factor, convert it back
-    if (!is.null(lvls)) {
-        x <- factor(x, levels = seq_along(lvls), labels = lvls)
-    }
-
-    x
-}
-
-
-#' If \code{val} is a function, evaluate it, otherwise return \code{val}
-#' @param val Function or value
-#' @param ... Argument passed to \code{val} if it is a function
-#' @examples
-#' valueOrFunction(3) # returns 3
-#' valueOrFunction(`+`, 1, 2) # also returns 3
-#' A = `+`
-#' valueOrFunction(A, 1, 2)
-#' @export
-valueOrFunction = function(val, ...) {
-  if (is.function(val)) {
-    val(...)
-  } else {
-    val
-  }
-}
-
-#' If \code{hook} is a function, apply it to \code{val}, otherwise return \code{val} unchanged
-#' @param hook (optional) function to apply to \code{val} and the other parameters
-#' @param val The value to which the hook is applied (ifgiven)
-#' @param ... optional parameters passed to the hook function (if it is a function)
-#' @examples
-#' applyHook(NULL, 3) # returns 3 unchanged
-#' applyHook(function(x) 2*x, 3) # applies the function, returns 6
-#' applyHook(`+`, 3, 1) # returns 4
-#' @export
-applyHook = function(hook, val, ...) {
-  if (is.function(hook)) {
-    hook(val, ...)
-  } else if (is.null(hook)) {
-    val
-  } else {
-    warning("Hook function", hook, "is neither a function nor NULL. Please provide a function or leave it empty!")
-  }
-}
-
-
-
-#' Overwrite all existing fields with default values given
-#'
-#' @description Overwrite all existing fields in the first argument with
-#' values given in valuelist. Members of valuelist that are not yet in
-#' fields are ignored. This allows a huge valuelist to be used to fill
-#' fields in multiple lists with given structure.
-#'
-#' @param fields existing list
-#' @param valuelist list of fields to replace in \code{fields}. Only keys that exist in \code{fields} are overwritten, no new fields are added to \code{fields}
-#'
-#' @export
-fillFields = function(fields, valuelist) {
-  fieldsToInsert = intersect(names(fields), names(valuelist));
-  fields[fieldsToInsert] = valuelist[fieldsToInsert]
-  fields
-}
-
-
-#' Replace missing values in ields by default fallback values
-#'
-#' @description Replace all missing values in fields (either missing or NA) with
-#' their corresponding values from fallback. Members in fallback that are missing
-#' in fields are inserted
-#' @param fields existing list
-#' @param valuelist list of fields to replace in \code{fields}. Only keys that are missing in \code{fields} are added, no existing fields in \code{fields} are overwritten
-#' @export
-fallbackFields = function(fields, valuelist) {
-  keepFields = !sapply(fields, is.null);
-  # We need to set all fields of valuelist, except those that are NOT NA in fields:
-  useFields = setdiff(names(valuelist), names(fields[keepFields]))
-  fields[useFields] = valuelist[useFields]
-  fields
-}
-
-#' Calculate the rolling mean of length 2
-#' @param x vector of values, for which the rolling mean is calculated
-#' @examples
-#' rollingmean(1:10)
-#' @export
-rollingmean = function(x) (tail(x, -1) + head(x, -1))/2
-
-
-# Sum two or more vectors and correctly handle (i.e. ignore) NULL values given
-plusNULL = function(v1, v2, ...) {
-  if (missing(v2) && length(list(...)) == 0) {
-    if (missing(v1) || is.null(v1)) {
-      return(0)
-    } else {
-      return(v1)
-    }
-  }
-  if (missing(v1) || is.null(v1)) {
-    return(plusNULL(v2, ...));
-  }
-  if (missing(v2) || is.null(v2)) {
-    return(plusNULL(v1, ...));
-  } else {
-    return(plusNULL(v1 + v2, ...))
-  }
-}
-
-
-######################################################################=#
-# Functions for handling sub-contract blocks                        ####
-
-# Helper functions to prepend/append rows to the arrays and sum them up
-padArray = function(arr = NULL, pad = 0, len = 0, value = 0) {
-  padEnd = max(0, len - pad - NROW(arr)) # if len is too short, return an array containing at least the arr
-  nrcols = ifelse(is.null(arr), 0, NCOL(arr))
-  rbind(
-    array(value, dim = c(pad, nrcols)) %>% `colnames<-`(colnames(arr)),
-    arr,
-    array(value, dim = c(padEnd, nrcols)) %>% `colnames<-`(colnames(arr))
-  ) %>% `colnames<-`(colnames(arr))
-}
-
-sumPaddedArrays = function(arr1 = NULL, arr2 = NULL, pad1 = 0, pad2 = 0) {
-  newlen = max(pad1 + NROW(arr1), pad2 + NROW(arr2))
-  if (is.null(arr2)) {
-    padArray(arr1, pad = pad1, len = newlen)
-  } else if (is.null(arr1)) {
-    padArray(arr2, pad = pad2, len = newlen)
-  } else {
-    # First prepend trailing zero rows according to pad1/pad2:
-    arr1 = padArray(arr1, pad = pad1, len = newlen)
-    arr2 = padArray(arr2, pad = pad2, len = newlen)
-
-    # arr1 and arr2 now should have the same dimensions => sum them up
-    arr1 + arr2
-  }
-}
-
-
-
-
diff --git a/R/InsuranceContract.R b/R/InsuranceContract.R
deleted file mode 100644
index 65680abc9b86bb45c821a72d9c7cd58372c0b3c8..0000000000000000000000000000000000000000
--- a/R/InsuranceContract.R
+++ /dev/null
@@ -1,1276 +0,0 @@
-#' @include HelperFunctions.R InsuranceParameters.R InsuranceTarif.R ProfitParticipation.R
-#'
-#' @import MortalityTables
-#' @import R6
-#' @import lubridate
-#  Prevent spurious imports warnings in CRAN checks:
-#' @importFrom kableExtra kable
-#' @importFrom pander pander
-#' @importFrom rmarkdown render
-NULL
-
-
-
-############ Class InsuranceContract ###########################################
-#' Base Class for Insurance Contracts
-#'
-#' R6 class that models a complete, general insurance contract.
-#' The corresponding tariff and the profit participation scheme, as well as
-#' all other relevant contract parameters (if not defined by the tariff or
-#' explicitly overridden by the contract) can be given in the constructor.
-#'
-#' # Usage
-#'
-#' The typical usage of this class is to simply call
-#' \ifelse{html}{\href{#method-new}{\code{InsuranceContract$new()}}}{\code{InsuranceContract$new()()}}.
-#'
-#' All parameters from the [InsuranceContract.ParameterDefaults] can be passed
-#' to the constructor of the class (i.e. the \ifelse{html}{\href{#method-new}{\code{InsuranceContract$new()}}}{\code{InsuranceContract$new()()}}-call).
-#' Parameters not explicitly given, will be taken from the tariff or as a fall-back
-#' mechanism from the [InsuranceContract.ParameterDefaults] defaults.
-#'
-#' Immediately upon construction, all premiums, reserves and cash flows for the
-#' whole contract period are calculated and can be accessed via the \code{Values}
-#' field of the object.
-#'
-#'
-#' # Calculation approach: Valuation
-#'
-#' The calculation of all contract values is controlled by the function
-#' \ifelse{html}{\href{#method-calculateContract}{\code{InsuranceContract$calculateContract()}}}{\code{InsuranceContract$calculateContract()()}} (using methods of the [InsuranceTarif]
-#' object) and follows the following logic:
-#'
-#' 1. First the **contingent (unit) cash flows** and the **transition probbilities**
-#' are determined.
-#' 2. The **actuarial equivalence principle** states that at time of inception, the
-#' (net and gross) premium must be determined in a way that the present value
-#' of the future benefits and costs minus the present value of the future premiums
-#' must be equal, i.e. in expectation the future premiums ove the whole lifetime
-#' of the contract will exactly cover the benefits and costs. Similarly, at all
-#' later time steps, the difference between these two present values needs to be
-#' reserved (i.e. has already been paid by the customer by previous premiums).
-#' 2. This allows the premiums to be calculated by first calculating the **present
-#' values** for all of the **benefit and costs cash flow** vectors.
-#' 3. The formulas
-#' to calculate the gross, Zillmer and net **premiums** involve simple linear
-#' combinations of these present values, so the **coefficients of these formulas**
-#' are determined next.
-#' 4. With the coefficients of the premium formulas calculated, all **premiums
-#' can be calculated** (first the gross premium, because due to potential gross
-#' premium refunds in case of death, the formula for the net premium requires
-#' the gross premium, which the formula for the gross premium involves no other
-#' type of premuim).
-#' 5. With premiums determined, all unit cash flows and unit present values can
-#' now be expressed in monetary terms / as **absolute cash flows** (i.e. the actual Euro-amount that flows
-#' rather than a percentage).
-#' 6. As described above, the difference between the present values of premiums
-#' and present values of benefits and costs is defined as the required amount
-#' of reserves, so the **reserves (net, gross, administration cost, balance sheet)**
-#' and all values derived from them (i.e. surrender value, sum insured in case of
-#' premium waiver, etc.) are calculated.
-#' 7. The **decomposition of the premium** into parts dedicated to specific purposes
-#' (tax, rebates, net premium, gross premium, Zillmer premium, cost components,
-#' risk premium, savings premium, etc.) can be done once the reserves are
-#' ready (since e.g. the savings premium is defined as the difference of
-#' discounted reserves at times $t$ and $t+1$).
-#' 8. If the contract has **(discretionary or obligatory) profit sharing**B mechanisms
-#' included, the corresponding [ProfitParticipation] object can calculate that
-#' profit sharing amounts, once all guaranteed values are calculated. This can
-#' also be triggered manually (with custom profit sharing rates) by calling
-#' the methods \ifelse{html}{\href{#method-profitScenario}{\code{InsuranceContract$profitScenario()}}}{\code{InsuranceContract$profitScenario()()}}]
-#' or \ifelse{html}{\href{#method-addProfitScenario}{\code{InsuranceContract$addProfitScenario()}}}{\code{InsuranceContract$addProfitScenario()()}}.
-#'
-#'
-#'
-#'
-#' # Calculation approach: Cash Flows
-#'
-#' An insurance contract is basically defined by the (unit) cash flows it produces:
-#' \itemize{
-#'   \item **Premium payments** (in advance or in arrears) at each timestep
-#'   \item **Survival payments** at each timestep
-#'   \item **Guaranteed payments** at each timestep
-#'   \item **Death benefits** at each timestep
-#'   \item **Disease benefits** at each timestep
-#' }
-#' Together with the transition probabilities (mortalityTable parameter)
-#' the present values can be calculated, from which the premiums follow and
-#' finally the reserves and a potential profit sharing.
-#'
-#' For example, a _**term life insurance with regular premiums**_ would have the following
-#' cash flows:
-#'
-#' * premium cash flows: 1, 1, 1, 1, 1, ...
-#' * survival cash flows: 0, 0, 0, 0, 0, ...
-#' * guaranteed cash flows: 0, 0, 0, 0, 0, ...
-#' * death benefit cash flows: 1, 1, 1, 1, 1, ...
-#'
-#' A _**single-premium term life insurance**_ would look similar, except for the premiums:
-#'
-#' * premium cash flows: 1, 0, 0, 0, 0, ...
-#'
-#' A _**pure endowment**_ has no death benefits, but a survival benefit of 1 at the
-#' maturity of the contract:
-#'
-#' * premium cash flows: 1, 1, 1, 1, 1, ...
-#' * survival cash flows: 0, 0, ..., 0, 1
-#' * guaranteed cash flows: 0, 0, 0, 0, 0, ...
-#' * death benefit cash flows: 0, 0, 0, 0, 0, ...
-#'
-#' An _**endowment**_ has also death benefits during the contract duration:
-#'
-#' * premium cash flows: 1, 1, 1, 1, 1, ...
-#' * survival cash flows: 0, 0, ..., 0, 1
-#' * guaranteed cash flows: 0, 0, 0, 0, 0, ...
-#' * death benefit cash flows: 1, 1, 1, 1, 1, ...
-#'
-#' A _**(deferred) annuity**B_ has premium cash flows only during the deferral peroid
-#' and only survival cash flows during the annuity payment phase. Often, in case
-#' of death during the deferral period, all premiums paid are refunded as a death
-#' benefit.:
-#'
-#' * premium cash flows: 1, 1, ...,  1, 0, 0, 0, ...
-#' * survival cash flows: 0, 0, ..., 0, 1, 1, 1,...
-#' * guaranteed cash flows: 0, 0, 0, 0, 0, ...
-#' * death benefit cash flows: 1, 2, 3, 4, 5, ..., 0, 0, ...
-#'
-#' A _**terme-fix insurance**_ has a guaranteed payment at maturity, even if the insured
-#' has already died. The premiums, however, are only paid until death (which is
-#' not reflected in the contingent cash flows, but rather in the transition
-#' probabilities):
-#'
-#' * premium cash flows: 1, 1, 1, 1, ...,  1
-#' * survival cash flows: 0, 0, 0, 0, ..., 0
-#' * guaranteed cash flows: 0, 0, 0, ..., 0, 1
-#' * death benefit cash flows: 0, 0, 0, 0, ..., 0
-#'
-
-#'
-#' @examples
-#' # TODO
-#'
-#' @export
-InsuranceContract = R6Class(
-    "InsuranceContract",
-
-    ######################### PUBLIC METHODS ##################################
-    public = list(
-        #' @field tarif
-        #' The [InsuranceTarif] underlying this contract. The tarif is the abstract
-        #' product description (i.e. defining the type of insurance, fixing tpyes
-        #' of benefits, specifying costs, guaranteed interest rate, mortality tables,
-        #' potential profit sharing mechanisms, etc.), while the contract holds
-        #' the individual parts like age, sum insured, contract duration, premium
-        #' payment frequency, etc.
-        tarif = NULL,
-        #' @field parent
-        #' A pointer to the parent contract. Some contracts consist of multiple
-        #' parts (e.g. a main savings contract with a dread-disease rider, or
-        #' a contract with multiple dynamic increases). These are internally
-        #' represented by one [InsuranceContract] object per contract part, plus
-        #' one contract object combining them and deriving combined premiums,
-        #' reserves and profit participation. The child contracts (i.e. the
-        #' objects representing the individual parts) have a pointer to their
-        #' parent, while the overall contract holds a list of all its child contract parts.
-        parent = NULL,
-
-        #' @field ContractParameters
-        #' Insurance contract parameters explicitly specified in the contract
-        #' (i.e. parameters that are NOT taken from the tariff of the defaults).
-        ContractParameters = InsuranceContract.ParameterStructure, # Only values explicitly given for this contract, not including fallback values from the tariff
-        #' @field Parameters
-        #' Full set of insurance contract parameters applying to this contract.
-        #' The set of parameters is a combination of explicitly given (contract-specific)
-        #' values, parameters determined by the tariff and default values.
-        Parameters = InsuranceContract.ParameterStructure,         # The whole parameter set, including values given by the tariff
-
-        #' @field Values
-        #' List of all contract values (cash flows, present values, premiums,
-        #' reserves, premium decomposition, profit participation, etc.). These
-        #' values will be calculated and filled when the contract is created
-        #' and updated whenever the contract is changed.
-        Values = InsuranceContract.Values,
-
-        #' @field blocks
-        #' For contracts with multiple contract parts: List of all tariff blocks
-        #' (independently calculated [InsuranceContract] objects, that are combined
-        #' to one contract, e.g. dynamic/sum increases). If this field is empty,
-        #' this object describes a contract block (calculated as a stand-alone
-        #' tariff), otherwise it will simply be the sum of its blocks (adjusted
-        #' to span the same time periods)
-        blocks = list(),
-
-        #' @field history
-        #' A list keeping track of all contract changes (including the whole
-        #' contract state and its values before the change).
-        history = list(),
-
-
-        #### The code:
-
-        #' @description  Create a new insurance contract (for the given tariff/product) and calculate all time series
-        #'
-        #' @details The \code{InsuranceContract$new()} function creates a new
-        #' insurance contract for the given tariff, using the parameters passed
-        #' to the function (and the defaults specified in the tariff).
-        #'
-        #' As soon as this function is called, the contract object calculates
-        #' all time series (cash flows, premiums, reserves, profit participation)
-        #' for the whole contract duration.
-        #'
-        #' The most important parameters that are typically passed to the
-        #' constructor are:
-        #' * \code{age} ... Age of the insured person (used to derive mortalities / transition probabilities)
-        #' * \code{policyPeriod} ... Maturity of the policy (in years)
-        #' * \code{premiumPeriod} ... How long premiums are paid (\code{premiumPeriod = 1}
-        #'        for single-premium contracts, \code{premiumPeriod} equals
-        #'        \code{policyPeriod} for regular premium payments for the whole
-        #'        contract period, while other premium payment durations indicate
-        #'        premium payments only for shorter periods than the whole contract
-        #'        duration. Contract extensions without any premium payments are
-        #'        indicated by \code{premiumPeriod}=0). Default is equal to
-        #'        \code{policyPeriod}
-        #' * \code{sumInsured} ... The sum insured (i.e. survival benefit for
-        #'         endowments, death benefit for whole/term life insurances,
-        #'         annuity payments for annuities)
-        #' * \code{contractClosing} ... Date of the contract beginning (typically
-        #'        created using something like \code{as.Date("2020-08-01")})
-        #' * \code{YOB} ... Year of birth of the insured (for cohort mortality
-        #'        tables). If not given, YOB is derived from \code{age} and
-        #'        \code{contractClosing}.
-        #' * \code{deferralPeriod} ... Deferral period for deferred annuities
-        #'        (i.e. when annuity payments start at a future point in time).
-        #'        Default is 0.
-        #' * \code{premiumFrequency} ... How many premium payments per year are
-        #'        made (e.g. 1 for yearly premiums, 4 for quarterly premiumd,
-        #'        12 for monthly premium payments). Default is 1 (yearly premiums).
-        #'
-        #' While these are the most common and most important parameters, all
-        #' parameters can be overwritten on a per-contract basis, even those
-        #' that are defined by the tariff. For a full list and explanation of all
-        #' parameters, see [InsuranceContract.ParameterDefaults].
-        #'
-        #' @param tarif The [InsuranceTarif] object describing the Tariff/Product
-        #'        and providing defaults for the parameters.
-        #' @param parent For contracts with multiple contract blocks (dynamic
-        #'        increases, sum increases, riders), each child is created with
-        #'        a pointer to its parent. NULL for single-block contracts or
-        #'        for the overall-contract of a multi-block contract. This
-        #'        parameter is used internally, but should not be used in
-        #'        user-written code.
-        #' @param calculate how much of the contract's time series need to be
-        #'        calculated. See [CalculationEnum] for all possible values. This
-        #'        is usefull to prevent calculation of e.g. reserves and profit
-        #'        participation, when one only wants to create a grid of premiums.
-        #' @param profitid The ID of the default profit participation scenario.
-        #'        The default profit participation scenario uses the default
-        #'        values passed, while further scenarios can be added by
-        #'        \ifelse{html}{\href{#method-addProfitScenario}{\code{InsuranceContract$addProfitScenario()}}}{\code{InsuranceContract$addProfitScenario()()}}.
-        #' @param ... Further parameters (age, sum insured, contract closing /
-        #'        begin, premium payment details, etc.) of the contract, which
-        #'        can also override parameters defined at the tariff-level.
-        #'        Possible values are all sub-fields of the
-        #'        [InsuranceContract.ParameterDefaults] data structure.
-        #'
-        initialize = function(tarif, parent = NULL, calculate = "all", profitid = "default", ...) {
-            if (getOption('LIC.debug.init', FALSE)) {
-                browser();
-            }
-            private$initParams = c(list(tarif = tarif, parent = parent, calculate = calculate, profitid = profitid), list(...))
-            self$tarif = tarif;
-            self$parent = parent;
-
-            # TODO-block: If parent exists, use its parameters as fallback, too
-            self$ContractParameters = InsuranceContract.ParametersFill(
-                ...,
-                premiumWaiver = FALSE,
-                surrenderPenalty = TRUE,
-                alphaRefunded = FALSE
-            );
-            # Set default values for required contract-specific data
-            # First, take the tariff defaults, then the  ProfitParticipation
-            # defaults, so a tariff can override the profit participation scheme
-            self$Parameters = self$ContractParameters;
-            self$Parameters = InsuranceContract.ParametersFallback(
-                self$ContractParameters,
-                self$tarif$getParameters()
-            );
-
-            ppScheme = self$Parameters$ProfitParticipation$profitParticipationScheme;
-            if (!is.null(ppScheme)) {
-                self$Parameters$ProfitParticipation = fallbackFields(
-                    self$Parameters$ProfitParticipation,
-                    ppScheme$Parameters);
-                self$Parameters$ProfitParticipation$scenarios[[profitid]] = list()
-            }
-
-            private$consolidateContractData(tarif = tarif, ...);
-            self$calculateContract(calculate = calculate);
-
-
-            invisible(self)
-        },
-
-        #' @description Add the current state of the contract to the history list
-        #'
-        #' @details The \code{InsuranceContract$addHistorySnapshot()} function
-        #' adds the current (or the explicitly given) state of the contract
-        #' (parameters, calculated values, tarif, list of all contract blocks)
-        #' to the history list (available in the \code{history} field of the
-        #' contract, i.e. \code{InsuranceContract$history}).
-        #'
-        #' @param time the time described by the snapshot
-        #' @param comment a comment to store together with the contract state
-        #' @param type The type of action that caused a history snapshot to
-        #'        be stored. Typical values are "Contract" to describe the initial
-        #'        contract, "Premium Waiver" or "Dynamic Increase".
-        #' @param params The set of params to be stored in the history snapshot
-        #'        (default is \code{self$Parameters}, if not explicitly given)
-        #' @param values The calculated time series of all contract values
-        #'        calculated so far. Default is \code{self$Values}, if not
-        #'        explicitly given
-        #' @param tarif The underlying [InsuranceTarif] object describing the
-        #'        Product/Tariff. Default is \code{self$tarif}, if not explicitly given.
-        #' @param blocks The list of all contract children for contracts with
-        #'        multiple insurance blocks (e.g. dynamic increases, riders, etc.)
-        #'
-        #' @examples
-        #' # TODO
-        addHistorySnapshot = function(time = 0, comment = "Initial contract values", type = "Contract", params = self$Parameters, values = self$Values, tarif = self$tarif, blocks = self$blocks) {
-            self$history = rbind(
-                self$history,
-                list(
-                    time = list(
-                        "time"    = time,
-                        "comment" = comment,
-                        "type"    = type,
-                        "params"  = params,
-                        "values"  = values,
-                        "tarif"   = tarif,
-                        "blocks"  = blocks
-                    )
-                )
-            );
-            invisible(self)
-        },
-
-        #' @description Add a child contract block (e.g. a dynamic increase or a rider) to an insurance contract
-        #'
-        #' @details Contracts with multiple contract blocks (typically either
-        #' contracts with dynamic increases, sum increases or protection riders)
-        #' are constructed by instantiating the child block (e.g. a single
-        #' dynamic increase or the rider) independently with its own (shorter)
-        #' duration and then inserting it into the parent contract with this
-        #' function at the given time.
-        #'
-        #' If no [InsuranceContract] object is passed as \code{block}, a copy
-        #' of the parent is created with overriding parameters given in \code{...}.
-        #'
-        #' @param id The identifier of the child block to be inserted
-        #' @param block The [InsuranceContract] object describing the child block.
-        #'        If NULL (or not given at all), a copy of the parent will be
-        #'        created.
-        #' @param t Then the child block starts, relative to the parent block.
-        #'        The child block is calculated independently (with time 0
-        #'        describing its own start), so when aggregating all values from
-        #'        the individual blocks to overall values for the whole contract,
-        #'        the child's values need to be translated to the parent contracts's
-        #'        time frame using this parameter
-        #' @param comment The comment to use in the history snapshot.
-        #' @param blockType The type of block to be added (e.g. Dynamics, Extension,
-        #'        etc.). Can be any (short) string.
-        #' @param ... parameters to be passed to \ifelse{html}{\href{#method-new}{\code{InsuranceContract$new()}}}{\code{InsuranceContract$new()()}} when
-        #'        \code{block} is not given and a copy of the parent should be
-        #'        created with overrides.
-        #'
-        #' @examples
-        #' # TODO
-        addBlock = function(id = NULL, block = NULL, t = block$Values$int$blockStart, comment = paste0("Additional block at time t=", t), blockType = "Dynamics", ...) {
-            if (getOption('LIC.debug.addBlock', FALSE)) {
-                browser();
-            }
-            if (missing(block) || is.null(block) || !is(block, "InsuranceContract")) {
-                # Create a block with the same tariff and parameters as the main contract, but allow overriding params with the ... arguments
-                block = InsuranceContract$new(id = id, ...)
-            }
-            if (missing(t) || is.null(t)) {
-                t = 0
-            }
-            # declare as child of 'self', store the time offset to the parent contract
-            block$parent = self
-            block$Parameters$ContractData$blockStart = t
-
-            if (length(self$blocks) == 0) {
-                main = self$clone()
-                main$parent = self
-                self$blocks[[main$Parameters$ContractData$id]] = main
-                self$Parameters$ContractData$id = "Gesamt"
-            }
-
-            if (missing(id) || is.null(id)) {
-                id = paste0("block", length(self$blocks) + 1)
-            }
-            self$blocks[[id]] = block
-            # recalculate the whole contract by consolidating values from each block
-            self$consolidateBlocks(valuesFrom = t)
-
-            self$addHistorySnapshot(time = t, comment = comment,
-                                    type = blockType, params = self$Parameters, values = self$Values);
-
-            invisible(self)
-        },
-
-        #' @description Add a dynamic increase with the same parameters as the main contract part
-        #'
-        #' @details This method adds a new contract block describing a dynamic
-        #'          or sum increase (increasing the sum insured at a later time
-        #'          $t$ than contract inception). This increase is modelled by a
-        #'          separate [InsuranceContract] object with the sum difference
-        #'          as its own \code{sumInsured}.
-        #'
-        #'          By default, all parameters are taken from the main contract,
-        #'          with the maturity adjusted to match the original contract's
-        #'          maturity.
-        #'
-        #'          The main contract holds all child blocks, controls their
-        #'          valueation and aggregates all children's values to the
-        #'          total values of the overall contract.
-        #'
-        #' @param t The time within the main contract when the sum increase happens.
-        #'          The [InsuranceContract] object describing the dynamic increase
-        #'          will still internally start at its own time 0, but the
-        #'          aggregation by the main contract will correctly offset to
-        #'          the time $t$ within the main contract.
-        #' @param NewSumInsured The over-all new sum insured (sum of original
-        #'          contract and all dynamica increaeses). The \code{sumInsured}
-        #'          of the new dynamic increase block will be determined as the
-        #'          difference of the old and new overall sum insured. Alternatively,
-        #'          it can directly be given as the \code{SumInsuredDelta}
-        #'          argument instead.
-        #' @param SumInsuredDelta The sum insured of only the dynamic increase,
-        #'          i.e. the sumInsured of the dynamic contract block only. The
-        #'          overall sum insured will increase by this amount. Only one of
-        #'          \code{NewSumInsured} and \code{SumInsuredDelta} is needed,
-        #'          the other one will be calculated accordingly. If both are
-        #'          given, the \code{SumInsuredDelta} will take precedence.
-        #' @param id The identifier of the contract block describing the dynamic
-        #'          increase. This is a free-form string that should be unique
-        #'          within the list of child blocks. It will be displayed in the
-        #'          Excel export feature and in the history snapshot list.
-        #' @param ... Paramters to override in the dynamic block. By default,
-        #'          all parameters of the main contract block will be used, but
-        #'          they can be overridden per dynamic increase block.
-        #'
-        #' @examples
-        #' # TODO
-        addDynamics = function(t, NewSumInsured, SumInsuredDelta, id, ...) {
-            if (getOption('LIC.debug.addDynamics', FALSE)) {
-                browser();
-            }
-
-            # TODO: Override only the required parameters
-            params = private$initParams
-            if (is.null(params)) params = list()
-            if (!is.null(params$age)) params$age = params$age + t
-            if (!is.null(params$policyPeriod)) params$policyPeriod = params$policyPeriod - t
-            if (!is.null(params$premiumPeriod)) params$premiumPeriod = max(0, params$premiumPeriod - t)
-            if (!is.null(params$deferralPeriod)) params$deferralPeriod = max(0, params$deferralPeriod - t)
-            if (!is.null(params$contractClosing)) params$contractClosing = params$contractClosing + years(t)
-            params$initialCapital = NULL
-            # TODO: Adjust non-constant parameters (e.g. profit rates or benefits given as vector) to the later start time
-
-            # TODO: Generalize this to also allow specifying dynamic premium rather than sum insured
-            if (!missing(SumInsuredDelta)) {
-                SIdelta = SumInsuredDelta
-                NewSumInsured = SIdelta + self$Values$reserves[t + 1, "SumInsured"]
-            } else if (!missing(NewSumInsured)) {
-                SIdelta = NewSumInsured - self$Values$reserves[t + 1, "SumInsured"]
-            } else {
-                warning("Neither NewSumInsured nor SumInsuredDelta are given. Unable to determine sum insured of the dynamic increase.")
-                return(invisible(self))
-            }
-            params$sumInsured = SIdelta
-
-            if (missing(id)) {
-                # numbering dynamics: Use # of blocks (except main) as a simplification
-                id = paste0("dyn", max(1, length(self$blocks)))
-            }
-
-            params$t = t
-            params$id = id
-            # Override with arguments explicitly given
-            arguments = list(...)
-            params[names(arguments)] = arguments[names(arguments)]
-            params$comment = sprintf("Dynamic increase at time %d to sum %0.2f", t, NewSumInsured)
-            params$blockType = "Dynamics";
-            do.call(self$addBlock, params)
-        },
-
-
-        #' @description Add a contract extension after the contract has ended
-        #' (existing reserve is used as initial capital of the follow-up contract).
-        #'
-        #' @details When a contract expires, this function adds a follow-up contract
-        #' (with either the same or a different tariff), using the existing
-        #' reserve as `additionalCapital` at inception.
-        #' Technically, a child block using the new contract data of the extension
-        #' is added to the original contract. The over-all contract values are then
-        #' the sum of the original contract (providing values until expiration)
-        #' and the extension (providing values after the extension).
-        #'
-        #'
-        #' @param id The identifier of the child block to be inserted
-        #' @param t The time of the extension (relative to the parent block),
-        #'        by default contract expiration of the parent block.
-        #'        The extension is calculated independently (with time 0
-        #'        describing its own start), but using the existing reserve as
-        #'        initialCapital and the parent's parameters as fall-back values.
-        #' @param comment The comment to use in the history snapshot.
-        #' @param ... Additional parameters to be passed to
-        #'        \ifelse{html}{\href{#method-new}{\code{InsuranceContract$new}}}{\code{InsuranceContract$new}} to create the contract
-        #'        extension object.
-        #'
-        #' @examples
-        #' # TODO
-        addExtension = function(id = NULL, t = NULL, comment = paste0("Contract extension at time t=", t), ...) {
-            if (getOption('LIC.debug.addExtension', FALSE)) {
-                browser();
-            }
-            if (missing(id) | is.null(id)) {
-                # numbering extensions: Use nr. of blocks (except main) as a
-                # simplification => numbering is withint all dynamics,
-                # extensions, riders, etc.!
-                id = paste0("dyn", max(1, length(self$blocks)))
-            }
-            if (missing(t) | is.null(t)) {
-                # By default, use the parent's expiration, so the extension
-                # is appended after the original contract has ended.
-                t = self$Parameters$ContractData$policyPeriod
-            }
-
-            # TODO: Override only the required parameters
-            params = private$initParams
-            if (is.null(params)) params = list()
-            if (!is.null(params$age)) params$age = params$age + t
-            # Remaining premium period is kept, can be overwritten in the
-            # arguments to this method. If premiumPeriod has already ended,
-            # a premium-free extension is added by default
-            if (!is.null(params$premiumPeriod)) params$premiumPeriod = max(0, params$premiumPeriod - t)
-            if (!is.null(params$deferralPeriod)) params$deferralPeriod = max(0, params$deferralPeriod - t)
-            if (!is.null(params$contractClosing)) params$contractClosing = params$contractClosing + years(t)
-            # Use the existing reserve as initialCapital, reset premium parameter and sumInsured of the old contract
-            params$initialCapital = self$Values$reserves[t + 1, "contractual"]
-            params$sumInsured = NULL
-            params$premium = NULL
-
-
-            # TODO: Adjust non-constant parameters (e.g. profit rates or benefits given as vector) to the later start time
-
-
-            params$t = t
-            params$id = id
-            # Override with arguments explicitly given
-            arguments = list(...)
-            params[names(arguments)] = arguments[names(arguments)]
-            params$comment = comment
-            params$blockType = "Contract Extension"
-
-            # Two cases:
-            # 1) extension with premium => either premium or sumInsured must be given
-            # 2) premium-free extension => no premium, no sumInsured given => set premium to 0, calculate sumInsured
-
-            noPremiums = (is.null(params$sumInsured) || (params$sumInsured == 0)) && (is.null(params$premium) || (params$premium == 0));
-            if (noPremiums) {
-                params$premium = 0;
-            }
-            do.call(self$addBlock, params)
-        },
-
-        #' @description Calculate all time series of the contract from the parameters
-        #'
-        #' @details This method calculates all contract values (potentially
-        #'          starting from and preserving all values before a later time
-        #'          \code{valuesFrom}). This function is not meant to be called
-        #'          directly, but internally, whenever a contract is created or
-        #'          modified.
-        #'
-        #'          There is, however, a legitimate case to call this function
-        #'          when a contract was initially created with a value of
-        #'          \code{calculate} other than "all", so not all values of the
-        #'          contract were calculated. When one later needs more values
-        #'          than were initially calculated, this function can be called.
-        #'          However, any contract changes might need to be rolled back
-        #'          and reapplied again afterwards. So even in this case it is
-        #'          probably easier to create the contract object from scratch
-        #'          again.
-        #' @param calculate Which values to calculate. See [CalculationEnum]
-        #' @param valuesFrom Calculate only values starting from this time step
-        #'        on (all values before that time will be preserved). This is
-        #'        required when a contract is changed significantly (potentially
-        #'        even switching to a new tariff), so that the calculation bases
-        #'        for previous periods are no longer available.
-        #' @param premiumCalculationTime The time point when the premium should
-        #'        be re-calculated (including existing reserves) based on the
-        #'        actuarial equivalence principle. All reserves will be based on
-        #'        these new premiums.
-        #' @param preservePastPV Whether present value before the recalculation
-        #'        time \code{valuesFrom} should be preserved or recalculated.
-        #'        When they are recalculated, the present values are consistent
-        #'        to the new cash flows over the whole contract period, but
-        #'        they no longer represent the actual contract state at these
-        #'        times. If values are not recalculated, the reserves at each
-        #'        time step represent the proper state at that point in time.
-        #' @param additionalCapital The capital that is added to the contract
-        #'        (e.g. capital carried over from a previous contract) at the
-        #'        premium calculation time.
-        #' @param recalculatePremiums Whether the premiums should be recalculated
-        #'        at time \code{premiumCalculationTime} at all.
-        #' @param recalculatePremiumSum Whether to recalculate the overall premium
-        #'        sum when the premium is recalculated.
-        #' @param history_comment The comment for the history snapshot entry
-        #' @param history_type The type (free-form string) to record in the history snapshot
-        #'
-        calculateContract = function(calculate = "all", valuesFrom = 0, premiumCalculationTime = 0, preservePastPV = TRUE, additionalCapital = 0, recalculatePremiums = TRUE, recalculatePremiumSum = TRUE, history_comment = NULL, history_type = "Contract") {
-            if (getOption('LIC.debug.calculateContract', FALSE)) {
-                browser();
-            }
-            if (!is.null(self$blocks)) {
-                for (b in self$blocks) {
-                    #
-                    # .args = as.list(match.call()[-1])
-                    # # correctly shift the valuesFrom by each block's blockStart parameter
-                    # .args$valuesFrom = max(0, .args$valuesFrom - b$Parameters$ContractData$blockStart)
-                    # do.call(b$calculateContract, .args)
-                    #
-                    b$calculateContract(
-                        calculate = calculate,
-                        valuesFrom = max(0, valuesFrom - b$Parameters$ContractData$blockStart),
-                        premiumCalculationTime = max(0, premiumCalculationTime - b$Parameters$ContractData$blockStart),
-                        preservePastPV = preservePastPV,
-                        additionalCapital = additionalCapital,
-                        recalculatePremiums = recalculatePremiums,
-                        recalculatePremiumSum = recalculatePremiumSum,
-                        history_comment = history_comment,
-                        history_type = history_type)
-                }
-            }
-            self$Values$int = private$determineInternalValues()
-            self$Values$transitionProbabilities = mergeValues(
-              starting = self$Values$transitionProbabilities,
-              ending = private$determineTransitionProbabilities(),
-              t = valuesFrom)
-            if (calculate == "probabilities") return(invisible(self));
-
-            self$Values$cashFlowsBasic = mergeValues(
-                starting = self$Values$cashFlowsBasic,
-                ending = private$determineCashFlowsBasic(),
-                t = valuesFrom);
-            self$Values$cashFlows = mergeValues(
-                starting = self$Values$cashFlows,
-                ending = private$determineCashFlows(),
-                t = valuesFrom);
-
-            if (additionalCapital > 0) {
-                self$Values$cashFlows[as.character(premiumCalculationTime), "additional_capital"] = additionalCapital
-            }
-
-            if (recalculatePremiumSum) {
-                # Premium waiver: Premium sum is not affected by premium waivers, i.e. everything depending on the premium sum uses the original premium sum!
-                self$Values$unitPremiumSum = private$determinePremiumSum();
-            }
-            self$Values$cashFlowsCosts = mergeValues3D(
-                starting = self$Values$cashFlowsCosts,
-                ending = private$determineCashFlowsCosts(),
-                t = valuesFrom);
-            if (calculate == "cashflows") return(invisible(self));
-
-
-            # Shall we re-calculate PV or preserve the old ones???
-            pv = private$calculatePresentValues()
-            pvCost = private$calculatePresentValuesCosts(presentValues = pv)
-            oldPV = self$Values$presentValues
-            if (preservePastPV) {
-                # Preserve past present values, i.e. the PV represents the PV
-                # with the knowledge of the past, even though the future CF
-                # might have changed meanwhile, so the PV at time 0 is no
-                # longer the PV of the current cash flows... The PV at time t
-                # always represents the information available at time t, but no
-                # future chagnes.
-                # This is useful to preserver the PV information neede to
-                # calculate the premiums from the past.
-                if (!is.null(self$Values$presentValues)) {
-                    self$Values$presentValues = self$Values$presentValues[,1:NCOL(pv)]
-                }
-                self$Values$presentValues = mergeValues(starting = self$Values$presentValues, ending = pv, t = valuesFrom)
-                self$Values$presentValuesCosts = mergeValues3D(starting = self$Values$presentValuesCosts, ending = pvCost, t = valuesFrom)
-            } else {
-                # Recalculate present value for times before start, i.e. make all PV consistent with the current cash flows
-                self$Values$presentValues = pv
-                self$Values$presentValuesCosts = pvCost
-            }
-            if (calculate == "presentvalues") return(invisible(self));
-
-
-            # If we have the premium given, determine the sumInsured from it
-            # Since the cash flows depend on the sumInsured (in particular, )
-            if (is.null(self$Parameters$ContractData$sumInsured)) {
-                self$Parameters$ContractData$sumInsured = private$calculateSumInsured(calculationTime = premiumCalculationTime)
-            }
-
-            # the premiumCalculation function returns the premiums AND the cofficients,
-            # so we have to extract the coefficients and store them in a separate variable
-            if (recalculatePremiums) {
-                res = private$calculatePremiums(premiumCalculationTime = premiumCalculationTime);
-                self$Parameters$ContractData$sumInsured = res[["sumInsured"]]
-                self$Values$premiumCoefficients = res[["coefficients"]];
-                # TODO: Store premiums in a data.frame, including the time they are calculated???
-                self$Values$premiums = res[["premiums"]]
-                self$Values$int$premiumCalculationTime = premiumCalculationTime
-            }
-            if (calculate == "premiums") return(invisible(self));
-
-            # Update the cash flows and present values with the values of the premium
-            pvAllBenefits = private$calculatePresentValuesBenefits()
-            if (preservePastPV) {
-                self$Values$presentValues = mergeValues(starting = oldPV, ending = cbind(pv, pvAllBenefits), t = valuesFrom)
-            } else {
-                self$Values$presentValues = cbind(pv, pvAllBenefits)
-            }
-
-            self$Values$absCashFlows       = mergeValues(starting = self$Values$absCashFlows,       ending = private$calculateAbsCashFlows(), t = valuesFrom);
-            self$Values$absPresentValues   = mergeValues(starting = self$Values$absPresentValues,   ending = private$calculateAbsPresentValues(), t = valuesFrom);
-            if (calculate == "absvalues") return(invisible(self));
-
-            self$Values$reserves           = mergeValues(starting = self$Values$reserves,           ending = private$calculateReserves(), t = valuesFrom);
-            if (calculate == "reserves") return(invisible(self));
-            self$Values$premiumComposition = mergeValues(starting = self$Values$premiumComposition, ending = private$premiumAnalysis(), t = valuesFrom);
-            self$Values$premiumCompositionSums = mergeValues(starting = self$Values$premiumCompositionSums, ending = private$premiumCompositionSums(), t = valuesFrom);
-            self$Values$premiumCompositionPV = mergeValues(starting = self$Values$premiumCompositionPV, ending = private$premiumCompositionPV(), t = valuesFrom);
-            self$Values$basicData          = mergeValues(starting = self$Values$basicData,          ending = private$getBasicDataTimeseries(), t = valuesFrom);
-            if (calculate == "premiumcomposition") return(invisible(self));
-
-            self$Values$reservesBalanceSheet = mergeValues(starting = self$Values$reservesBalanceSheet,ending = private$calculateReservesBalanceSheet(), t = valuesFrom);
-            if (calculate == "reservesbalancesheet") return(invisible(self));
-
-            private$profitParticipation(calculateFrom = valuesFrom);
-            if (calculate == "profitparticipation") return(invisible(self));
-
-            self$addHistorySnapshot(
-                time    = valuesFrom,
-                comment = ifelse(is.null(history_comment),
-                                 ifelse(valuesFrom == 0, "Initial contract values", paste("Contract recalculation at time", premiumCalculationTime)),
-                                 history_comment),
-                type    = history_type,
-                params  = self$Parameters,
-                values  = self$Values
-            );
-            if (calculate == "history") return(invisible(self));
-
-            invisible(self)
-        },
-
-        #' @description Aggregate values from all child contract blocks (if any)
-        #'
-        #' @details This function is an internal function for contracts with
-        #'        multiple child blocks (dynamic increases, sum increases, riders).
-        #'        It takes the values from all child blocks and calculates the
-        #'        overall values from all child blocks aggregated.
-        #'
-        #'        This function should not be called manually.
-        #'
-        #' @param valuesFrom The time from when to aggragate values. Values before
-        #'        that time will be left unchanged.
-        consolidateBlocks = function(valuesFrom = 0) {
-            if (getOption('LIC.debug.consolidateBlocks', FALSE)) {
-                browser();
-            }
-            # First, Re-calculate all children that have children on their own
-            for (b in self$blocks) {
-                if (length(b$blocks) > 0) {
-                    # correctly shift the valuesFrom by each block's blockStart parameter
-                    b$consolidateBlocks(valuesFrom = max(0, valuesFrom - b$Parameters$ContractData$blockStart))
-                }
-            }
-
-            sumKeyedArrays = function(arr1 = NULL, arr2 = NULL) {
-                if (is.null(arr2)) {
-                    arr1
-                } else if (is.null(arr1)) {
-                    arr2
-                } else {
-                    bind_rows(arr1, arr2) %>%
-                        group_by(date) %>%
-                        summarise_all(list(sum))
-                }
-            }
-            consolidateField = function(field, keyed = FALSE) {
-                vals = NULL
-                if (length(self$blocks) == 0) {
-                    vals = self$Values[[field]]
-                }
-                for (b in self$blocks) {
-                    if (keyed) {
-                        # The rows of the two data.frames can be associated by the values of a certain column
-                        vals = sumKeyedArrays(arr1 = vals, arr2 = b$Values[[field]])
-                    } else {
-                        # Simply pad the arrays and sum them up:
-                        vals = sumPaddedArrays(arr1 = vals, arr2 = b$Values[[field]], pad2 = b$Parameters$ContractData$blockStart)
-                    }
-                }
-                mergeValues(starting = self$Values[[field]],   ending = vals, t = valuesFrom);
-            }
-
-
-            # Some values do not make sense for consolidated values
-            self$Values$cashFlowsBasic = NULL
-            self$Values$cashFlows = NULL
-            self$Values$cashFlowsCosts = NULL
-            self$Values$presentValues = NULL
-            self$Values$presentValuesCosts = NULL
-
-            self$Values$unitPremiumSum = NULL
-            self$Values$premiumCoefficients = NULL
-            self$Values$premiums = NULL
-
-            # self$Values$transitionProbabilities = consolidateField("transitionProbabilities")
-            # self$Values$cashFlowsBasic       = consolidateField("cashFlowsBasic")
-            # self$Values$cashFlows            = consolidateField("cashFlows")
-            # self$Values$cashFlowsCosts       = consolidateField("cashFlowsCosts")
-            self$Values$absCashFlows           = consolidateField("absCashFlows")
-            self$Values$absPresentValues       = consolidateField("absPresentValues")
-            self$Values$premiumComposition     = consolidateField("premiumComposition")
-            self$Values$premiumCompositionSums = consolidateField("premiumCompositionSums")
-            self$Values$premiumCompositionPV   = consolidateField("premiumCompositionPV")
-            self$Values$reserves               = consolidateField("reserves")
-            self$Values$reservesBalanceSheet   = consolidateField("reservesBalanceSheet", keyed = TRUE)
-            # TODO: Basic Data cannot simply be summed, e.g. the interest rate!
-            self$Values$basicData              = consolidateField("basicData")
-
-            # Some fields can NOT be summed, but have to be left untouched.
-            # Hard-code these to use the values from the main contract part:
-            rows = nrow(self$Values$reservesBalanceSheet)
-            colDt = rep(as.Date(NA), rows)
-            colTime = rep(NA_real_, rows)
-            colIntR = rep(NA_real_, rows)
-            colDur = rep(NA_real_, rows)
-            colPrem = rep(NA_real_, rows)
-            polPeriod = self$Parameters$ContractData$policyPeriod
-            for (b in self$blocks) {
-                start = b$Parameters$ContractData$blockStart
-                polPeriod = max(polPeriod, b$Parameters$ContractData$policyPeriod + start)
-                colDt = coalesce(colDt, pad0(b$Values$reservesBalanceSheet[,"date"],     start = start, value = as.Date(NA), value.start = as.Date(NA), l = rows))
-                colTime = coalesce(colTime, pad0(b$Values$reservesBalanceSheet[,"time"] + start, start = start, value = NA, value.start = NA, l = rows))
-
-                colIntR = coalesce(colIntR, pad0(b$Values$basicData[,"InterestRate"],    start = start, value = NA, value.start = NA, l = rows))
-                colDur  = coalesce(colDur,  pad0(b$Values$basicData[,"PolicyDuration"],  start = start, value = NA, value.start = NA, l = rows))
-                colPrem = coalesce(colPrem, pad0(b$Values$basicData[,"PremiumPeriod"],   start = start, value = NA, value.start = NA, l = rows))
-            }
-            self$Parameters$ContractData$policyPeriod = polPeriod;
-            self$Values$reservesBalanceSheet[,"date"] = colDt;
-            self$Values$reservesBalanceSheet[,"time"] = colTime;
-            self$Values$basicData[,"InterestRate"] = colIntR
-            self$Values$basicData[,"PolicyDuration"] = colDur
-            self$Values$basicData[,"PremiumPeriod"] = colPrem
-
-            self$Values$int$l = rows
-
-            invisible(self)
-        },
-
-        #' @description Stop premium payments and re-calculate sumInsured of the paid-up contract
-        #'
-        #' @details This function modifies the contract at time $t$ so that
-        #'        no further premiums are paid (i.e. a paid-up contract) and the
-        #'        \code{sumInsured} is adjusted according to the existing reserves.
-        #'
-        #' @param t Time of the premium waiver.
-        #' @param ... Further parameters (currently unused)
-        #'
-        #' @examples
-        #' # TODO
-        premiumWaiver = function(t, ...) {
-            if (getOption('LIC.debug.premiumWaiver', FALSE)) {
-                browser();
-            }
-            if (length(self$blocks) > 0) {
-                for (b in self$blocks) {
-                    b$premiumWaiver(t - b$Parameters$ContractData$blockStart, ...)
-                }
-            } else {
-                newSumInsured = self$Values$reserves[[toString(t), "PremiumFreeSumInsured"]];
-                self$Parameters$ContractData$sumInsured = newSumInsured;
-            }
-            self$Parameters$ContractState$premiumWaiver = TRUE;
-            self$Parameters$ContractState$surrenderPenalty = FALSE; # Surrender penalty has already been applied, don't apply a second time
-            self$Parameters$ContractState$alphaRefunded = TRUE;     # Alpha cost (if applicable) have already been refunded partially, don't refund again
-            # TODO: Extract current amount of premium refund and feed that into the calculateContract function...
-
-            self$calculateContract(
-                valuesFrom = t,
-                premiumCalculationTime = t,
-                preservePastPV = TRUE, recalculatePremiums = TRUE, recalculatePremiumSum = FALSE,
-                history_comment = sprintf("Premium waiver at time %d", t), history_type = "PremiumWaiver")
-
-            invisible(self)
-        },
-
-
-
-        #' @description Calculate one profit scenario and return all values
-        #'
-        #' @details This function calculates one profit scenario with the
-        #'         provided profit participation parameters (all parameters
-        #'         not given in the call are taken from their values of the
-        #'         contract, profit participation scheme or tariff).
-        #'
-        #' @param ... Scenario-specific profit sharing parameters, overriding
-        #'         the default values. Typically, adjusted profit rates are required
-        #'         in a profitScenario.
-        #' @return a data.frame holding all profit participation values (rates,
-        #'         bases for the different profit types, profit allocations,
-        #'         terminal bonus funds, profit in case of death/surrender/premium waiver)
-        #'
-        #' @examples
-        #' # TODO
-        profitScenario = function(...) {
-            if (getOption('LIC.debug.profitScenario', FALSE)) {
-                browser();
-            }
-            private$calculateProfitParticipation(...)
-        },
-
-        #' @description Calculate one profit scenario and store it in the contract
-        #'
-        #' @details This function calculates one profit scenario with the
-        #'         provided profit participation parameters (all parameters
-        #'         not given in the call are taken from their values of the
-        #'         contract, profit participation scheme or tariff). The results
-        #'         are stored in a list of profit scenarios inside the contract.
-        #'
-        #'         This function can be chained to calculate and add multiple
-        #'         profit scenarios.
-        #'
-        #' @param id The unique ID of the profit scenario. Will be used as key
-        #'         in the list of profit scenarios and printed out in the Excel
-        #'         export.
-        #' @param ... Scenario-specific profit sharing parameters, overriding
-        #'         the default values. Typically, adjusted profit rates are required
-        #'         in a profitScenario.
-        #'
-        #' @examples
-        #' # TODO
-        addProfitScenario = function(id, ...) {
-            if (getOption('LIC.debug.addProfitScenario', FALSE)) {
-                browser();
-            }
-            .args = as.list(match.call()[-1])
-            self$Parameters$ProfitParticipation$scenarios[[id]] = list(...)
-            if (length(self$blocks) > 0) {
-                vals = NULL
-                for (b in self$blocks) {
-                    # TODO: shift the profit rates by b$Parameters$ContractData$blockStart
-                    do.call(b$addProfitScenario, .args)
-                    vals = sumPaddedArrays(arr1 = vals, arr2 = b$Values$profitScenarios[[id]], pad2 = b$Parameters$ContractData$blockStart)
-                    # TODO: consolidate reserves after profit!
-                }
-                # Consolidate all child blocks
-                self$Values$profitScenarios[[id]] = vals
-            } else {
-                # profitParticipation will assign the values to Values$profitScenarios[[id]] and Values$reservesAfterProfit[[id]]
-                # private$profitParticipation(id = id, ...)
-                pp = private$calculateProfitParticipation(...)
-                self$Values$profitScenarios[[id]] = pp
-                self$Values$reservesAfterProfit[[id]] = private$calculateReservesAfterProfit(profitScenario = pp, ...)
-            }
-
-            invisible(self)
-        },
-
-
-        #' @field dummy.public
-        #' dummy field to allow a trailing comma after the previous field/method
-        dummy.public = NULL
-    ),
-
-    ######################### PRIVATE METHODS ##################################
-    private = list(
-        initParams = NULL,
-
-        consolidateContractData = function(...) {
-            args = list(...);
-            # TODO-blocks
-
-            if (getOption('LIC.debug.consolidateContractData', FALSE)) {
-                browser();
-            }
-            # YOB is deprecated in favor of birthDate. If it is given, use January 1
-            if (is.null(self$Parameters$ContractData$birthDate) && !is.null(self$Parameters$ContractData$YOB)) {
-                self$Parameters$ContractData$birthDate = make_date(self$Parameters$ContractData$YOB, 1, 1)
-            }
-
-            # Calculate date/year of birth, age, contract closing etc. from each other
-            # 1. Contract date (if not given) is NOW, unless age + YOB is given => Then year is derived as YOB+age
-            if (is.null(self$Parameters$ContractData$contractClosing)) {
-                # Default is contractClosing is NOW:
-                self$Parameters$ContractData$contractClosing = Sys.Date()
-
-                # However, if age and DOB / YOB is given, calculate contract closing from that:
-                # age is given (and not a function that calculates age from DOB and Contract closing)
-                if (!is.null(self$Parameters$ContractData$age) &&
-                    !is.function(self$Parameters$ContractData$age)
-                ) {
-                    if (!is.null(self$Parameters$ContractData$birthDate)) {
-                        ag = self$Parameters$ContractData$age
-                        # Whole years are added as period (so the day stays the same), remaining fractions are added as dyears
-                        self$Parameters$ContractData$contractClosing = as.Date(self$Parameters$ContractData$birthDate +
-                            years(floor(self$Parameters$ContractData$age)) +
-                            dyears(self$Parameters$ContractData$age %% 1))
-                        # TODO: Always start at the nearest beginning of a month? Or leave the contract closing at any day?
-                    }
-                }
-            }
-
-            # 2. Current age: If age is given, use it
-            if (!is.null(self$Parameters$ContractData$age)) {
-                self$Parameters$ContractData$age = valueOrFunction(
-                    self$Parameters$ContractData$age,
-                    params = self$Parameters, values = self$Values);
-            } else {
-            # 3. Otherwise, either use the birth date to calculate the age
-                if (!is.null(self$Parameters$ContractData$birthDate)) {
-                    # TODO: Decide for variant 1 or 2...
-                    # Variant 1: Exact age rounded to the nearest whole number
-                    self$Parameters$ContractData$age = age.exactRounded(self$Parameters, self$Values)
-                    # Variant 2: Year of contract closing - YOB
-                    self$Parameters$ContractData$age = age.yearDifference(self$Parameters, self$Values)
-                } else {
-            # 4. Or use age=40 as default
-                    self$Parameters$ContractData$age = 40
-                    warning("InsuranceContract: Missing age, no information to derive age from YOB and contractClosing => Assuming default age 40. Tariff: ", self$tarif$name)
-                }
-            }
-            if (is.null(self$Parameters$ContractData$birthDate)) {
-                self$Parameters$ContractData$birthDate = as.Date(self$Parameters$ContractData$contractClosing -
-                    years(floor(self$Parameters$ContractData$age)) -
-                    dyears(self$Parameters$ContractData$age %% 1))
-            }
-
-
-
-            # Evaluate policy period, i.e. if a function is used, calculate its numeric value
-            self$Parameters$ContractData$policyPeriod = valueOrFunction(
-                self$Parameters$ContractData$policyPeriod,
-                params = self$Parameters, values = self$Values);
-
-            self$Parameters$ContractData$guaranteedPeriod = valueOrFunction(
-                self$Parameters$ContractData$guaranteedPeriod,
-                params = self$Parameters, values = self$Values);
-
-            #### #
-            # PREMIUM PAYMENT PERIOD (default: policyPeriod, can be given as function or numeric value)
-            #### #
-            if (is.null(self$Parameters$ContractData$premiumPeriod)) {
-                self$Parameters$ContractData$premiumPeriod = self$Parameters$ContractData$policyPeriod
-            }
-            self$Parameters$ContractData$premiumPeriod = valueOrFunction(
-                self$Parameters$ContractData$premiumPeriod,
-                params = self$Parameters, values = self$Values);
-            # premium period is at most contract duration!
-            self$Parameters$ContractData$premiumPeriod =
-                min(
-                    self$Parameters$ContractData$premiumPeriod,
-                    self$Parameters$ContractData$policyPeriod
-                );
-
-            self$Parameters$Loadings$commissionPeriod = valueOrFunction(
-                self$Parameters$Loadings$commissionPeriod,
-                params = self$Parameters, values = self$Values);
-            self$Parameters$Loadings$commissionPeriod =
-                min(
-                    self$Parameters$Loadings$commissionPeriod,
-                    self$Parameters$ContractData$policyPeriod
-                )
-
-
-            # Evaluate deferral period, i.e. if a function is used, calculate its numeric value from the other parameters
-            self$Parameters$ContractData$deferralPeriod = valueOrFunction(
-                self$Parameters$ContractData$deferralPeriod,
-                params = self$Parameters, values = self$Values);
-            self$Parameters$ContractData$deferralPeriod =
-                min(
-                    self$Parameters$ContractData$deferralPeriod,
-                    self$Parameters$ContractData$policyPeriod
-                )
-
-            # Premium refund period (if applicable):
-            self$Parameters$ContractData$premiumRefundPeriod = valueOrFunction(
-                self$Parameters$ContractData$premiumRefundPeriod,
-                params = self$Parameters, values = self$Values);
-
-            #### #
-            # AGES for multiple joint lives:
-            #### #
-            # For joint lives, some parameters can be given multiple times: age, sex
-            # Collect all given values into one vector!
-
-            # TODO: First person has birthDate handled properly, handle all other persons, too!
-            age = unlist(args[names(args) == "age"], use.names = FALSE)
-            if (!is.null(age) && length(age) > 1) {
-                self$Parameters$ContractData$age = c(self$Parameters$ContractData$age[[1]], tail(age, -1));
-                # TODO: Calculate ages for all other persons, too. Or rather, allow multiple birthDate values, too
-            }
-            sex = unlist(args[names(args) == "sex"], use.names = FALSE)
-            if (!is.null(sex) && length(sex) > 1) {
-                self$Parameters$ContractData$sex = sex;
-            }
-            if (is.null(self$Parameters$ContractData$ageDifferences)) {
-                self$Parameters$ContractData$ageDifferences = diff(self$Parameters$ContractData$age);
-            } else {
-                self$Parameters$ContractData$ageDifferences = valueOrFunction(
-                    self$Parameters$ContractData$ageDifferences,
-                    params = self$Parameters, values = self$Values);
-            }
-
-
-            #### #
-            # TECHNICAL AGE
-            #### #
-            # Calculate the technical age (e.g. female are made younger, contracts on joint lives, etc.)
-            if (is.null(self$Parameters$ContractData$technicalAge)) {
-                self$Parameters$ContractData$technicalAge = self$Parameters$ContractData$age[1]
-            } else {
-                self$Parameters$ContractData$technicalAge = valueOrFunction(
-                    self$Parameters$ContractData$technicalAge,
-                    params = self$Parameters, values = self$Values);
-            }
-
-            # Evaluate all possibly variable values (mortalityTable depending on sex, etc.)
-            self$Parameters$ActuarialBases$mortalityTable = valueOrFunction(
-                self$Parameters$ActuarialBases$mortalityTable,
-                params = self$Parameters, values = self$Values)
-
-            #### #
-            # COSTS PARAMETERS: can be a function => evaluate it to get the real costs
-            # This needs to be last, as the costs can depend on present values
-            # => mortality table is needed
-            #### #
-            self$Parameters$Costs = private$evaluateCosts()
-
-
-            ##### #
-            # SUM INSURED: By default, sum insured is required and the premium
-            # is calculated from the SI. However, it is also possible (not yet
-            # fully implemented) to prescribe the premium and/or initial capital
-            # to determine the SI. If neither is given, a warning should be printed
-            # and a default of sumInsured=10000 should be applied
-            if (is.null(self$Parameters$ContractData$sumInsured) &&
-                is.null(self$Parameters$ContractData$premium) &&
-                (is.null(self$Parameters$ContractData$initialCapital) ||
-                 self$Parameters$ContractData$initialCapital == 0)) {
-                self$Parameters$ContractData$sumInsured = 10000
-                warning("InsuranceContract: Neither sumInsured nor premium nor initialCapital given! => Assuming default sum insured 10.000. Tariff: ", self$tarif$name)
-            }
-
-            invisible(self)
-        },
-
-        evaluateCosts = function() {
-            self$tarif$getCostValues(params = self$Parameters)
-        },
-
-        determineInternalValues = function(...) {
-            self$tarif$getInternalValues(params = self$Parameters, ...);
-        },
-
-        determineTransitionProbabilities = function(...) {
-            self$tarif$getTransitionProbabilities(params = self$Parameters, values = self$Values, ...);
-        },
-        determineCashFlowsBasic = function(...) {
-            self$tarif$getBasicCashFlows(params = self$Parameters, values = self$Values, ...);
-        },
-        determineCashFlows = function(...) {
-            self$tarif$getCashFlows(params = self$Parameters, values = self$Values, ...);
-        },
-        determinePremiumSum = function(...) {
-            sum(self$Values$cashFlows$premiums_advance + self$Values$cashFlows$premiums_arrears);
-        },
-        determineCashFlowsCosts = function(...) {
-            self$tarif$getCashFlowsCosts(params = self$Parameters, values = self$Values, ...);
-        },
-        calculatePresentValues = function(...) {
-            self$tarif$presentValueCashFlows(params = self$Parameters, values = self$Values, ...);
-        },
-        calculatePresentValuesCosts = function(...) {
-            self$tarif$presentValueCashFlowsCosts(params = self$Parameters, values = self$Values, ...);
-        },
-        calculateSumInsured = function(...) {
-            self$tarif$sumInsuredCalculation(params = self$Parameters, values = self$Values, ...)
-        },
-        calculatePremiums = function(...) {
-            self$tarif$premiumCalculation(params = self$Parameters, values = self$Values, ...);
-        },
-        calculatePresentValuesBenefits = function(...) {
-            self$tarif$presentValueBenefits(params = self$Parameters, values = self$Values, ...);
-        },
-        calculateAbsCashFlows = function(...) {
-            self$tarif$getAbsCashFlows(params = self$Parameters, values = self$Values, ...);
-        },
-        calculateAbsPresentValues = function(...) {
-            self$tarif$getAbsPresentValues(params = self$Parameters, values = self$Values, ...);
-        },
-        calculateReserves = function(...) {
-            self$tarif$reserveCalculation(params = self$Parameters, values = self$Values, ...);
-        },
-        calculateReservesBalanceSheet = function(...) {
-            self$tarif$reserveCalculationBalanceSheet(params = self$Parameters, values = self$Values, ...);
-        },
-        premiumAnalysis = function(...) {
-            self$tarif$premiumDecomposition(params = self$Parameters, values = self$Values, ...);
-        },
-        premiumCompositionSums = function(...) {
-            self$tarif$calculateFutureSums(cf = self$Values$premiumComposition, params = self$Parameters, values = self$Values, ...);
-        },
-        premiumCompositionPV = function(...) {
-            self$tarif$calculatePresentValues(self$Values$premiumComposition, params = self$Parameters, values = self$Values, ...);
-        },
-
-        profitParticipation = function(...) {
-            scens = self$Parameters$ProfitParticipation$scenarios
-            lapply(seq_along(scens), function(x) {
-                nm = names(scens)[x]
-                scn = NULL
-                if (!is.null(self$Values$profitScenarios) && length(self$Values$profitScenarios) >= x) {
-                    scn = self$Values$profitScenarios[[x]]
-                }
-                pp = do.call(private$calculateProfitParticipation, c(list(profitScenario = scn, ...), scens[x]))
-                res = do.call(private$calculateReservesAfterProfit, c(list(profitScenario = pp, ...), scens[x]))
-                if (nm != "" && !is.null(nm)) {
-                    self$Values$profitScenarios[[nm]] = pp
-                    self$Values$reservesAfterProfit[[nm]] = res
-                } else {
-                    self$Values$profitScenarios[[x]] = pp
-                    self$Values$reservesAfterProfit[[x]] = res
-                }
-            })
-
-            # For convenience, return the profit participation table:
-            # (self$Values$reservesAfterProfit was also changed, but is not returned!)
-            self$Values$profitScenarios
-        },
-
-        calculateProfitParticipation = function(...) {
-            self$tarif$calculateProfitParticipation(params = self$Parameters, values = self$Values, ...);
-        },
-        calculateReservesAfterProfit = function(profitScenario, ...) {
-            self$tarif$reservesAfterProfit(profitScenario = profitScenario, params = self$Parameters, values = self$Values, ...);
-        },
-
-
-        getBasicDataTimeseries = function(...) {
-            self$tarif$getBasicDataTimeseries(params = self$Parameters, values = self$Values, ...);
-        },
-
-        dummy.private = NULL
-    )
-)
-
diff --git a/R/InsuranceParameters.R b/R/InsuranceParameters.R
deleted file mode 100644
index 337ff57040dc4383bc4370cf4aa17dc3ecf761a0..0000000000000000000000000000000000000000
--- a/R/InsuranceParameters.R
+++ /dev/null
@@ -1,769 +0,0 @@
-#' @include HelperFunctions.R
-NULL
-
-#' Update one component of an [InsuranceTarif]'s cost structure
-#'
-#' Insurance tariff costs are defined by a cost matrix with dimensions: {CostType, Basis, Period}, where:
-#' \describe{
-#'     \item{CostType:}{alpha, Zillmer, beta, gamma, gamma_nopremiums, unitcosts}
-#'     \item{Basis:}{SumInsured, SumPremiums, GrossPremium, NetPremium, Constant}
-#'     \item{Period:}{once, PremiumPeriod, PremiumFree, PolicyPeriod, AfterDeath, FullContract}
-#' }
-#' After creation (using the function [initializeCosts()]), the funciton \code{setCost}
-#' can be used to modify a single entry. While [initializeCosts()] provides arguments
-#' to set the most common types of cost parameters in one call, the \code{setCost}
-#' function allows to modify any cost parameter.
-#'
-#' This function modifies a copy of the cost structure and returns it, so this
-#' function can be chained as often as desired and final return value will contain
-#' all cost modifications.
-#'
-#' @param costs The cost definition matrix (usually created by [initializeCosts()])
-#' @param type The cost type (alpha, Zillmer, beta, gamma, gamma_nopremiums, unitcosts)
-#' @param basis The basis fo which the cost rate is applied (default is SumInsured)
-#' @param frequency How often / during which period the cost is charged (once, PremiumPeriod, PremiumFree, PolicyPeriod, FullContract)
-#' @param value The new cost value to set for the given type, basis and frequency
-#'
-#' @return The modified cost structure
-#'
-#' @examples
-#' costs = initializeCosts()
-#' setCost(costs, "alpha", "SumPremiums", "once", 0.05)
-#'
-#' @export
-setCost = function(costs, type, basis = "SumInsured", frequency = "PolicyPeriod", value) {
-  costs[type, basis, frequency] = value
-  costs
-}
-
-
-#' Initialize or modify a data structure for the definition of [InsuranceTarif] costs
-#'
-#' Initialize a cost matrix with dimensions: {CostType, Basis, Period}, where:
-#' \describe{
-#'     \item{CostType:}{alpha, Zillmer, beta, gamma, gamma_nopremiums, unitcosts}
-#'     \item{Basis:}{SumInsured, SumPremiums, GrossPremium, NetPremium, Benefits, Constant}
-#'     \item{Period:}{once, PremiumPeriod, PremiumFree, PolicyPeriod, CommissionPeriod}
-#' }
-#' This cost structure can then be modified for non-standard costs using the [setCost()] function.
-#' The main purpose of this structure is to be passed to [InsuranceContract] or
-#' [InsuranceTarif] definitions.
-# TODO: gamma an Erlebensleistungen?
-#'
-#' @param costs (optional) existing cost structure to duplicate / use as a starting point
-#' @param alpha Alpha costs (charged once, relative to sum of premiums)
-#' @param alpha.commission Alpha costs (charged during the commission period,
-#'                         relative to sum of premiums; Use the \code{commissionPeriod}
-#'                         and \code{alphaCostsCommission} contract parameters
-#'                         to set the length of the commission period and whether
-#'                         the \code{alpha.commission} val´ue is understood as yearly
-#'                         cost or the sum or present value of the commission
-#'                         charges over the whole commission period)
-#' @param Zillmer Zillmer costs (charged once, relative to sum of premiums)
-#' @param beta Collection costs (charged on each gross premium, relative to gross premium)
-#' @param gamma Administration costs while premiums are paid (relative to sum insured)
-#' @param gamma.paidUp Administration costs for paid-up contracts (relative to sum insured)
-#' @param gamma.premiumfree Administration costs for planned premium-free period (reltaive to sum insured)
-#' @param gamma.contract Administration costs for the whole contract period (relative to sum insured)
-#' @param gamma.afterdeath Administration costs after the insured person has dies (for term-fix insurances)
-#' @param gamma.fullcontract Administration costs for the full contract period,
-#'                           even if the insured has already dies (for term-fix insurances)
-#' @param unitcosts Unit costs (absolute monetary amount, during premium period)
-#' @param unitcosts.PolicyPeriod Unit costs (absolute monetary amount, during full contract period)
-#'
-#' @examples
-#' # empty cost structure (only 0 costs)
-#' initializeCosts()
-#'
-#' # the most common cost types can be given in initializeCosts()
-#' initializeCosts(alpha = 0.04, Zillmer = 0.025, beta = 0.05, gamma.contract = 0.001)
-#'
-#' # The same cost structure manually
-#' costs.Bsp = initializeCosts();
-#' costs.Bsp[["alpha", "SumPremiums", "once"]] = 0.04;
-#' costs.Bsp[["Zillmer", "SumPremiums", "once"]] = 0.025;
-#' costs.Bsp[["beta", "GrossPremium", "PremiumPeriod"]] = 0.05;
-#' costs.Bsp[["gamma", "SumInsured", "PolicyPeriod"]] = 0.001;
-#'
-#' # The same structure using the setCost() function:
-#' library(magrittr)
-#' costs.Bsp = initializeCosts() %>%
-#'   setCost("alpha", "SumPremiums", "once", 0.04) %>%
-#'   setCost("Zillmer", "SumPremiums", "once", 0.025) %>%
-#'   setCost("beta", "GrossPremium", "PremiumPeriod", 0.05) %>%
-#'   setCost("gamma", "SumInsured", "PolicyPeriod", 0.001)
-#'
-#'
-#'
-#'
-#' @export
-initializeCosts = function(costs, alpha, Zillmer, alpha.commission, beta, gamma, gamma.paidUp, gamma.premiumfree, gamma.contract, gamma.afterdeath, gamma.fullcontract, unitcosts, unitcosts.PolicyPeriod) {
-    if (missing(costs)) {
-        dimnm = list(
-          type = c("alpha", "Zillmer", "beta", "gamma", "gamma_nopremiums", "unitcosts"),
-            basis = c("SumInsured", "SumPremiums", "GrossPremium", "NetPremium", "Benefits", "Constant", "Reserve"),
-            frequency = c("once", "PremiumPeriod", "PremiumFree", "PolicyPeriod", "AfterDeath", "FullContract", "CommissionPeriod")
-        );
-        costs = array(
-            0,
-            dim = sapply(dimnm, length),
-            dimnames = dimnm
-        );
-    }
-    if (!missing(alpha)) {
-        costs = setCost(costs, "alpha",  "SumPremiums", "once", alpha)
-    }
-    if (!missing(alpha.commission)) {
-        costs = setCost(costs, "alpha",  "SumPremiums", "CommissionPeriod", alpha.commission)
-        costs = setCost(costs, "Zillmer",  "SumPremiums", "CommissionPeriod", alpha.commission)
-    }
-    if (!missing(Zillmer)) {
-      costs = setCost(costs, "Zillmer","SumPremiums", "once", Zillmer)
-    }
-    if (!missing(beta))  {
-      costs = setCost(costs, "beta", "GrossPremium", "PremiumPeriod", beta)
-    }
-    if (!missing(gamma)) {
-      costs = setCost(costs, "gamma", "SumInsured", "PremiumPeriod", gamma)
-    }
-    if (!missing(gamma.premiumfree)) {
-      costs = setCost(costs, "gamma", "SumInsured", "PremiumFree", gamma.premiumfree)
-    }
-    if (!missing(gamma.paidUp))  {
-      costs = setCost(costs, "gamma_nopremiums", "SumInsured", "PolicyPeriod", gamma.paidUp)
-    }
-    if (!missing(gamma.contract))  {
-      costs = setCost(costs, "gamma", "SumInsured", "PolicyPeriod", gamma.contract)
-      # costs = setCost(costs, "gamma_nopremiums", "SumInsured", "PolicyPeriod", gamma.contract)
-    }
-    if (!missing(gamma.afterdeath))  {
-      costs = setCost(costs, "gamma", "SumInsured", "AfterDeath", gamma.afterdeath)
-      costs = setCost(costs, "gamma_nopremiums", "SumInsured", "AfterDeath", gamma.afterdeath)
-    }
-    if (!missing(gamma.fullcontract))  {
-      costs = setCost(costs, "gamma", "SumInsured", "FullContract", gamma.fullcontract)
-      costs = setCost(costs, "gamma_nopremiums", "SumInsured", "FullContract", gamma.fullcontract)
-    }
-    if (!missing(unitcosts)) {
-      costs = setCost(costs, "unitcosts", "Constant", "PremiumPeriod", unitcosts)
-    }
-    if (!missing(unitcosts.PolicyPeriod)) {
-      costs = setCost(costs, "unitcosts", "Constant", "PolicyPeriod", unitcosts.PolicyPeriod)
-    }
-    costs
-}
-
-#' Helper function to define base costs with base alpha, but otherwise unchanged costs
-#'
-#' Returns a function that sets base alpha (and Zillmer) costs to the given value,
-#' but otherwise uses the full costs defined by the Costs parameter.
-#'
-#' This function can be set as minCosts parameter for a tariff and makes sure
-#' that only alpha costs are modified / waived, but no other costs.
-#'
-#' @param alpha The minimum alpha / Zillmer cost that cannot be waived
-#'
-#' @export
-costs.baseAlpha = function(alpha) {
-  function(params, values, costs) {
-    costs = setCost(costs, "alpha", "SumPremiums", "once", alpha)
-    if (costs["Zillmer", "SumPremiums", "once"] != 0) {
-      costs = setCost(costs, "Zillmer", "SumPremiums", "once", alpha)
-    }
-    costs
-  }
-}
-
-#' Helper function to modify alpha costs of an insurance contract individually
-#'
-#' Returns a function that modifies alpha (and Zillmer) costs by the given scale,
-#' but otherwise uses the full costs defined by the Costs parameter.
-#'
-#' This function can be set as adjustCosts or adjustMinCosts hook parameters
-#' for a tariff or contract and can be used to apply cost adjustments on a
-#' per-contract basis.
-#'
-#' @param scale The scale for  alpha / Zillmer cost
-#'
-#' @export
-costs.scaleAlpha = function(scale) {
-  function(costs, ...) {
-    costs[c("alpha", "Zillmer"),,] = costs[c("alpha", "Zillmer"),,] * scale
-    costs
-  }
-}
-
-
-#' Helper function to display all cost definitions in a concise table
-#'
-#' Returns a data.frame with columns
-#'
-#' @param costs The cost structure to be displayed in a concise table style.
-#' @export
-costsDisplayTable = function(costs) {
-  costtable = as.data.frame.table(setInsuranceValuesLabels(costs) )
-  colnames(costtable) = c("Kostenart", "Basis", "Periode", "Kostensatz");
-  costtable[costtable[,"Kostensatz"] != 0.0000,]
-}
-
-
-
-
-#' Data structure (filled only with NULL) for insurance contract class member values.
-#' @export
-InsuranceContract.Values = list(
-    basicData = NULL,
-    transitionProbabilities = NULL,
-
-    cashFlowsBasic = NULL,
-    cashFlows = NULL,
-    cashFlowsCosts = NULL,
-    unitPremiumSum = 0,
-
-    presentValues = NULL,
-    presentValuesCosts = NULL,
-
-    premiumCoefficients = NULL,
-    premiums = NULL,
-    absCashFlows = NULL,
-    absPresentValues = NULL,
-
-    reserves = NULL,
-    reservesBalanceSheet = NULL,
-
-    premiumComposition = NULL,
-
-    profitParticipation = list()
-);
-
-# InsuranceContract.ParameterDefaults #######################################
-#
-#' Default parameters for the InsuranceContract class.
-#'
-#' A new contract will be
-#' pre-filled with these values, and values passed in the constructor (or with
-#' other setter functions) will override these values.
-#'
-#' @format The parameter list is a list of lists with the following structure:
-#'
-#' Sublists:
-#' \itemize{
-#'     \item \code{$ContractData} ... Contract-specific data (policy period,
-#'               closing, age, sum insured, premium payments, etc.)
-#'     \item \code{$ContractState} ... Current contract state (paid-up, surrender
-#'               penalty already applied, alpha costs already (partially) refunded)
-#'     \item \code{$ActuarialBases} ... Actuarial bases for the contract
-#'               calculation (mortality/invalidity table, guaranteed interest,
-#'               surrender penalty, etc.)
-#'     \item \code{$Costs}, \code{$minCosts} ... Expenses charged to the contract (see [initializeCosts()])
-#'     \item \code{$Loadings} ... Loadings, rebates and other charges of the
-#'               tariff / contract (tax, unit costs, surcharge for no medial exam, premium/benefit frequency loading)
-#'     \item \code{$Features} ... Peculiarities of the tariff (to enable
-#'               non-standard formulas for certain company-specific historical
-#'               "glitches" in the tariff definitions.)
-#'     \item \code{$ProfitParticipation} ... Profit scheme and profit participation
-#'               rates (default values, can be overwritten per profit scenario)
-#'     \item \code{$Hooks} ... Hook functions to allow modification of various
-#'               calculation aspects (e.g. modify the default cash flows after
-#'               their setup)
-#' }
-#'
-#' ## Elements of sublist \code{InsuranceContract.ParameterDefault$ContractData}
-#'
-#' These values are typically set per contract and not by the tariff. Notable
-#' exceptions are the contract duration in some instances and the premiumPeriod=1
-#' for single-premium contracts.
-#'
-#' \describe{
-#'     \item{\code{$id}}{ID of the contract (to distinguish individual parts in
-#'               contracts with multiple parts, e.g. dynamic increases),
-#'               default = "Hauptvertrag"}
-#'     \item{\code{$sumInsured}}{Sum insured, default = 100,000}
-#'     \item{\code{$premium}}{Premium, given to determine the sumInsured (default: NULL)}
-#'     \item{\code{$initialCapital}}{Reserve/Capital that is already available
-#'               at contract inception, e.g. from a previous contract. No tax
-#'               or acquisition costs are applied to this capital.}
-#'     \item{\code{$YOB (deprecated)}}{Year of birth of the insured, used to determine the
-#'               age for the application of the mortality table}
-#'     \item{\code{$birthDate}}{Date  of birth of the insured, used to determine the
-#'               age for the application of the mortality table. Alternatively,
-#'               the year alone can be passed as \code{YOB}.}
-#'     \item{\code{$age}}{Age of the insured}
-#'     \item{\code{$technicalAge}}{Technical age of the insured (when the age
-#'               for the application of the mortality table does not coincide
-#'               with the real age)}
-#'     \item{\code{$ageDifferences}}{Vector of age differences to the first
-#'               insured for contracts with multiple insured (i.e. joint-lives)}
-#'     \item{\code{$sex}}{Sex of the insured, to allow gender-specific prixing
-#'               (e.g. different mortalities or age modification), default="unisex",
-#'               Type is [SexEnum]}
-#'     \item{\code{$policyPeriod}}{Policy Duration (in years)}
-#'     \item{\code{$premiumPeriod}}{Premium payment period (in year), for
-#'               single-premium contracts, \code{premiumPeriod = 1}. Default is
-#'               \code{policyPeriod}, i.e. regular premiums during the whole
-#'               contract period}
-#'     \item{\code{$deferralPeriod}}{deferral period for annuities, i.e. the
-#'               period survival payments start only after this period, typically
-#'               the retirement age.  This applies mostly to tariffs of type
-#'               annuity, although deferral periods are possible (but not common)
-#'               for all other types of insurance, too.}
-#'     \item{\code{$guaranteedPeriod}}{guaranteed annuity payment period. The
-#'               annuity pays out for this period, even if the insured dies.
-#'               This applies only to tariffs of type annuity.}
-#'     \item{\code{$contractClosing}}{The date (variable of type [Date]) when
-#'               the coverage of the contract starts (not neccessarily equal to
-#'               the date when the contract was signed). Typically generated by
-#'               a call to [as.Date()]. The year is relevant to derive the age
-#'               of the insured, while month and day are relevant for the
-#'               interpolation of the balance sheet reserves}
-#'     \item{\code{$blockStart}}{For contracts with multiple blocks (e.g.
-#'               multiple dynamic increases, where each increase is modelled
-#'               like a separate contract), this variable holds the offset of
-#'               the current contract block relative to the main contract block.
-#'               The main block starts a 0, dynamic increases start later! This
-#'               value is only used by the parent block (i.e. $t=0$ of the child
-#'               is aligned with $t=blockStart$ of the parent block.}
-#'     \item{\code{$premiumPayments}}{Whether premiums are paid in advance
-#'               (default) or arrears. Value is of type [PaymentTimeEnum]
-#'               with possible values "in advance" and "in arrears"}
-#'     \item{\code{$benefitPayments}}{Whether recurring benefits (e.g. annuities)
-#'               are paid in advance (default) or arrears. Value is of type
-#'               [PaymentTimeEnum] with possible values "in advance" and
-#'               "in arrears"}
-#'     \item{\code{$premiumFrequency}}{Number of premium payments per year, default is 1.}
-#'     \item{\code{$benefitFrequency}}{Number of benefit payments per year, default is 1.}
-#'     \item{\code{$premiumRefund}}{Proportion of (gross) premiums refunded on
-#'               death (including additional risk, e.g. 1.10 = 110% of paid premiums)}
-#'     \item{\code{$premiumRefundPeriod}}{The period, during which the premium
-#'               refund on death applies. By default, deferred contracts will
-#'               refund premiums only during the deferral period, all other
-#'               contracts during the whole contract. Default is
-#'               \code{premiumRefundPeriod.default}}
-#'     \item{\code{$premiumIncrease}}{The yearly growth factor of the premium,
-#'               i.e. 1.05 means +5% increase each year; a vector describes the
-#'               premiums for all years}
-#'     \item{\code{$annuityIncrease}}{The yearly growth factor of the annuity
-#'               payments, i.e. 1.05 means +5% increase each year; a vector
-#'               describes the annuity unit payments for all years}
-#'     \item{\code{$deathBenefit}}{The yearly relative death benefit (relative
-#'               to the initial sum insured); Can be set to a \code{function(len,
-#'               params, values)}, e.g. \code{deathBenefit = deathBenefit.linearDecreasing}}
-#'     \item{\code{$benefitParameter}}{(optional) Tariff-specific parameter to
-#'               indicate special benefit conditions (e.g. for non-constant benefits
-#'               the initial starting value, or a minimum benefit, etc.). This
-#'               parameter is not used automatically, but needs to be processed
-#'               by a custom \code{$deathBenefit} function.}
-#'
-#'    \item{\code{$costWaiver}}{The fraction of the costs that are waived (only
-#'               those cost components that are defined to be waivable, i.e. by
-#'               defining a corresponding \code{$minCosts}). Linearly interpolates
-#'               between \code{$Costs} and \code{$minCosts}, if the latter is set.
-#'               Otherwise is has no effect.}
-#'    \item{\code{$attributes}}{Additional custom attributes (as a named list),
-#'               which can be used for particular behaviour of different contracts
-#'               or contract slices.}
-#' }
-#'
-#' ## Elements of sublist \code{InsuranceContract.ParameterDefault$ContractState}
-#'
-#' Contract-specific status variables holding the status of the contract.
-#'
-#' \describe{
-#'     \item{\code{$premiumWaiver}}{Whether the contract is paid-up.}
-#'     \item{\code{$surrenderPenalty}}{Whether a surrender penalty still applies
-#'          (e.g. because it has already been applied during a contract change,
-#'          or because due to legal reasons it can no longer be applied)}
-#'     \item{\code{$alphaRefunded}}{Whether alpha costs have (at least partially)
-#'          been refunded (e.g. when a contract is changed or paid-up). Default
-#'          is not yet refunded.}
-#' }
-#'
-#'
-#' ## Elements of sublist \code{InsuranceContract.ParameterDefault$ActuarialBases}
-#'
-#' Tarif-specific actuarial calculation parameters of the contract. Typically,
-#' these values are set by the tariff, but can be overridden by contract (e.g.
-#' while prototyping a new product or a product change).
-#'
-#' \describe{
-#'     \item{\code{$mortalityTable}}{The [mortalityTable] object describing the
-#'               mortality of the insured}
-#'     \item{\code{$invalidityTable}}{For contracts with invalidity benefits,
-#'               the [mortalityTable] object describing the probabilities of
-#'               invalidity}
-#'     \item{\code{$invalidityEndsContract}}{For contracts with invalidity
-#'               benefits, whether a payment of an invalidity benefit ends the
-#'               contract.}
-#'     \item{\code{$i}}{Guaranteed yearly interest rate, default is 0.00, i.e. 0%}
-#'     \item{\code{$balanceSheetDate}}{The day/month when balance sheet reserves
-#'               are calculated. Value of type [Date], typically generated with
-#'               [as.Date()]. The year is actually irrelevant, only the day and
-#'               month are relevant.}
-#'     \item{\code{$balanceSheetMethod}}{How to interpolate the balance sheet
-#'               reserves (at the balandeSheetDate) from the yearly contractual
-#'               reserves. Either a string "30/360", "act/act", "act/360", "act/365"
-#'               or a function with signature \code{balanceSheetMethod(params, contractDates, balanceDates)}
-#'               that returns a vector of coefficients for each year to
-#'               interpolate the reserves available at the given \code{contractDates}
-#'               for the desired \code{balanceDates}}
-#'     \item{\code{$unearnedPremiumsMethod}}{How to calculate the unearned
-#'               premiums (considering the balance sheet date and the premium
-#'               frequency). A function with signature \code{unearnedPremiumsMethod(params, dates)}}
-#'     \item{\code{$surrenderValueCalculation}}{A function describing the surrender
-#'               value calculation. If NULL, the full reserve will be used as
-#'               surrender value. If given, it must be a function with signature
-#'               \code{function(SurrenderReserve, params, values)}.}
-#'     \item{\code{$premiumWaiverValueCalculation}}{A function describing the
-#'               reserve used to derive the premium-free sum insured. If NULL,
-#'               the surrender value will be used. If given, it must be a function
-#'               with signature \code{function(SurrenderReserve, params, values)}}
-#'     \item{\code{$premiumFrequencyOrder}}{Order of the approximation for
-#'               payments within the year (unless an extra frequency loading is
-#'               used => then leave this at 0)}
-#'     \item{\code{$benefitFrequencyOrder}}{Order of the approximation for
-#'               payments within the year (unless an extra frequency loading is
-#'               used => then leave this at 0)}
-#' }
-#'
-#' ## Elements of sublist \code{InsuranceContract.ParameterDefault$Costs}
-#'
-#' Definition of contractual costs charged to the contract. See [initializeCosts()].
-#'
-#' \describe{
-#'     \item{\code{$Costs}}{The full cost defined for the contract / tariff,
-#'               usually set with [initializeCosts()] and [setCost()]}
-#'     \item{\code{$minCosts}}{The minimum costs defined for the contract / tariff
-#'               that cannot be waived. Either an explicit cost definition structure
-#'               generated by [initializeCosts()] and [setCost()], or a
-#'               `function(params, values, costs)`, where the full costs are passed
-#'               as third parameter, so the function can modify only those cost parts
-#'               that can be waived at all. }
-#' }
-#'
-#' ## Elements of sublist \code{InsuranceContract.ParameterDefault$Loadings}
-#'
-#' \describe{
-#'     \item{\code{$ongoingAlphaGrossPremium}}{Acquisition cost that increase the gross premium}
-#'     \item{\code{$tax}}{insurance tax, factor on each premium paid, default is 4%, i.e. \code{i=0.04}}
-#'     \item{\code{$unitcosts}}{Annual unit cost for each policy, absolute value (can be a function)}
-#'     \item{\code{$security}}{Additional security loading on all benefit payments, factor on all benefits}
-#'     \item{\code{$noMedicalExam}}{Loading when no medicial exam is done, % of SumInsured}
-#'     \item{\code{$noMedicalExamRelative}}{Loading when no medicial exam is done, % of gross premium}
-#'     \item{\code{$sumRebate}}{gross premium reduction for large premiums, % of SumInsured}
-#'     \item{\code{$extraRebate}}{gross premium reduction for any reason, % of SumInsured}
-#'     \item{\code{$premiumRebate}}{gross premium reduction for large premiums, % of gross premium}
-#'     \item{\code{$partnerRebate}}{Rebate on premium with all surcharges and
-#'               rebates when more than one contract is written with identical
-#'               parameters. Sums with advanceBonusInclUnitCost and premiumRebate.}
-#'     \item{\code{$extraChargeGrossPremium}}{extra charges on gross premium
-#'               (smoker, leisure activities, BMI too high, etc.)}
-#'     \item{\code{$benefitFrequencyLoading}}{Loading on the benefit for premium
-#'               payment frequencies of more than once a year. Format is
-#'               \code{list("1" = 0.0, "2" = 0.0, "4" = 0.0, "12" = 0.0)}}
-#'     \item{\code{$premiumFrequencyLoading}}{Loading on the premium for premium
-#'               payment frequencies of more than once a year. Format is
-#'               \code{list("1" = 0.0, "2" = 0.0, "4" = 0.0, "12" = 0.0)}}
-#'     \item{\code{$alphaRefundPeriod}}{How long the acquisition costs should be
-#'               (partially) refunded in case of surrender or premium waiver.}
-#'     \item{\code{$commissionPeriod}}{Period, over which the acquisition costs
-#'               are charged to the contract (if not fully up-front or over the
-#'               whole contract period). This has only an effect for cost definitions
-#'               with duration "CommissionPeriod". Default is 5 years.}
-#' }
-#'
-#'
-#' ## Elements of sublist \code{InsuranceContract.ParameterDefault$Features}
-#'
-#' \describe{
-#'     \item{\code{$zillmering}}{Whether the contract uses Zillmering (and bases
-#'               reserves on the Zillmer reserve as opposed to the adequate
-#'               reserve) (default: TRUE)}
-#'     \item{\code{$betaGammaInZillmer}}{Whether beta and gamma-costs should be
-#'               included in the Zillmer premium calculation}
-#'     \item{\code{$alphaRefundLinear}}{Whether the refund of alpha-costs on
-#'               surrender is linear in t or follows the NPV of an annuity}
-#'     \item{\code{$useUnearnedPremiums}}{Whether unearned premiums should be
-#'               reported in the balance sheet reserves. Otherwise, a premium
-#'               paid at the beginning of the period is added to the reserve at
-#'               that time for balance-sheet purposes.
-#'               For regular premiums, the default is TRUE, i.e. the balance-sheet
-#'               reserve at time $t$ does not include the premium paid at time
-#'               $t$, but unearned premiums are included in the balance sheet
-#'               reserves. For single-premium contracts, there are no "unearned"
-#'               premiums, but the initial single premium is added to the reserve
-#'               immediately for balance-sheet purposes. In particular, the
-#'               balance sheet reserve at time $t=0$ is not 0, but the
-#'               premium paid. In turn, no unearned premiums are applied.}
-#'     \item{\code{$surrenderIncludesCostsReserves}}{Whether (administration)
-#'               cost reserves are paid out on surrender (i.e. included in the
-#'               surrender value before surrender penalties are applied)}
-#'     \item{\code{$unitcostsInGross}}{Whether unit costs are included in the
-#'               gross premium calculation or added after gross premiums. (default: FALSE)}
-#'     \item{\code{$absPremiumRefund}}{Constant death benefit (typically premium
-#'               refund of a previous contract), relative to the sum insured.}
-#'     \item{\code{$alphaCostsCommission}}{Whether alpha costs over the commision
-#'               period are given as their actual yearly value ("actual"), or
-#'               whether the given value is the sum ("sum") or the present value
-#'               ("presentvalue") over the whole commission period.}
-#' }
-#'
-#' ## Elements of sublist \code{InsuranceContract.ParameterDefault$ProfitParticipation}
-#'
-#' Parameters describing the profit participation (instance of [ProfitParticipation])
-#' Most element descrive some kind of profit rate (which can vary in time),
-#' while the bases, on which they are applied is defined in the profit scheme.
-#'
-#' \describe{
-#'     \item{\code{$advanceProfitParticipation}}{Advance profit participation
-#'               rate (percentage rebate of the gross premium)}
-#'     \item{\code{$advanceProfitParticipationInclUnitCost}}{Advance profit
-#'               participation rate (percentage rebate on the gross premium after all surcharges and unit costs.}
-#'     \item{\code{$waitingPeriod}}{Waiting period of the profit sharing (e.g.
-#'               no profit in the first two years of a contract, or similar)}
-#'     \item{\code{$guaranteedInterest}}{Individual contract-specific overrides
-#'               of the guaranteed interest rate (i.e. not keyed by year)}
-#'     \item{\code{$interestProfitRate}}{Interest profit rate (guaranteed interest
-#'               rate + interest profit rate = total credited rate)}
-#'     \item{\code{$totalInterest}}{Total credited rate (guarantee + interest profit)}
-#'     \item{\code{$mortalityProfitRate}}{Mortality Profit rate}
-#'     \item{\code{$expenseProfitRate}}{Expense profit rate}
-#'     \item{\code{$sumProfitRate}}{Sum profit rate (for high sumInsured)}
-#'     \item{\code{$terminalBonusRate}}{Terminal bonus rate (non-terminal-bonus
-#'              fund, but "old" Austrian terminal bonus)}
-#'     \item{\code{$terminalBonusFundRate}}{Terminal bonus fund rate}
-#'     \item{\code{$profitParticipationScheme}}{Profit participation scheme (object of class [ProfitParticipation])}
-#'     \item{\code{$profitComponents}}{Profit components of the profit scheme. List containing one or more of \code{c("interest", "risk", "expense", "sum", "terminal")}}
-#'     \item{\code{$profitClass}}{String describing the profit class the tariff
-#'               is assigned to. Profit classes are used to bundle similar
-#'               contracts (e.g. following similar risks) together. Profit
-#'               participation rates are defined at the level of profit classes.}
-#'     \item{\code{$profitRates}}{General, company-wide profit rates, key columns are year and profitClass}
-#'     \item{\code{$scenarios}}{profit participation scenarios (list of overridden parameters for each scenario)}
-#' }
-#'
-#' ## Elements of sublist \code{InsuranceContract.ParameterDefault$Hooks}
-#'
-#' \describe{
-#'     \item{\code{$adjustCashFlows}}{Function with signature \code{function(x, params, values, ...)} to adjust the benefit/premium cash flows after their setup.}
-#'     \item{\code{$adjustCashFlowsCosts}}{Function with signature \code{function(x, params, values, ...)} to adjust the costs cash flows after their setup.}
-#'     \item{\code{$adjustCosts}}{Function with signature \code{function(costs, params, values, ...)} to adjust the tariff costs after their setup (e.g. contract-specific conditions/waivers, etc.).}
-#'     \item{\code{$adjustMinCosts}}{Function with signature \code{function(minCosts, costs, params, values, ...)} to adjust the tariff minimum (unwaivable) costs after their setup (e.g. contract-specific conditions/waivers, etc.).}
-#'     \item{\code{$adjustPresentValues}}{Adjust the present value vectors that are later used to derive premiums and reserves. \code{function(presentValues, params, values)}}
-#'     \item{\code{$adjustPresentValuesCosts}}{Adjust the present value cost vectors used to derive premiums and reserves. \code{function(presentValuesCosts, params, values)}}
-#'     \item{\code{$adjustPremiumCoefficients}}{Function with signature \code{function(coeff, type, premiums, params, values, premiumCalculationTime)} to adjust the coefficients for premium calculation after their default setup. Use cases are e.g. term-fix tariffs where the Zillmer premium term contains the administration cost over the whole contract, but not other gamma- or beta-costs.}
-#'     \item{\code{$adjustPremiums}}{Adjust the resulting premiums. \code{function(premiums = list(premiums, coefficients, sumInsured), params, values)}}
-#'     \item{\code{$adjustPVForReserves}}{Adjust the absolute present value vectors used to derive reserves (e.g. when a sum rebate is subtracted from the gamma-cost reserves without influencing the premium calculation). \code{function(absPV, params, values)}}
-#'     \item{\code{$premiumRebateCalculation}}{Calculate the actual premium rebate from the rebate rate (e.g. when the premium rate is given as a yearly cost reduction applied to a single-premium contract). \code{function(premiumRebateRate, params = params, values = values)}}
-#' }
-#'
-#'
-#' @examples
-#' InsuranceContract.ParameterDefaults
-#' @export
-InsuranceContract.ParameterDefaults = list(
-    ContractData = list(
-        id = "Hauptvertrag",
-        sumInsured = NULL,
-        premium = NULL,
-        birthDate = NULL,
-        YOB = NULL,
-        age = NULL,
-        technicalAge = NULL,
-        ageDifferences = NULL,                  # Age differences of all other insured relative to the first one, for joint live insurances
-        sex = "unisex",                         # Sex, to allow gender-sepecific pricing (e.g. different mortalities or age modification)
-        policyPeriod = 25,                      # total policy duration (including deferral period, guaranteed annuity payments etd.)
-        premiumPeriod = NULL,                   # Default: policyPeriod, unless explicitly overridden
-        deferralPeriod = 0,                     # deferral period for annuities
-        guaranteedPeriod = 0,                   # guaranteed payments for annuities
-        contractClosing = NULL,                 # Contract closing date (day/month is relevant for balance sheet reserves)
-        initialCapital = 0,
-        blockStart = 0,                         # When the current tariff block starts (main block starts a 0, dynamic increases start later!), only used by the parent block (i.e. t=0 of child is aligned with t=blockStart of parent)
-
-        premiumPayments = "in advance",         # premium payments in advance or arrears
-        benefitPayments = "in advance",         # benefit payments in advance or arrears (annuities!)
-
-        premiumFrequency = 1,                   # number of premium payments per year
-        benefitFrequency = 1,                   # number of benefit payments per year (for annuities) or death benefit at the end of every 1/k-th year
-
-        premiumRefund = 0,                      # Proportion of premiums refunded on death (including additional risk, e.g. 1.10 = 110% of paid premiums)
-        premiumRefundPeriod = premiumRefundPeriod.default,  # The time period, during which the premium refund upon death will be paid (default: deferral period, otherwise whole contract)
-        premiumIncrease = 1,                    # The yearly growth factor of the premium, i.e. 1.05 means +5% increase each year; a Vector describes the premiums for all years
-        annuityIncrease = 1,                    # The yearly growth factor of the annuity payments, i.e. 1.05 means +5% incrase each year; a vector describes the annuity unit payments for all years
-        deathBenefit = 1,                       # The yearly relative death benefit (relative to the initial sum insured); Can be fixed, e.g. 0.5 for 50% death cover, or  set to a function(len, params, values) like deathBenefit = deathBenefit.linearDecreasing
-        benefitParameter = NULL,                # Tariff-Specific additional parameter to define custom benefits (e.g. a minimum death benefit quota, an initial )
-
-        costWaiver = 0,                         # The cost waiver (up to minCosts, 0=no cost waiver, 1=full cost waiver down to minCosts)
-        attributes = list()                     # List of additional attributes with custom meaning (not standardized, but can be used by any tariff to implement custom behavior for certain contracts or slices)
-    ),
-    ContractState = list(
-        premiumWaiver = FALSE,                  # contract is paid-up
-        surrenderPenalty = TRUE,                # Set to FALSE after the surrender penalty has been applied once, e.g. on a premium waiver
-        alphaRefunded = FALSE                   # Alpha costs not yet refunded (in case of contract changes)
-    ),
-    ActuarialBases = list(
-        mortalityTable = NULL,
-        invalidityTable = NULL,
-        invalidityEndsContract = TRUE,          # Whether a claim for disease ends the contract or not
-        i = 0.00,                               # guaranteed interest rate
-        balanceSheetDate = as.Date("1900-12-31"),  # Balance sheet date (for the calculation of the balance sheet reserves, year is irrelevant)
-        balanceSheetMethod = "30/360",
-        unearnedPremiumsMethod = NULL,          # Function to calculate the factors for unearned premiums
-        surrenderValueCalculation = NULL,       # By default no surrender penalties
-        premiumWaiverValueCalculation = NULL,   # By default, surrender value will be used
-
-        premiumFrequencyOrder = function(params, ...) { if (is.null(params$Loadings$premiumFrequencyLoading)) 0 else -1}, # Order of the approximation for payments within the year (unless an extra frequency loading is used => then leave this at 0)
-        benefitFrequencyOrder = function(params, ...) { if (is.null(params$Loadings$benefitFrequencyLoading)) 0 else -1}
-    ),
-    Costs = initializeCosts(),
-    minCosts = NULL,               # Base costs, which cannot be waived
-    Loadings = list( # Loadings can also be function(sumInsured, premiums)
-        ongoingAlphaGrossPremium = 0,           # Acquisition cost that increase the gross premium
-        tax = 0.04,                             # insurance tax, factor on each premium paid
-        unitcosts = 0,                          # Annual unit cost for each policy, absolute value (can be a function)
-        security = 0,                           # Additional security loading on all benefit payments, factor on all benefits
-        noMedicalExam = 0,                      # Loading when no medicial exam is done, % of SumInsured
-        noMedicalExamRelative = 0,              # Loading when no medicial exam is done, % of gross premium
-        sumRebate = 0,                          # gross premium reduction for large premiums, % of SumInsured
-        extraRebate = 0,                        # gross premium reduction for any reason, % of SumInsured
-        premiumRebate = 0,                      # gross premium reduction for large premiums, % of gross premium # TODO
-        partnerRebate = 0,                      # Partner rabate on premium (including loading and other rebates) if more than one similar contract is concluded
-        extraChargeGrossPremium = 0,            # extra charges on gross premium (smoker, leisure activities, BMI too high, etc.)
-        benefitFrequencyLoading = NULL, # TODO: Properly implement this as a function
-        premiumFrequencyLoading = NULL, # TODO: Properly implement this as a function
-        alphaRefundPeriod = 5,                   # How long acquisition costs should be refunded in case of surrender
-        commissionPeriod = 5
-    ),
-    Features = list(                            # Special cases for the calculations
-        zillmering = TRUE,                      # Whether the contract uses Zillmering (and bases reserves on the Zillmer reserve as opposed to the adequate reserve)
-        betaGammaInZillmer = FALSE,             # Whether beta and gamma-costs should be included in the Zillmer premium calculation
-        alphaRefundLinear  = TRUE,              # Whether the refund of alpha-costs on surrender is linear in t or follows the NPV of an annuity
-        useUnearnedPremiums = isRegularPremiumContract, # Whether unearned premiums should be calculated in the balance sheet reserves. Otherwise, a premium paid at the beginning of the period is added to the reserve for balance-sheet purposes.
-        surrenderIncludesCostsReserves = TRUE,  # Whether (administration) cost reserves are paid out on surrender (i.e. included in the surrender value before surrender penalties are applied)
-        unitcostsInGross = FALSE,
-        absPremiumRefund = 0,                   # Constant death benefit (irrespective of the type of contract), typically a premium refund for a previous contract
-        alphaCostsCommission = "actual"         # Whether alpha costs over the commision period are given as their actual yearly value ("actual"), or whether the given value is the sum ("sum") or the present value ("presentvalue") over the whole commission period
-    ),
-
-    ProfitParticipation = list(
-        advanceProfitParticipation = 0,                # advance profit participation (percentage of gross premium)
-        advanceProfitParticipationInclUnitCost = 0,    # advance profit participation (percentage of premium including unit cost and all charges and rebates)
-
-        waitingPeriod = NULL,
-
-        guaranteedInterest = NULL,                # Individual contract-specific overrides (i.e. not keyed by year)
-        interestProfitRate = NULL,
-        totalInterest = NULL,
-        mortalityProfitRate = NULL,
-        expenseProfitRate = NULL,
-        sumProfitRate = NULL,
-        terminalBonusRate = NULL,
-        terminalBonusFundRate = NULL,
-
-        profitParticipationScheme = NULL,       # Gewinnbeteiligungssystem (object of class Profit Participation)
-        profitComponents = c(),                 # Potential values: "interest", "risk", "expense", "sum", "terminal", "TBF"
-        profitClass = NULL,
-        profitRates = NULL,                     # General, company-wide profit rates, key columns are year and profitClass
-
-        scenarios = list()                      # profit participation scenarios (list of overridden parameters for each scenario)
-    ),
-
-    Hooks = list(
-      # Functions with signature function(x, params, values, ...), default NULL is equivalent to function(x, ...) {x}
-      adjustCashFlows = NULL,
-      adjustCashFlowsCosts = NULL,
-      adjustCosts = NULL,
-      adjustMinCosts = NULL,
-      adjustPresentValues = NULL,        # function(presentValues, params, values)
-      adjustPresentValuesCosts = NULL,   # function(presentValuesCosts, params, values)
-      adjustPremiumCoefficients = NULL,  # function(coeff, type = type, premiums = premiums, params = params, values = values, premiumCalculationTime = premiumCalculationTime)
-      adjustPremiums = NULL,             # function(premiums = list(premiums, coefficients, sumInsured), params, values)
-      adjustPVForReserves = NULL,        # function(absPresentValues, params, values)
-      premiumRebateCalculation = NULL    # function(premiumRebateRate, params = params, values = values)
-    )
-);
-
-
-#' Full insurance contract parameter structure.
-#'
-#' All values are filled with NULL,
-#' so the functions \code{\link{InsuranceContract.ParametersFill}} and
-#' \code{\link{InsuranceContract.ParametersFallback}} can be used to override
-#' existing parameters or to provide default values for unset (NULL) entries.
-#'
-#' @export
-InsuranceContract.ParameterStructure = rapply(InsuranceContract.ParameterDefaults, function(x) NULL, how = "replace")
-InsuranceContract.ParameterStructure$Loadings["benefitFrequencyLoading"] = list(NULL)
-InsuranceContract.ParameterStructure$Loadings["premiumFrequencyLoading"] = list(NULL)
-
-
-#' Initialize the insurance contract parameters from passed arguments
-#'
-#' Initialize the insurance contract parameters from the passed
-#' arguments. Arguments not given are left unchanged. If no existing parameter
-#' structure is given, an empty (i.e. all NULL entries) structure is used.
-#'
-#' @param params Initial values of the insurance contract parameters. (default: empty parameter structure)
-#' @param costs,minCosts,... Values for any of the entries in the insurance contract
-#'                  parameter structure. These values take precedence over the
-#'                  initial parameters provided in \code{params}.
-#'
-#' @export
-InsuranceContract.ParametersFill = function(params = InsuranceContract.ParameterStructure, costs = NULL, minCosts = NULL, ...) {
-    # params = InsuranceContract.ParameterStructure;
-    params$ContractData = fillFields(params$ContractData, list(...));
-    params$ContractState = fillFields(params$ContractState, list(...));
-    params$ActuarialBases = fillFields(params$ActuarialBases, list(...));
-    params$Loadings = fillFields(params$Loadings, list(...));
-    params$Features = fillFields(params$Features, list(...));
-    params$ProfitParticipation = fillFields(params$ProfitParticipation, list(...));
-    params$Hooks = fillFields(params$Hooks, list(...))
-
-    # Costs are a special case, because they are an array rather than a list:
-    # TODO: Find a way to partially override
-    if (!missing(costs)) params$Costs = costs;
-    if (!missing(minCosts)) params$minCosts = minCosts;
-    params
-}
-
-#' Use fallback values for missing contract parameters
-#'
-#' Provide default values for the insurance contract parameters if any of the
-#' parameters is not explicitly set.
-#'
-#' @param params Current, explicitly set contract parameters. All NULL values
-#'               will be filled with the corresponding entry from \code{fallback}.
-#' @param fallback Fallback values that will be used when the corresponding
-#'                 entry in \code{params} is NULL.
-#' @param ppParameters Whether profit participation parameters should also be
-#'                     filled (default is TRUE)
-#'
-#' @export
-InsuranceContract.ParametersFallback = function(params, fallback, ppParameters = TRUE) {
-    # params = InsuranceContract.ParameterStructure;
-    params$ContractData = fallbackFields(params$ContractData, fallback$ContractData);
-    params$ContractState = fallbackFields(params$ContractState, fallback$ContractState);
-    params$ActuarialBases = fallbackFields(params$ActuarialBases, fallback$ActuarialBases);
-    params$Loadings = fallbackFields(params$Loadings, fallback$Loadings);
-    params$Features = fallbackFields(params$Features, fallback$Features);
-    if (ppParameters) {
-        params$ProfitParticipation = fallbackFields(params$ProfitParticipation, fallback$ProfitParticipation);
-    }
-    params$Hooks = fallbackFields(params$Hooks, fallback$Hooks);
-
-    # Costs are a special case, because they are an array rather than a list:
-    # TODO: Find a way to partially fall back
-    if (is.null(params$Costs)) {
-        # Fallback can either be a full
-        if (!is.null(fallback$costs)) {
-            params$Costs = fallback$costs;
-        } else {
-            params$Costs = fallback$Costs;
-        }
-    }
-    if (is.null(params$minCosts)) {
-      params$minCosts = fallback$minCosts;
-    }
-    params
-}
-
-
diff --git a/R/InsuranceTarif.R b/R/InsuranceTarif.R
deleted file mode 100644
index aa5de30957e4a36e57cf3c4fd38c3aa86b3da33e..0000000000000000000000000000000000000000
--- a/R/InsuranceTarif.R
+++ /dev/null
@@ -1,1764 +0,0 @@
-#' @include HelperFunctions.R InsuranceParameters.R ProfitParticipation.R
-#'
-#' @import MortalityTables
-#' @import R6
-#' @importFrom lubridate year month years days year<-
-#' @importFrom objectProperties setSingleEnum
-NULL
-
-#' An enum specifying the main characteristics of the tarif.
-#'
-#' @description Possible values are:
-#' \describe{
-#'   \item{annuity}{Whole life or term annuity (periodic survival benefits)
-#'        with flexible payouts (constand, increasing, decreasing, arbitrary,
-#'        etc.)}
-#'   \item{wholelife}{A whole or term life insurance with only death benefits.
-#'        The benefit can be constant, increasing, decreasing, described by
-#'        a function, etc.}
-#'   \item{endowment}{An  endowment with death and survival benefits,
-#'        potentially with different benefits.}
-#'   \item{pureendowment}{A pure endowment with only a survival benefit at
-#'        the end of the contract. Optionally, in case of death, all or part
-#'        of the premiums paid may be refunded.}
-#'   \item{terme-fix}{A terme-fix insurance with a fixed payout at the end
-#'        of the contract, even if the insured dies before that time.
-#'        Premiums are paid until death of the insured.}
-#'   \item{dread-disease}{A dread-disease insurance, which pays in case of
-#'        a severe illness (typically heart attacks, cancer, strokes, etc.),
-#'        but not in case of death.}
-#'   \item{endowment + dread-disease}{A combination of an endowment and a
-#'        temporary dread-disease insurance. Benefits occur either on death,
-#'        severe illness or survival, whichever comes first.}
-#' }
-#' @export
-TariffTypeEnum = objectProperties::setSingleEnum(
-  "TariffType",
-  levels = c(
-    "annuity",
-    "wholelife",
-    "endowment",
-    "pureendowment",
-    "terme-fix",
-    "dread-disease",
-    "endowment + dread-disease"
-  ))
-setValidity("TariffTypeSingleEnum", function(object) {
-  if (length(object) != 1L) {
-    "Only one tariff type can be given"
-  } else if (!object %in% levels(object)) {
-    paste("Tarif type '", object, "' does not exist. Valid tariff types are:",
-          paste0("\n('", paste0(levels(object), collapse = "', '"),
-                 "')"), sep = "")
-  }
-});
-
-
-############# Class InsuranceTarif ###########################################
-#' Base class for traditional Insurance Tarifs (with fixed guarantee, profit
-#' sharing and no unit-linked component)
-#'
-#' @description The class \code{InsuranceTarif} provides the code and general
-#' framework to implement contract-independent functionality of a life insurance
-#' product.
-#'
-#' @details This is a base class for holding contract-independent values and
-#' providing methods to calculate cash flows, premiums, etc. Objects of this
-#' class do NOT contain contract-specific values like age, death probabilities,
-#' premiums, reserves, etc. Rather, they are the calculation kernels that will
-#' be called by the \code{\link{InsuranceContract}} objects to make the actual,
-#' tariff-specific calculations.
-#'
-#' Most methods of this class are not meant to be called manually, but are supposed
-#' to be called by the InsuranceContract object with contract-specific information.
-#' The only methods that are typically used for defining an insurance tariff are
-#' the constructor \href{#method-new}{\code{InsuranceTarif$new()}} and the cloning method
-#' \href{#method-createModification}{\code{InsuranceTarif$createModification()}}.
-#' All other methods should never be called manually.
-#'
-#' However, as overriding private methods is not possible in an R6 class, all the
-#' methods need to be public to allow overriding them in derived classes.
-#'
-# # Parameters for the constructors
-#' @param name The unique name / ID of the tariff
-#' @param type An enum specifying the main characteristics of the tarif. See [TariffTypeEnum]
-#' @param tarif The tariff's public name to be stored in the `tarif` field.
-#' @param desc A short human-readable description to be stored in the `desc` field.
-# # General parameters for (almost) all function
-#' @param params Contract-specific, full set of parameters of the contract
-#'      (merged parameters of the defaults, the tariff, the profit participation
-#'      scheme and the contract)
-#' @param values Contract values calculated so far (in the \code{contract$Values}
-#'      list) then this method is called by the contract object
-#'
-#' @param premiumCalculationTime The time when the premiums should be
-#'        (re-)calculated according to the equivalence principle. A time 0
-#'        means the initial premium calculation at contract closing, later
-#'        premium calculation times can be used to re-calculate the new
-#'        premium after a contract change (possibly including an existing reserve)
-#'
-#' @import MortalityTables
-#' @examples
-#' # Define an insurance tariff for 10-year endowments, using a guaranteed interest
-#' # rate of 1% and the Austrian population mortality table of the census 2011.
-#' # Premiums are paid monthly in advance during the whole contract period.
-#' MortalityTables::mortalityTables.load("Austria_Census")
-#' # Cost structure:
-#' #   - 4% up-front acquisition costs (of premium sum)
-#' #   - 1% collection cost of each premium paid
-#' #   - 1%o yearly administration cost (of the sum insured) as long as premiums are paid
-#' #   - 2%o yearly administration cost for paid-up contracts
-#' #   - 10 Euro yearly unit costs (as long as premiums are paid)
-#' costs.endw = initializeCosts(alpha = 0.04, beta = 0.01, gamma = 0.001,
-#'     gamma.paidUp = 0.002, gamma.premiumfree = 0.002, unitcosts = 10)
-#'
-#' endowment.AT1 = InsuranceTarif$new(
-#'     name = "Endow AT 1%", type = "endowment", tarif = "Austrian Endowment",
-#'     desc = "An endowment for Austrian insured with 1% interest and no profit participation",
-#'     ContractPeriod = 10,
-#'     i = 0.01, mortalityTable = mort.AT.census.2011.unisex,
-#'     costs = costs.endw, premiumFrequency = 12)
-#'
-#' # The instantiation of the actual contract will provide the contract specific
-#' # information and immediately calculate all further values:
-#' ctr.end.AT1 = InsuranceContract$new(tarif = endowment.AT1,
-#'     contractClosing = as.Date("2020-07-01"), age = 42)
-#'
-#' # All values for the contract are already calculated during construction and
-#' # stored in the ctr.end.AT1$Values list:
-#' ctr.end.AT1$Values$basicData
-#' ctr.end.AT1$Values$transitionProbabilities
-#' ctr.end.AT1$Values$cashFlowsCosts
-#' ctr.end.AT1$Values$presentValues
-#' ctr.end.AT1$Values$premiums
-#' ctr.end.AT1$Values$reserves
-#' ctr.end.AT1$Values$premiumComposition
-#' # etc.
-#' @export
-InsuranceTarif = R6Class(
-  "InsuranceTarif",
-
-  ######################### PUBLIC METHODS ##################################
-  public  = list(
-    #' @field name The tariff's unique name. Will also be used as the key for exported data.
-    name  = "Insurance Contract Type",
-    #' @field tarif The tariff's public name (typically a product name), not necessarily unique.
-    tarif = NULL,
-    #' @field desc A short human-readable description of the tariff and its main features.
-    desc  = NULL,
-    #' @field tariffType An enum specifying the main characteristics of the tarif.
-    #' Possible values are:
-    #' \describe{
-    #'   \item{annuity}{Whole life or term annuity (periodic survival benefits)
-    #'        with flexible payouts (constand, increasing, decreasing, arbitrary,
-    #'        etc.)}
-    #'   \item{wholelife}{A whole or term life insurance with only death benefits.
-    #'        The benefit can be constant, increasing, decreasing, described by
-    #'        a function, etc.}
-    #'   \item{endowment}{An  endowment with death and survival benefits,
-    #'        potentially with different benefits.}
-    #'   \item{pureendowment}{A pure endowment with only a survival benefit at
-    #'        the end of the contract. Optionally, in case of death, all or part
-    #'        of the premiums paid may be refunded.}
-    #'   \item{terme-fix}{A terme-fix insurance with a fixed payout at the end
-    #'        of the contract, even if the insured dies before that time.
-    #'        Premiums are paid until death of the insured.}
-    #'   \item{dread-disease}{A dread-disease insurance, which pays in case of
-    #'        a severe illness (typically heart attacks, cancer, strokes, etc.),
-    #'        but not in case of death.}
-    #'   \item{endowment + dread-disease}{A combination of an endowment and a
-    #'        temporary dread-disease insurance. Benefits occur either on death,
-    #'        severe illness or survival, whichever comes first.}
-    #' }
-    tariffType = TariffTypeEnum("wholelife"),
-
-    #' @field Parameters A data structure (nested list) containing all relevant
-    #' parameters describing a contract, its underlying tariff, the profit
-    #' participation scheme etc. See [InsuranceContract.ParameterStructure] for
-    #' all fields.
-    Parameters = InsuranceContract.ParameterStructure,
-
-    #' @description Initialize a new tariff object
-    #' @details The constructor function defines a tariff and generates the
-    #' corresponding data structure, which can then be used with the [InsuranceContract]
-    #' class to define an actual contract using the tariff.
-    #'
-    #' The arguments passed to this function will be stored inside the
-    #' \code{Parameters} field of the class, inside one of the lists sublists.
-    #' The parameters are stacked from different layers (higher levels override
-    #' default values from lower layers):
-    #'
-    #' * InsuranceContract object (parameters passed directly to the individual
-    #'     contract)
-    #' * ProfitParticipation object (parameters for profit participation, passed
-    #'     to the definition of the profit plan, which is used for the tarif
-    #'     definition or the contract)
-    #' * InsuranceTarif object (parameters passed to the definition of the tariff
-    #'     that was used for the contract)
-    #' * Defaults taken from [InsuranceContract.ParameterStructure]
-    #'
-    #' The general implementation of this parameter layering means that (a) a tariff
-    #' can already provide default values for contracts (e.g. a default maturity,
-    #' default sum insured, etc) and (b) individual contracts can override all
-    #' parameters defined with the underlying tariff. In particular the latter
-    #' feature has many use-cases in prototyping: E.g. when you have a tariff
-    #' with a guaranteed interest rate of 1\% and a certain mortality table,
-    #' one can immediately instantiate a contract with an updated interest rate
-    #' or mortality table for comparison. There is no need to re-implement a
-    #' tariff for such comparisons, as long as only parameters are changed.
-    #'
-    #' @param ... Parameters for the [InsuranceContract.ParameterStructure],
-    #'            defining the characteristics of the tariff.
-    #' @import MortalityTables
-    #' @examples
-    #' MortalityTables::mortalityTables.load("Austria_Annuities_AVOe2005R")
-    #' tarif.male = InsuranceTarif$new(name = "Annuity Males", type = "annuity",
-    #'     i = 0.01, mortalityTable = AVOe2005R.male)
-    initialize = function(name = NULL, type = "wholelife", tarif = "Generic Tarif", desc = "Description of tarif", ...) {
-      if (getOption('LIC.debug.Tarif.init', FALSE)) {
-        browser();
-      }
-      if (!missing(name))           self$name = name;
-      if (!missing(type)) {
-        self$tariffType = TariffTypeEnum(type)
-      }
-      if (!missing(tarif))          self$tarif = tarif;
-      if (!missing(desc))           self$desc = desc;
-
-      # Set the passed arguments as tariff parameters
-      self$Parameters = InsuranceContract.ParametersFill(self$Parameters, ...)
-
-      # Use the profit participation's parameters as fallback for initialized parameters
-      ppScheme = self$Parameters$ProfitParticipation$profitParticipationScheme;
-      if (!is.null(ppScheme)) {
-          self$Parameters$ProfitParticipation = InsuranceContract.ParametersFallback(self$Parameters$ProfitParticipation, ppScheme$Parameters)
-      }
-
-      # Fill all remaining uninitialized values with their defaults, except for profit participation params
-      self$Parameters = InsuranceContract.ParametersFallback(self$Parameters, InsuranceContract.ParameterDefaults, ppParameters = FALSE);
-    },
-
-    #' @description create a copy of a tariff with certain parameters changed
-    #' @details This method \code{createModification} returns a copy of the tariff
-    #' with all given arguments changed in the tariff's `InsuranceTarif$Parameters`
-    #' parameter list.
-    #'
-    #' As InsuranceTarif is a R6 class with reference logic, simply assigning
-    #' the object to a new variable does not create a copy, but references the
-    #' original tariff object. To create an actual copy, one needs to call this
-    #' method, which first clones the whole object and then adjusts all parameters
-    #' to the values passed to this method.
-    #'
-    #' @param tariffType An enum specifying the main characteristics of the tarif.
-    #'       See [TariffTypeEnum]
-    #' @param ... Parameters for the [InsuranceContract.ParameterStructure],
-    #'            defining the characteristics of the tariff.
-    #' @import MortalityTables
-    #' @examples
-    #' MortalityTables::mortalityTables.load("Austria_Annuities_AVOe2005R")
-    #' tarif.male = InsuranceTarif$new(name = "Annuity Males", type = "annuity",
-    #'     i = 0.01, mortalityTable = AVOe2005R.male)
-    #' tarif.unisex = tarif.male$createModification(name = "Annuity unisex",
-    #'     mortalityTable = AVOe2005R.unisex)
-    createModification = function(name  = NULL, tarif = NULL, desc  = NULL, tariffType = NULL, ...) {
-      if (getOption('LIC.debug.createModification', FALSE)) {
-        browser();
-      }
-      cloned = self$clone();
-      if (!missing(name))       cloned$name = name;
-      if (!missing(tarif))      cloned$tarif = tarif;
-      if (!missing(desc))       cloned$desc = desc;
-      if (!missing(tariffType)) cloned$tariffType = tariffType;
-
-      cloned$Parameters = InsuranceContract.ParametersFill(cloned$Parameters, ...);
-      cloned
-    },
-
-    #' @description Retrieve the parameters for this tariff (can be overridden
-    #' for each contract)
-    #'
-    #' @examples
-    #' tarif.male = InsuranceTarif$new(name = "Annuity Males", type = "annuity",
-    #'     i = 0.01, mortalityTable = AVOe2005R.male)
-    #' tarif.male$getParameters()
-    getParameters = function() {
-      self$Parameters
-    },
-
-    #' @description Get some internal parameters cached (length of data.frames,
-    #' policy periods cut at max.age, etc.)
-    #'
-    #' @details This methos is not meant to be called explicitly, but rather used
-    #' by the InsuranceContract class. It returns a list of maturities and ages
-    #' relevant for the contract-specific calculations
-    #'
-    #' @param ... currently unused
-    getInternalValues = function(params, ...) {
-      if (getOption('LIC.debug.getInternalValues', FALSE)) {
-        browser();
-      }
-      age = params$ContractData$technicalAge
-      maxAge = MortalityTables::getOmega(params$ActuarialBases$mortalityTable)
-      policyTerm = min(maxAge + 1 - age, params$ContractData$policyPeriod)
-      # Length of CF vectors / data.frames is always 1 more than the policy period, since there might be a survival payment at the end!
-      list(
-        l = policyTerm + 1, # Length of CF vectors (1 larger than policy period!)
-        # maxAge is the last age with a given death probability, so it can be included in the policy term!
-        # The policy must end AFTER that final year, not at the beginning!
-        policyTerm = policyTerm,
-        premiumTerm = min(policyTerm, params$ContractData$premiumPeriod)
-      )
-    },
-
-
-    #' @description Calculate the contract-relevant age(s) given a certain
-    #' parameter data structure (contract-specific values)
-    #'
-    #' @details This method is not meant to be called explicitly, but rather used
-    #' by the InsuranceContract class. It returns the relevant ages during the
-    #' whole contract period
-    getAges = function(params) {
-      if (getOption('LIC.debug.getAges', FALSE)) {
-        browser();
-      }
-      ages = ages(params$ActuarialBases$mortalityTable, YOB = year(params$ContractData$birthDate));
-      # Append one last age, just in case we need to pad the qx with one more entry:
-      ages = c(ages, tail(ages, 1) + 1)
-      age = params$ContractData$technicalAge;
-      if (age > 0) {
-        ages = ages[-age:-1];
-      }
-      ages
-    },
-
-    #' @description Calculate the transition probabilities from the contract-specific
-    #'  parameters passed as \code{params} and the already-calculated contract
-    #'  values \code{values}
-    #' @details Not to be called directly, but implicitly by the [InsuranceContract] object.
-    getTransitionProbabilities = function(params, values) {
-      if (getOption('LIC.debug.getTransitionProbabilities', FALSE)) {
-        browser();
-      }
-      if (!is.null(values$transitionProbabilities)) {
-        values$transitionProbabilities
-      } else {
-        age = params$ContractData$technicalAge;
-        ages = self$getAges(params);
-        qx = MortalityTables::deathProbabilities(params$ActuarialBases$mortalityTable, YOB = year(params$ContractData$birthDate), ageDifferences = params$ContractData$ageDifferences);
-        if (age > 0) {
-          qx    = qx[-age:-1];
-        }
-        qx = pad0(qx, length(ages), value = 1)
-        if (!is.null(params$ActuarialBases$invalidityTable)) {
-          ix = MortalityTables::deathProbabilities(params$ActuarialBases$invalidityTable, YOB = year(params$ContractData$birthDate), ageDifferences = params$ContractData$ageDifferences);
-          if (age > 0) {
-            ix    = ix[-age:-1];
-          }
-        } else {
-          ix = rep(0, length(qx));
-        }
-        ix = pad0(ix, length(qx));
-        # invalidity/disease does NOT end the contract if flag is set!
-        if (params$ActuarialBases$invalidityEndsContract) {
-          px = 1 - qx - ix
-        } else {
-          px = 1 - qx
-        }
-        df = data.frame(age = ages, qx = qx, ix = ix, px = px, row.names = ages - age)
-        df
-      }
-    },
-
-    #' @description Obtain the cost structure from the cost parameter and the
-    #' given paremeter set
-    #' @details Not to be called directly, but implicitly by the [InsuranceContract] object.
-    #' The cost parameter can be either an array of costs (generated by [initializeCosts()])
-    #' or a function with parameters \code{param} and \code{values}(=NULL) returning
-    #' an array of the required dimensions. This function makes sures that the
-    #' latter function is actually evaluated.
-    #'
-    #' @param params The parameters of the contract / tariff
-    getCostValues = function(params) {
-      if (getOption('LIC.debug.getCostValues', FALSE)) {
-        browser();
-      }
-      costs = valueOrFunction(params$Costs, params = params, values = NULL)
-      costs = applyHook(params$Hooks$adjustCosts, costs, params = params, values = NULL);
-      baseCost = valueOrFunction(params$minCosts, params = params, values = NULL, costs = costs)
-      baseCost = applyHook(params$Hooks$adjustMinCosts, baseCost, costs = costs, params = params, values = NULL);
-      if (!is.null(baseCost)) {
-        costWaiver = valueOrFunction(params$ContractData$costWaiver, params = params, values = NULL, costs = costs, minCosts = baseCost)
-        if (is.numeric(costWaiver)) {
-          costs = costs * (1 - costWaiver) + baseCost * costWaiver
-        } else if (is.boolean(costWaiver)) {
-          if (isTRUE(costWaiver)) {
-            costs = baseCost
-          }
-        }
-      }
-      costs
-    },
-
-    #' @description Returns the unit premium cash flow for the whole contract period.
-    #'   - For constant premiums it will be rep(1, premiumPeriod),
-    #'   - for single premiums it will be c(1, 0, 0, ...),
-    #'   - for increasing premiums it will be (1+increase)^(0:(premiumPeriod-1))
-    #' and 0 after the premium period
-    #' @details Not to be called directly, but implicitly by the [InsuranceContract] object.
-    #' @param len The desired length of the returned data frame (the number of contract periods desire)
-    getPremiumCF = function(len, params, values) {
-      if (getOption('LIC.debug.getPremiumCF', FALSE)) {
-        browser();
-      }
-      premPeriod = min(params$ContractData$premiumPeriod, params$ContractData$policyPeriod, len);
-      if (premPeriod <= 0) {
-        return(rep(0, len))
-      }
-      if (is.null(params$ContractData$premiumIncrease)) {
-        pad0(rep(1, premPeriod - 1), len)
-      } else {
-        inc = valueOrFunction(params$ContractData$premiumIncrease, premiumPeriod = premPeriod, params = params, values = values)
-        if (is.vector(inc) && length(inc) > 1) {
-          # If premiumIncrease is (or returns) a vector, treat it as
-          # relative premium amounts, ie. c(1, 1.1, 1.2) means +10% of
-          # the initial premium for the second and third year
-          pad0(inc, len)
-        } else {
-          pad0(inc ^ (0:(premPeriod - 1)), len)
-        }
-      }
-    },
-
-    #' @description Returns the unit annuity cash flow (guaranteed and contingent) for
-    #'     the whole annuity payment period (after potential deferral period)
-    #'   - For constant annuity it will be rep(1, annuityPeriod),
-    #'   - for increasing annuities it will be (1+increase)^(0:(premiumPeriod-1))
-    #' and 0 after the premium period
-    #' @details Not to be called directly, but implicitly by the [InsuranceContract] object.
-    #' @param len The desired length of the returned data frame (the number of contract periods desire)
-    getAnnuityCF = function(len, params, values) {
-      if (getOption('LIC.debug.getAnnuityCF', FALSE)) {
-        browser();
-      }
-      annuityPeriod = min(params$ContractData$policyPeriod - params$ContractData$deferralPeriod, len);
-      if (is.null(params$ContractData$annuityIncrease)) {
-        pad0(rep(1, annuityPeriod), len);
-      } else {
-        inc = valueOrFunction(params$ContractData$annuityIncrease, annuityPeriod = annuityPeriod, params = params, values = values)
-        if (is.vector(inc) && length(inc) > 1) {
-          # If annuityIncrease is (or returns) a vector, treat it as
-          # relative annuity amounts, ie. c(1, 1.1, 1.2) means +10% of
-          # the initial annuity for the second and third year
-          pad0(inc, len)
-        } else {
-          # a numeric value means constant yearly increases (multiplicative)
-          pad0(inc ^ (0:annuityPeriod), len)
-        }
-      }
-    },
-
-    #' @description Returns the unit death cash flow for the whole protection
-    #' period (after potential deferral period!)
-    #'   - For constant death benefit it will be rep(1, policyPeriod),
-    #'   - for linearly decreasing sum insured it will be (policyPeriod:0)/policyPeriod
-    #' @details Not to be called directly, but implicitly by the [InsuranceContract] object.
-    #' @param len The desired length of the returned data frame (the number of contract periods desire)
-    getDeathCF = function(len, params, values) {
-      if (getOption('LIC.debug.getDeathCF', FALSE)) {
-        browser();
-      }
-      period = params$ContractData$policyPeriod - params$ContractData$deferralPeriod;
-      if (is.null(params$ContractData$deathBenefit)) {
-        pad0(rep(1, period), len)
-      } else {
-        benefit = valueOrFunction(params$ContractData$deathBenefit, len = len, params = params, values = values)
-        if (is.vector(benefit) && length(benefit) > 1) {
-          # If deathBenefit is (or returns) a vector, treat it as
-          # relative annuity amounts, ie. c(1, 1.1, 1.2) means +10% of
-          # the initial annuity for the second and third year
-          pad0(benefit, len)
-        } else {
-          # constant death benefit
-          pad0(rep(benefit, period), len)
-        }
-      }
-    },
-
-    #' @description Returns the basic (unit) cash flows associated with the type
-    #' of insurance given in the InsuranceTarif's `tariffType` field
-    #' @details Not to be called directly, but implicitly by the [InsuranceContract] object.
-    getBasicCashFlows = function(params, values) {
-      if (getOption('LIC.debug.getBasicCashFlows', FALSE)) {
-        browser();
-      }
-      deferralPeriod = params$ContractData$deferralPeriod;
-      guaranteedPeriod = params$ContractData$guaranteedPeriod;
-
-      zeroes = pad0(0, values$int$l)
-
-      cf = data.frame(
-        guaranteed = zeroes,
-        survival = zeroes,
-        death = zeroes,
-        disease = zeroes,
-        sumInsured = rep(1, values$int$l)
-      );
-      if (self$tariffType == "annuity") {
-        annuityPeriod = values$int$policyTerm - deferralPeriod;
-        annuityCF = self$getAnnuityCF(len = annuityPeriod, params = params, values = values)
-        # guaranteed payments exist only with annuities (first n years of the payment)
-        cf$guaranteed = pad0(
-          c(
-            rep(0, deferralPeriod),
-            head(annuityCF, n = guaranteedPeriod)
-          ), values$int$l);
-        cf$survival = pad0(c(
-          rep(0, deferralPeriod + guaranteedPeriod),
-          if (guaranteedPeriod > 0) tail(annuityCF, n = -guaranteedPeriod) else annuityCF,
-          0), values$int$l)
-
-        # start current contract block after deferral period
-#        cf$sumInsured = pad0(rep(#c(rep(0, deferralPeriod), annuityCF) # <= TODO!!!
-
-
-      } else if (self$tariffType == "terme-fix") {
-        # Begin of bock does not have any influence
-        cf$guaranteed = c(rep(0, values$int$policyTerm), 1)
-
-      } else if (self$tariffType == "dread-disease") {
-        # potential Payments start after deferral period
-        cf$disease = c(
-          rep(0, deferralPeriod),
-          rep(1, values$int$l - 1 - deferralPeriod),
-          0)
-      } else {
-        # For endowments, use the death factor here in the basic death CF
-        # to fix the relation of death to survival benefit
-        deathCF = self$getDeathCF(values$int$l - 1 - deferralPeriod, params = params, values = values)
-
-        if (self$tariffType == "endowment" || self$tariffType == "pureendowment" || self$tariffType == "endowment + dread-disease") {
-          cf$survival = c(rep(0, values$int$policyTerm), 1)
-        }
-        if (self$tariffType == "endowment" || self$tariffType == "wholelife" || self$tariffType == "endowment + dread-disease") {
-          cf$death = c(rep(0, deferralPeriod), deathCF, 0)
-          # cf$sumInsured = c(rep(0, deferralPeriod), deathCF, 1);
-        }
-        if (self$tariffType == "endowment + dread-disease") {
-          cf$disease = c(
-            rep(0, deferralPeriod),
-            rep(1, values$int$l - 1 - deferralPeriod),
-            0);
-        }
-      }
-      cf
-    },
-
-    #' @description Returns the cash flows for the contract given the parameters
-    #' @details Not to be called directly, but implicitly by the [InsuranceContract] object.
-    getCashFlows = function(params, values) {
-      if (getOption('LIC.debug.getCashFlows', FALSE)) {
-        browser();
-      }
-      age = params$ContractData$technicalAge;
-
-      if (is.null(values$cashFlowsBasic)) {
-        values$cashFlowsBasic = self$getBasicCashFlows(params, values);
-      }
-      cflen = values$int$l
-      zeroes = pad0(0, cflen)
-      ages = pad0(self$getAges(params), cflen);
-      cf = data.frame(
-        premiums_advance   = zeroes,
-        premiums_arrears   = zeroes,
-        additional_capital = zeroes,
-        guaranteed_advance = zeroes,
-        guaranteed_arrears = zeroes,
-        survival_advance   = zeroes,
-        survival_arrears   = zeroes,
-        death_SumInsured   = zeroes,
-        disease_SumInsured = zeroes,
-        death_GrossPremium = zeroes,
-        death_Refund_past  = zeroes,
-        death_PremiumFree  = zeroes,
-        row.names          = ages - age
-      );
-
-      cf$additional_capital = pad0(params$ContractData$initialCapital, cflen)
-
-      # Premiums:
-      if (!params$ContractState$premiumWaiver) {
-        premiums = self$getPremiumCF(len = cflen, params = params, values = values)
-        if (params$ContractData$premiumPayments == "in advance") {
-          cf$premiums_advance = premiums;
-        } else {
-          cf$premiums_arrears = premiums;
-        }
-      }
-
-      # Survival Benefits
-      if (params$ContractData$benefitPayments == "in advance") {
-        cf$guaranteed_advance = pad0(values$cashFlowsBasic$guaranteed, cflen);
-        cf$survival_advance = pad0(values$cashFlowsBasic$survival, cflen);
-      } else {
-        cf$guaranteed_arrears = pad0(values$cashFlowsBasic$guaranteed, cflen);
-        cf$survival_arrears = pad0(values$cashFlowsBasic$survival, cflen);
-      }
-
-      # Death Benefits
-      cf$death_SumInsured = pad0(values$cashFlowsBasic$death, cflen);
-      if ((!is.null(params$Features$absPremiumRefund)) && (params$Features$absPremiumRefund > 0)) {
-        cf$death_SumInsured = cf$death_SumInsured + pad0(padLast(params$Features$absPremiumRefund, min(cflen - 1, params$ContractData$premiumRefundPeriod)), cflen);
-      }
-      cf$disease_SumInsured = pad0(values$cashFlowsBasic$disease, cflen);
-      cf$death_PremiumFree = cf$death_SumInsured;
-      # premium refund
-      if (params$ContractData$premiumRefund != 0) {
-        totalpremiumcf = cf$premiums_advance + pad0(c(0, cf$premiums_arrears), cflen);
-
-        # death benefit for premium refund is the sum of all premiums so far, but only during the premium refund period, afterwards it's 0:
-        cf$death_GrossPremium = pad0(pad0(Reduce("+", totalpremiumcf[0:params$ContractData$policyPeriod], accumulate = TRUE), params$ContractData$premiumRefundPeriod), cflen)
-        cf$death_Refund_past = cf$death_GrossPremium
-        cf$death_Refund_past[(cf$death_GrossPremium > 0)] = 1;
-      }
-
-      applyHook(params$Hooks$adjustCashFlows, cf, params, values)
-    },
-
-    #' @description Returns the cost cash flows of the contract given the contract
-    #'  and tariff parameters
-    #' @details Not to be called directly, but implicitly by the [InsuranceContract] object.
-    getCashFlowsCosts = function(params, values) {
-      if (getOption('LIC.debug.getCashFlowsCosts', FALSE)) {
-        browser();
-      }
-      dm = dim(params$Costs);
-      dmnames = dimnames(params$Costs);
-
-      cf = array(
-        0,
-        dim = list(values$int$l, dm[1], dm[2], 3),
-        dimnames = list(0:(values$int$l - 1), dmnames[[1]], dmnames[[2]], c("survival", "guaranteed", "after.death"))
-      );
-      cf[1,,,"survival"] = cf[1,,,"survival"] + params$Costs[,,"once"]
-      if (values$int$premiumTerm > 0){
-        for (i in 1:values$int$premiumTerm) {
-          cf[i,,,"survival"] = cf[i,,,"survival"] + params$Costs[,,"PremiumPeriod"];
-        }
-      }
-      if (values$int$premiumTerm < values$int$policyTerm) {
-        for (i in (values$int$premiumTerm + 1):values$int$policyTerm) {
-          cf[i,,,"survival"] = cf[i,,,"survival"] + params$Costs[,,"PremiumFree"];
-        }
-      }
-      for (i in 1:values$int$policyTerm) {
-        cf[i,,,"survival"] = cf[i,,,"survival"] + params$Costs[,,"PolicyPeriod"];
-
-        # Guaranteed cost charged (charged no matter if the person is still alive or death).
-        # Used mainly for term-fix or premium waivers upton death
-        cf[i,,,"guaranteed"] = params$Costs[,,"FullContract"]
-        cf[i,,,"after.death"] = params$Costs[,,"AfterDeath"]
-      }
-
-      # Costs charged only for a specific time (i.e. acquisition costs / commissions)
-      # There are several conventions to scale alpha costs over the commision period:
-      # a) alpha cost once (i.e. not distributed), not scaled
-      # b) uniformly over the period (i.e. sum of k equal commisions is given as cost)
-      # c) by present value (i.e. present value of k equal commission is given as cost)
-      if (params$Features$alphaCostsCommission == "sum") {
-          params$Costs[,,"CommissionPeriod"] = params$Costs[,,"CommissionPeriod"] / params$Loadings$commissionPeriod
-      } else if (params$Features$alphaCostsCommission == "presentvalue") {
-          # Use yearly constant premiums in advance, irrespective of the actual
-          # contract. This is a simplification, but the actual present values
-          # are calculated later, so for now we just assume standard parameters!
-          len = params$Loadings$commissionPeriod;
-          q = self$getTransitionProbabilities(params, values);
-          px = pad0(c(1,q$px), len); # by defualt, premiums are in advance, so first payment has 100% probability
-          v = 1/(1 + params$ActuarialBases$i)^((1:len)-1)
-          params$Costs[,,"CommissionPeriod"] = params$Costs[,,"CommissionPeriod"] / sum(cumprod(px)*v)
-      } else if (params$Features$alphaCostsCommission == "actual") {
-          # NOP, nothing to do
-      } else {
-          warning("unrecognized value given for commissionPeriod: ",params$Features$alphaCostsCommission )
-      }
-      for (i in 1:params$Loadings$commissionPeriod) {
-          cf[i,,,"survival"] = cf[i,,,"survival"] + params$Costs[,,"CommissionPeriod"];
-      }
-
-      # After premiums are waived, use the gamma_nopremiums instead of gamma:
-      if (params$ContractState$premiumWaiver) {
-        cf[,"gamma",,"survival"] = cf[,"gamma_nopremiums",,"survival"];
-      }
-
-      # some values like sumInsured or gross premium might change over time,
-      # so multiply them with the unit cash flows stored in values$cashFlows
-      cf[,,"SumInsured",] = cf[,,"SumInsured",] * values$cashFlowsBasic$sumInsured
-
-      applyHook(params$Hooks$adjustCashFlowsCosts, cf, params, values)
-    },
-
-    #' @description Returns the present values of the cash flows of the contract
-    #' (cash flows already calculated and stored in the \code{cashFlows} data.frame)
-    #' @details Not to be called directly, but implicitly by the [InsuranceContract] object.
-    #' @param cashFlows data.frame of cash flows calculated by a call to \href{#method-getCashFlows}{\code{InsuranceTarif$getCashFlows()}}
-    presentValueCashFlows = function(params, values) {
-      if (getOption('LIC.debug.presentValueCashFlows', FALSE)) {
-        browser();
-      }
-
-      qq = self$getTransitionProbabilities(params, values);
-
-      i = params$ActuarialBases$i;
-      v = 1/(1 + i);
-      benefitFreqCorr = correctionPaymentFrequency(
-        i = i, m = params$ContractData$benefitFrequency,
-        order = valueOrFunction(params$ActuarialBases$benefitFrequencyOrder, params = params, values = values));
-      premiumFreqCorr = correctionPaymentFrequency(
-        i = i, m = params$ContractData$premiumFrequency,
-          order = valueOrFunction(params$ActuarialBases$premiumFrequencyOrder, params = params, values = values));
-
-      pvf = PVfactory$new(qx = qq, m = params$ContractData$benefitFrequency, mCorrection = benefitFreqCorr, v = v);
-
-      pvRefund = pvf$death(values$cashFlows$death_GrossPremium);
-      pvRefundPast = pvf$death(values$cashFlows$death_Refund_past) *
-        (values$cashFlows[,"death_GrossPremium"] - values$cashFlows[,"premiums_advance"]);
-
-      pv = cbind(
-        premiums = pvf$survival(values$cashFlows$premiums_advance, values$cashFlows$premiums_arrears,
-          m = params$ContractData$premiumFrequency, mCorrection = premiumFreqCorr),
-        additional_capital = pvf$survival(advance = values$cashFlows$additional_capital),
-        guaranteed = pvf$guaranteed(values$cashFlows$guaranteed_advance, values$cashFlows$guaranteed_arrears),
-        survival = pvf$survival(values$cashFlows$survival_advance, values$cashFlows$survival_arrears),
-        death_SumInsured = pvf$death(values$cashFlows$death_SumInsured),
-        disease_SumInsured = pvf$disease(values$cashFlows$disease_SumInsured),
-        death_GrossPremium = pvRefund,
-        death_Refund_past = pvRefundPast,
-        death_Refund_future = pvRefund - pvRefundPast,
-        death_PremiumFree = pvf$death(values$cashFlows$death_PremiumFree)
-      );
-
-      rownames(pv) <- pad0(rownames(qq), values$int$l);
-      applyHook(hook = params$Hooks$adjustPresentValues, val = pv, params = params, values = values)
-    },
-
-    #' @description Calculates the present values of the cost cash flows of the
-    #' contract (cost cash flows alreay calculated by \href{#method-getCashFlowsCosts}{\code{InsuranceTarif$getCashFlowsCosts()}}
-    #' and stored in the \code{values} list
-    #' @details Not to be called directly, but implicitly by the [InsuranceContract] object.
-    #' @param presentValues The present values of the insurance claims (without costs)
-    presentValueCashFlowsCosts = function(params, values, presentValues) {
-      if (getOption('LIC.debug.presentValueCashFlowsCosts', FALSE)) {
-        browser();
-      }
-      len = values$int$l;
-      q = self$getTransitionProbabilities(params, values);
-      i = params$ActuarialBases$i
-      v = 1/(1 + i)
-      pvf = PVfactory$new(qx = q, v = v)
-
-      costs = values$cashFlowsCosts;
-      pvc = costs * 0;
-
-      # survival cash flows (until death)
-      if (any(costs[,,,"survival"] != 0)) {
-        pvc[,,,"survival"] = pvf$survival(advance = costs[,,,"survival"]);
-      }
-      # guaranteed cash flows (even after death)
-      if (any(costs[,,,"guaranteed"] != 0)) {
-        pvc[,,,"guaranteed"] = pvf$guaranteed(advance = costs[,,,"guaranteed"]);
-      }
-
-      # Cash flows only after death
-      if (any(costs[,,,"after.death"] != 0)) {
-        pvc[,,,"after.death"] = pvf$afterDeath(advance = costs[,,,"after.death"]);
-      }
-
-      # Costs based on actual benefits need to be calculated separately
-      # (need to be recalculated with the benefit CFs multiplied by the cost
-      # rate for each type and each year). In most cases, the cost rates will be
-      # constant, but in general we can not assume this => need to re-calculate
-      if (any(values$cashFlowsCosts[,,"Benefits",] != 0)) {
-        bFreq = params$ContractData$benefitFrequency
-        benefitFreqCorr = correctionPaymentFrequency(
-          i = i, m = bFreq,
-          order = valueOrFunction(params$ActuarialBases$benefitFrequencyOrder, params = params, values = values));
-        pvfben = PVfactory$new(qx = q, m = bFreq, mCorrection = benefitFreqCorr, v = v);
-
-        cfCosts = values$cashFlowsCosts[,,"Benefits",];
-        cf = values$cashFlows;
-
-        # Guaranteed + Survival + Death cover + disease
-        pvc[,,"Benefits",] =
-            pvfben$guaranteed(cf$guaranteed_advance * cfCosts, cf$guaranteed_arrears * cfCosts) +
-            pvfben$survival(cf$survival_advance * cfCosts, cf$survival_arrears * cfCosts) +
-            pvfben$death(cf$death_SumInsured * cfCosts) +
-            pvfben$disease(cf$disease_SumInsured * cfCosts);
-      }
-
-      applyHook(hook = params$Hooks$adjustPresentValuesCosts, val = pvc, params = params, values = values, presentValues = presentValues)
-    },
-
-    #' @description Calculate the cash flows in monetary terms of the insurance contract
-    #' @details Once the premiums of the insurance contracts are calculated, all
-    #' cash flows can also be expressed in absolute terms. This function
-    #' calculates these time series in monetary terms, once the premiums
-    #' are calculated by the previous functions of this class.
-    #'
-    #' This method is NOT to be called directly, but implicitly by the [InsuranceContract] object.
-    getAbsCashFlows = function(params, values) {
-      if (getOption('LIC.debug.getAbsCashFlows', FALSE)) {
-        browser();
-      }
-
-      # TODO: Set up a nice list with coefficients for each type of cashflow,
-      # rather than multiplying each item manually (this also mitigates the risk
-      # of forgetting a dimension, because then the dimensions would not match,
-      # while here it's easy to overlook a multiplication)
-      # Multiply each CF column by the corresponding basis
-      #
-      # All propSI cash flows are already set up with the correct multiple
-      # of the sumInsured (in cashFlowsBasic) for non-constant sums insured.
-      # So here, we don't need to multiply with  values$cashFlowsBasic$sumInsured!
-      propGP = c("premiums_advance", "premiums_arrears");
-      propSI = c("guaranteed_advance", "guaranteed_arrears",
-                 "survival_advance", "survival_arrears", "death_SumInsured",
-                 "death_PremiumFree", "disease_SumInsured");
-      propPS = c("death_GrossPremium", "death_Refund_past");
-      values$cashFlows[,propGP] = values$cashFlows[,propGP] * values$premiums[["gross"]];
-      values$cashFlows[,propSI] = values$cashFlows[,propSI] * params$ContractData$sumInsured;
-      values$cashFlows[,propPS] = values$cashFlows[,propPS] * values$premiums[["gross"]] * params$ContractData$premiumRefund;
-
-      # Sum all death-related payments to "death"  and remove the death_GrossPremium column
-      values$cashFlows[,"death_SumInsured"] = values$cashFlows[,"death_SumInsured"] + values$cashFlows[,"death_GrossPremium"]
-      colnames(values$cashFlows)[colnames(values$cashFlows) == "death_SumInsured"] = "death";
-      # cashFlows[,"death_GrossPremium"] = NULL;
-
-      # costs relative to sumInsured are already set up as the correct multiple
-      # of the original SI, including the dynamic changes over time!
-      values$cashFlowsCosts = values$cashFlowsCosts[,,"SumInsured",] * params$ContractData$sumInsured +
-        values$cashFlowsCosts[,,"SumPremiums",] * values$unitPremiumSum * values$premiums[["gross"]] +
-        values$cashFlowsCosts[,,"GrossPremium",] * values$premiums[["gross"]] +
-        values$cashFlowsCosts[,,"NetPremium",] * values$premiums[["net"]] +
-        # values$cashFlowsCosts[,,"Benefits",] * TODO!!!
-        values$cashFlowsCosts[,,"Constant",];
-
-      # Handle survival CF differently, because we don't want ".survival" in the column names!
-      cbind(values$cashFlows, values$cashFlowsCosts[,,"survival"], values$cashFlowsCosts[,,-1])
-    },
-
-    #' @description Calculate the absolute present value time series of the insurance contract
-    #' @details Once the premiums of the insurance contracts are calculated, all
-    #' present values can also be expressed in absolute terms. This function
-    #' calculates these time series in monetary terms, once the premiums and the
-    #'  unit-benefit present values are calculated by the previous functions of
-    #'  this classe.
-    #'
-    #' This method is NOT to be called directly, but implicitly by the [InsuranceContract] object.
-    getAbsPresentValues = function(params, values) {
-      if (getOption('LIC.debug.getAbsPresentValues', FALSE)) {
-        browser();
-      }
-      pv = values$presentValues;
-
-      #pv[,"age"] = pv[,"premiums"];
-      #colnames(pv)[colnames(pv)=="age"] = "premiums.unit";
-
-      # Multiply each CF column by the corresponding basis
-      pv[,"premiums"] = pv[,"premiums"] * values$premiums[["gross"]];
-      pv[,c("guaranteed", "survival", "death_SumInsured", "disease_SumInsured", "death_PremiumFree")] =
-        pv[,c("guaranteed", "survival", "death_SumInsured", "disease_SumInsured", "death_PremiumFree")] * params$ContractData$sumInsured;
-      pv[,c("death_GrossPremium", "death_Refund_past", "death_Refund_future")] = pv[,c("death_GrossPremium", "death_Refund_past", "death_Refund_future")] * values$premiums[["gross"]] * params$ContractData$premiumRefund;
-      pv[,c("benefits", "additional_capital", "benefitsAndRefund", "alpha", "Zillmer", "beta", "gamma", "gamma_nopremiums", "unitcosts")] =
-        pv[,c("benefits", "additional_capital", "benefitsAndRefund", "alpha", "Zillmer", "beta", "gamma", "gamma_nopremiums", "unitcosts")] * params$ContractData$sumInsured;
-
-      # Sum all death-related payments to "death"  and remove the death_SumInsured column
-      pv[,"death_SumInsured"] = pv[,"death_SumInsured"] + pv[,"death_GrossPremium"]
-      colnames(pv)[colnames(pv) == "death_SumInsured"] = "death";
-
-      cbind("premiums.unit" = values$presentValues[,"premiums"], pv)
-    },
-
-
-    #' @description Calculate the absolute present value time series of the
-    #' benefits of the insurance contract
-    #' @details Once the premiums of the insurance contracts are calculated, all
-    #' present values can also be expressed in absolute terms. This function
-    #' calculates these time series of the benefits present values in monetary
-    #' terms, once the premiums and the unit-benefit present values are calculated
-    #'  by the previous functions of this classe.
-    #'
-    #' This method is NOT to be called directly, but implicitly by the [InsuranceContract] object.
-    presentValueBenefits = function(params, values) {
-      if (getOption('LIC.debug.presentValueBenefits', FALSE)) {
-        browser();
-      }
-      # TODO: Here we don't use the securityLoading parameter => Shall it be used or are these values to be understood without additional security loading?
-      benefits    = values$presentValues[,"survival"] +
-                    values$presentValues[,"guaranteed"] +
-                    values$presentValues[,"death_SumInsured"] +
-                    values$presentValues[,"disease_SumInsured"];
-      allBenefits = benefits +
-          values$presentValues[,"death_GrossPremium"] * values$premiums[["unit.gross"]] * params$ContractData$premiumRefund;
-      benefitsCosts = rowSums( # Sum over the fourth dimension, leave the first three intact
-        values$presentValuesCosts[,,"SumInsured",] +
-        values$presentValuesCosts[,,"SumPremiums",] * values$unitPremiumSum * values$premiums[["unit.gross"]] +
-        values$presentValuesCosts[,,"GrossPremium",] * values$premiums[["unit.gross"]] +
-        values$presentValuesCosts[,,"NetPremium",] * values$premiums[["unit.net"]] +
-        values$presentValuesCosts[,,"Constant",] / params$ContractData$sumInsured,
-        dims = 2)
-
-
-      cbind(
-        benefits = benefits,
-        benefitsAndRefund = allBenefits,
-        benefitsCosts)
-    },
-
-    #' @description Calculate the linear coefficients of the premium calculation formula for the insurance contract
-    #' @details Not to be called directly, but implicitly by the [InsuranceContract] object.
-    #' When \code{getPremiumCoefficients} is called, the \code{values$premiums}
-    #' array has NOT yet been filled! Instead, all premiums already calculated
-    #' (and required for the premium coefficients) are passed in the \code{premiums}
-    #' argument.
-    #'
-    #' @param type The premium that is supposed to be calculated ("gross", "Zillmer", "net")
-    #' @param coeffBenefits (empty) data structure of the benefit coefficients.
-    #'        The actual values have no meaning, this parameter is only used to
-    #'        derive the required dimensions
-    #' @param coeffCosts (empty) data structure of the cost coefficients. The
-    #'        actual values have no meaning, this parameter is only used to
-    #'        derive the required dimensions
-    #' @param premiums The premium components that have already been calculated
-    #'         (e.g. for net and Zillmer, the gross premium has already been
-    #'         calculated to allow modelling the premium refund)
-    getPremiumCoefficients = function(type = "gross", coeffBenefits, coeffCosts, premiums, params, values, premiumCalculationTime = values$int$premiumCalculationTime) {
-      if (getOption('LIC.debug.getPremiumCoefficients', FALSE)) {
-        browser();
-      }
-      # Merge a possibly passed loadings override with the defaults of this class:
-      securityLoading = valueOrFunction(params$Loadings$security, params = params, values = values);
-      t = as.character(premiumCalculationTime)
-
-      coeff = list(
-        "SumInsured" = list("benefits" = coeffBenefits*0, "costs" = coeffCosts*0),
-        "Premium"    = list("benefits" = coeffBenefits*0, "costs" = coeffCosts*0)
-      );
-
-      coeff[["Premium"]][["benefits"]][["premiums"]]            = 1;
-      if (!is.null(params$ContractData$sumInsured)) {
-          coeff[["SumInsured"]][["benefits"]][["additional_capital"]]            = -1 / params$ContractData$sumInsured;
-      } else {
-          coeff[["SumInsured"]][["benefits"]][["additional_capital"]]            = 0;
-      }
-
-      # Costs proportional to NetPremium introduce a non-linearity, as the NP is not available when the gross premium is calculated
-      # => the corresponding costs PV is included in the coefficient!
-      coeff.benefits = (1 + securityLoading);
-      if (type == "gross") {
-          # TODO: How to include this into the Zillmer premium calculation?
-          if (values$presentValues[[t,"premiums"]] != 0) {
-            coeff.benefits = coeff.benefits * (1 + sum(values$presentValuesCosts[t, c("alpha", "beta", "gamma"), "NetPremium",]) / values$presentValues[[t,"premiums"]])
-          }
-      }
-      coeff[["SumInsured"]][["benefits"]][["guaranteed"]]       = coeff.benefits;
-      coeff[["SumInsured"]][["benefits"]][["survival"]]         = coeff.benefits;
-      coeff[["SumInsured"]][["benefits"]][["death_SumInsured"]] = coeff.benefits;
-      coeff[["SumInsured"]][["benefits"]][["disease_SumInsured"]] = coeff.benefits;
-
-      # Premium refund is handled differently for gross and net premiums, because it is proportional to the gross premium
-      if (type == "gross") {
-        coeff[["Premium"]][["benefits"]][["death_GrossPremium"]] = -params$ContractData$premiumRefund * coeff.benefits;
-      } else if (type == "net" || type == "Zillmer") {
-        coeff[["SumInsured"]][["benefits"]][["death_GrossPremium"]] = premiums[["unit.gross"]] * params$ContractData$premiumRefund * (1 + securityLoading);
-      }
-
-
-      # coefficients for the costs
-
-      if (type == "gross") {
-        affected = c("alpha", "beta", "gamma")
-        if (params$Features$unitcostsInGross) {
-          affected = c(affected, "unitcosts")
-        }
-        coeff[["SumInsured"]][["costs"]][affected, "SumInsured",  ] = 1;
-        coeff[["SumInsured"]][["costs"]][affected, "Benefits",  ] = 1;
-        # TODO: How to handle beta costs proportional to Sum Insured
-        coeff[["Premium"]]   [["costs"]][affected, "SumPremiums", ] = -values$unitPremiumSum;
-        coeff[["Premium"]]   [["costs"]][affected, "GrossPremium",] = -1;
-        if (!is.null(params$ContractData$sumInsured)) {
-            coeff[["SumInsured"]][["costs"]][affected, "Constant",    ] = 1 / params$ContractData$sumInsured;
-        } else {
-            coeff[["SumInsured"]][["costs"]][affected, "Constant",    ] = 0;
-        }
-      } else if (type == "Zillmer") {
-          # TODO: Include costs with basis NetPremium and fixed costs!
-        affected = c("Zillmer")
-        if (params$Features$betaGammaInZillmer) {
-          affected = c(affected, "beta", "gamma")
-        }
-        coeff[["SumInsured"]][["costs"]][affected,"SumInsured",  ] = 1;
-        coeff[["SumInsured"]][["costs"]][affected,"SumPremiums", ] = values$unitPremiumSum * premiums[["unit.gross"]];
-        coeff[["SumInsured"]][["costs"]][affected,"GrossPremium",] = premiums[["unit.gross"]];
-      }
-
-      applyHook(params$Hooks$adjustPremiumCoefficients, coeff, type = type, premiums = premiums, params = params, values = values, premiumCalculationTime = premiumCalculationTime)
-    },
-
-    #' @description Calculate the sumInsured of the InsuranceContract given the
-    #' parameters and premiums given and teh , present values already calculated and
-    #' stored in the \code{params} and \code{values} lists.
-    #' @param calculationTime the time when the sumInsured should be recalculated from the given premium
-    #'
-    #' @details Not to be called directly, but implicitly by the [InsuranceContract] object.
-    sumInsuredCalculation = function(params, values, calculationTime = values$int$premiumCalculationTime) {
-      if (getOption('sumInsuredCalculation', FALSE)) {
-        browser();
-      }
-      loadings = params$Loadings;
-      values$premiums = c(
-        "unit.net" = 0, "unit.Zillmer" = 0, "unit.gross" = 0,
-        "net" = 0, "Zillmer" = 0, "gross" = 0,
-        "unitcost" = 0, "written_yearly" = 0,
-        "written_beforetax" = 0, "tax" = 0, "written" = 0, "additional_capital" = 0);
-      coefficients = list("gross" = c(), "Zillmer" = c(), "net" = c());
-
-      # Get the present values of the premiums, claims and costs at time 'calculationTime' (where the premium is to be calculated)
-      t = as.character(calculationTime)
-      pv = values$presentValues[t,]
-      pvCost = values$presentValuesCosts[t,,,]
-
-      #======================================================================== =
-      # Calculate sumInsured from Premium, if needed
-      # ======================================================================= =
-      sumInsured = 1
-      params$ContractData$sumInsured = 1 # Temporarily set to 1!
-
-      # Premium type can be given using a named array, e.g. premium = c(gross = 1000)
-      premiumtype = names(params$ContractData$premium)
-      if (is.null(premiumtype)) premiumtype = "written";
-      premium = unname(params$ContractData$premium);
-      # if ((premium == 0) || (params$ContractData$premiumPeriod == 0)) premiumtype = "noPremium";
-      calculating = FALSE;
-
-
-      # Calculate unit gross premium (sumInsured=1)
-      values$premiums["additional_capital"] = values$cashFlows[t, "additional_capital"]
-      coeff = self$getPremiumCoefficients("gross", pv * 0, pvCost * 0, premiums = values$premiums, params = params, values = values, premiumCalculationTime = calculationTime)
-      #### BEGIN TWEAK_RK 21.1.2023
-      # Since we don't know the sumInsured, the initial capital cannot be scaled to sumInsured=1 => handle differently!
-      # Calculate pv of benefits without initialCapital:
-      coeff.initialCapital = coeff[["SumInsured"]][["benefits"]][["additional_capital"]]
-      coeff[["SumInsured"]][["benefits"]][["additional_capital"]] = 0
-      #### END TWEAK_RK 21.1.2023
-
-      enumerator  = sum(coeff[["SumInsured"]][["benefits"]] * pv) + sum(coeff[["SumInsured"]][["costs"]] * pvCost);
-      denominator = sum(coeff[["Premium"   ]][["benefits"]] * pv) + sum(coeff[["Premium"   ]][["costs"]] * pvCost);
-      if (is.na(denominator) || (denominator == 0)) {
-        values$premiums[["unit.gross"]] = 0;
-        denominator = 1
-      } else {
-        values$premiums[["unit.gross"]] = enumerator/denominator * (1 + loadings$ongoingAlphaGrossPremium);
-      }
-
-      # Calculate other premium components:
-      # ATTENTION: This will not work if any of these depend on the absolute values of the premiums, or depend on net or Zillmer premium!
-      tax           = valueOrFunction(loadings$tax,          params = params, values = values);
-      unitCosts     = valueOrFunction(loadings$unitcosts,    params = params, values = values);
-      noMedicalExam = valueOrFunction(loadings$noMedicalExam,params = params, values = values);
-      noMedicalExam.relative = valueOrFunction(loadings$noMedicalExamRelative,params = params, values = values);
-      extraRebate   = valueOrFunction(loadings$extraRebate,  params = params, values = values);
-      sumRebate     = valueOrFunction(loadings$sumRebate,    params = params, values = values);
-      premiumRebateRate = valueOrFunction(loadings$premiumRebate,params = params, values = values);
-      premiumRebate = applyHook(params$Hooks$premiumRebateCalculation, premiumRebateRate, params = params, values = values);
-
-      extraChargeGrossPremium = valueOrFunction(loadings$extraChargeGrossPremium, params = params, values = values);
-      advanceProfitParticipation = 0;
-      advanceProfitParticipationUnitCosts = 0;
-      ppScheme      = params$ProfitParticipation$profitParticipationScheme;
-      if (!is.null(ppScheme)) {
-        advanceProfitParticipation = ppScheme$getAdvanceProfitParticipation(params = params, values = values)
-        advanceProfitParticipationUnitCosts = ppScheme$getAdvanceProfitParticipationAfterUnitCosts(params = params, values = values)
-      }
-      if (is.null(advanceProfitParticipation)) advanceProfitParticipation = 0;
-      if (is.null(advanceProfitParticipationUnitCosts)) advanceProfitParticipationUnitCosts = 0;
-
-      partnerRebate = valueOrFunction(loadings$partnerRebate, params = params, values = values);
-
-      # Start from the given premium to derive the sumInsured step-by-step:
-      temp = premium
-      #
-      # Written premium after tax
-      calculating = calculating | (premiumtype == "written");
-      if (calculating) {
-        temp = temp / (1 + tax);
-      }
-      # Written premium before tax
-      calculating = calculating | (premiumtype == "written_beforetax");
-      if (calculating) {
-        temp = temp / (1 - premiumRebate - advanceProfitParticipationUnitCosts - partnerRebate);
-
-        pv.unitcosts = sum(
-          pvCost["unitcosts","SumInsured",] * sumInsured +
-            pvCost["unitcosts","SumPremiums",] * values$unitPremiumSum * values$premiums[["gross"]] +
-            pvCost["unitcosts","GrossPremium",] * values$premiums[["gross"]] +
-            pvCost["unitcosts","NetPremium",] * values$premiums[["net"]] +
-            pvCost["unitcosts","Constant",]
-        )
-        if (pv[["premiums"]] == 0) {
-          premium.unitcosts = 0
-        } else {
-          premium.unitcosts = pv.unitcosts / pv[["premiums"]] + valueOrFunction(loadings$unitcosts, params = params, values = values);
-        }
-        if (!params$Features$unitcostsInGross) {
-          temp = temp - premium.unitcosts;
-        }
-        temp = temp / (1 - advanceProfitParticipation)
-      }
-      calculating = calculating | (premiumtype == "gross");
-      if (calculating) {
-        # handle initialCapital here (coefficient for initialCapital is typically negative, as it reduces the premium!)
-        temp = temp - coeff.initialCapital * values$premiums[["additional_capital"]] / denominator;
-        temp = temp /
-          (enumerator / denominator * (1 + noMedicalExam.relative + extraChargeGrossPremium) + noMedicalExam - sumRebate - extraRebate);
-      }
-      sumInsured = temp
-
-      sumInsured
-    },
-
-    #' @description Calculate the premiums of the InsuranceContract given the
-    #' parameters, present values and premium cofficients already calculated and
-    #' stored in the \code{params} and \code{values} lists.
-    #'
-    #' @details Not to be called directly, but implicitly by the [InsuranceContract] object.
-    premiumCalculation = function(params, values, premiumCalculationTime = values$int$premiumCalculationTime) {
-      if (getOption('LIC.debug.premiumCalculation', FALSE)) {
-        browser();
-      }
-      loadings = params$Loadings;
-      sumInsured = params$ContractData$sumInsured
-      values$premiums = c(
-        "unit.net" = 0, "unit.Zillmer" = 0, "unit.gross" = 0,
-        "net" = 0, "Zillmer" = 0, "gross" = 0,
-        "unitcost" = 0, "written_yearly" = 0,
-        "written_beforetax" = 0, "tax" = 0, "written" = 0, "additional_capital" = 0);
-      coefficients = list("gross" = c(), "Zillmer" = c(), "net" = c());
-
-      # Get the present values of the premiums, claims and costs at time 'premiumCalculationTime' (where the premium is to be calculated)
-      t = as.character(premiumCalculationTime)
-      pv = values$presentValues[t,]
-      pvCost = values$presentValuesCosts[t,,,]
-
-      values$premiums["additional_capital"] = values$cashFlows[t, "additional_capital"]
-
-      # If there are no premium payments, no need to calculate premium components
-      # if (pv[["premiums"]] == 0) {
-      #   return(list("premiums" = values$premiums, "coefficients" = coefficients, "sumInsured" = params$ContractData$sumInsured))
-      # }
-
-
-
-      #======================================================================== =
-      # net, gross and Zillmer premiums are calculated from the present values using the coefficients on each present value as described in the formulas document
-      # ======================================================================= =
-      # GROSS Premium
-      # ----------------------------------------------------------------------- -
-      coeff = self$getPremiumCoefficients("gross", pv * 0, pvCost * 0, premiums = values$premiums, params = params, values = values, premiumCalculationTime = premiumCalculationTime)
-      enumerator  = sum(coeff[["SumInsured"]][["benefits"]] * pv) + sum(coeff[["SumInsured"]][["costs"]] * pvCost);
-      denominator = sum(coeff[["Premium"   ]][["benefits"]] * pv) + sum(coeff[["Premium"   ]][["costs"]] * pvCost);
-      values$premiums[["unit.gross"]] = enumerator/ifelse(denominator == 0, 1, denominator) * (1 + loadings$ongoingAlphaGrossPremium);
-      values$premiums[["gross"]] = values$premiums[["unit.gross"]] * sumInsured;
-      coefficients[["gross"]] = coeff;
-
-      # ======================================================================= =
-      # NET Premium
-      # ----------------------------------------------------------------------- -
-      coeff = self$getPremiumCoefficients("net", pv*0, pvCost*0, premiums = values$premiums, params = params, values = values, premiumCalculationTime = premiumCalculationTime)
-      enumerator  = sum(coeff[["SumInsured"]][["benefits"]] * pv) + sum(coeff[["SumInsured"]][["costs"]] * pvCost);
-      denominator = sum(coeff[["Premium"   ]][["benefits"]] * pv) + sum(coeff[["Premium"   ]][["costs"]] * pvCost);
-      values$premiums[["unit.net"]] = enumerator/ifelse(denominator == 0, 1, denominator);
-      values$premiums[["net"]] = values$premiums[["unit.net"]] * sumInsured;
-      coefficients[["net"]] = coeff;
-
-      # ======================================================================= =
-      # ZILLMER Premium
-      # ----------------------------------------------------------------------- -
-      coeff = self$getPremiumCoefficients("Zillmer", pv * 0, pvCost * 0, premiums = values$premiums, params = params, values = values, premiumCalculationTime = premiumCalculationTime);
-      enumerator  = sum(coeff[["SumInsured"]][["benefits"]] * pv) + sum(coeff[["SumInsured"]][["costs"]] * pvCost);
-      denominator = sum(coeff[["Premium"   ]][["benefits"]] * pv) + sum(coeff[["Premium"   ]][["costs"]] * pvCost);
-      values$premiums[["unit.Zillmer"]] = enumerator/ifelse(denominator == 0, 1, denominator);
-      values$premiums[["Zillmer"]] = values$premiums[["unit.Zillmer"]] * sumInsured;
-      coefficients[["Zillmer"]] = coeff;
-
-
-      # ======================================================================= =
-      # Additional premium components (after gross premium)
-      # ----------------------------------------------------------------------- -
-      # The written premium is the gross premium with additional loadings, rebates, unit costs and taxes
-      tax           = valueOrFunction(loadings$tax,          params = params, values = values);
-      unitCosts     = valueOrFunction(loadings$unitcosts,    params = params, values = values);
-      noMedicalExam = valueOrFunction(loadings$noMedicalExam,params = params, values = values);
-      noMedicalExam.relative = valueOrFunction(loadings$noMedicalExamRelative,params = params, values = values);
-      extraRebate   = valueOrFunction(loadings$extraRebate,  params = params, values = values);
-      sumRebate     = valueOrFunction(loadings$sumRebate,    params = params, values = values);
-      premiumRebateRate = valueOrFunction(loadings$premiumRebate,params = params, values = values);
-      premiumRebate = applyHook(params$Hooks$premiumRebateCalculation, premiumRebateRate, params = params, values = values);
-
-      extraChargeGrossPremium = valueOrFunction(loadings$extraChargeGrossPremium, params = params, values = values);
-      advanceProfitParticipation = 0;
-      advanceProfitParticipationUnitCosts = 0;
-      ppScheme      = params$ProfitParticipation$profitParticipationScheme;
-      if (!is.null(ppScheme)) {
-          advanceProfitParticipation = ppScheme$getAdvanceProfitParticipation(params = params, values = values)
-          advanceProfitParticipationUnitCosts = ppScheme$getAdvanceProfitParticipationAfterUnitCosts(params = params, values = values)
-      }
-      if (is.null(advanceProfitParticipation)) advanceProfitParticipation = 0;
-      if (is.null(advanceProfitParticipationUnitCosts)) advanceProfitParticipationUnitCosts = 0;
-
-      partnerRebate = valueOrFunction(loadings$partnerRebate, params = params, values = values);
-
-      pv.unitcosts = sum(
-        pvCost["unitcosts","SumInsured",] * sumInsured +
-        pvCost["unitcosts","SumPremiums",] * values$unitPremiumSum * values$premiums[["gross"]] +
-        pvCost["unitcosts","GrossPremium",] * values$premiums[["gross"]] +
-        pvCost["unitcosts","NetPremium",] * values$premiums[["net"]] +
-        pvCost["unitcosts","Constant",]
-      )
-      premium.unitcosts = ifelse(pv[["premiums"]] == 0, 0, pv.unitcosts / pv[["premiums"]] + valueOrFunction(loadings$unitcosts, params = params, values = values));
-
-
-      frequencyLoading = self$evaluateFrequencyLoading(loadings$premiumFrequencyLoading, params$ContractData$premiumFrequency, params = params, values = values)
-      premiumBeforeTax = (values$premiums[["unit.gross"]]*(1 + noMedicalExam.relative + extraChargeGrossPremium) + noMedicalExam - sumRebate - extraRebate) * sumInsured * (1 - advanceProfitParticipation);
-      if (!params$Features$unitcostsInGross) {
-        premiumBeforeTax = premiumBeforeTax + premium.unitcosts;
-      }
-      premiumBeforeTax = premiumBeforeTax * (1 - premiumRebate - advanceProfitParticipationUnitCosts - partnerRebate);
-      premiumBeforeTax.y = premiumBeforeTax * (1 + frequencyLoading);
-      premiumBeforeTax = premiumBeforeTax.y / params$ContractData$premiumFrequency;
-      values$premiums[["written_yearly"]] = premiumBeforeTax.y * (1 + tax)
-      values$premiums[["written_beforetax"]] = premiumBeforeTax;
-      values$premiums[["tax"]] = premiumBeforeTax * tax;
-      values$premiums[["written"]] = premiumBeforeTax * (1 + tax);
-
-      applyHook(
-        params$Hooks$adjustPremiums,
-        list("premiums" = values$premiums, "coefficients" = coefficients, "sumInsured" = params$ContractData$sumInsured),
-        params = params, values = values
-      )
-    },
-
-    #' @description Calculate the reserves of the InsuranceContract given the
-    #' parameters, present values and premiums already calculated and stored in
-    #' the \code{params} and \code{values} lists.
-    #'
-    #' @details Not to be called directly, but implicitly by the [InsuranceContract] object.
-    reserveCalculation = function(params, values) {
-      if (getOption('LIC.debug.reserveCalculation', FALSE)) {
-        browser();
-      }
-      t = "0"
-      securityFactor = (1 + valueOrFunction(params$Loadings$security, params = params, values = values));
-      ppScheme      = params$ProfitParticipation$profitParticipationScheme;
-
-      absPV = applyHook(params$Hooks$adjustPVForReserves, values$absPresentValues, params = params, values = values);
-
-      # Net, Zillmer and Gross reserves
-      resNet = absPV[,"benefitsAndRefund"] * securityFactor - values$premiums[["net"]] * absPV[,"premiums.unit"];
-      BWZcorr = ifelse(absPV[t, "premiums"] == 0, 0,
-                       absPV[t, "Zillmer"] / absPV[t, "premiums"]) * absPV[,"premiums"];
-      resZ = resNet - BWZcorr;
-
-      resAdeq = absPV[,"benefitsAndRefund"] * securityFactor +
-          absPV[,"alpha"] + absPV[,"beta"] + absPV[,"gamma"] -
-        values$premiums[["gross"]] * absPV[,"premiums.unit"];
-      if (params$Features$unitcostsInGross) {
-          resAdeq = resAdeq + absPV[, "unitcosts"]
-      }
-
-      resGamma = absPV[,"gamma"] -
-        ifelse(absPV[t, "premiums"] == 0, 0,
-               absPV[t, "gamma"] / absPV[t, "premiums"]) * absPV[,"premiums"]
-
-
-      advanceProfitParticipation = 0;
-      if (!is.null(ppScheme)) {
-          advanceProfitParticipation = ppScheme$getAdvanceProfitParticipation(params = params, values = values)
-      }
-
-      # Alpha refund: Distribute alpha-costs to 5 years (or if shorter, the policy period), always starting at time 0:
-      # If alphaRefunded==TRUE, don't refund a second time!
-      if (params$ContractState$alphaRefunded) {
-        alphaRefund = 0
-      } else {
-        r = min(params$ContractData$policyPeriod, params$Loadings$alphaRefundPeriod);
-        ZillmerSoFar = Reduce("+", values$absCashFlows$Zillmer, accumulate = TRUE);
-        ZillmerTotal = sum(values$absCashFlows$Zillmer);
-        len = length(ZillmerSoFar);
-        if (params$Features$alphaRefundLinear) {
-          ZillmerVerteilungCoeff = pad0((0:r)/r, len, 1);
-        } else {
-          q = self$getTransitionProbabilities(params, values);
-          pvf = PVfactory$new(qx = q, v = 1/(1 + params$ActuarialBases$i))
-          # vector of all ä_{x+t, r-t}
-          pvAlphaTmp = pvf$survival(advance = pad0(rep(1,r), len))
-          ZillmerVerteilungCoeff = (1 - pvAlphaTmp/pvAlphaTmp[[1]]);
-        }
-        alphaRefund = ZillmerSoFar - ZillmerVerteilungCoeff * ZillmerTotal;
-      }
-
-      # Reduction Reserve: Reserve used for contract modifications:
-      if (params$Features$zillmering) {
-        resContractual = resZ + resGamma
-        resReduction = resZ + alphaRefund;
-      } else {
-        resContractual = resAdeq + resGamma
-        resReduction = resAdeq + alphaRefund;
-      }
-      resConversion = resContractual * (1 - advanceProfitParticipation);
-      if (params$Features$surrenderIncludesCostsReserves) {
-        resReduction = resReduction + resGamma;
-      }
-      resReduction = pmax(0, resReduction) # V_{x,n}^{Rkf}
-
-      # Collect all reserves to one large matrix
-      res = cbind(
-            "SumInsured"  = head0(rep(params$ContractData$sumInsured, values$int$l)),
-            "net"         = resNet,
-            "Zillmer"     = resZ,
-            "adequate"    = resAdeq,
-            "gamma"       = resGamma,
-            "contractual" = resContractual,
-            "conversion"  = resConversion,
-            "alphaRefund" = alphaRefund,
-            "reduction"   = resReduction
-            #, "Reserve.premiumfree"=res.premiumfree, "Reserve.gamma.premiumfree"=res.gamma.premiumfree);
-      );
-      rownames(res) <- rownames(absPV);
-      values$reserves = res;
-
-      # The surrender value functions can have arbitrary form, so we store a function
-      # here in the tarif and call that, passing the reduction reserve as
-      # starting point, but also all reserves, cash flows, premiums and present values
-      if (!params$ContractState$surrenderPenalty) {
-          # No surrender penalty any more (has already been applied to the first contract change!)
-          surrenderValue = resReduction;
-      } else if (!is.null(params$ActuarialBases$surrenderValueCalculation)) {
-          surrenderValue = params$ActuarialBases$surrenderValueCalculation(resReduction, params, values);
-      } else {
-          # by default, refund the full reduction reserve, except the advance profit participation, which is also included in the reserve, but not charged on the premium!
-          advanceProfitParticipationUnitCosts = 0;
-          ppScheme      = params$ProfitParticipation$profitParticipationScheme;
-          if (!is.null(ppScheme)) {
-              advanceProfitParticipationUnitCosts = ppScheme$getAdvanceProfitParticipationAfterUnitCosts(params = params, values = values)
-          }
-          partnerRebate = valueOrFunction(params$Loadings$partnerRebate, params = params, values = values);
-          surrenderValue = resReduction * (1 - advanceProfitParticipationUnitCosts - partnerRebate);
-      }
-
-
-      # Calculate new sum insured after premium waiver
-      if (!is.null(params$ActuarialBases$premiumWaiverValueCalculation)) {
-        premiumfreeValue = params$ActuarialBases$premiumWaiverValueCalculation(resReduction, params, values);
-      } else {
-        premiumfreeValue = surrenderValue
-      }
-      Storno = 0; # TODO: Implement storno costs
-      premiumfreePV = (absPV[, "benefits"] * securityFactor + absPV[, "gamma_nopremiums"]); # PV of future premium free claims + costs
-      newSI = ifelse(premiumfreePV == 0, 0,
-        (premiumfreeValue - absPV[,"death_Refund_past"] * securityFactor - c(Storno)) /
-        premiumfreePV * params$ContractData$sumInsured);
-
-      cbind(res,
-            "PremiumsPaid" = Reduce("+", values$absCashFlows$premiums_advance, accumulate = TRUE),
-            "Surrender" = surrenderValue,
-            "PremiumFreeSumInsured" = newSI
-      )
-    },
-
-    #' @description Calculate the (linear) interpolation factors for the balance
-    #' sheet reserve (Dec. 31) between the yearly contract closing dates
-    #' @details Not to be called directly, but implicitly by the [InsuranceContract] object.
-    #' @param method The method for the balance sheet interpolation (30/360, act/act, act/360, act/365 or a function)
-    #' @param years how many years to calculate (for some usances, the factor
-    #'      is different in leap years!)
-    getBalanceSheetReserveFactor = function(method, params, years = 1) {
-      if (getOption('LIC.debug.getBalanceSheetReserveFactor', FALSE)) {
-        browser();
-      }
-      balanceDate = params$ActuarialBases$balanceSheetDate
-      year(balanceDate) = year(params$ContractData$contractClosing);
-      if (balanceDate < params$ContractData$contractClosing) {
-        balanceDate = balanceDate + years(1);
-      }
-
-      # contractDates = params$ContractData$contractClosing + years(1:years);
-      # balanceDates = balanceDate + years(1:years - 1);
-      contractDates = seq(params$ContractData$contractClosing, length.out = years, by = "year")
-      balanceDates = seq(balanceDate, length.out = years, by = "year")
-
-      if (is.function(method)) {
-        baf = method(params = params, contractDates = contractDates, balanceDates = balanceDates)
-      } else if (method == "30/360") {
-        baf = ((month(balanceDates + days(1)) - month(contractDates) - 1) %% 12 + 1) / 12
-      } else if (method == "act/act") {
-        baf = as.numeric((balanceDates + days(1)) - contractDates, units = "days" ) / as.numeric(balanceDates - (balanceDates - years(1)), units = "days")
-      } else if (method == "act/360") {
-        baf = pmin(as.numeric((balanceDates + days(1)) - contractDates, units = "days" ) / 360, 1)
-      } else if (method == "act/365") {
-        baf = pmin(as.numeric((balanceDates + days(1)) - contractDates, units = "days" ) / 365, 1)
-      }
-      data.frame(date = balanceDates, time = baf + (1:years) - 1, baf = baf)
-    },
-
-    #' @description Calculate the reserves for the balance sheets at Dec. 31 of each
-    #'              year by interpolation from the contract values calculated for
-    #'              the yearly reference date of the contract
-    #' @details Not to be called directly, but implicitly by the [InsuranceContract] object.
-    reserveCalculationBalanceSheet = function(params, values) {
-      if (getOption('LIC.debug.reserveCalculationBalanceSheet', FALSE)) {
-        browser();
-      }
-      reserves = values$reserves;
-      years = length(reserves[,"Zillmer"]);
-      # Balance sheet reserves:
-      factors = self$getBalanceSheetReserveFactor(method = params$ActuarialBases$balanceSheetMethod, params = params, years = years);
-      baf = factors$baf
-      factors$baf = NULL
-
-      useUnearnedPremiums = valueOrFunction(params$Features$useUnearnedPremiums, params = params, values = values)
-      resN_BS = (1 - baf) * (reserves[,"net"] + if (!useUnearnedPremiums) values$premiumComposition[,"net"] else 0) + baf * c(reserves[-1, "net"], 0)
-      resZ_BS = (1 - baf) * (reserves[,"Zillmer"] + if (!useUnearnedPremiums) values$premiumComposition[,"Zillmer"] else 0) + baf * c(reserves[-1, "Zillmer"], 0)
-      resGamma_BS = (1 - baf) * (reserves[,"gamma"] + if (!useUnearnedPremiums) values$premiumComposition[,"gamma"] else 0) + baf * c(reserves[-1, "gamma"], 0)
-      resGross_BS = (1 - baf) * (reserves[,"adequate"] + if (!useUnearnedPremiums) sum(values$premiumComposition[,c("alpha", "beta", "gamma")]) else 0) + baf * c(reserves[-1, "adequate"], 0)
-      if (params$Features$zillmering) {
-        res_BS = resZ_BS + resGamma_BS;
-      } else {
-        res_BS = resGross_BS;
-      }
-
-      # Premium transfer / unearned premium:
-      if (useUnearnedPremiums) {
-        fact = valueOrFunction(params$ActuarialBases$unearnedPremiumsMethod, params = params, dates = factors$date)
-        if (is.null(fact) || is.na(fact)) {
-          freq = params$ContractData$premiumFrequency
-          bm = month(params$ContractData$contractClosing)
-
-                    fact = (bm - month(factors$date) + 12 - 1) %% (12/freq) * (freq/12)
-        }
-        # TODO: We have no vector of actual written premiums (implicit assumption
-        # seems to be that the premium stays constant!). Once we have such a vector,
-        # rewrite the following code
-        unearnedPremiums = fact * values$cashFlows$premiums_advance * values$premiums[["written_beforetax"]] # TODO
-        # If advance profit participation is granted, unearned premiums still apply to the whole gross premium without PP and partner rebate!
-        ppScheme      = params$ProfitParticipation$profitParticipationScheme;
-        if (!is.null(ppScheme)) {
-          partnerRebate = valueOrFunction(params$Loadings$partnerRebate, params = params, values = values);
-          advanceProfitParticipation = ppScheme$getAdvanceProfitParticipationAfterUnitCosts(params = params, values = values);
-          unearnedPremiums = unearnedPremiums / (1 - partnerRebate - advanceProfitParticipation);
-        }
-      } else {
-        # If reserves contain single-premium, no unearned premiums are shown in the balance sheet!
-        unearnedPremiums = 0
-      }
-
-      # Collect all reserves to one large matrix
-      res = cbind(factors,
-                  "net"                   = pmax(resN_BS,0),
-                  "Zillmer"               = pmax(resZ_BS,0),
-                  "gamma"                 = pmax(resGamma_BS,0),
-                  "gross"                 = pmax(resGross_BS,0),
-                  "Balance Sheet Reserve" = pmax(res_BS,0),
-                  "unearned Premiums"     = unearnedPremiums
-      );
-      rownames(res) <- rownames(reserves);
-      res
-    },
-
-    #' @description Calculate the profit participation given the contract
-    #' parameters and the already calculated reserves of the contract.
-    #'
-    #' @details Not to be called directly, but implicitly by the [InsuranceContract] object.
-    #' @param ... Additional parameters for the profit participation calculation, passed
-    #'            through to the profit participation scheme's \href{../../LifeInsuranceContracts/html/ProfitParticipation.html#method-getProfitParticipation}{\code{ProfitParticipation$getProfitParticipation()}}
-    calculateProfitParticipation = function(params, ...) {
-      if (getOption('LIC.debug.calculateProfitParticipation', FALSE)) {
-        browser();
-      }
-      ppScheme = params$ProfitParticipation$profitParticipationScheme;
-        if (!is.null(ppScheme)) {
-            ppScheme$getProfitParticipation(params = params, ...)
-        }
-    },
-
-    #' @description Calculate the reserves after profit participation for the given profit scenario
-    #' @details Not to be called directly, but implicitly by the [InsuranceContract] object.
-    #' @param profitScenario The ID of the profit scenario for which to calculate the reserves
-    #' @param ... TODO
-    reservesAfterProfit = function(profitScenario, params, values, ...) {
-      if (getOption('LIC.debug.reservesAfterProfit', FALSE)) {
-        browser();
-      }
-      # TODO
-    },
-
-
-    #' @description Return the time series of the basic contract
-    #' @details Not to be called directly, but implicitly by the [InsuranceContract] object.
-    getBasicDataTimeseries = function(params, values) {
-      if (getOption('LIC.debug.getBasicDataTimeseries', FALSE)) {
-        browser();
-      }
-      res = cbind(
-            "PremiumPayment" = values$premiumComposition[, "charged"] > 0,
-            "SumInsured" = values$reserves[, "SumInsured"],
-            "Premiums" = values$absCashFlows$premiums_advance + values$absCashFlows$premiums_arrears,
-            "InterestRate" = rep(params$ActuarialBases$i, values$int$l),
-            "PolicyDuration" = rep(values$int$policyTerm, values$int$l),
-            "PremiumPeriod" = rep(values$int$premiumTerm, values$int$l)
-        );
-        rownames(res) = 0:(values$int$l-1);
-        res
-    },
-
-    #' @description Calculate the time series of the premium decomposition of the contract
-    #' @details Not to be called directly, but implicitly by the [InsuranceContract] object.
-    #'          All premiums, reserves and present values have already been calculated.
-    premiumDecomposition = function(params, values) {
-      if (getOption('LIC.debug.premiumDecomposition', FALSE)) {
-        browser();
-      }
-      loadings   = params$Loadings;
-      sumInsured = params$ContractData$sumInsured;
-      premiums   = values$premiums;
-      v          = 1/(1 + params$ActuarialBases$i);
-      l          = dim(values$reserves)[[1]];
-      ppScheme   = params$ProfitParticipation$profitParticipationScheme;
-      t          = as.character(0) # Time for original premium calculation => TODO: Use values stored in ContractData?
-
-      # TODO: This assumes all premiums are paid in advance!
-      premium.gross    = values$absCashFlows[,"premiums_advance"];
-
-      # First get the charges and rebates that are added to the gross premium to obtain the charged premium:
-
-      # charge for no medical exam:
-      extraChargeGrossPremium = valueOrFunction(loadings$extraChargeGrossPremium, params = params, values = values);
-      noMedExam        = valueOrFunction(loadings$noMedicalExam,params = params, values = values);
-      noMedExam.rel    = valueOrFunction(loadings$noMedicalExamRelative,params = params, values = values);
-      withMedExam      = premium.gross * (1 + noMedExam.rel + extraChargeGrossPremium) + noMedExam * sumInsured;
-      charge.noMedicalExam = withMedExam - premium.gross;
-
-      # sum rebate:
-      sumRebate        = valueOrFunction(loadings$sumRebate,    params = params, values = values);
-      extraRebate      = valueOrFunction(loadings$extraRebate,  params = params, values = values);
-      afterSumRebate   = withMedExam - (sumRebate + extraRebate) * sumInsured; # calculate the charge as the difference, because we want a vector!
-      rebate.sum       = afterSumRebate - withMedExam;
-
-      # advance profit participation has two parts, one before and one after unit costs. Part 1:
-      advanceProfitParticipation = 0;
-      if (!is.null(ppScheme)) {
-          advanceProfitParticipation = ppScheme$getAdvanceProfitParticipation(params = params, values = values)
-      }
-      afterProfit      = afterSumRebate * (1 - advanceProfitParticipation);
-      profits.advance  = afterProfit - afterSumRebate;
-
-      # unit costs
-      unitCosts        = premiums[["unitcost"]];
-      # unit costs are only charged if a premium is paid, so exclude all times with premium==0!
-      if (!params$Features$unitcostsInGross) {
-          afterUnitCosts   = afterProfit + (afterProfit != 0)*unitCosts;
-          unitcosts        = afterUnitCosts - afterProfit;
-      } else {
-          afterUnitCosts   = afterProfit;
-          unitcosts        = 0;
-      }
-
-      # advance profit participation, Part 2:
-      advanceProfitParticipationUnitCosts = 0;
-      if (!is.null(ppScheme)) {
-          advanceProfitParticipationUnitCosts = ppScheme$getAdvanceProfitParticipationAfterUnitCosts(params = params, values = values)
-      }
-      afterProfit      = afterUnitCosts * (1 - advanceProfitParticipationUnitCosts);
-      profits.advance  = profits.advance + afterProfit - afterUnitCosts;
-
-      # premium rebate
-      premiumRebateRate = valueOrFunction(loadings$premiumRebate,params = params, values = values);
-      premiumRebate = applyHook(params$Hooks$premiumRebateCalculation, premiumRebateRate, params = params, values = values);
-
-      afterPremiumRebate = afterUnitCosts * (1 - premiumRebate);
-      rebate.premium   = afterPremiumRebate - afterUnitCosts;
-
-      # partner rebate
-      partnerRebate    = valueOrFunction(loadings$partnerRebate,params = params, values = values);
-      afterPartnerRebate = afterUnitCosts * (1 - partnerRebate);
-      rebate.partner   = afterPartnerRebate - afterUnitCosts;
-
-      # value after all rebates
-      afterRebates     = afterProfit + rebate.premium + rebate.partner;
-
-      # premium frequency loading
-            frequencyLoading = self$evaluateFrequencyLoading(loadings$premiumFrequencyLoading, params$ContractData$premiumFrequency, params = params, values = values)
-
-            afterFrequency   = afterRebates * (1 + frequencyLoading);
-      charge.frequency = afterFrequency - afterRebates;
-
-      # insurance tax
-      taxRate          = valueOrFunction(loadings$tax,          params = params, values = values);
-      premium.charged  = afterFrequency * (1 + taxRate);
-      tax              = premium.charged - afterFrequency;
-
-
-      # Gross premium = net + zillmeredAlpha + unzillmeredAlpha + beta + gamma premium
-      unit.premiumCF   = if (premiums[["gross"]] == 0) { premium.gross * 0 } else { premium.gross / premiums[["gross"]] }
-      if (values$absPresentValues[t, "premiums.unit"] == 0) {
-        premium.gamma    = 0
-        premium.beta     = 0
-        premium.alpha    = 0
-        premium.alpha.Zillmer = 0
-      } else {
-        premium.gamma    = unit.premiumCF * values$absPresentValues[t, "gamma"] / values$absPresentValues[t, "premiums.unit"];
-        premium.beta     = unit.premiumCF * values$absPresentValues[t, "beta"]  / values$absPresentValues[t, "premiums.unit"];
-        premium.alpha    = unit.premiumCF * values$absPresentValues[t, "alpha"] / values$absPresentValues[t, "premiums.unit"];
-        premium.alpha.Zillmer = unit.premiumCF * values$absPresentValues[t, "Zillmer"] / values$absPresentValues[t, "premiums.unit"];
-      }
-      premium.Zillmer  = unit.premiumCF * premiums[["Zillmer"]];
-      premium.alpha.noZ = premium.alpha - premium.alpha.Zillmer; # ungezillmerter Teil der Abschlusskosten
-
-      premium.net       = unit.premiumCF * premiums[["net"]];
-
-      securityLoading   = valueOrFunction(params$Loadings$security, params = params, values = values);
-      qq = self$getTransitionProbabilities(params, values);
-      premium.risk.actual   = v * (values$absCashFlows[,"death"] - c(values$reserves[,"net"][-1], 0)) * pad0(qq$qx, l);
-      premium.risk.security = v * (values$absCashFlows[,"death"] * securityLoading) * pad0(qq$qx, l);
-      premium.risk          = premium.risk.actual + premium.risk.security;
-
-      premium.risk.disease.actual   = v * (values$absCashFlows[,"disease_SumInsured"] - c(values$reserves[,"net"][-1], 0)) * pad0(qq$ix, l);
-      premium.risk.disease.security = v * (values$absCashFlows[,"disease_SumInsured"] * securityLoading) * pad0(qq$ix, l);
-      premium.risk.disease          = premium.risk.disease.actual + premium.risk.disease.security;
-      premium.savings       = getSavingsPremium(
-          values$reserves[,"net"], v = v,
-          survival_advance = values$absCashFlows[,"survival_advance"] + values$absCashFlows[,"guaranteed_advance"],
-          survival_arrears = values$absCashFlows[,"survival_arrears"] + values$absCashFlows[,"guaranteed_arrears"]
-      )
-
-      premium.Zillmer.risk.actual   = v * (values$absCashFlows[,"death"] - c(values$reserves[,"contractual"][-1], 0)) * pad0(qq$qx, l);
-      premium.Zillmer.risk.security = v * (values$absCashFlows[,"death"] * securityLoading) * pad0(qq$qx, l);
-      premium.Zillmer.risk          = premium.Zillmer.risk.actual + premium.Zillmer.risk.security;
-      premium.Zillmer.risk.disease.actual   = v * (values$absCashFlows[,"disease_SumInsured"] - c(values$reserves[,"contractual"][-1], 0)) * pad0(qq$ix, l);
-      premium.Zillmer.risk.disease.security = v * (values$absCashFlows[,"disease_SumInsured"] * securityLoading) * pad0(qq$ix, l);
-      premium.Zillmer.risk.disease          = premium.Zillmer.risk.disease.actual + premium.Zillmer.risk.disease.security;
-
-
-      premium.Zillmer.savings  = getSavingsPremium(
-          values$reserves[,"contractual"], v = v,
-          survival_advance = values$absCashFlows[,"survival_advance"] + values$absCashFlows[,"guaranteed_advance"],
-          survival_arrears = values$absCashFlows[,"survival_arrears"] + values$absCashFlows[,"guaranteed_arrears"]
-      )
-      premium.Zillmer.amortization = getSavingsPremium(
-              pmin(0, values$reserves[,"contractual"]), v = v
-      )
-      premium.Zillmer.actsavings = getSavingsPremium(
-              pmax(0, values$reserves[,"contractual"]), v = v,
-              survival_advance = values$absCashFlows[,"survival_advance"] + values$absCashFlows[,"guaranteed_advance"],
-              survival_arrears = values$absCashFlows[,"survival_arrears"] + values$absCashFlows[,"guaranteed_arrears"]
-      )
-
-      res = cbind(
-        "charged"         = premium.charged,
-        "tax"             = tax,
-        "loading.frequency" = charge.frequency,
-        "rebate.premium"  = rebate.premium,
-        "rebate.partner"  = rebate.partner,
-        "unitcosts"       = unitcosts,
-        "profit.advance"  = profits.advance,
-        "rebate.sum"      = rebate.sum,
-        "charge.noMedicalExam" = charge.noMedicalExam,
-        "gross"           = premium.gross,
-
-        "gamma"           = premium.gamma,
-        "beta"            = premium.beta,
-        "alpha"           = premium.alpha,
-        "alpha.noZillmer" = premium.alpha.noZ,
-        "alpha.Zillmer"   = premium.alpha.Zillmer,
-        "Zillmer"         = premium.Zillmer,
-
-        "net"                   = premium.net,
-
-        "risk"                          = premium.risk,
-        "premium.risk.actual"           = premium.risk.actual,
-        "premium.risk.security"         = premium.risk.security,
-        "risk.disease"                  = premium.risk.disease,
-        "premium.risk.disease.actual"   = premium.risk.disease.actual,
-        "premium.risk.disease.security" = premium.risk.disease.security,
-        "savings"                       = premium.savings,
-
-        "Zillmer.risk"                  =  premium.Zillmer.risk,
-        "Zillmer.risk.actual"           = premium.Zillmer.risk.actual,
-        "Zillmer.risk.security"         = premium.Zillmer.risk.security,
-        "Zillmer.risk.disease"          = premium.Zillmer.risk.disease,
-        "Zillmer.risk.disease.actual"   = premium.Zillmer.risk.disease.actual,
-        "Zillmer.risk.disease.security" = premium.Zillmer.risk.disease.security,
-
-        "Zillmer.savings"               = premium.Zillmer.savings,
-        "Zillmer.amortization"          = premium.Zillmer.amortization,
-        "Zillmer.savings.real"          = premium.Zillmer.actsavings
-      )
-      rownames(res) <- rownames(premiums);
-      res
-    },
-
-
-    #' @description Generic function to calculate future sums of the values
-    #' @param cf The time series, for which future sums at all times are desired
-    #' @param ... currently unused
-    calculateFutureSums = function(cf, ...) {
-      rcumsum = function(vec) rev(cumsum(rev(vec)))
-      apply(cf, 2, rcumsum)
-    },
-    #' @description Calculate all present values for a given time series. The
-    #' mortalities are taken from the contract's parameters.
-    #' @param cf The time series, for which future present values at all
-    #'      times are desired
-    #' @param ... currently unused
-    calculatePresentValues = function(cf, params, values) {
-      len = dim(cf)[1];
-      qq = self$getTransitionProbabilities(params, values);
-      i = params$ActuarialBases$i;
-      premFreq = params$ContractData$premiumFrequency;
-      premFreqCorr = correctionPaymentFrequency(
-        i = i, m = premFreq,
-        order = valueOrFunction(params$ActuarialBases$premiumFrequencyOrder, params = params, values = values));
-
-      pvf = PVfactory$new(qx = qq, m = premFreq, mCorrection = premFreqCorr, v = 1/(1 + i));
-      pvf$survival(advance = cf)
-    },
-
-    #' @description Calculate the premium frequency loading, i.e. the surcharge
-    #' on the premium for those cases where the premium is not paid yearly.
-    #' Return values can be either a numeric value or a named list with all
-    #' possible premium frequencies as keys.
-    #' @param loading The premiumFrequencyLoading parameter of the Contract or Tariff to be evaluated
-    #' @param frequency The premiumFrequency parameter of the contract
-    evaluateFrequencyLoading = function(loading, frequency, params, values) {
-      frequencyLoading = valueOrFunction(loading, frequency = frequency, params = params, values = values);
-      if (is.null(frequencyLoading)) {
-        0
-      } else if (is.list(frequencyLoading)) {
-        if (as.character(frequency) %in% names(frequencyLoading)) {
-          frequencyLoading[[as.character(frequency)]]
-        } else {
-          warning("Unable to handle premium frequency ", frequency, " with the given loading ", frequencyLoading);
-        }
-      } else if (is.numeric(frequencyLoading)) {
-        frequencyLoading
-      } else {
-        warning("premiumFrequencyLoading must be a number or a named list, given: ", frequencyLoading);
-        0
-      }
-    },
-
-
-
-    #' @field dummy Dummy field to allow commas after the previous method
-    dummy = 0
-  )
-)
-
diff --git a/R/ProfitParticipation.R b/R/ProfitParticipation.R
deleted file mode 100644
index 1bf0964668009a59f0244ef293270d9180864cc6..0000000000000000000000000000000000000000
--- a/R/ProfitParticipation.R
+++ /dev/null
@@ -1,580 +0,0 @@
-#' @include HelperFunctions.R InsuranceParameters.R ProfitParticipation_Functions.R
-#'
-#' @import R6
-#' @import dplyr
-NULL
-# Shut up the package checker:
-# if (getRversion() >= "2.15.1")  utils::globalVariables(c("profitClass"))
-
-#' Filter the whole data.frame of profit rates for the given profit classes
-#'
-#' This is a rather trivial helper function, which just calls [dplyr::filter()].
-#'
-#' @param rates data.frame containing all profit rates for multiple profit classes
-#' @param classes the profit classes, for which rates should be extracted
-#'
-#' @export
-filterProfitRates = function(rates, classes) {
-  rates %>%
-    dplyr::filter(.data$profitClass %in% classes)
-}
-
-
-#' Base Class for Profit Participation Schemes
-#'
-#' Base class for Profit Participation schemes  (holding contract-independent values and
-#' providing methods to calculate the profit participation values from the given
-#' reserves).
-#'
-#' The profit participation object is typically not used directly, but rather
-#' defined once and then passed on to an [InsuranceTarif] or [InsuranceContract]
-#' object, where it will be used internally when profit participation is
-#' calculated.
-#'
-#' This class provides the technical implementation of a profit plan for traditional
-#' life insurance contracts with a guaranteed component (calculated before the
-#' profit scheme comes into play) and a discretionary profit on top.
-#'
-#' @param params Contract-specific, full set of parameters of the contract
-#'      (merged parameters of the defaults, the tariff, the profit participation
-#'      scheme and the contract)
-#' @param values Contract values calculated so far (guaranteed component of the
-#'     insurance contract, including cash flows, premiums, reserves etc.).
-#'
-#' @export
-ProfitParticipation = R6Class(
-  "ProfitParticipation",
-  public  = list(
-    #' @field name The human-readable name of the profit plan.
-    name  = "Name des Gewinnplans",
-    #' @field Parameters Parameter template for profit-participation-specific
-    #' parameters, i.e. the \code{ProfitParticipation} element of the
-    #' [InsuranceContract.ParameterStructure] data structure.
-    #'
-    #' All elements defined in the profit scheme can be overriden per contract
-    #' in the call to \code{[InsuranceContract]$new} or even in the explicit
-    #' call to \ifelse{html}{\href{../../LifeInsuranceContracts/html/InsuranceContract.html#method-profitScenario}{\code{InsuranceContract$profitScenario()}}}{\code{InsuranceContract$profitScenario()()}}
-    #' or \ifelse{html}{\href{../../LifeInsuranceContracts/html/InsuranceContract.html#method-addProfitScenario}{\code{InsuranceContract$addProfitScenario()}}}{\code{InsuranceContract$addProfitScenario()()}}.
-    #'
-    #'
-    Parameters = InsuranceContract.ParameterStructure$ProfitParticipation,
-
-    ########################################################################m#
-    # Function blocks (modular) to determine bases, rates and calculation ##m#
-    ########################################################################m#
-    #' @field Functions list of functions defined to calculate the individual
-    #' components. For each of the profit components
-    #' \itemize{
-    #'     \item interest profit
-    #'     \item risk profit
-    #'     \item expense profit
-    #'     \item sum profit
-    #'     \item terminal bonus
-    #'     \item terminal bonus fund
-    #' }
-    #' a rate,  a profit base and a calculation function can be defined, by assigning one of the pre-defined
-    #' [ProfitParticipationFunctions] or proving your own function with signature
-    #' \code{function(rates, params, values, ...)}. Additionally, for each of the
-    #' benefit types (survival, death, surrender, premium waiver) a function can
-    #' be provided to calculate the benefit stemming from profit participation.
-    Functions = list(
-
-        #++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-        # Calculation bases for the various types of profit
-        # Can / shall be overridden in child classes that use other bases!
-        #++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-        getInterestProfitBase   = PP.base.meanContractualReserve,
-        getRiskProfitBase       = PP.base.ZillmerRiskPremium,
-        getExpenseProfitBase    = PP.base.sumInsured,
-        getSumProfitBase        = PP.base.sumInsured,
-        getTerminalBonusBase    = PP.base.sumInsured,
-        getTerminalBonusFundBase = PP.base.totalProfitAssignment,
-
-        #++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-        # Profit rates for the various types of profit
-        # Can / shall be overridden in child classes that use other schemes!
-        #++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-        getInterestProfitRate   = PP.rate.interestProfit,
-        getRiskProfitRate       = PP.rate.riskProfit,
-        getExpenseProfitRate    = PP.rate.expenseProfit,
-        getSumProfitRate        = PP.rate.sumProfit,
-        getTerminalBonusRate    = PP.rate.terminalBonus,
-        getTerminalBonusFundRate= PP.rate.terminalBonusFund,
-
-
-        getInterestOnProfits    = PP.rate.totalInterest,
-
-
-
-        calculateInterestProfit = PP.calculate.RateOnBase,
-        calculateRiskProfit     = PP.calculate.RateOnBase,
-        calculateExpenseProfit  = PP.calculate.RateOnBase,
-        calculateSumProfit      = PP.calculate.RateOnBase,
-
-        calculateTerminalBonus  = PP.calculate.RateOnBase,
-        getTerminalBonusReserve = function(profits, rates, terminalBonus, terminalBonusAccount, params, values) {
-            n = length(terminalBonusAccount)
-            terminalBonusAccount * 1/(1.07) ^ ((n - 1):0)
-        },
-        calculateTerminalBonusFund = PP.calculate.RateOnBase,
-
-        #++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-        # Calculations of the assigned profit amounts, based on the bases and
-        # rates defined with the functions above.
-        # Can / shall be overridden in child classes that use other bases!
-        #++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-
-        calculateSurvivalBenefit      = PP.benefit.ProfitPlusTerminalBonusReserve,
-        calculateDeathBenefitAccrued  = PP.benefit.ProfitPlusGuaranteedInterest,
-        calculateDeathBenefitTerminal = PP.benefit.TerminalBonus5YearsProRata,
-        calculateSurrenderBenefitAccrued = PP.benefit.ProfitPlusHalfGuaranteedInterest,
-        calculateSurrenderBenefitTerminal = PP.benefit.TerminalBonus5YearsProRata,
-        calculatePremiumWaiverBenefitAccrued = PP.benefit.Profit,
-        calculatePremiumWaiverBenefitTerminal = PP.benefit.TerminalBonus5YearsProRata,
-
-
-        dummy = 0
-    ),
-
-
-    #' @description Create a new profit participation scheme
-    #' @details This function is called when a new profit participation scheme
-    #' is created with a call to \code{ProfitParticipation$new(...)}. Possible
-    #' parameters to the \code{new}-Call are all parameters from the `ProfitParticipation` sublist of the
-    #' [InsuranceContract.ParameterStructure] parameter
-    #' structure (which are understood as template values that can be overridden
-    #' per contract or even per profit participation scenario) and the components
-    #' of the `Functions` field defining the functions to calculate the individual
-    #' components of the profit participation (rates, calculation bases, calculation, benefits)
-    #'
-    #' @param name The name of the profit scheme (typicall the name of the profit plan and its version)
-    #' @param ... profit participation parameters to be stored in the
-    #' `Parameters field or calculation functions to be stored in the `Functions`
-    #' field
-    initialize = function(name = NULL, ...) {
-      if (!missing(name))           self$name = name;
-      self$setParameters(...);
-      self$setFunctions(...);
-      self$setFallbackParameters();
-    },
-
-
-    #' @description Store all passed parameters in the `Parameters` field
-    #' @param ... any of the named fields defined in the `ProfitParticipation` sublist of the
-    #'      [InsuranceContract.ParameterStructure]. All other arguments will be ignored
-    setParameters = function(...) {
-        self$Parameters = fillFields(self$Parameters, list(...));
-    },
-
-    #' @description Store all passed functions in the `Functions` field
-    #' @param ... any of the functions defined in the `Functions` field. All other
-    #'     arguments will be ignored
-    setFunctions = function(...) {
-        self$Functions = fillFields(self$Functions, list(...));
-    },
-
-    #' @description Fill all missing parameters with the default fall-back values
-    setFallbackParameters = function() {
-        self$Parameters = fallbackFields(self$Parameters, list(profitParticipationScheme = self));
-        self$Parameters = fallbackFields(self$Parameters, InsuranceContract.ParameterDefaults$ProfitParticipation);
-    },
-
-    #' @description create a copy of a profit scheme with certain parameters changed
-    #' @details This method \code{createModification} returns a copy of the profit scheme
-    #' with all given arguments changed in the schmes's `Parameters`
-    #' parameter list.
-    #'
-    #' As ProfitParticipation is a R6 class with reference logic, simply assigning
-    #' the object to a new variable does not create a copy, but references the
-    #' original profit scheme object. To create an actual copy, one needs to call this
-    #' method, which first clones the whole object and then adjusts all parameters
-    #' to the values passed to this method.
-    #'
-    #' @param name The new name for the cloned [ProfitParticipation] object
-    #' @param ... Parameters for the [InsuranceContract.ParameterStructure],
-    #'            defining the characteristics of the tariff.
-    createModification = function(name  = NULL, ...) {
-        cloned = self$clone();
-        if (!missing(name)) cloned$name = name;
-        cloned$Parameters = fillFields(cloned$Parameters, list(...));
-        cloned$Functions  = fillFields(cloned$Functions, list(...));
-        cloned
-    },
-
-
-    ##########################################################################m#
-    # Advance Profit Participation                                          ####
-    ##########################################################################m#
-
-    #' @description Calculate and return the advance profit participation (to be
-    #' applied on the actuarial gross premium)
-    #'
-    #' @details The [InsuranceContract]'s param structure [InsuranceContract.ParameterStructure]
-    #'     contains the field \code{params$ProfitParticipation$advanceProfitParticipation},
-    #'     which can either be numeric rate for advance profit participation, or
-    #'     a function with signature \code{function(params, values, ...)} that
-    #'     returns the advance profit participation rate when called with the
-    #'     contract's parameters and the values calculated so far (cash flows and premiums)
-    #' @return Return either one numerical value (constant for the whole premium payment period)
-    #' of a vector of numerical values for the whole contract period
-    #'
-    #' @param ... optional parameters, to be passed to the advanceProfitParticipation
-    #'     field of the parameter structure (if that is a function)
-    getAdvanceProfitParticipation = function(params, values, ...) {
-        valueOrFunction(params$ProfitParticipation$advanceProfitParticipation, params, values, ...)
-    },
-
-
-    #' @description Calculate and return the advance profit participation (to be
-    #' applied after unit costs are added to the gross premium)
-    #'
-    #' @details The [InsuranceContract]'s param structure [InsuranceContract.ParameterStructure]
-    #'     contains the field \code{params$ProfitParticipation$advanceProfitParticipationInclUnitCost},
-    #'     which can either be numeric rate for advance profit participation, or
-    #'     a function with signature \code{function(params, values, ...)} that
-    #'     returns the advance profit participation rate when called with the
-    #'     contract's parameters and the values calculated so far (cash flows and premiums)
-    #' @return Return either one numerical value (constant for the whole premium payment period)
-    #' of a vector of numerical values for the whole contract period
-    #'
-    #' @param ... optional parameters, to be passed to the advanceProfitParticipationInclUnitCost
-    #'     field of the parameter structure (if that is a function)
-    getAdvanceProfitParticipationAfterUnitCosts = function(params, values, ...) {
-        valueOrFunction(params$ProfitParticipation$advanceProfitParticipationInclUnitCost, params, values, ...)
-    },
-
-
-    ##########################################################################m#
-    # Traditional Profit participation:                                     ####
-    #   - Interest profit                                                   ##m#
-    #   - Risk profit                                                       ##m#
-    #   - Expense profit                                                    ##m#
-    #   - Sum profit                                                        ##m#
-    #   - Terminal bonus                                                    ##m#
-    ##########################################################################m#
-
-
-    #' @description Set up the data.frame containing the profit participation rates
-    #' @param ... additional parameters passed to the profit calculation functions
-      #'     stored in the `Functions` field.
-    setupRates = function(params, values, ...) {
-        # 1) Profit scheme or contract provides general company-wide profit rates for some years:
-        #       profitRates
-        # 2) Contract can override individual rates (either for calendar years or contract years):
-        #       guaranteedInterest, interestProfitRate, totalInterest, mortalityProfitRate,
-        #       expenseProfitRate, sumProfitRate, terminalBonusRate, terminalBonusFundRate
-        # 3) Explicit function arguments (either for calendar years or contract years).
-        # 4) Any missing values will be taken from the last given year
-        startYear = year(params$ContractData$contractClosing);
-        policyPeriod = params$ContractData$policyPeriod;
-        years = startYear:(startYear + policyPeriod);
-
-        columns = c(
-            "year",
-            "guaranteedInterest", "interestProfitRate", "totalInterest", "interestProfitRate2", "totalInterest2",
-            "mortalityProfitRate", "expenseProfitRate", "expenseProfitRate_premiumfree",
-            "sumProfitRate",
-            "terminalBonusRate", "terminalBonusFundRate")
-        rates = data.frame(matrix(ncol = length(columns), nrow = length(years), dimnames = list(years = years, rates = columns)))
-        rates$year = years;
-
-        # 1) profitRates are general company-wide tables with all default rates
-        # => use them as default, unless overridden
-        defrates = params$ProfitParticipation$profitRates
-        if (!is.null(defrates)) {
-            profclass = params$ProfitParticipation$profitClass
-            defrates = dplyr::filter(defrates, profitClass == profclass)
-            rownames(defrates) = defrates$year
-
-            defcols = intersect(columns, colnames(defrates))
-
-            rates[rownames(defrates), defcols] = defrates[, defcols]
-        }
-
-        # 2) Add the explicit overrides per profit rate (from the contract)
-        for (col in columns) {
-            if (!is.null(params$ProfitParticipation[[col]])) {
-                rt = valueOrFunction(params$ProfitParticipation[[col]], params = params, values = values);
-                if (is.null(names(rt))) {
-                    # numeric value or vector => assume values from the contract start year
-                    # and fill ALL policy years with the given rates (last entry repeated)
-                    rates[as.character(years), col] = padLast(rt, length(years));
-                } else {
-                    # values with years assigned => use them only for the given year(s), don't override any other year
-                    rates[names(rt), col] = rt;
-                    rates[names(rt), "year"] = names(rt);
-                }
-            }
-        }
-
-        # 3) Use explicit function param overrides per profit rate (from this function call)
-        argcols = match.call(expand.dots = FALSE)$`...`;
-        matching.cols = intersect(columns, names(argcols))
-        for (col in matching.cols) {
-            rt = eval(argcols[[col]]);
-            if (!is.null(rt)) {
-                rt = valueOrFunction(rt, params = params, values = values);
-                if (is.null(names(rt))) {
-                    # numeric value or vector => assume values from the contract start year
-                    # and fill ALL policy years with the given rates (last entry repeated)
-                    rates[as.character(years), col] = padLast(rt, length(years));
-                } else {
-                    # values with years assigned => use them only for the given year(s), don't override any other year
-                    rates[names(rt), col] = rt;
-                    rates[names(rt), "year"] = names(rt);
-                }
-            }
-        }
-        rownames(rates) = rates[, "year"]
-
-        # 4) Fill all NAs with the last known value
-        # First, make sure that all entries are in the correct order (sorted by year)
-        rates
-        newrates = rates %>% dplyr::arrange(year) %>% dplyr::mutate_all(fillNAgaps)
-        rownames(newrates) = newrates$year
-
-        # 5) Replace all NA values with 0, so we don't run into any problems later on
-        newrates[is.na(newrates)] <- 0
-
-        # TODO: Fix guaranteedInterest + interestProfitRate = totalInterest, where one of them might be missing!
-
-        # Return only the policy years...
-        self$adjustRates(newrates[as.character(years),], params = params, values = values)
-    },
-
-    #' @description Adjust the data.frame of profit participation rates after their setup
-    #' @details This function provides an easy way to modify the whole set of
-    #' profit rates after their initial setup. Possible applications are waiting
-    #' periods, which can be implemented once for all rates rather than inside
-    #' each individual calculation period.
-    #' @param rates data.frame of profit paticipation rates
-    adjustRates = function(rates, params, values) {
-        rates[1,] = 0;
-        rates
-    },
-
-
-
-
-
-    #' @description Calculation the full time series of profit participation for
-    #' the given contract values
-    #'
-    #' @param calculateFrom The time from which to start calculating the profit
-    #' participation. When a contract is changed at some time t (possibly even
-    #' changing the profit scheme), all future profit participation needs to be
-    #' re-calculated from that time on, without changing past profit participation.
-    #' All values before \code{calculateFrom} will not be calculated.
-    #' @param profitScenario profit participation values from a previous calculation
-    #' (NULL if profit calculation is to be calculated from the contract inception).
-    #' Values before \code{calculateFrom} will be used from this data.frame.
-    #' @param ... additional parameters to be passed to \href{../../LifeInsuranceContracts/html/ProfitParticipation.html#method-setupRates}{\code{ProfitParticipation$setupRates()}}
-    getProfitParticipation = function(calculateFrom = 0, profitScenario = NULL, params, values, ...) {
-        waiting      = valueOrFunction(params$ProfitParticipation$waitingPeriod, params = params, values = values);
-        if (is.numeric(waiting) && waiting > 0) {
-            waitingFactor = c(rep(0, waiting + 1), rep(1, params$ContractData$policyPeriod - waiting));
-        } else {
-            waitingFactor = 1;
-        }
-        rates        = self$setupRates(params = params, values = values, ...)
-
-        # Initialize all rates, bases and calc functions to NULL and then set
-        # only those that are actually used in this profit scheme (all values
-        # with NULL will silently be ignored in the cbind call)
-        intBase      = riskBase     = expenseBase   = sumBase      = NULL;
-        intRate      = riskRate     = expenseRate   = sumRate      = NULL;
-        intProfit    = riskProfit   = expenseProfit = sumProfit   = NULL
-
-        interestOnProfitRate = self$Functions$getInterestOnProfits(rates = rates, params = params, values = values);
-        if ("interest" %in% params$ProfitParticipation$profitComponents) {
-          intBase      = self$Functions$getInterestProfitBase(rates = rates, params = params, values = values);
-          intRate      = self$Functions$getInterestProfitRate(rates = rates, params = params, values = values);
-          intProfit     = self$Functions$calculateInterestProfit(base = intBase, rate = intRate, waiting = waitingFactor, rates = rates, params = params, values = values);
-        }
-        if ("risk" %in% params$ProfitParticipation$profitComponents) {
-          riskBase     = self$Functions$getRiskProfitBase(rates = rates, params = params, values = values);
-          riskRate     = self$Functions$getRiskProfitRate(rates = rates, params = params, values = values);
-          riskProfit    = self$Functions$calculateRiskProfit(base = riskBase, rate = riskRate, waiting = waitingFactor, rates = rates, params = params, values = values);
-        }
-        if ("expense" %in% params$ProfitParticipation$profitComponents) {
-          expenseBase  = self$Functions$getExpenseProfitBase(rates = rates, params = params, values = values);
-          expenseRate  = self$Functions$getExpenseProfitRate(rates = rates, params = params, values = values);
-          expenseProfit = self$Functions$calculateExpenseProfit(base = expenseBase, rate = expenseRate, waiting = waitingFactor, rates = rates, params = params, values = values);
-        }
-        if ("sum" %in% params$ProfitParticipation$profitComponents) {
-          sumBase      = self$Functions$getSumProfitBase(rates = rates, params = params, values = values);
-          sumRate      = self$Functions$getSumProfitRate(rates = rates, params = params, values = values);
-          sumProfit     = self$Functions$calculateSumProfit(base = sumBase, rate = sumRate, waiting = waitingFactor, rates = rates, params = params, values = values);
-        }
-
-        res = cbind(
-            # Profit Calculation Bases
-            interestBase = c(intBase),
-            riskBase = c(riskBase),
-            expenseBase = c(expenseBase),
-            sumBase = c(sumBase),
-
-            # Profit Rates
-            guaranteedInterest = c(rates$guaranteedInterest),
-            totalInterest = c(rates$totalInterest),
-            interestProfitRate = c(intRate),
-            riskProfitRate = c(riskRate),
-            expenseProfitRate = c(expenseRate),
-            sumProfitRate = c(sumRate),
-            interestOnProfitRate = c(interestOnProfitRate),
-
-            # Profit components
-            interestProfit = c(intProfit),
-            riskProfit = c(riskProfit),
-            expenseProfit = c(expenseProfit),
-            sumProfit = c(sumProfit),
-            componentsProfit = plusNULL(intProfit, riskProfit, expenseProfit, sumProfit),
-            interestOnProfit = c(0),
-            totalProfitAssignment = c(0),
-
-            totalProfit = c(0)
-        );
-
-        # Use only newly calculated values starting at 'calculateFrom', but use
-        # old values up to that moment (might be a contract change with a
-        # completely different profit participation system before!)
-        res = mergeValues(starting = profitScenario[,colnames(res)], ending = res, t = calculateFrom);
-
-        if (calculateFrom > 0 && !is.null(profitScenario)) {
-          prev = profitScenario[calculateFrom - 1, "totalProfit"]
-        } else {
-          prev = 0;
-        }
-        # TODO: turn the interest on profit into a calculator function!
-        # res = self$Functions$calculateInterestOnProfit(base = sumBase, rate = sumRate, waiting = waitingFactor, rates = rates, params = params, values = values);
-        for (i in (calculateFrom + 1):nrow(res)) {
-            res[i,"interestOnProfit"] = res[i,"interestOnProfitRate"] * prev;
-            res[i,"totalProfitAssignment"] = res[i, "componentsProfit"] + res[i,"interestOnProfit"];
-            res[i,"totalProfit"] = prev + res[i,"totalProfitAssignment"];
-            prev = res[i,"totalProfit"];
-        }
-        regularBonusAssignment = res[,"totalProfitAssignment"]
-
-        ###########################################################################################################%#
-        #### OLD Terminal bonus (not through terminal bonus fund, i.e. part of ongoing profits, but in addition) ####
-        #### Terminal Bonus calculations (might depend on the individual profit assignments calculated above!
-        ###########################################################################################################%#
-        #### => TODO: Pass the current profit calculation inside the values!)
-        if ("terminal" %in% params$ProfitParticipation$profitComponents) {
-          terminalBase = self$Functions$getTerminalBonusBase(res, rates = rates, params = params, values = values);
-          terminalRate = self$Functions$getTerminalBonusRate(res, rates = rates, params = params, values = values);
-          terminalBonus = self$Functions$calculateTerminalBonus(res,
-                  base = terminalBase, rate = terminalRate, calculateFrom = calculateFrom,
-                  waiting = waitingFactor, rates = rates, params = params, values = values); # TODO: Add the AF(v) factor!
-
-          if (calculateFrom == 0) {
-            terminalBonusAccount = cumsum(terminalBonus); # TODO: Generalize! Not every scheme uses a cumulative account!
-          } else {
-            past = profitScenario[1:calculateFrom, "terminalBonusAccount"]
-            # Preserve values up to calculateFrom, start from the last known value at calculateFrom-1 and sum all further contributions:
-            terminalBonusAccount = c(head(past, -1), cumsum(c(tail(past,1), tail(terminalBonus, -calculateFrom))))
-          }
-          terminalBonusReserve = self$Functions$getTerminalBonusReserve(res, rates = rates, terminalBonus, terminalBonusAccount, params = params, values = values)
-
-          resTerminal = cbind(
-            terminalBase,
-            terminalRate,
-            terminalBonus,
-            terminalBonusAccount,
-            terminalBonusReserve
-          )
-          resTerminal = mergeValues(starting = profitScenario[,colnames(resTerminal)], ending = resTerminal, t = calculateFrom)
-          # Add the terminal bonus values to the array:
-          res = cbind(res, resTerminal)
-        }
-
-        ###########################################################################################################%#
-        #### NEW Terminal bonus fund (part of regular profits, but not paid out on surrender, reserved as part of the free RfB) ####
-        ###########################################################################################################%#
-        if ("TBF" %in% params$ProfitParticipation$profitComponents) {
-          TBFBase = self$Functions$getTerminalBonusFundBase(res, rates = rates, params = params, values = values);
-          TBFRate = self$Functions$getTerminalBonusFundRate(res, rates = rates, params = params, values = values);
-          TBFBonusAssignment = self$Functions$calculateTerminalBonusFund(res,
-                base = TBFBase, rate = TBFRate, calculateFrom = calculateFrom,
-                waiting = waitingFactor, rates = rates, params = params, values = values);
-          regularBonusAssignment = res[,"totalProfitAssignment"] - TBFBonusAssignment
-
-          # Calculate TBF and regular bonus as cumulative sum  of the assignments starting at t = calculateFrom plus the previous value!
-          if (calculateFrom == 0) {
-            TBF = cumsum(TBFBonusAssignment)
-          } else {
-            past = profitScenario[1:calculateFrom, "TBF"]
-            # Preserve values up to calculateFrom, start from the last known value at calculateFrom-1 and sum all further contributions:
-            TBF = c(head(past, -1), cumsum(c(tail(past,1), tail(TBFBonusAssignment, -calculateFrom))))
-          }
-
-
-          resTBF = cbind(
-            TBFBase,
-            TBFRate,
-            TBFBonusAssignment,
-            TBF
-          )
-          resTBF = mergeValues(starting = profitScenario[,colnames(resTBF)], ending = resTBF, t = calculateFrom)
-          # Add the terminal bonus fund values to the array:
-          res = cbind(res, resTBF)
-        }
-
-        ###########################################################################################################%#
-        #### Regular bonus assignment / accrued regular bonus AFTER TBF                                          ####
-        ###########################################################################################################%#
-        # Calculate regular bonus (after potential TBF subtraction) as cumulative sum  of the assignments starting at t = calculateFrom plus the previous value!
-        if (calculateFrom == 0) {
-          regularBonus = cumsum(regularBonusAssignment)
-        } else {
-          past = profitScenario[1:calculateFrom, "regularBonus"]
-          regularBonus = c(head(past, -1), cumsum(c(tail(past,1), tail(regularBonusAssignment, -calculateFrom))))
-        }
-        resRegular = cbind(regularBonusAssignment, regularBonus)
-        resRegular = mergeValues(starting = profitScenario[,colnames(resRegular)], ending = resRegular, t = calculateFrom)
-        res = cbind(res, resRegular)
-
-
-        ###########################################################################################################%#
-        #### BENEFITS                                                                                            ####
-        ###########################################################################################################%#
-
-        survival       = self$Functions$calculateSurvivalBenefit(res, rates = rates, params = params, values = values);
-
-        deathAccrued   = self$Functions$calculateDeathBenefitAccrued(res, rates = rates, params = params, values = values);
-        deathTerminalBonus = self$Functions$calculateDeathBenefitTerminal(res, rates = rates, params = params, values = values);
-
-        surrenderAccrued  = self$Functions$calculateSurrenderBenefitAccrued(res, rates = rates, params = params, values = values);
-        surrenderTerminalBonus = self$Functions$calculateSurrenderBenefitTerminal(res, rates = rates, params = params, values = values);
-
-        premiumWaiverAccrued  = self$Functions$calculatePremiumWaiverBenefitAccrued(res, rates = rates, params = params, values = values);
-        premiumWaiverTerminalBonus = self$Functions$calculatePremiumWaiverBenefitTerminal(res, rates = rates, params = params, values = values);
-
-        resBenefit = cbind(
-          survival = survival,
-
-          deathAccrued = deathAccrued,
-          deathTerminalBonus = deathTerminalBonus,
-          death = deathAccrued + deathTerminalBonus,
-
-          surrenderAccrued  = surrenderAccrued,
-          surrenderTerminalBonus = surrenderTerminalBonus,
-          surrender      = surrenderAccrued + surrenderTerminalBonus,
-
-          premiumWaiverAccrued  = premiumWaiverAccrued,
-          premiumWaiverTerminalBonus = premiumWaiverTerminalBonus,
-          premiumWaiver  = premiumWaiverAccrued + premiumWaiverTerminalBonus
-        )
-        # Preserve values up to time t=calculateFrom of the old scenario values
-        resBenefit = mergeValues(starting = profitScenario[,colnames(resBenefit)], ending = resBenefit, t = calculateFrom)
-
-        res = cbind(res, resBenefit);
-        res
-    },
-
-
-
-   #' @field dummy Dummy to allow commas in the previous method
-    dummy = 0
-  )
-)
diff --git a/R/ProfitParticipation_Functions.R b/R/ProfitParticipation_Functions.R
deleted file mode 100644
index 942b3b5e4113376f2ed59de109548bb530089ebd..0000000000000000000000000000000000000000
--- a/R/ProfitParticipation_Functions.R
+++ /dev/null
@@ -1,359 +0,0 @@
-#' @include HelperFunctions.R InsuranceParameters.R
-#'
-#' @import dplyr
-NULL
-
-#' Helper functions for profit participation
-#'
-#' Various helper functions for the \code{ProfitParticipation} class that
-#' provide the building blocks for the individual components of profit participation,
-#' the rates and how the assigned profit is calculated.
-#'
-#' @name ProfitParticipationFunctions
-#' @param rates data.frame of profit rates
-#' @param params Contract-specific, full set of parameters of the contract
-#'      (merged parameters of the defaults, the tariff, the profit participation
-#'      scheme and the contract)
-#' @param values Contract values calculated so far (guaranteed component of the
-#'     insurance contract, including cash flows, premiums, reserves etc.).
-#' @param ... Other values that might be used for the calculation (currently unused)
-#'
-#' @param base The profit calculation base, on which the rate is to be applied
-#' @param rate The profit participation rate
-#' @param waiting A possible waiting period
-NULL
-
-shiftBy = function(rate, n = 1) {
-  nm = names(rate)
-  res = c(rep(0, n), head(rate, -n))
-  names(res) = nm
-  res
-
-}
-
-##########################################################################m##
-# Calculation bases for the various types of profit                      ####
-##########################################################################m##
-
-#' @describeIn ProfitParticipationFunctions
-#' Basis for profit: NONE (i.e. always returns 0)
-#' @export
-PP.base.NULL = function(rates, params, values, ...) {
-  rep(0, values$int$l)
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Basis for profit: Previous Zillmer reserve (no administration cost reserve)
-#' @export
-PP.base.PreviousZillmerReserve = function(rates, params, values, ...) {
-    shiftBy(values$reserves[,"Zillmer"], n = 1)
-}
-
-#' @describeIn ProfitParticipationFunctions
-#' Basis for profit: Zillmer reserve (no administration cost reserve) at time t-2
-#' @export
-PP.base.ZillmerReserveT2 = function(rates, params, values, ...) {
-    shiftBy(values$reserves[,"Zillmer"], n = 2)
-}
-
-#' @describeIn ProfitParticipationFunctions
-#' Basis for profit: Contractual reserve (including administration costs) at time t
-#' @export
-PP.base.contractualReserve = function(rates, params, values, ...) {
-  pmax(0, values$reserves[,"contractual"])
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Basis for profit: Contractual reserve (including administration costs) at time t-1
-#' @export
-PP.base.previousContractualReserve = function(rates, params, values, ...) {
-  shiftBy(values$reserves[,"contractual"], n = 1)
-}
-
-#' @describeIn ProfitParticipationFunctions
-#' Basis for profit: Contractual reserve (including administration costs) averaged over t and t-1
-#' @export
-PP.base.meanContractualReserve = function(rates, params, values, ...) {
-    # Rolling mean of the value for the current and previous year.
-    pmax(0, rollingmean(c(0, values$reserves[,"contractual"])))
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Basis for risk/mortality profit: Zillmer Risk Premium of the past year
-#' @export
-PP.base.ZillmerRiskPremium = function(rates, params, values, ...) {
-    # The risk premium of t=0 is used to determine the risk profit at time
-    # t=1, so shift the whole vector!
-    shiftBy(values$premiumComposition[,"Zillmer.risk"], n = 1)
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Basis for expense/sum profit: sum insured
-#' @export
-PP.base.sumInsured = function(rates, params, values, ...) {
-  params$ContractData$sumInsured
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Basis for Terminal Bonus Fund Assignment: total profit assignment of the year
-#'
-#' @param res the data.frame of reserves.
-#' @export
-PP.base.totalProfitAssignment = function(res, ...) {
-  res[,"totalProfitAssignment"]
-}
-
-
-#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-# Profit rates for the various types of profit
-# Can / shall be overridden in child classes that use other schemes!
-#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-#' @describeIn ProfitParticipationFunctions
-#' Returns the array of interest profit rates (keyed by year)
-#' @export
-PP.rate.interestProfit = function(rates, ...) {
-  rates$interestProfitRate
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Returns the array of risk profit rates (keyed by year)
-#' @export
-PP.rate.riskProfit = function(rates, ...) {
-  rates$mortalityProfitRate
-};
-#' @describeIn ProfitParticipationFunctions
-#' Returns the array of expense profit rates (keyed by year)
-#' @export
-PP.rate.expenseProfit = function(rates, ...) {
-  rates$expenseProfitRate
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Returns the array of sum profit rates (keyed by year)
-#' @export
-PP.rate.sumProfit = function(rates, ...) {
-  rates$sumProfitRate
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Returns the array of terminal bonus rates (keyed by year)
-#' @export
-PP.rate.terminalBonus = function(rates, ...) {
-  rates$terminalBonusRate
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Returns the array of terminal bonus rates (keyed by year) as the terminal bonus fund ratio
-#' @export
-PP.rate.terminalBonusFund = function(rates, ...) {
-  rates$terminalBonusFundRate
-};
-
-
-#' @describeIn ProfitParticipationFunctions
-#' Rate for interest on past profits: total credited rate, but at least the guarantee
-#' @export
-PP.rate.interestProfitPlusGuarantee = function(rates, ...) {
-  rates$interestProfitRate + rates$guaranteedInterest
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Rate for interest on past profits: total creditedrate2, but at least the guarantee
-#' @export
-PP.rate.interestProfit2PlusGuarantee = function(rates, ...) {
-  rates$interestProfitRate2 + rates$guaranteedInterest
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Rate for interest on past profits: total interest rate
-#' @export
-PP.rate.totalInterest = function(rates, ...) {
-  rates$totalInterest
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Rate for interest on past profits: second total interest rate
-#' @export
-PP.rate.totalInterest2 = function(rates, ...) {
-  rates$totalInterest2
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Rate for interest on past profits: second interest profit rate (not including guaranteed interest), keyed by year
-#' @export
-PP.rate.interestProfit2 = function(rates, ...) {
-  rates$interestProfitRate2
-};
-
-
-# TODO
-#' @describeIn ProfitParticipationFunctions
-#'
-#' Calculate the terminal bonus reserve.
-#' @param profits The data.frame of profits assigned
-#' @param terminalBonus The terminal bonus calculated
-#' @param terminalBonusAccount The terminal bonus account (like a bank account,
-#'        where terminal bonuses are accrued, potentiall discounted from the maturity)
-getTerminalBonusReserve = function(profits, rates, terminalBonus, terminalBonusAccount, params, values, ...) {
-  n = length(terminalBonusAccount)
-  terminalBonusAccount * 1/(1.07) ^ ((n - 1):0)
-};
-
-
-#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-# Calculations of the assigned profit amounts, based on the bases and
-# rates defined with the functions above.
-# Can / shall be overridden in child classes that use other bases!
-#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-
-#' @describeIn ProfitParticipationFunctions
-#' Calculate profit by a simple rate applied on the basis (with an optional waiting vector of values 0 or 1)
-#' @export
-PP.calculate.RateOnBase = function(base, rate, waiting, rates, params, values, ...) {
-  base * rate * waiting
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Calculate profit by a simple rate applied on the basis (with an optional waiting vector of values 0 or 1), bound below by 0
-#' @export
-PP.calculate.RateOnBaseMin0 = function(base, rate, waiting, rates, params, values, ...) {
-  pmax(0, base * rate * waiting)
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Calculate profit by a rate + guaranteed interest applied on the basis (with an optional waiting vector of values 0 or 1)
-#' @export
-PP.calculate.RatePlusGuaranteeOnBase = function(base, rate, waiting, rates, params, values, ...) {
-  base * (rate + rates$guaranteedInterest) * waiting
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Calculate profit by a simple rate applied on the basis (with only (1-SGFFactor) put into profit participation, and an optional waiting vector of values 0 or 1)
-#' @export
-PP.calculate.RateOnBaseSGFFactor = function(base, rate, waiting, rates, params, values, ...) {
-  base * rate * waiting * (1 - rates$terminalBonusFund)
-};
-
-
-
-#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-# Calculations of the benefits, based on the assigned profit amounts and
-# rates defined with the functions above.
-#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-
-#' @describeIn ProfitParticipationFunctions
-#' Extract the given columns of the profit participation array of values and sum
-#' them up. Columns that do not exist, because the profit scheme does not
-#' provide the corresponding profit component will be silently ignored.
-#' This allows generic benefit calculation functions to be written that do
-#' not need to distinguish e.g. whether an old-style terminal bonus or a terminal
-#' bonus fund is provided.
-#'
-#' This function is not meant to be called directly, but within a profit benefit
-#' calculation function.
-#'
-#' @param profits The array of profit participation component values
-#' @param cols The columns of the profit values array to be summed (columns given that do not exist in the profits array are ignired)
-#' @export
-sumProfits = function(profits, cols) {
-  # extract the columns -- if they exist -- and sum them up:
-  rowSums(
-    profits[, intersect(cols, colnames(profits)), drop = FALSE]
-  )
-}
-
-#' @describeIn ProfitParticipationFunctions
-#' Calculate survival benefit as total profit amount plus the terminal bonus reserve
-#' @export
-PP.benefit.ProfitPlusTerminalBonusReserve = function(profits, ...) {
-  sumProfits(profits, c("regularBonus", "TBF", "terminalBonusReserve"))
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Calculate benefit as total profit accrued so far
-#' @export
-PP.benefit.Profit = function(profits, ...) {
-  profits[,"regularBonus"]
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Calculate accrued death benefit as total profit with (guaranteed) interest for one year
-#' @export
-PP.benefit.ProfitPlusGuaranteedInterest = function(profits, rates, ...) {
-  profits[,"regularBonus"] * (1 + rates$guaranteedInterest)
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Calculate accrued death benefit as total profit with total interest (interest on profit rate) for one year
-#' @export
-PP.benefit.ProfitPlusTotalInterest = function(profits, rates, params, values) {
-  profits[,"regularBonus"] * (1 + profits[,"interestOnProfitRate"])
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Calculate accrued benefit as total profit with total interest (interest on profit rate) for half a year
-#' @export
-PP.benefit.ProfitPlusHalfTotalInterest = function(profits, ...) {
-  profits[,"regularBonus"] * (1 + profits[,"interestOnProfitRate"]/2)
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Calculate death benefit as total profit with (guaranteed) interest for one year
-#' @export
-PP.benefit.ProfitPlusHalfGuaranteedInterest = function(profits, rates, ...) {
-  profits[,"regularBonus"] * (1 + rates$guaranteedInterest/2)
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Calculate accrued benefit as total profit with interest for one year (max of guarantee and total interest)
-#' @export
-PP.benefit.ProfitPlusInterestMinGuaranteeTotal = function(profits, rates, ...) {
-  profits[,"regularBonus"] * (1 + pmax(rates$guaranteedInterest, rates$totalInterest))
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Calculate accrued benefit as total profit with interest for half a year (max of guarantee and total interest)
-#' @export
-PP.benefit.ProfitPlusHalfInterestMinGuaranteeTotal = function(profits, rates, ...) {
-  profits[,"regularBonus"] * (1 + pmax(rates$guaranteedInterest, rates$totalInterest)/2)
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Calculate accrued benefit as regular profit, but used to cover initial Zillmerization
-#' @export
-PP.benefit.ProfitGuaranteeSupporting = function(profits, rates, params, values, ...) {
-  pmax(0, values$reserves[,"contractual"] + profits[,"regularBonus"] - pmax(0, values$reserves[,"contractual"]))
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Calculate benefit from terminal bonus as 1/n parts of the terminal bonus reserve during the last 5 years
-#' @export
-PP.benefit.TerminalBonus5YearsProRata = function(profits, params, ...) {
-  n = params$ContractData$policyPeriod;
-  sumProfits(profits, c("TBF", "terminalBonusReserve")) * (0:n)/n * ((0:n) >= max(10, n - 5))
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' Terminal bonus is only paid out during the last 5 years of the contract (but never during the first 10 years)
-#' @export
-PP.benefit.TerminalBonus5Years = function(profits, params, ...) {
-  n = params$ContractData$policyPeriod;
-  sumProfits(profits, c("TBF", "terminalBonusReserve")) * ((0:n) >= max(10, n - 5))
-}
-
-#' @describeIn ProfitParticipationFunctions
-#' Calculate benefit from terminal bonus (full bonus), either old-style terminal bonus reserve or Terminal Bonus Fund (TBF)
-#' @export
-PP.benefit.TerminalBonus = function(profits, params, ...) {
-  sumProfits(profits, c("TBF", "terminalBonusReserve"))
-};
-
-#' @describeIn ProfitParticipationFunctions
-#' No benefit paid out
-#' @export
-PP.benefit.None = function(profits, ...) {
-  0
-};
-
-
-"dummy"
diff --git a/R/addDataTableWorksheet.R b/R/addDataTableWorksheet.R
deleted file mode 100644
index a8b0f3ed4ba43dc575f978c150dfe66f2915fae0..0000000000000000000000000000000000000000
--- a/R/addDataTableWorksheet.R
+++ /dev/null
@@ -1,73 +0,0 @@
-#' Add a new worksheet to the excel workbook and export the given data table x to it nicely formatted.
-# @export
-# addDataTableWorksheet = function(wb, sheet, title = NULL, x = NULL, loopdim = 3, style = NULL, tableStyle = "TableStyleMedium17", comparisons = NULL, comparisonStyle = NULL, ...) {
-#     addWorksheet(wb, sheet);
-#     rw = 1;
-#     if (!missing(title)) {
-#         titleStyle = createStyle(
-#             fontSize = 26,
-#             fontColour = "#365F91", borderColour = "#4F81BD",
-#             borderStyle = "medium", border = "Bottom", textDecoration = "bold")
-#         writeData(wb, sheet, title, startCol = 1, startRow = rw)
-#         addStyle(wb, sheet, style = titleStyle, rows = rw, cols = 1);
-#         rw = rw + 2;
-#     }
-#     if (!missing(x)) {
-#         if (loopdim > length(dim(x)))
-#             loopdim = length(dim(x));
-#         if (loopdim < 0)
-#             loopdim = 1;
-#         # str(dimnames(x));
-#         rnames = dimnames(x)[[1]];
-#         cnames = dimnames(x)[[2]];
-#         # str("rnames, cnames: ");str(rnames);str(cnames);
-#         dmname = names(dimnames(x))[[loopdim]];
-#         dmnameStyle = createStyle(
-#             fontSize = 20,
-#             fontColour = "#4F81BD", #borderColour = "#4F81BD",
-#             # borderStyle = "medium", border = "Bottom",
-#             textDecoration = "bold")
-#         headerStyle = createStyle(halign = "center", valign = "center");
-#         lapply(
-#             seq_along(dimnames(x)[[loopdim]]),
-#             function(i) {
-#                 dmheader = paste(dmname, dimnames(x)[[loopdim]][i], sep = " = ")
-#                 writeData(wb, sheet, dmheader, startCol = 1, startRow = rw)
-#                 addStyle(wb, sheet, style = dmnameStyle, rows = rw, cols = 1);
-#                 rw <<- rw + 1;
-#                 writeDataTable(
-#                     wb, sheet,
-#                     x = as.data.frame(x[,,i]), # TODO: Generalize this to use loopdim!
-#                     colNames = TRUE, rowNames = TRUE,
-#                     withFilter = FALSE,
-#                     startCol = 1, startRow = rw,
-#                     tableStyle = tableStyle, headerStyle = headerStyle);
-#                 if (!is.null(style)) {
-#                     addStyle(wb, sheet, style = style, rows = rw + seq_along(rnames), cols = 1 + seq_along(cnames), gridExpand = TRUE, stack = TRUE);
-#                 }
-#                 cl = 1 + length(cnames) + 2;
-#
-#                 lapply(
-#                     seq_along(comparisons),
-#                     function(j) {
-#                         writeData(wb, sheet, names(comparisons)[j], startRow = rw - 1, startCol = cl)
-#                         addStyle(wb, sheet, style = dmnameStyle, rows = rw - 1, cols = cl);
-#
-#                         writeDataTable(
-#                             wb, sheet,
-#                             x = as.data.frame(comparisons[[j]][,,i]), # TODO: Generalize this to use loopdim!
-#                             colNames = TRUE, rowNames = TRUE,
-#                             withFilter = FALSE,
-#                             startCol = cl, startRow = rw,
-#                             tableStyle = tableStyle, headerStyle = headerStyle);
-#                         if (!is.null(comparisonStyle)) {
-#                             addStyle(wb, sheet, style = comparisonStyle, rows = rw + seq_along(rnames), cols = cl + seq_along(cnames), gridExpand = TRUE, stack = TRUE);
-#                         }
-#                         cl <<- cl + 1 + length(cnames) + 1;
-#                     }
-#                 )
-#                 rw <<- rw + length(rnames) + 1 + 2; # TODO: Generalize this to use loopdim!
-#             }
-#         );
-#     }
-# }
diff --git a/R/contractGrid.R b/R/contractGrid.R
deleted file mode 100644
index 407e9f7d6ab97b137f99c934d513330c9179a7af..0000000000000000000000000000000000000000
--- a/R/contractGrid.R
+++ /dev/null
@@ -1,161 +0,0 @@
-#' @title Create a grid of InsuranceContract objects or premiums with each axis representing one varying parameter
-#'
-#' @description The function \code{contractGrid} creates a (two- or multi-dimensional) grid
-#' of InsuranceContract objects, where each axis represents one of the insurance
-#' parameters varying as given in the \code{axes} argument (as a named list).
-#'
-#' @description The function \code{contractGridPremium} returns a grid of premiums as requested in
-#' the \code{premium} parameter rather than the full InsuranceContract objects.
-#' It is a convenience wrapper around \code{contractGrid} and is recommended if
-#'  one is only interested in a grid of one particular value (typically some
-#' kind of premium).
-#' The function \code{contractGridPremium} can also be used on an existing
-#' \code{contractGrid}-generated grid of contracts to extract grid of numerical
-#' values of the specified premiums. If no contract grid is passed to
-#' \code{contractGridPremium}, \code{contractGrid} will be called to create it.
-#'
-#'
-#' @details The function \code{contractGrid} will return the full [InsuranceContract]
-#' objects, so apply can later be used to extract premiums, reserves and other
-#' values to display in a grid. For this feature, one can also use the convenience
-#' function \code{contractGridPremium}.
-#'
-#' The \code{axes} list describing the parameters changing along the axes of the
-#' resulting grid is internally expanded with [expand.grid()]. The resulting flat
-#' list of parameter (together with the fixed parameters passed as \code{...})
-#' is then passed to the \ifelse{html}{\href{../../LifeInsuranceContracts/html/InsuranceContract.html#method-new}{\code{InsuranceContract$new()}}}{\code{InsuranceContract$new()()}} call to create the corresponding
-#' contract object.
-#'
-#' To create the human-readable row-/columnnames of the resulting array,
-#' the function [makeContractGridDimname()] for each value of the axes, allowing
-#' human-readable representations e.g. of a tariff or a mortality table as
-#' the dimension label.
-#'
-#'
-#'
-#' @param axes List of paramters spanning the dimensions of the grid.
-#' @param YOB optional year of bith. If missing, the \code{observationYear} and the contract's age
-#' @param observationYear The observation year, for which the grid shall be calculated. If given, the YOB is calculated from it, otherwise the contract's YOB is used
-#' @param ... In \code{contractGrid}: Additional parameters to be passed to \ifelse{html}{\href{../../LifeInsuranceContracts/html/InsuranceContract.html#method-new}{\code{InsuranceContract$new()}}}{\code{InsuranceContract$new()()}}; In \code{contractGridPremium}: Additional parameters to be passed to \code{contractGrid}.
-#
-# Params of the contractGridPreimium function:
-#' @param contractGrid (optional) existing contract grid from which to derive
-#' premiums. If not given, [contractGrid] is called with all parameters, so
-#' \code{...} should contain an \code{axes} argument in that case.
-#' @param premium The type of premium to derive (key of the \code{contract$Values$premiums} list.
-#' @param .fun The function to extract the desired premium from a contract
-#'         object. By default it accesses the premium vector and extracts the
-#'         type of premium given in the \code{premium} parameter. One can,
-#'         however pass any other extractor function to access e.g. reserves,
-#'         cash flows etc. at any desired time.
-#'
-#' @rdname contractGrid
-#'
-#' @examples
-#' # TODO
-#'
-#' @export
-contractGrid = function(axes = list(age = seq(20, 60, 10), policyPeriod = seq(5, 35, 5)), YOB = NULL, observationYear = NULL, ...) {
-
-    obsYear = observationYear;
-    # Create all combinations of the variables given for the axes:
-    gridByRow = expand.grid(axes, KEEP.OUT.ATTRS = FALSE);
-    # Apply InsuranceContract$new to each combination (and add the additional arguments)
-    vals = apply(gridByRow, 1, function(axisVals) {
-        args = c(as.list(axisVals), list(...));
-        if (!is.null(observationYear)) {
-            args$YOB = obsYear - args$age;
-        }
-        do.call(InsuranceContract$new, args)
-    })
-    dimnames = makeContractGridDimnames(axes)
-    array(vals, dim = sapply(axes, length), dimnames = dimnames)
-}
-
-# describeIn makeContractGridDimname Create a dimensional name for an [InsuranceTarif] object
-#' @export
-makeContractGridDimname.InsuranceTarif = function(value) { value$name }
-# describeIn makeContractGridDimname Create a dimensional name for an R6 object (using its \code{name} field)
-#' @export
-makeContractGridDimname.R6 = function(value) { value$name }
-# describeIn makeContractGridDimname Create a dimensional name for an [mortalityTable] object
-#' @export
-makeContractGridDimname.mortalityTable = function(value) { value@name }
-# describeIn makeContractGridDimname Create a dimensional name for a numeric parameter value
-#' @export
-makeContractGridDimname.numeric = function(value) { value }
-# describeIn makeContractGridDimname Create a dimensional name for a numeric parameter value
-#' @export
-makeContractGridDimname.double = function(value) { value }
-# describeIn makeContractGridDimname Create a dimensional name for an object that can be directly used as a human-readable row-/columnname
-#' @export
-makeContractGridDimname.default = function(value) { value }
-#' Create human-readable labels for the dimensions in a [contractGrid()]
-#'
-#' The function \code{makeContractGridDimname} generates a short, human-readable
-#' dimension label for the entries along the axes of a [contractGrid()].
-#' The default is to use the \code{value} unchanged as the row-/columnname, but
-#' for some parameter values (like a [InsuranceTarif] or [mortalityTable])
-#' a custom method of this function is needed to create the (short) human-readable
-#' representation for the axes in the grid.
-#'
-#' @param value the value along the axis, for which a name should be generated
-#' @describeIn makeContractGridDimname Create a short, human-readable dimensional name for an object (default S3 method)
-#' @examples
-#' library(MortalityTables)
-#' mortalityTables.load("Austria_Census")
-#'
-#' makeContractGridDimname(mort.AT.census.2011.unisex)
-#'
-#' makeContractGridDimnames(axes = list(
-#'     age = seq(30,60,10),
-#'     mortalityTable = c(mort.AT.census.2011.unisex, mort.AT.census.2011.male,
-#'                        mort.AT.census.2011.female))
-#' )
-#' @export
-makeContractGridDimname = function(value) { UseMethod("makeContractGridDimname", value) }
-
-#' @description The function \code{makeContractGridDimnames} generate proper
-#' dimnames for all entries of the axes of a [contractGrid()] by calling
-#' \code{makeContractGridDimname} on each of the axes' values
-#' @param axes the axes with all names, for which a name should be generated
-#' @describeIn makeContractGridDimname Generate proper dimnames for all entries of the axes of a [contractGrid()]
-#' @export
-makeContractGridDimnames = function(axes) {
-    lapply(axes, function(axis) { lapply(axis, makeContractGridDimname); } )
-}
-
-# Create a grid of insurance premiums with each axes representing one varying parameter
-#
-# The function \code{contractGridPremium} creates a (two- or multi-dimensional) grid
-#  of premiums for insurance contracts, where each axes represents one of the
-# insurance parameters varying as given in the axes argument (as named list).
-#
-# This function will return the full InsuranceContract objects, so apply can
-# later be used to extract premiums, reserves and other values to display in
-# a grid.
-#
-# If one is only interested in a grid of one particular value (typically some
-# kind of premium), the convenience function \code{contractGridPremium} is
-# provided, which returns a grid of only the desired value.
-#
-#' @param contractGrid (optional) existing contract grid from which to derive
-#' premiums. If not given, [contractGrid] is called with all parameters, so
-#' \code{...} should contain an \code{axes} argument in that case.
-#' @param premium The type of premium to derive (key of the \code{contract$Values$premiums} list.
-#' @param .fun The function to extract the desired premium from a contract
-#'         object. By default it accesses the premium vector and extracts the
-#'         type of premium given in the \code{premium} parameter. One can,
-#'         however pass any other extractor function to access e.g. reserves,
-#'         cash flows etc. at any desired time.
-#'
-#' @rdname contractGrid
-#' @export
-contractGridPremium = function(contractGrid = NULL, premium="written", .fun = function(cntr) { cntr$Values$premiums[[premium]] }, ...) {
-    if (missing(contractGrid) || is.null(contractGrid)) {
-        contractGrid = contractGrid(...)
-    }
-    apply(contractGrid, 1:length(dim(contractGrid)), function(c) { .fun(c[[1]])})
-}
-
-
diff --git a/R/create_LIC_project.R b/R/create_LIC_project.R
deleted file mode 100644
index b90ccf296c547fafc8f322a024d55792d26eac70..0000000000000000000000000000000000000000
--- a/R/create_LIC_project.R
+++ /dev/null
@@ -1,76 +0,0 @@
-# Custom project creation function, copied as a starting point from
-#     https://rstudio.github.io/rstudio-extensions/rstudio_project_templates.html
-# Copying functions and replacements originally taken from
-#     https://blog.devgenius.io/make-your-own-rstudio-project-template-1f77c4888e79
-# and heavily modified
-
-create_LIC_project <- function(path, ...) {
-    dots <- list(...)
-    CompanyName = dots$Company
-
-
-
-    ########################################
-    #####  1. ensure destination path exists, sanity checks on the company name
-
-    dir.create(path, recursive = TRUE, showWarnings = FALSE)
-
-
-    ########################################
-    #####  2. copy over all files from the template directory
-
-    LIC.src <- function (..., lib.loc = NULL, mustWork = FALSE){
-        system.file("rstudio", "templates", "project", ...,
-                    package = "LifeInsuranceContracts",
-                    lib.loc = lib.loc, mustWork = mustWork)
-    }
-    from <- LIC.src("LifeInsuranceContracts")
-    fs::dir_copy(path = from, new_path = path, overwrite = TRUE)
-
-
-    ########################################
-    #####  3. Rename all files with XXXCOMPANYXXX -> CompanyName
-
-    patternFiles = list.files(path = path, pattern = "XXXCOMPANYXXX", full.names = TRUE, recursive = TRUE)
-    replacementFiles = str_replace(patternFiles, "XXXCOMPANYXXX", CompanyName)
-    file.rename(patternFiles, replacementFiles)
-    copied_files <- list.files(path = path, recursive = TRUE)
-
-
-    ########################################
-    #####  4. Replace all file contents with XXXCOMPANYXXX -> CompanyName
-
-    LIC.replaceFileContents <- function(file, pattern, replace) {
-        suppressWarnings(tx <- readLines(file))
-        tx2 <- gsub(pattern = pattern, replacement = replace, x = tx)
-        writeLines(tx2, con = file)
-    }
-
-    LIC.replaceAllFilesContents <- function(
-        copied_files, pattern, replace, path) {
-        # Going through copied files to replace package name
-        for (f in copied_files) {
-            copied_file <- file.path(path, f)
-
-            try({
-                LIC.replaceFileContents(
-                    file = copied_file,
-                    pattern = pattern,
-                    replace = replace
-                )
-            }, silent = TRUE)
-        }
-    }
-    LIC.replaceAllFilesContents(
-        copied_files,
-        pattern = "XXXCOMPANYXXX",
-        replace = CompanyName,
-        path
-    )
-
-
-    ########################################
-    #####  5. All other small tasks
-
-
-}
diff --git a/R/exportInsuranceContractExample.R b/R/exportInsuranceContractExample.R
deleted file mode 100644
index b4b3b00824a4e5ba2e07c54cb7baca31c67e93d5..0000000000000000000000000000000000000000
--- a/R/exportInsuranceContractExample.R
+++ /dev/null
@@ -1,76 +0,0 @@
-#' @include showVmGlgExamples.R exportInsuranceContract_xlsx.R InsuranceContract.R InsuranceTarif.R
-#'
-#' @import stringr
-NULL
-
-#' Export the example calculations of an insurance contract
-#'
-#' Export the given contract to excel (full history/timeseries of all cash
-#' flows, reserves, premiums, etc.) and to a text file (sample calculation
-#' required by the Austrian regulation).
-#'
-#' Three output files are generated:
-#'   - {DATE}_{TARIFF}_Example.xlsx: Full history/timeseries
-#'   - {DATE}_{TARIFF}_Example_PremiumWaiver_t10.xlsx: Full history/timeseries
-#'                 after a premium waiver at the given time \code{prf}
-#'   - {DATE}_{TARIFF}_Examples_VmGlg.txt: Example calculation required for the
-#'                 Austrian regulation (LV-VMGLV)
-#'
-#' @param contract The \code{\link{InsuranceContract}} object to be exported
-#' @param prf The time of the premium waiver
-#' @param outdir The output directory (the file names are not configurable)
-#' @param basename The base output filename (sans .xlsx). If missing, a name of
-#'       the form 2020-08-01_TARIFNAME_EXTRANAME_RZ0.01_x35_YoB1977_LZ45_PrZ20_VS100000
-#'       is used. If given, the main contract without modification will be
-#'       exported to basename.xlsx, while the example with premium waiver will be
-#'       exported to basename_PremiumWaiver_t10.xlsx and the text file containing
-#'       the examples required by the LV-VMGV is exported to basename_VmGlg.txt.
-#' @param extraname If basename is not given, this allows a suffix to distinguish
-#'       multiple exports.
-#' @param ... Further parameters (passed on to \code{\link{showVmGlgExamples}})
-#'
-#' @examples
-#' library("MortalityTables")
-#' mortalityTables.load("Austria_Annuities_AVOe2005R")
-#' # A trivial deferred annuity tariff with no costs:
-#' tariff = InsuranceTarif$new(name="Test Annuity", type="annuity", tarif = "Annuity 1A",
-#'     mortalityTable = AVOe2005R.unisex, i=0.01)
-#' contract = InsuranceContract$new(
-#'     tariff,
-#'     age = 35, YOB = 1981,
-#'     policyPeriod = 30, premiumPeriod = 15, deferralPeriod = 15,
-#'     sumInsured = 1000,
-#'     contractClosing = as.Date("2016-10-01")
-#' );
-#' \dontrun{exportInsuranceContractExample(contract, prf = 10)}
-#'
-#' @export
-exportInsuranceContractExample = function(contract, prf = 10, outdir = ".", basename=NULL, extraname = NULL, ...) {
-    if (!("InsuranceContract" %in% class(contract))) {
-        stop("First argument to function showVmGlgExamples need to be an InsuranceContract object! ",
-             "Given object is of class: ",
-             paste(class(contract), collapse = ", "));
-    }
-    cleanname = contract$tarif$name;
-    cleanname = str_replace_all(cleanname, " ", "_");
-    cleanname = str_replace_all(cleanname, "[/:]", "-");
-    if (missing(basename)) {
-        basename = paste(outdir, "/", Sys.Date(), "_", cleanname, sep = "");
-        if (!missing(extraname) && !is.null(extraname)) {
-            basename = paste(basename, "_", extraname, sep = "")
-        }
-        params = contract$Parameters
-        basename = paste(basename, "_RZ", sprintf("%.2f", params$ActuarialBases$i), "_x", params$ContractData$age, "_YoB", year(params$ContractData$birthDate), "_LZ", params$ContractData$policyPeriod, "_PrZ", params$ContractData$premiumPeriod, "_VS", params$ContractData$sumInsured, sep = "" )
-    }
-
-    filename = paste(basename, ".xlsx", sep = "");
-    exportInsuranceContract.xlsx(contract, filename);
-
-    contract.prf = contract$clone()
-    contract.prf$premiumWaiver(t = prf)
-    filename = paste(basename, "_PremiumWaiver_t", prf, ".xlsx", sep = "");
-    exportInsuranceContract.xlsx(contract.prf, filename);
-
-    filename = paste(basename, "_VmGlg.txt", sep = "")
-    showVmGlgExamples(contract, prf = prf, ..., file = filename)
-}
diff --git a/R/exportInsuranceContract_xlsx.R b/R/exportInsuranceContract_xlsx.R
deleted file mode 100644
index 19c49f2dc01191b3b91a921fc1456d3528a03d40..0000000000000000000000000000000000000000
--- a/R/exportInsuranceContract_xlsx.R
+++ /dev/null
@@ -1,1035 +0,0 @@
-#' @include HelperFunctions.R InsuranceContract.R InsuranceParameters.R InsuranceTarif.R ProfitParticipation.R
-#'
-#' @import openxlsx
-#' @import MortalityTables
-#' @import R6
-#' @import tidyr
-#' @importFrom rlang .data
-NULL
-
-
-
-################################################ #
-# Helper Functions                            ####
-################################################ #
-
-addValuesWorksheet = function(wb, sheet, ...) {
-  addWorksheet(wb, sheet, gridLines = FALSE, ...)
-  # showGridLines(wb, sheet, showGridLines = FALSE)
-  setColWidths(wb, sheet, cols = 1:50, widths = "auto", ignoreMergedCells = TRUE)
-}
-
-
-writeAgeQTable = function(wb, sheet, probs, crow = 1, ccol = 1, styles = list()) {
-  writeData(wb, sheet, "Sterblichkeiten", startCol = ccol + 2, startRow = crow);
-  addStyle(wb, sheet, style = styles$header, rows = crow, cols = ccol + 2, stack = TRUE);
-  mergeCells(wb, sheet, rows = crow, cols = (ccol + 2):(ccol + 4))
-  writeDataTable(wb, sheet, setInsuranceValuesLabels(probs),
-                 startRow = crow + 1, startCol = ccol, colNames = TRUE, rowNames = TRUE,
-                 tableStyle = "tableStyleMedium3", withFilter = FALSE, headerStyle = styles$tableHeader);
-  # freezePane(wb, sheet, firstActiveRow = crow + 2, firstActiveCol = ccol + 2)
-  addStyle(wb, sheet, style = styles$center, rows = (crow + 2):(crow + 1 + dim(probs)[[1]]), cols = ccol:(ccol + 1), gridExpand = TRUE, stack = TRUE);
-  addStyle(wb, sheet, style = styles$qx, rows = (crow + 2):(crow + 1 + dim(probs)[[1]]), cols = (ccol + 2):(ccol + 3), gridExpand = TRUE, stack = TRUE);
-  dim(probs)[[2]] + 2;
-};
-
-writeTableCaption = function(wb, sheet, caption, rows, cols, style = NULL) {
-    r = min(rows);
-    c = min(cols);
-    writeData(wb, sheet, caption, startCol = c, startRow = r);
-    if (!is.null(style)) {
-        addStyle(wb, sheet, style = style, rows = r, cols = c, stack = TRUE);
-    }
-    mergeCells(wb, sheet, rows = rows, cols = cols);
-}
-
-writeValuesTable = function(wb, sheet, values, caption = NULL, crow = 1, ccol = 1, rowNames = FALSE, tableStyle = "tableStyleLight17", tableName = NULL, withFilter=FALSE, styles = list(), valueStyle = NULL) {
-  nrrow = dim(values)[[1]];
-  nrcol = dim(values)[[2]];
-  addcol = if (rowNames) 1 else 0;
-  ecol = ccol + addcol + nrcol - 1;
-  if (!missing(caption)) {
-      writeTableCaption(wb, sheet, caption, rows = crow, cols = (ccol + addcol):ecol, style = styles$header)
-  }
-
-  writeDataTable(wb, sheet, values, startRow = crow + 1, startCol = ccol, colNames = TRUE,
-                 rowNames = rowNames, tableStyle = tableStyle,
-                 tableName = tableName, withFilter = withFilter, headerStyle = styles$tableHeader)
-  if (!missing(valueStyle)) {
-    addStyle(wb, sheet, style = valueStyle, rows = (crow + 2):(crow + nrrow + 1), cols = (ccol + addcol):ecol, gridExpand = TRUE, stack = TRUE);
-  }
-  # width of table is the return value
-  nrcol + addcol
-};
-
-writePremiumCoefficients = function(wb, sheet, values, tarif = NULL, type = "benefits", crow = crow, ccol = ccol) {
-  writeData(wb, sheet, matrix(c(
-    "Nettopr\u00e4mie", "", "Zillmerpr\u00e4mie", "", "Bruttopr\u00e4mie", "",
-    "rel. zu VS", "rel. zu Pr\u00e4mie", "rel. zu VS", "rel. zu Pr\u00e4mie", "rel. zu VS", "rel. zu Pr\u00e4mie"), 6, 2
-  ), startCol = ccol, startRow = crow, colNames = FALSE, borders = "rows", borderColour = "gray5", borderStyle = "thin");
-  mergeCells(wb, sheet, cols = ccol, rows = crow:(crow + 1));
-  mergeCells(wb, sheet, cols = ccol, rows = (crow + 2):(crow + 3));
-  mergeCells(wb, sheet, cols = ccol, rows = (crow + 4):(crow + 5));
-  addStyle(wb, sheet, style = createStyle(halign = "left", valign = "center",
-                                        borderColour = "gray5", border = "LeftBottomTop",
-                                        borderStyle = "thin"),
-           rows = crow:(crow + 5), cols = ccol);
-  addStyle(wb, sheet, style = createStyle(halign = "right", valign = "center",
-                                        borderColour = "gray5", border = "RightBottomTop",
-                                        borderStyle = "thin"),
-           rows = crow:(crow + 5), cols = ccol + 1);
-
-  # The first column of the benefits coefficients is for "age", which we want to remove
-  mod = function(vals) { if (!is.null(vals)) as.data.frame(t(vals)) else NULL };
-  if (type == "costs") {
-    mod = function(vals) {
-      if (is.null(vals)) return(NULL)
-      vals = setInsuranceValuesLabels(vals);
-      newvals = vals;
-      dimn = dimnames(newvals);
-      dim(newvals) = c(1, dim(vals));
-      dimnames(newvals) = c(list("Coeff"), dimn);
-      costValuesAsDF(newvals)
-    };
-  }
-  coeff = rbind(mod(values[["net"]][["SumInsured"]][[type]]),
-                mod(values[["net"]][["Premium"]][[type]]),
-                mod(values[["Zillmer"]][["SumInsured"]][[type]]),
-                mod(values[["Zillmer"]][["Premium"]][[type]]),
-                mod(values[["gross"]][["SumInsured"]][[type]]),
-                mod(values[["gross"]][["Premium"]][[type]]));
-
-  writeData(wb, sheet, coeff, startCol = ccol + 2, startRow = crow, colNames = FALSE, borders = "rows", borderColour = "gray5", borderStyle = "thin");
-  dim(coeff)[[2]]
-}
-
-labelsReplace = function(labels) {
-  # TODO: Use recode here!
-
-  # Prämienarten
-  labels[labels == "unit.net"] = "Netto";
-  labels[labels == "unit.Zillmer"] = "Zillmer";
-  labels[labels == "unit.gross"] = "Brutto";
-  labels[labels == "written_yearly"] = "Verrechnet";
-  labels[labels == "written"] = "netto";
-  labels[labels == "unitcost"] = "St\u00fcckkosten";
-  labels[labels == "written_beforetax"] = "vor Steuer";
-
-  # Kosten
-  labels[labels == "alpha"] = "\u03b1";
-  labels[labels == "Zillmer"] = "Zill.";
-  labels[labels == "beta"] = "\u03b2";
-  labels[labels == "gamma"] = "\u03b3";
-  labels[labels == "gamma_nopremiums"] = "\u03b3 prf.";
-  labels[labels == "unitcosts"] = "StkK";
-
-  # Kosten-Basen
-  labels[labels == "SumInsured"] = "VS";
-  labels[labels == "SumPremiums"] = "PS";
-  labels[labels == "GrossPremium"] = "BP";
-  labels[labels == "NetPremium"] = "NP";
-  labels[labels == "Constant"] = "";
-  labels[labels == "Reserve"] = "Res.";
-
-  # Cash Flows
-  labels[labels == "premiums_advance"] = "Pr\u00e4m. vorsch.";
-  labels[labels == "premiums_arrears"] = "Pr\u00e4m. nachsch.";
-  labels[labels == "additional_capital"] = "Einschuss";
-  labels[labels == "guaranteed_advance"] = "Gar. vorsch.";
-  labels[labels == "guaranteed_arrears"] = "Gar. nachsch.";
-  labels[labels == "survival_advance"] = "Erl. vorsch.";
-  labels[labels == "survival_arrears"] = "Erl. nachsch.";
-
-  # Barwerte
-  labels[labels == "premiums"] = "Pr\u00e4m.";
-  labels[labels == "guaranteed"] = "Gar.";
-  labels[labels == "survival"] = "Erl.";
-  labels[labels == "after.death"] = "tot";
-  labels[labels == "death_SumInsured"] = "Abl. VS";
-  labels[labels == "death_GrossPremium"] = "Abl. BP";
-  labels[labels == "death"] = "Abl.";
-  labels[labels == "disease_SumInsured"] = "Krkh.";
-  labels[labels == "death_Refund_past"] = "PrRG(verg.)";
-  labels[labels == "death_Refund_future"] = "PrRG(zuk.)";
-
-  labels[labels == "death_PremiumFree"] = "Abl. prf";
-  labels[labels == "benefits"] = "Abl.Lst.";
-  labels[labels == "benefitsAndRefund"] = "Abl. + RG";
-
-  labels[labels == "once"] = "einm."
-  labels[labels == "PremiumPeriod"] = "PD"
-  labels[labels == "PremiumFree"] = "Pr.Fr."
-  labels[labels == "PolicyPeriod"] = "LZ"
-
-  # R\u00fcckstellungen
-  labels[labels == "adequate"] = "ausr.";
-  labels[labels == "contractual"] = "vertragl.";
-  labels[labels == "conversion"] = "Umrechn.";
-  labels[labels == "alphaRefund"] = "\u03b1-R\u00fccktrag";
-  labels[labels == "reduction"] = "Sparpr.f\u00fcr DK";
-  labels[labels == "PremiumsPaid"] = "Pr.Summe";
-  labels[labels == "Surrender"] = "R\u00fcckkauf";
-  labels[labels == "PremiumFreeSumInsured"] = "Prf.VS";
-  labels[labels == "Balance Sheet Reserve"] = "Bilanzreserve"
-
-  # Pr\u00e4mienzerlegung
-  labels[labels == "charged"] = "verrechnet"
-  labels[labels == "tax"] = "VSt."
-  labels[labels == "loading.frequency"] = "UJZ"
-  labels[labels == "rebate.premium"] = "Pr\u00e4m.Rab."
-  labels[labels == "rebate.partner"] = "Partn.Rab."
-  labels[labels == "unitcosts"] = "StkK"
-  labels[labels == "profit.advance"] = "Vw.GB"
-  labels[labels == "rebate.sum"] = "Summenrab."
-  labels[labels == "charge.noMedicalExam"] = "o.\u00e4rztl.U."
-  labels[labels == "gross"] = "Brutto"
-  labels[labels == "alpha.noZillmer"] = "\u03b1 (ungez.)";
-  labels[labels == "alpha.Zillmer"] = "\u03b1 (gezill.)";
-  labels[labels == "net"] = "Netto";
-  labels[labels == "risk"] = "Risikopr.";
-  labels[labels == "savings"] = "Sparpr.";
-  labels[labels == "Zillmer.risk"] = "gez.Risikopr.";
-  labels[labels == "Zillmer.savings"] = "gez.Sparpr.";
-  labels[labels == "Zillmer.amortization"] = "gez.AK-Tilgung";
-  labels[labels == "Zillmer.savings.real"] = "Sparpr.f\u00fcr DK";
-
-  # Vertragseigenschaften
-  labels[labels == "InterestRate"] = "i";
-  labels[labels == "PolicyDuration"] = "LZ";
-  labels[labels == "PremiumPayment"] = "Pr\u00e4mienzhlg.";
-  labels[labels == "Premiums"] = "Pr\u00e4mien";
-  labels[labels == "age"] = "Alter";
-  labels[labels == "Sum insured"] = "Vers.summe";
-  labels[labels == "Mortality table"] = "Sterbetafel";
-  labels[labels == "i"] = "Garantiezins";
-  labels[labels == "Age"] = "Alter";
-  labels[labels == "Policy duration"] = "Laufzeit";
-  labels[labels == "Premium period"] = "Pr\u00e4mienzahlung";
-  labels[labels == "Deferral period"] = "Aufschub";
-  labels[labels == "Guaranteed payments"] = "Garantiezeit";
-
-  labels[labels == "time"] = "ZP t";
-  labels[labels == "Comment"] = "Bemerkung";
-  labels[labels == "type"] = "Art";
-
-
-  labels
-}
-
-setInsuranceValuesLabels = function(vals) {
-  dimnames(vals) = lapply(dimnames(vals), labelsReplace);
-  vals
-}
-
-tableName = function(...) {
-  gsub('[^A-Za-z0-9_]', '', paste0(...))
-}
-
-
-exportBlockID = function(wb, sheet, id, cols, rows, styles = c()) {
-  writeData(wb, sheet, x = id, xy = c(cols[1], rows[1]))
-  addStyle(wb, sheet, style = styles$blockID, rows = rows, cols = cols, stack = TRUE);
-}
-
-getContractBlockValues = function(contract) {
-  values = data.frame(
-      "ID"                  = contract$Parameters$ContractData$id,
-      "Tariff"              = contract$tarif$tarif,
-      "Start of Contract"   = contract$Parameters$ContractData$contractClosing,
-      "Sum insured"         = contract$Parameters$ContractData$sumInsured,
-      "Mortality table"     = contract$Parameters$ActuarialBases$mortalityTable@name,
-      i                     = contract$Parameters$ActuarialBases$i,
-      "Birth Date"          = contract$Parameters$ContractData$birthDate,
-      "Age"                 = contract$Parameters$ContractData$age,
-      "Technical Age"       = contract$Parameters$ContractData$technicalAge,
-      "Policy duration"     = contract$Parameters$ContractData$policyPeriod,
-      "Premium period"      = contract$Parameters$ContractData$premiumPeriod,
-      "Deferral period"     = contract$Parameters$ContractData$deferralPeriod,
-      "Guaranteed payments" = contract$Parameters$ContractData$guaranteed,
-      stringsAsFactors = FALSE, check.names = FALSE
-    )
-  # Append all values from sub-blocks, one per line in the data.frame
-  for (b in contract$blocks) {
-    values = bind_rows(values, getContractBlockValues(b))
-  }
-  values
-}
-
-getContractBlockPremiums = function(contract) {
-  values = NULL
-  if (!is.null(contract$Values$premiums)){
-    values = bind_cols(
-      data.frame(
-        "ID" = contract$Parameters$ContractData$id,
-        stringsAsFactors = FALSE, check.names = FALSE
-      ),
-      data.frame(t(contract$Values$premiums), stringsAsFactors = FALSE, check.names = FALSE)
-    )
-  }
-  # Append all values from sub-blocks, one per line in the data.frame
-  for (b in contract$blocks) {
-    values = bind_rows(values, getContractBlockPremiums(b))
-  }
-  values
-}
-
-#' Convert the multi-dimensional costs array to a data.frame for output to a file
-#'
-#' @description Convert the cost values array to a tx15 matrix
-#' @details Not to be called directly, but implicitly by the [InsuranceContract] object.
-#' Convert the array containing cost values like cashflows, present
-#' values, etc. (objects of dimension tx5x3) to a matrix with dimensions (tx15)
-#'
-#' @param costValues Cost definition data structure
-costValuesAsDF = function(costValues) {
-  as.data.frame.table(costValues, responseName = "Value", stringsAsFactors = TRUE) %>%
-    mutate(Var4 = recode(.data$Var4, "Erl." = "")) %>%
-    arrange(.data$Var4, .data$Var2, .data$Var3, .data$Var1) %>%
-    unite("costtype", "Var2", "Var3", "Var4", sep = " ") %>%
-    pivot_wider(names_from = .data$costtype, values_from = .data$Value) %>%
-    mutate(Var1 = NULL)
-}
-
-
-
-exportLoadingsTable = function(wb, sheet, contract, crow, ccol, styles = styles, seprows = 3, tariffs.handled = c()) {
-  tarifname = contract$tarif$tarif
-  if (!(tarifname %in% tariffs.handled)) {
-    costtable = costsDisplayTable(contract$Parameters$Costs)
-    # costtable = as.data.frame.table(setInsuranceValuesLabels(contract$Parameters$Costs) )
-    # colnames(costtable) = c("Kostenart", "Basis", "Periode", "Kostensatz");
-    # costtable = costtable[costtable[,"Kostensatz"] != 0.0000,]
-    cap = sprintf("Kosten (Tarif %s)", tarifname)
-    writeValuesTable(wb, sheet, costtable, crow = crow, ccol = 1, tableName = tableName("Kosten_", tarifname), styles = styles, caption = cap);
-    # writeDataTable(wb, sheet, costtable, startCol = 1, startRow = crow + 1, colNames = TRUE, rowNames = FALSE,
-    # tableStyle = "tableStyleMedium3", headerStyle = styles$tableHeader);
-    addStyle(wb, sheet, style = styles$cost0, rows = (crow + 2):(crow + dim(costtable)[[1]] + 1), cols = 4, stack = TRUE);
-    crow = crow + dim(costtable)[[1]] + 3;
-    tariffs.handled = c(tariffs.handled, tarifname)
-  }
-
-  for (b in contract$blocks) {
-    values = exportLoadingsTable(wb = wb, sheet = sheet, contract = b, crow = crow, ccol = ccol, styles = styles, seprows = seprows, tariffs.handled = tariffs.handled)
-    crow = values$crow
-    tariffs.handled = values$tariffs.handled
-  }
-  list(crow = crow, tariffs.handled = tariffs.handled)
-}
-
-
-
-
-#' @importFrom rlang .data
-exportContractDataTable = function(wb, sheet, contract, ccol = 1, crow = 1, styles = c()) {
-  contractValues = getContractBlockValues(contract)
-  contractPremiums = getContractBlockPremiums(contract)
-  # Some types of tables don't need the birth year -> leave it out rather than throwing an error on opening in Excel!
-  # if (is.null(values["YOB"])) values["YOB"] = NULL;
-
-  # General Contract data ####
-  # TODO!
-  crow = 1;
-  writeData(wb, sheet, matrix(c(
-    "Tarif:", contract$tarif$tarif,
-    "Tarifname:", contract$tarif$name,
-    "Description:", contract$tarif$desc
-  ), 3, 2, byrow = TRUE), startCol = 1, startRow = 1, colNames = FALSE, rowNames = FALSE);
-  mergeCells(wb, sheet, cols = 2:10, rows = 1);
-  mergeCells(wb, sheet, cols = 2:10, rows = 2);
-  mergeCells(wb, sheet, cols = 2:10, rows = 3);
-  addStyle(wb, sheet, style = styles$wrap, rows = 3, cols = 2:11, stack = TRUE);
-  addStyle(wb, sheet, style = createStyle(valign = "top"), rows = 1:3, cols = 1:11, gridExpand = TRUE, stack = TRUE);
-
-  crow = crow + 4;
-  # Values (parameters, premiums, etc.) of all blocks   ####
-  additional_capital = contractPremiums$additional_capital
-  if (is.null(contract$Values$premiums)) {
-      # Contracts with multiple child blocks do not have their own premium structure => set additional capital to 0
-      additional_capital = c(0, additional_capital)
-  }
-  tmp = contractValues %>%
-    mutate(`Initial Capital` = additional_capital) %>%
-    select(
-      Vertragsteil = .data$ID, Beginn = .data$`Start of Contract`, Tarif = .data$Tariff, .data$`Sum insured`,
-      .data$`Initial Capital`,
-      .data$`Mortality table`, .data$i, .data$Age, .data$`Policy duration`, .data$`Premium period`,
-      .data$`Deferral period`, .data$`Guaranteed payments`)
-  writeValuesTable(wb, sheet, values = setInsuranceValuesLabels(tmp),
-                   caption = "Basisdaten der Vertragsteile", crow = crow, ccol = 1,
-                   tableName = "BlocksBasicData", styles = styles)
-  # Second column is start date of contract, fourth is sum insured, sixth is guaranteed interest rate
-  addStyle(wb, sheet, style = styles$currency0, rows = crow + 1 + (1:NROW(tmp)), cols = 4:5, gridExpand = TRUE, stack = TRUE);
-  addStyle(wb, sheet, style = styles$cost0, rows = crow + 1 + (1:NROW(tmp)), cols = 7, gridExpand = TRUE, stack = TRUE);
-
-  crow = crow + NROW(tmp) + 2 + 2 # 2 rows for caption/table header, 2 rows padding
-
-  # Unit Premiums ####
-  tmp = contractPremiums %>%
-    select(Vertragsteil = .data$ID, .data$unit.net, .data$unit.Zillmer, .data$unit.gross)
-  writeValuesTable(wb, sheet, values = setInsuranceValuesLabels(tmp),
-                   caption = "Pr\u00e4miens\u00e4tze (auf VS 1)", crow = crow, ccol = 1,
-                   tableName = "UnitPremiums", styles = styles, valueStyle = styles$unitpremiums)
-  crow = crow + NROW(tmp) + 2 + 2 # 2 rows for caption/table header, 2 rows padding
-
-  # Yearly Premiums ####
-  tmp = contractPremiums %>%
-    select(Vertragsteil = .data$ID, .data$net, .data$Zillmer, .data$gross, .data$written_yearly)
-  writeValuesTable(wb, sheet, values = setInsuranceValuesLabels(tmp),
-                   caption = "Jahrespr\u00e4mien", crow = crow, ccol = 1,
-                   tableName = "YearlyPremiums", styles = styles, valueStyle = styles$currency0)
-  crow = crow + NROW(tmp) + 2 + 2 # 2 rows for caption/table header, 2 rows padding
-
-  # Written Premiums ####
-  tmp = contractPremiums %>%
-    select(Vertragsteil = .data$ID, .data$written, .data$unitcost, .data$written_beforetax, .data$tax)
-  writeValuesTable(wb, sheet, values = setInsuranceValuesLabels(tmp),
-                   caption = "Pr\u00e4mien (pro Zahlungsweise)", crow = crow, ccol = 1,
-                   tableName = "WrittenPremiums", styles = styles, valueStyle = styles$currency0)
-  crow = crow + NROW(tmp) + 2 + 2 # 2 rows for caption/table header, 2 rows padding
-
-
-  # Cost structure #######
-  crow.history = crow
-
-  vals = exportLoadingsTable(wb = wb, sheet = sheet, contract = contract, crow = crow, ccol = 1, styles = styles, seprows = 3)
-  crow = vals$crow
-
-  # costtable = as.data.frame.table(setInsuranceValuesLabels(contract$Parameters$Costs) )
-  # colnames(costtable) = c("Kostenart", "Basis", "Periode", "Kostensatz");
-  # costtable = costtable[costtable[,"Kostensatz"] != 0.0000,]
-  # writeValuesTable(wb, sheet, costtable, crow = crow, ccol = 1, tableName = "Kosten", styles = styles, caption = "Kosten");
-  # # writeDataTable(wb, sheet, costtable, startCol = 1, startRow = crow + 1, colNames = TRUE, rowNames = FALSE,
-  # # tableStyle = "tableStyleMedium3", headerStyle = styles$tableHeader);
-  # addStyle(wb, sheet, style = styles$cost0, rows = (crow + 2):(crow + dim(costtable)[[1]] + 1), cols = 4, stack = TRUE);
-  # crow = crow + dim(costtable)[[1]] + 3;
-
-  # Contract history
-  # time=t, comment=sprintf("Premium waiver at time %d", t), type = "PremiumWaiver"
-  histtime = unlist(lapply(contract$history, function(xl) xl$time));
-  histcomment = unlist(lapply(contract$history, function(xl) xl$comment));
-  histtype = unlist(lapply(contract$history, function(xl) xl$type));
-  writeValuesTable(wb, sheet, setInsuranceValuesLabels(data.frame(time = histtime, Comment = histcomment, type = histtype)),
-                   crow = crow.history, ccol = 6, tableName = "Vertragshistorie", styles = styles,
-                   caption = "Vertragshistorie");
-  crow.history = crow.history + dim(histtime)[[1]] + 3;
-
-
-}
-
-exportBasicDataTable = function(wb, sheet, contract, ccol = 1, crow = 1, styles = c(), seprows = 5, freeze = TRUE) {
-  id = contract$Parameters$ContractData$id
-  nrrow = contract$Values$int$l
-
-  blockid.row = crow
-  crow = crow + 2
-  endrow = (crow + 1 + nrrow)
-  if (freeze) {
-    freezePane(wb, sheet, firstActiveRow = crow + 2, firstActiveCol = ccol + 2)
-  }
-
-  qp = contract$Values$transitionProbabilities[1:nrrow,]; # extract the probabilities once, will be needed in
-  cl = ccol
-
-  tbl = qp[,"age", drop = FALSE];
-  writeDataTable(wb, sheet, setInsuranceValuesLabels(tbl),
-                 startRow = crow + 1, startCol = cl, colNames = TRUE, rowNames = TRUE,
-                 tableStyle = "tableStyleMedium3", withFilter = FALSE, headerStyle = styles$tableHeader);
-  addStyle(wb, sheet, style = styles$center, rows = (crow + 2):endrow, cols = cl:(cl + 1), gridExpand = TRUE, stack = TRUE);
-  cl = cl + dim(tbl)[[2]] + 2;
-
-  cl.table = cl - 1;
-  cl = cl + writeValuesTable(
-    wb, sheet, as.data.frame(setInsuranceValuesLabels(contract$Values$basicData)),
-    crow = crow, ccol = cl, tableName = tableName("Grunddaten_", id), styles = styles,
-    caption = "Vertragsgrunddaten im Zeitverlauf") + 1;
-
-  # Change InterestRate column to percent format
-  # Change premiumPayment column to single-digit column
-  # Change period columnts to normal numbers
-  cnames = colnames(contract$Values$basicData);
-
-  r = (crow + 2):endrow;
-  addStyle(wb, sheet, style = styles$rate, rows = r, cols = grep("^InterestRate$", cnames) + cl.table, gridExpand = TRUE, stack = TRUE);
-  addStyle(wb, sheet, style = styles$digit, rows = r,
-           cols = grep("^(PremiumPayment|PolicyDuration|PremiumPeriod)$", cnames) + cl.table,
-           gridExpand = TRUE, stack = TRUE);
-  addStyle(wb, sheet, style = styles$currency0, rows = r, cols = grep("^(SumInsured|Premiums)$", cnames) + cl.table, gridExpand = TRUE, stack = TRUE);
-
-  exportBlockID(wb, sheet, id = id, rows = blockid.row, cols = ccol:cl, styles = styles)
-  crow = endrow + seprows
-
-  for (b in contract$blocks) {
-    crow = exportBasicDataTable(
-      wb = wb, sheet = sheet, contract = b,
-      ccol = ccol, crow = crow, styles = styles, seprows = seprows, freeze = FALSE)
-  }
-  crow
-}
-
-exportReserveTable = function(wb, sheet, contract, ccol = 1, crow = 1, styles = c(), seprows = 5, freeze = TRUE) {
-  id = contract$Parameters$ContractData$id
-  nrrow = contract$Values$int$l
-
-  blockid.row = crow
-  crow = crow + 2
-
-  if (freeze) {
-    freezePane(wb, sheet, firstActiveRow = crow + 2, firstActiveCol = ccol + 2)
-  }
-  qp = contract$Values$transitionProbabilities[1:nrrow,]; # extract the probabilities once, will be needed in
-  cl = ccol
-
-  cl = cl + writeAgeQTable(wb, sheet, probs = qp, crow = crow, ccol = cl, styles = styles);
-  cl = cl + writeValuesTable(
-    wb, sheet, as.data.frame(setInsuranceValuesLabels(contract$Values$reserves)),
-    crow = crow, ccol = cl, tableName = tableName("Reserves_", id), styles = styles,
-    caption = "Reserven", valueStyle = styles$currency0) + 1;
-
-  oldccol = cl
-  cl = cl + writeValuesTable(
-    wb, sheet, as.data.frame(setInsuranceValuesLabels(contract$Values$reservesBalanceSheet)),
-    crow = crow, ccol = cl, tableName = tableName("Bilanzreserve_", id), styles = styles,
-    caption = "Bilanzreserve", valueStyle = styles$currency0) + 1;
-
-  endrow = (crow + 1 + nrrow)
-  # First column of balance sheet reserves is the date, the second the fractional time within the contract
-  addStyle(wb, sheet, style = createStyle(numFmt = "DATE"), cols = oldccol,
-           rows = (crow + 2):endrow, gridExpand = TRUE, stack = TRUE);
-  addStyle(wb, sheet, style = createStyle(numFmt = "0.0##"), cols = oldccol + 1,
-           rows = (crow + 2):endrow, gridExpand = TRUE, stack = TRUE);
-
-  exportBlockID(wb, sheet, id = id, rows = blockid.row, cols = ccol:cl, styles = styles)
-  crow = endrow + seprows
-
-  for (b in contract$blocks) {
-    crow = exportReserveTable(
-      wb = wb, sheet = sheet, contract = b,
-      ccol = ccol, crow = crow, styles = styles, seprows = seprows, freeze = FALSE)
-  }
-  crow
-}
-
-exportProfitParticipationTable = function(wb, sheet, contract, ccol = 1, crow = 1, styles = c(), seprows = 5, freeze = TRUE) {
-  id = contract$Parameters$ContractData$id
-  nrrow = contract$Values$int$l
-  blockid.row = crow
-  crow = crow + 2
-
-  if (freeze) {
-    freezePane(wb, sheet, firstActiveRow = crow + 2, firstActiveCol = ccol + 2)
-  }
-  qp = contract$Values$transitionProbabilities[1:contract$Values$int$l,]; # extract the probabilities once, will be needed in
-
-  for (s in names(contract$Values$profitScenarios)) {
-    cl = ccol
-    sc = contract$Values$profitScenarios[[s]]
-    writeData(wb = wb, sheet = sheet, x = s, startRow = crow, startCol = ccol)
-    addStyle(wb = wb, sheet = sheet, rows = crow, cols = ccol, style = styles$scenarioID, stack = TRUE)
-    cl = cl + writeAgeQTable(wb, sheet, probs = qp, crow = crow, ccol = cl, styles = styles);
-    ccol.table = cl - 1;
-    cl = cl + writeValuesTable(wb, sheet, as.data.frame(setInsuranceValuesLabels(sc)),
-                               crow = crow, ccol = cl, # tableName = tableName("ProfitParticipation_", id, "_", s),
-                               styles = styles,
-                               # caption = s,
-                               valueStyle = styles$currency0) + 1;
-
-    cnames = colnames(sc);
-    # Make sure "terminalBonusRate" is NOT matched! Need to use a negative lookahead..
-    baseCols = grep("^(?!terminal|TBF).*Base$", cnames, perl = TRUE);
-    rateCols = grep("^(?!terminal|TBF).*(Interest|Rate)$", cnames, perl = TRUE);
-    profitCols = grep(".*Profit$", cnames);
-    terminalBonusCols = grep("^terminal.*", cnames);
-    TBFCols = grep("^TBF.*", cnames);
-    deathCols = grep("^death.*", cnames);
-    surrenderCols = grep("^surrender.*", cnames);
-    premiumWaiverCols = grep("^premiumWaiver.*", cnames);
-
-    endrow = (crow + 1 + nrrow)
-
-    # Rates are displayed in %:
-    addStyle(wb, sheet, style = styles$rate, rows = (crow + 2):endrow, cols = rateCols + ccol.table, gridExpand = TRUE, stack = TRUE);
-
-    # Add table headers for the various sections:
-    if (length(baseCols) > 0) {
-      writeTableCaption(wb, sheet, "Basisgr\u00f6\u00dfen", rows = crow, cols = baseCols + ccol.table, style = styles$header);
-    }
-    if (length(rateCols) > 0) {
-      writeTableCaption(wb, sheet, "Gewinnbeteiligungss\u00e4tze", rows = crow, cols = rateCols + ccol.table, style = styles$header);
-    }
-    if (length(profitCols) > 0) {
-      writeTableCaption(wb, sheet, "GB Zuweisungen", rows = crow, cols = profitCols + ccol.table, style = styles$header);
-    }
-    if (length(terminalBonusCols) > 0) {
-      writeTableCaption(wb, sheet, "Schlussgewinn", rows = crow, cols = terminalBonusCols + ccol.table, style = styles$header);
-    }
-    if (length(TBFCols) > 0) {
-      writeTableCaption(wb, sheet, "Schlussgewinnfonds", rows = crow, cols = TBFCols + ccol.table, style = styles$header);
-    }
-    if (length(deathCols) > 0) {
-      writeTableCaption(wb, sheet, "Todesfallleistung", rows = crow, cols = deathCols + ccol.table, style = styles$header);
-    }
-    if (length(surrenderCols) > 0) {
-
-            writeTableCaption(wb, sheet, "R\u00fcckkauf", rows = crow, cols = surrenderCols + ccol.table, style = styles$header);
-    }
-    if (length(premiumWaiverCols) > 0) {
-      writeTableCaption(wb, sheet, "Pr\u00e4mienfreistellung", rows = crow, cols = premiumWaiverCols + ccol.table, style = styles$header);
-    }
-
-    exportBlockID(wb, sheet, id = id, rows = blockid.row, cols = ccol:cl, styles = styles)
-    crow = endrow + seprows
-  }
-
-  for (b in contract$blocks) {
-    crow = exportProfitParticipationTable(
-      wb = wb, sheet = sheet, contract = b,
-      ccol = ccol, crow = crow + seprows, styles = styles, seprows = seprows, freeze = FALSE)
-  }
-  crow
-}
-
-exportPremiumCompositionTable = function(wb, sheet, contract, ccol = 1, crow = 1, styles = c(), seprows = 5, freeze = TRUE) {
-  id = contract$Parameters$ContractData$id
-  nrrow = contract$Values$int$l
-
-  blockid.row = crow
-  crow = crow + 2
-
-  if (freeze) {
-    freezePane(wb, sheet, firstActiveRow = crow + 2, firstActiveCol = ccol + 2)
-  }
-  qp = contract$Values$transitionProbabilities[1:nrrow,]; # extract the probabilities once, will be needed in
-  cl = ccol
-
-  cl = cl + writeAgeQTable(wb, sheet, probs = qp, crow = crow, ccol = cl, styles = styles);
-  cl = cl + writeValuesTable(
-    wb, sheet, as.data.frame(setInsuranceValuesLabels(contract$Values$premiumComposition)),
-    crow = crow, ccol = cl, tableName = tableName("Premium_Decomposition_", id), styles = styles,
-    caption = "Pr\u00e4mienzerlegung", valueStyle = styles$currency0) + 1;
-
-  crow = crow + nrrow + 4;
-
-  cl = ccol
-  cl = cl + writeAgeQTable(wb, sheet, probs = qp, crow = crow, ccol = cl, styles = styles);
-  cl = cl + writeValuesTable(
-    wb, sheet, as.data.frame(setInsuranceValuesLabels(contract$Values$premiumCompositionSums)),
-    crow = crow, ccol = cl, tableName = tableName("Premium_DecompositionSums_", id), styles = styles,
-    caption = "Pr\u00e4mienzerlegung (Summe zuk\u00fcnftiger Pr\u00e4mien)", valueStyle = styles$currency0) + 1;
-
-  crow = crow + nrrow + 4;
-
-  cl = ccol
-  cl = cl + writeAgeQTable(wb, sheet, probs = qp, crow = crow, ccol = cl, styles = styles);
-  cl = cl + writeValuesTable(
-    wb, sheet, as.data.frame(setInsuranceValuesLabels(contract$Values$premiumCompositionPV)),
-    crow = crow, ccol = cl, tableName = tableName("Premium_DecompositionPV_", id), styles = styles,
-    caption = "Pr\u00e4mienzerlegung(Barwerte zuk\u00fcnftiger Pr\u00e4mien)", valueStyle = styles$currency0) + 1;
-
-  endrow = (crow + 1 + nrrow)
-
-  # Insert a separator line (with minimum height and dark background)
-  addStyle(wb, sheet, style = styles$separator, rows = (endrow + 2), cols = ccol:cl, gridExpand = TRUE, stack = TRUE)
-
-
-  exportBlockID(wb, sheet, id = id, rows = blockid.row, cols = ccol:cl, styles = styles)
-  crow = endrow + 2 + seprows
-
-  for (b in contract$blocks) {
-    crow = exportPremiumCompositionTable(
-      wb = wb, sheet = sheet, contract = b,
-      ccol = ccol, crow = crow, styles = styles, seprows = seprows, freeze = FALSE)
-  }
-  crow
-}
-
-exportAbsPVTable = function(wb, sheet, contract, ccol = 1, crow = 1, styles = c(), seprows = 5, freeze = TRUE) {
-  id = contract$Parameters$ContractData$id
-  nrrow = contract$Values$int$l
-
-  blockid.row = crow
-  crow = crow + 2
-  endrow = (crow + 1 + nrrow)
-
-  if (freeze) {
-    freezePane(wb, sheet, firstActiveRow = crow + 2, firstActiveCol = ccol + 2)
-  }
-  qp = contract$Values$transitionProbabilities[1:nrrow,]; # extract the probabilities once, will be needed in
-  cl = ccol
-
-  cl = cl + writeAgeQTable(wb, sheet, probs = qp, crow = crow, ccol = cl, styles = styles);
-  cl = cl + writeValuesTable(
-    wb, sheet, as.data.frame(setInsuranceValuesLabels(contract$Values$absPresentValues)),
-    crow = crow, ccol = cl, tableName = tableName("PVabsolute_", id), styles = styles,
-    caption = "abs. Leistungs- und Kostenbarwerte", valueStyle = styles$currency0) + 1;
-
-  exportBlockID(wb, sheet, id = id, rows = blockid.row, cols = ccol:cl, styles = styles)
-  crow = endrow + seprows
-
-  for (b in contract$blocks) {
-    crow = exportAbsPVTable(
-      wb = wb, sheet = sheet, contract = b,
-      ccol = ccol, crow = crow, styles = styles, seprows = seprows, freeze = FALSE)
-  }
-  crow
-}
-
-exportAbsCFTable = function(wb, sheet, contract, ccol = 1, crow = 1, styles = c(), seprows = 5, freeze = TRUE) {
-  id = contract$Parameters$ContractData$id
-  nrrow = contract$Values$int$l
-
-  blockid.row = crow
-  crow = crow + 2
-  endrow = (crow + 1 + nrrow)
-
-  if (freeze) {
-    freezePane(wb, sheet, firstActiveRow = crow + 2, firstActiveCol = ccol + 2)
-  }
-  qp = contract$Values$transitionProbabilities[1:nrrow,]; # extract the probabilities once, will be needed in
-  cl = ccol
-
-  cl = cl + writeAgeQTable(wb, sheet, probs = qp, crow = crow, ccol = cl, styles = styles);
-  cl = cl + writeValuesTable(
-    wb, sheet, as.data.frame(setInsuranceValuesLabels(contract$Values$absCashFlows)),
-    crow = crow, ccol = cl, tableName = tableName("CFabsolute_", id), styles = styles,
-    caption = "abs. Leistungs- und Kostencashflows", valueStyle = styles$currency0) + 1;
-
-  exportBlockID(wb, sheet, id = id, rows = blockid.row, cols = ccol:cl, styles = styles)
-  crow = endrow + seprows
-
-  for (b in contract$blocks) {
-    crow = exportAbsCFTable(
-      wb = wb, sheet = sheet, contract = b,
-      ccol = ccol, crow = crow, styles = styles, seprows = seprows, freeze = FALSE)
-  }
-  crow
-}
-
-# Return list of all column indices witout any non-zero entries => these columns are to be hidden later
-empty.col.indices = function(df) {
-  unname(which(colSums(df != 0) == 0))
-}
-
-exportPVTable = function(wb, sheet, contract, ccol = 1, crow = 1, styles = c(), seprows = 5, freeze = TRUE) {
-  empty.cols = NULL;
-  if (!is.null(contract$Values$presentValues)) {
-    id = contract$Parameters$ContractData$id
-    nrrow = contract$Values$int$l
-
-    blockid.row = crow
-    crow = crow + 2
-    if (freeze) {
-      freezePane(wb, sheet, firstActiveRow = crow + 2 + 6, firstActiveCol = ccol + 2)
-    }
-
-    # Time the premium was last calculated (i.e. access the present values at that time rather than 0 in the formulas for the premium)
-    tPrem = contract$Values$int$premiumCalculationTime
-
-    qp = contract$Values$transitionProbabilities[1:nrrow,]; # extract the probabilities once, will be needed in
-    costPV = costValuesAsDF(setInsuranceValuesLabels(contract$Values$presentValuesCosts))
-    cl = ccol
-
-    # We add six lines before the present values to show the coefficients for the premium calculation
-    cl = cl + writeAgeQTable(wb, sheet, probs = qp, crow = crow + 6, ccol = cl, styles = styles);
-
-    # Store the start/end columns of the coefficients, since we need them later in the formula for the premiums!
-    w1 = writePremiumCoefficients(wb, sheet, contract$Values$premiumCoefficients, type = "benefits", crow = crow, ccol = cl - 2, tarif = contract$tarif);
-    area.premiumcoeff = paste0(int2col(cl), "%d:", int2col(cl + w1 - 1), "%d");
-    area.premiumvals  = paste0("$", int2col(cl), "$", crow + 6 + 2 + tPrem, ":$", int2col(cl + w1 - 1), "$", crow + 6 + 2 + tPrem);
-    empty.cols = c(empty.cols, empty.col.indices(contract$Values$presentValues) - 1 + cl)
-    cl = cl + writeValuesTable(wb, sheet, as.data.frame(setInsuranceValuesLabels(contract$Values$presentValues)),
-                                  crow = crow + 6, ccol = cl, tableName = tableName("PresentValues_Benefits_", id), styles = styles,
-                                  caption = "Leistungsbarwerte", valueStyle = styles$pv0) + 1;
-
-    w2 = writePremiumCoefficients(wb, sheet, contract$Values$premiumCoefficients, type = "costs", crow = crow, ccol = cl - 2, tarif = contract$tarif);
-    area.costcoeff = paste0(int2col(cl), "%d:", int2col(cl + w2 - 1), "%d");
-    area.costvals  = paste0("$", int2col(cl), "$", crow + 6 + 2 + tPrem, ":$", int2col(cl + w2 - 1), "$", crow + 6 + 2 + tPrem);
-    empty.cols = c(empty.cols, empty.col.indices(as.data.frame(costPV)) - 1 + cl)
-    cl = cl + writeValuesTable(wb, sheet, as.data.frame(costPV),
-                               crow = crow + 6, ccol = cl, tableName = tableName("PresentValues_Costs_", id), styles = styles,
-                               caption = "Kostenbarwerte", valueStyle = styles$cost0) + 1;
-
-    # Now print out the formulas for premium calculation into the columns 2 and 3:
-    writeData(wb, sheet, as.data.frame(c("Nettopr\u00e4mie", contract$Values$premiums[["net"]],"Zillmerpr\u00e4mie", contract$Values$premiums[["Zillmer"]], "Bruttopr\u00e4mie", contract$Values$premiums[["gross"]])), startCol = ccol, startRow = crow, colNames = FALSE, borders = "rows");
-    for (i in 0:5) {
-      writeFormula(wb, sheet, paste0("SUMPRODUCT(", sprintf(area.premiumcoeff, crow + i, crow + i), ", ", area.premiumvals, ") + SUMPRODUCT(", sprintf(area.costcoeff, crow + i, crow + i), ", ", area.costvals, ")"), startCol = ccol + 2, startRow = crow + i);
-      addStyle(wb, sheet, style = styles$pv0, rows = crow + i, cols = ccol + 2, stack = TRUE);
-    }
-    for (i in c(0,2,4)) {
-      writeFormula(wb, sheet, paste0(int2col(3), crow + i, "/", int2col(ccol + 2), crow + i + 1), startCol = ccol + 1, startRow = crow + i);
-      addStyle(wb, sheet, style = styles$pv0, rows = crow + i, cols = ccol + 1, stack = TRUE);
-    }
-    for (i in c(1,3,5)) {
-      writeFormula(wb, sheet, paste0(int2col(2), crow + i - 1, "*", contract$Parameters$ContractData$sumInsured), startCol = ccol + 1, startRow = crow + i);
-      addStyle(wb, sheet, style = styles$currency0, rows = crow + i, cols = ccol:(ccol + 1), stack = TRUE, gridExpand = TRUE);
-    }
-
-
-    endrow = (crow + 6 + 1 + nrrow)
-    exportBlockID(wb, sheet, id = id, rows = blockid.row, cols = ccol:cl, styles = styles)
-    crow = endrow + seprows
-  }
-
-  for (b in contract$blocks) {
-    res = exportPVTable(
-      wb = wb, sheet = sheet, contract = b,
-      ccol = ccol, crow = crow, styles = styles, seprows = seprows, freeze = FALSE)
-    # exportPVTable returns a list of the next excel table row and a list of all empty columns (to be hidden later on)
-    crow = res$crow
-    if (is.null(empty.cols)) {
-      empty.cols = res$empty.cols
-    } else {
-      empty.cols = intersect(empty.cols, res$empty.cols)
-    }
-  }
-  list(crow = crow, empty.cols = empty.cols)
-}
-
-exportCFTable = function(wb, sheet, contract, ccol = 1, crow = 1, styles = c(), seprows = 5, freeze = TRUE) {
-  # Write out only if the contract has unit cash flows (i.e. it is a leaf contract block without children on its own!)
-  empty.cols = NULL;
-  if (!is.null(contract$Values$cashFlows)) {
-    id = contract$Parameters$ContractData$id
-    nrrow = contract$Values$int$l
-    empty.cols = c()
-
-    blockid.row = crow
-    crow = crow + 2
-    endrow = (crow + 1 + nrrow)
-
-    if (freeze) {
-      freezePane(wb, sheet, firstActiveRow = crow + 2, firstActiveCol = ccol + 2)
-    }
-    qp = contract$Values$transitionProbabilities[1:nrrow,]; # extract the probabilities once, will be needed in
-    cl = ccol
-
-    cl = cl + writeAgeQTable(wb, sheet, probs = qp, crow = crow, ccol = cl, styles = styles);
-    empty.cols = c(empty.cols, empty.col.indices(contract$Values$cashFlows)- 1  + cl)
-    cl = cl + writeValuesTable(
-      wb, sheet, setInsuranceValuesLabels(contract$Values$cashFlows),
-      crow = crow, ccol = cl, tableName = tableName("CF_", id), styles = styles,
-      caption = "Leistungscashflows", valueStyle = styles$hide0) + 1;
-    costCF = costValuesAsDF(setInsuranceValuesLabels(contract$Values$cashFlowsCosts))
-    empty.cols = c(empty.cols, empty.col.indices(costCF)- 1  + cl)
-    cl = cl + writeValuesTable(
-      wb, sheet, costCF,
-      crow = crow, ccol = cl, tableName = tableName("CFcosts_", id), styles = styles,
-      caption = "Kostencashflows", valueStyle = styles$cost0) + 1;
-
-    exportBlockID(wb, sheet, id = id, rows = blockid.row, cols = ccol:cl, styles = styles)
-    crow = endrow + seprows
-  }
-
-  for (b in contract$blocks) {
-    res = exportCFTable(
-      wb = wb, sheet = sheet, contract = b,
-      ccol = ccol, crow = crow, styles = styles, seprows = seprows, freeze = FALSE)
-    # exportCFTable returns a list of the next excel table row and a list of all empty columns (to be hidden later on)
-    crow = res$crow
-    if (is.null(empty.cols)) {
-      empty.cols = res$empty.cols
-    } else {
-      empty.cols = intersect(empty.cols, res$empty.cols)
-    }
-  }
-  list(crow = crow, empty.cols = empty.cols)
-}
-
-
-
-
-
-############################################################################### #
-#
-# The actual export function
-#
-#    exportInsuranceContract.xlsx(contract, filename)
-#
-############################################################################### #
-
-#' Export an insurance act object tocontract (object of class [InsuranceContract]) to an Excel file
-#'
-#' @details The function \code{exportInsuranceContract.xlsx} exports an object
-#' of class [InsuranceContract] to an Excel file. All basic data, as well as
-#' the time series of (absolute and unit) cash flows, reserves, premiums, premium
-#' composition and all profit participation scenarios are exported to the file
-#' in nicely looking tables.
-#'
-#' No new calculations are done in this function. It only prints out the values
-#' stored in \code{contract$Values}.
-#'
-#' @param contract The insurance contract to export
-#' @param filename Target Excel filename for export
-#'
-#' @examples
-#' library("MortalityTables")
-#' mortalityTables.load("Austria_Annuities_AVOe2005R")
-#' # A trivial deferred annuity tariff with no costs:
-#' tariff = InsuranceTarif$new(name = "Test Annuity", type = "annuity", tarif = "Annuity 1A",
-#'     mortalityTable = AVOe2005R.unisex, i=0.01)
-#' contract = InsuranceContract$new(
-#'     tariff,
-#'     age = 35, YOB = 1981,
-#'     policyPeriod = 30, premiumPeriod = 15, deferralPeriod = 15,
-#'     sumInsured = 1000,
-#'     contractClosing = as.Date("2016-10-01")
-#' );
-#' \dontrun{exportInsuranceContract.xlsx(contract, "Example_annuity_contract.xlsx")}
-#' @export
-exportInsuranceContract.xlsx = function(contract, filename) {
-  # TODO: argument checking for contract and filename
-
-  ###
-  nrrows = contract$Values$int$l; # Some vectors are longer(e.g. qx), so determine the max nr or rows
-  qp = contract$Values$transitionProbabilities[1:nrrows,]; # extract the probabilities once, will be needed in every sheet
-
-  ############################################### #
-  # Style information                          ####
-  ############################################### #
-  styles = list(
-    blockID = createStyle(border = "Bottom", borderColour = "#ab6310", fgFill = "#d0d0d0", halign = "left", textDecoration = "bold", fontSize = 14),
-    scenarioID = createStyle(halign = "left", textDecoration = "bold", fontSize = 14),
-    header = createStyle(border = "TopBottomLeftRight", borderColour = "#DA9694", borderStyle = "medium",
-                         fgFill = "#C0504D", fontColour = "#FFFFFF",
-                         halign = "center", valign = "center", textDecoration = "bold"),
-    tableHeader = createStyle(#border = "To2pLeftRight", borderColour = "#DA9694", borderstyle = "medium",
-                              #bgFill = "#2C0504D", fontColour = "#FFFFFF",
-                              fgFill = "#E0E0E0",
-                              halign = "center", valign = "center", textDecoration = "bold"),
-    hide0 = createStyle(numFmt = "General; General; \"\""),
-    currency0 = createStyle(numFmt = "[$\u20ac-C07] #,##0.00;[red]-[$\u20ac-C07] #,##0.00;\"\""),
-    cost0 = createStyle(numFmt = "0.0##%; 0.0##%; \"\""),
-    pv0 = createStyle(numFmt = "0.00000;-0.00000;\"\""),
-    qx = createStyle(numFmt = "0.000000"),
-    rate = createStyle(numFmt = "0.00####%"),
-    digit = createStyle(numFmt = "0;-0;\"\""),
-    wrap = createStyle(wrapText = TRUE),
-    center = createStyle(halign = "center", valign = "center"),
-    separator = createStyle(fgFill = "#000000"),
-    unitpremiums = createStyle(numFmt = "0.00000%; -0.00000%;"),
-    date = createStyle(numFmt = "DATE")
-  );
-
-  ############################################### #
-  # General Workbook setup                     ####
-  ############################################### #
-  wb = openxlsx::createWorkbook();
-
-
-  ############################################### #
-  # Basic parameters                           ####
-  ############################################### #
-
-  # Print out general Contract and Tariff information, including results
-  sheet = "Tarifinformationen"
-  addValuesWorksheet(wb, sheet);
-  exportContractDataTable(
-    wb, sheet = sheet, contract = contract,
-    ccol = 1, crow = 1, styles = styles)
-
-
-  ################################################# #
-  # Print out Basic contract data as time series ####
-  ################################################# #
-
-  sheet = "Basisdaten";
-  addValuesWorksheet(wb, sheet);
-  exportBasicDataTable(
-    wb = wb, sheet = sheet, contract = contract,
-    ccol = 1, crow = 4, styles = styles)
-
-
-  ############################################### #
-  # Print out Reserves                         ####
-  ############################################### #
-
-  sheet = "Reserven";
-  addValuesWorksheet(wb, sheet);
-  exportReserveTable(
-    wb = wb, sheet = sheet, contract = contract,
-    ccol = 1, crow = 4, styles = styles)
-
-
-  ################################################ #
-  # Print out Profit Participation              ####
-  ################################################ #
-
-  if (!is.null(contract$Values$profitParticipation)) {
-    sheet = "Gewinnbeteiligung";
-    addValuesWorksheet(wb, sheet);
-    exportProfitParticipationTable(
-      wb = wb, sheet = sheet, contract = contract,
-      ccol = 1, crow = 4, styles = styles)
-  }
-
-
-  ############################################### #
-  # Print out premium decomposition            ####
-  ############################################### #
-
-  sheet = "Pr\u00e4mienzerlegung";
-  addValuesWorksheet(wb, sheet);
-  exportPremiumCompositionTable(
-    wb = wb, sheet = sheet, contract = contract,
-    ccol = 1, crow = 4, styles = styles)
-
-
-  ################################################ #
-  # Print out absolute values of present values ####
-  ################################################ #
-
-  sheet = "abs.Barwerte";
-  addValuesWorksheet(wb, sheet);
-  exportAbsPVTable(
-    wb = wb, sheet = sheet, contract = contract,
-    ccol = 1, crow = 4,styles = styles)
-
-
-  ############################################### #
-  # Print out absolute values for cash flows   ####
-  ############################################### #
-
-  sheet = "abs.Cash-Flows";
-  addValuesWorksheet(wb, sheet);
-  exportAbsCFTable(
-    wb = wb, sheet = sheet, contract = contract,
-    ccol = 1, crow = 4, styles = styles)
-
-
-  ############################################### #
-  # Print out present values                   ####
-  ############################################### #
-
-  # TODO-blocks
-  sheet = "Barwerte";
-  addValuesWorksheet(wb, sheet);
-  res = exportPVTable(
-    wb = wb, sheet = sheet, contract = contract,
-    ccol = 1, crow = 4,styles = styles)
-  if (length(res$empty.cols) > 0) {
-    setColWidths(wb, sheet = sheet, cols = res$empty.cols, hidden = TRUE)
-  }
-
-
-  ############################################## #
-  # Print out cash flows                      ####
-  ############################################## #
-
-  sheet = "Cash-Flows";
-  addValuesWorksheet(wb, sheet);
-  res = exportCFTable(
-    wb = wb, sheet = sheet, contract = contract,
-    ccol = 1, crow = 4, styles = styles)
-  if (length(res$empty.cols) > 0) {
-    setColWidths(wb, sheet = sheet, cols = res$empty.cols, hidden = TRUE)
-  }
-
-
-
-
-  ############################################## #
-  # Save file                                 ####
-  ############################################## #
-
-  openxlsx::saveWorkbook(wb, filename, overwrite = TRUE)
-
-}
diff --git a/R/showVmGlgExamples.R b/R/showVmGlgExamples.R
deleted file mode 100644
index 3fff4d5134ac2177485e39167e25b4e9dcd125a1..0000000000000000000000000000000000000000
--- a/R/showVmGlgExamples.R
+++ /dev/null
@@ -1,374 +0,0 @@
-#' @include InsuranceContract.R
-#'
-#' @import MortalityTables
-#' @import scales
-#' @importFrom methods is
-NULL
-
-# Internal helper function to calculate all values => will be used by
-# showVmGlgExamples, testVmGlgExample and vmGlgExample.generateTest
-calcVmGlgExample = function(contract, prf = 10, t = 10, t_prf = 12, ...) {
-
-    if (is(contract, "InsuranceTarif")) {
-        tariff = contract
-        contract = InsuranceContract$new(tariff, ...)
-    }
-    has.prf = prf < contract$Parameters$ContractData$premiumPeriod;
-    if (!is(contract, "InsuranceContract")) {
-        stop("First argument to the functions showVmGlgExamples, testVmGlgExample
-             and vmGlgExample.generateTest need to be an InsuranceContract or InsuranceTarif object! ",
-             "Given object is of class: ",
-             paste(class(contract), collapse = ", "));
-    }
-    if (has.prf) {
-        contract.prf = contract$clone();
-        contract.prf$premiumWaiver(t = prf)
-    }
-
-    vals = list(
-        t = t,
-        prf = prf,
-        t_prf = t_prf,
-        contractClosing = contract$Parameters$ContractData$contractClosing,
-
-        TarifName = contract$tarif$name,
-        TarifDesc = contract$tarif$desc,
-        TarifType = as.character(contract$tarif$tariffType),
-        VS = contract$Parameters$ContractData$sumInsured,
-        Age = contract$Parameters$ContractData$age,
-        policyPeriod = contract$Parameters$ContractData$policyPeriod,
-        premiumPeriod = contract$Parameters$ContractData$premiumPeriod,
-        deferralPeriod = contract$Parameters$ContractData$deferralPeriod,
-        guaranteedPeriod = contract$Parameters$ContractData$guaranteedPeriod,
-        Interest = contract$Parameters$ActuarialBases$i,
-        MortalityTable = contract$Parameters$ActuarialBases$mortalityTable@name,
-
-        net = contract$Values$premiums[["net"]],
-        Zillmer = contract$Values$premiums[["Zillmer"]],
-        gross = contract$Values$premiums[["gross"]],
-        written = contract$Values$premiums[["written"]],
-        savings = contract$Values$premiumComposition[[t + 1, "Zillmer.savings"]],
-        risk = contract$Values$premiumComposition[[t + 1, "Zillmer.risk"]],
-        ZillmerRes = contract$Values$reserves[[t + 1, "Zillmer"]],
-        ZillmerRes.prf = if(has.prf) contract.prf$Values$reserves[[t_prf + 1, "Zillmer"]],
-        VwKostenRes = contract$Values$reserves[[t + 1, "gamma"]],
-        VwKostenRes.prf = if(has.prf) contract.prf$Values$reserves[[t_prf + 1, "gamma"]],
-        Bilanzstichtag = contract$Values$reservesBalanceSheet[[t + 1, "time"]],
-        Bilanzreserve = contract$Values$reservesBalanceSheet[[t + 1, "Balance Sheet Reserve"]],
-        Praemienuebertrag = contract$Values$reservesBalanceSheet[[t + 1, "unearned Premiums"]],
-        Rueckkaufsreserve = contract$Values$reserves[[t + 1, "reduction"]],
-        Rueckkaufswert = contract$Values$reserves[[t + 1, "Surrender"]],
-        Abschlusskostenruecktrag = contract$Values$reserves[[t + 1, "alphaRefund"]],
-        Rueckkaufswert.prf = if(has.prf) contract.prf$Values$reserves[[t_prf + 1, "Surrender"]],
-        VS.after_prf = if(has.prf) contract.prf$Values$reserves[[t_prf + 1, "PremiumFreeSumInsured"]],
-        VS.prf = if(has.prf) contract$Values$reserves[[t + 1, "PremiumFreeSumInsured"]]
-
-    );
-    # manually remove all NULL elements (premium waiver not possible  )
-    vals = Filter(Negate(is.null), vals)
-    vals
-}
-
-
-#' Display insurance contract calculation example
-#'
-#' Display the values of the example calculation of the given insurance contract
-#' as required by the Austrian regulation (LV-VMGLV, "LV
-#' Versicherungsmathematische Grundlagen Verordnung").
-#'
-#' @param contract The insurance contract to calculate and show
-#' @param t Time for which to show all values (except premium-free values)
-#' @param prf Time of premium waiver (premium-free)
-#' @param t_prf Time for which to show all values after the premium waiver
-#' @param file If given, outputs all information to the file rather than the console
-#' @param ... Further parameters for generating the contract for a tariff object
-#'
-#' @examples
-#' library(MortalityTables)
-#' mortalityTables.load("Austria_Annuities_AVOe2005R")
-#' # A trivial deferred annuity tariff with no costs:
-#' tariff = InsuranceTarif$new(name="Test Annuity", type="annuity",
-#'     mortalityTable = AVOe2005R.unisex, i=0.01)
-#' contract = InsuranceContract$new(
-#'     tariff,
-#'     age = 35, YOB = 1981,
-#'     policyPeriod = 30, premiumPeriod = 15, deferralPeriod = 15,
-#'     sumInsured = 1000,
-#'     contractClosing = as.Date("2016-10-01")
-#' );
-#' showVmGlgExamples(contract)
-#'
-#' # Optionally output to a file rather than the console:
-#' \dontrun{
-#' showVmGlgExamples(contract, file = "annuity-example.txt")
-#' }
-#' @export
-showVmGlgExamples = function(contract, prf = 10, t = 10, t_prf = 12, file = "", ...) {
-    if (getOption('LIC.debug.showVmGlgExamples', FALSE)) {
-        browser();
-    }
-    vals = calcVmGlgExample(contract, prf = prf, t = t, t_prf = t_prf, ...);
-
-    has.prf = prf < contract$Parameters$ContractData$premiumPeriod;
-
-    output = c(
-        sprintf("Tarif: %s", vals$TarifName),
-        vals$tarifDesc,
-        sprintf("Typ: %s", vals$tariffType),
-        sprintf("VS: %.2f", vals$VS),
-        sprintf("Alter: %d, LZ: %d, Pr\u00e4mienzahlung: %d, Aufschubzeit: %d, Garantiezeit: %d",
-                vals$age,
-                vals$policyPeriod,
-                vals$premiumPeriod,
-                vals$deferralPeriod,
-                vals$guaranteedPeriod),
-
-        sprintf("Rechenzins: %s, Sterbetafel: %s",
-                scales::percent(vals$Interest), vals$MortalityTable),
-        "",
-
-        "Pr\u00e4mien:",
-        "========",
-        sprintf("Nettopr\u00e4mie:         %8.2f", vals$net),
-        sprintf("Zillmerpr\u00e4mie:       %8.2f", vals$Zillmer),
-        sprintf("Bruttopr\u00e4mie:        %8.2f", vals$gross),
-        sprintf("Vorgeschr.Pr.:       %8.2f", vals$written),
-        "",
-
-        sprintf("Sparpr\u00e4mie (t=%d):   %8.2f", vals$t, vals$savings),
-        sprintf("Risikopr\u00e4mie (t=%d): %8.2f", vals$t, vals$risk),
-        "",
-
-        "Reserven:",
-        "=========",
-        sprintf("Pr\u00e4mienpflichtig (t=%d):             %8.2f", vals$t, vals$ZillmerRes),
-        sprintf("Pr.Frei (mangels Zahlung) (tprf=%d): %8.2f", vals$t_prf, vals$ZillmerRes.prf),
-        sprintf("VwKostenreserve (t=%d):              %8.2f", vals$t, vals$VwKostenRes),
-        sprintf("VwKostenreserve (Pr.Frei) (tprf=%d): %8.2f", vals$t_prf, vals$VwKostenRes.prf),
-        "",
-
-        sprintf("Bilanzreserve (t=%.2f):             %8.2f",
-                vals$Bilanzstichtag, vals$Bilanzreserve),
-        sprintf("Pr\u00e4mien\u00fcbertrag (BM=%2d):             %8.2f",
-                lubridate::month(vals$contractClosing), vals$Praemienuebertrag),
-        "",
-
-        "R\u00fcckkauf und Pr\u00e4mienfreistellung:",
-        "=================================",
-        sprintf("R\u00fcckkaufsreserve (t=%d):          %8.2f", vals$t, vals$Rueckkaufsreserve),
-        sprintf("R\u00fcckkaufswert (t=%d):             %8.2f", vals$t, vals$Rueckkaufswert),
-        sprintf("Abschlusskostenr\u00fccktrag (t=%d):   %8.2f", vals$t, vals$Abschlusskostenruecktrag),
-        "",
-
-        sprintf("R\u00fcckkaufswert (Prf.) (t=%d):      %8.2f (VS: %.2f)",
-                vals$t_prf, vals$Rueckkaufswert, vals$VS.after_prf),
-        "",
-
-        sprintf("Pr\u00e4mienfreie VS (t=%d):           %8.2f",
-                vals$t, vals$VS.prf)
-    );
-    output.str = paste(output, collapse = '\r\n')
-    cat(output.str, file = file)
-}
-
-
-#' Perform unit tests of given standard values of the insurance contract example
-#'
-#' Check the values of the example calculation of the given insurance contract
-#' as required by the Austrian regulation (LV-VMGLV, "LV
-#' Versicherungsmathematische Grundlagen Verordnung").
-#' Missing params not passed to the function call will be silently ignored and
-#' not cause unit test failures.
-#'
-#' The easiest way to write unit-tests is using the function \code{vmGlgExample.generateTest}
-#'
-#' @param contract The insurance contract to calculate and check
-#' @param t Time for which to check all values (except premium-free values)
-#' @param prf Time of premium waiver (premium-free)
-#' @param t_prf Time for which to check all values after the premium waiver
-#' @param net,Zillmer,gross,written,savings,risk,ZillmerRes,ZillmerRes.prf,VwKostenRes,VwKostenRes.prf,Bilanzreserve,Praemienuebertrag,Rueckkaufsreserve,Rueckkaufswert,Abschlusskostenruecktrag,Rueckkaufswert.prf,VS.prf Values as printed out by showVmGlgExamples
-#' @param absTolerance If non-NULL, will ignore small floating point differences. It uses same algorithm as all.equal()
-#' @param ... Further parameters for generating the contract for a tariff object
-#'
-#' @examples
-#' library(MortalityTables)
-#' mortalityTables.load("Austria_Annuities_AVOe2005R")
-#'
-#' \dontrun{
-#' test_that("Testtarif", {
-#'     # A trivial deferred annuity tariff with no costs:
-#'     tariff = InsuranceTarif$new(name="Test Annuity", type="annuity",
-#'         mortalityTable = AVOe2005R.unisex, i=0.01)
-#'     contract = InsuranceContract$new(
-#'         tariff,
-#'         age = 35, YOB = 1981,
-#'         policyPeriod = 30, premiumPeriod = 15, deferralPeriod = 15,
-#'         sumInsured = 1000,
-#'         contractClosing = as.Date("2016-10-01")
-#'     );
-#'
-#'     testVmGlgExample(
-#'         contract, t = 10,
-#'         net = 850.09, # NOT_CHECKED: Zillmer = 950.09,
-#'         gross = 850.09,
-#'         written = 884.09,
-#'         savings = 857.09, risk = -7.00,
-#'         ZillmerRes = 9011.40,
-#'         ZillmerRes.prf = 9205.96,
-#'         VwKostenRes = 0.00,
-#'         VwKostenRes.prf = 0.00,
-#'         Bilanzreserve = 9250.35,
-#'         Praemienuebertrag = 212.52,
-#'         Rueckkaufsreserve = 9011.40,
-#'         Rueckkaufswert = 9011.40,
-#'         Abschlusskostenruecktrag = 0.00,
-#'         Rueckkaufswert.prf = 9205.96,
-#'         VS.prf = 685.12
-#'     )
-#' })
-#'}
-#'
-#' @export
-testVmGlgExample = function(contract, prf = 10, t = 10, t_prf = 12, net, Zillmer, gross, written, savings, risk,
-                            ZillmerRes, ZillmerRes.prf, VwKostenRes, VwKostenRes.prf,
-                            Bilanzreserve, Praemienuebertrag,
-                            Rueckkaufsreserve, Rueckkaufswert, Abschlusskostenruecktrag,
-                            Rueckkaufswert.prf, VS.prf, absTolerance = 0.015,
-                            ...
-) {
-    if (getOption('LIC.debug.testVmGlgExample', FALSE)) {
-        browser();
-    }
-    vals = calcVmGlgExample(contract, prf = prf, t = t, t_prf = t_prf, ...);
-    has.prf = prf < contract$Parameters$ContractData$premiumPeriod;
-
-    if (!missing(net)) {
-        eval(bquote(expect_equal(vals$net, .(net), tolerance = abs(absTolerance / .(net)))))
-    }
-    if (!missing(Zillmer)) {
-        eval(bquote(expect_equal(vals$Zillmer, .(Zillmer), tolerance = abs(absTolerance / .(Zillmer)))))
-    }
-    if (!missing(gross)) {
-        eval(bquote(expect_equal(vals$gross, .(gross), tolerance = abs(absTolerance / .(gross)))))
-    }
-    if (!missing(written)) {
-        eval(bquote(expect_equal(vals$written, .(written), tolerance = abs(absTolerance / .(written)))))
-    }
-    if (!missing(savings)) {
-        eval(bquote(expect_equal(vals$savings, .(savings), tolerance = abs(absTolerance / .(savings)))))
-    }
-    if (!missing(risk)) {
-        eval(bquote(expect_equal(vals$risk, .(risk), tolerance = abs(absTolerance / .(risk)))))
-    }
-
-    if (!missing(ZillmerRes)) {
-        eval(bquote(expect_equal(vals$ZillmerRes, .(ZillmerRes), tolerance = abs(absTolerance / .(ZillmerRes)))))
-    }
-    if (!missing(ZillmerRes.prf)) {
-        eval(bquote(expect_equal(vals$ZillmerRes.prf, .(ZillmerRes.prf), tolerance = abs(absTolerance / .(ZillmerRes.prf)))))
-    }
-    if (!missing(VwKostenRes)) {
-        eval(bquote(expect_equal(vals$VwKostenRes, .(VwKostenRes), tolerance = abs(absTolerance / .(VwKostenRes)))))
-    }
-    if (!missing(VwKostenRes.prf)) {
-        eval(bquote(expect_equal(vals$VwKostenRes.prf, .(VwKostenRes.prf), tolerance = abs(absTolerance / .(VwKostenRes.prf)))))
-    }
-
-
-    if (!missing(Bilanzreserve)) {
-        eval(bquote(expect_equal(vals$Bilanzreserve, .(Bilanzreserve), tolerance = abs(absTolerance / .(Bilanzreserve)))))
-    }
-    if (!missing(Praemienuebertrag)) {
-        eval(bquote(expect_equal(vals$Praemienuebertrag, .(Praemienuebertrag), tolerance = abs(absTolerance / .(Praemienuebertrag)))))
-    }
-
-    if (!missing(Rueckkaufsreserve)) {
-        eval(bquote(expect_equal(vals$Rueckkaufsreserve, .(Rueckkaufsreserve), tolerance = abs(absTolerance / .(Rueckkaufsreserve)))))
-    }
-    if (!missing(Rueckkaufswert)) {
-        eval(bquote(expect_equal(vals$Rueckkaufswert, .(Rueckkaufswert), tolerance = abs(absTolerance / .(Rueckkaufswert)))))
-    }
-    if (!missing(Abschlusskostenruecktrag)) {
-        eval(bquote(expect_equal(vals$Abschlusskostenruecktrag, .(Abschlusskostenruecktrag), tolerance = abs(absTolerance / .(Abschlusskostenruecktrag)))))
-    }
-    if (!missing(Rueckkaufswert.prf)) {
-        eval(bquote(expect_equal(vals$Rueckkaufswert.prf, .(Rueckkaufswert.prf), tolerance = abs(absTolerance / .(Rueckkaufswert.prf)))))
-    }
-    if (!missing(VS.prf)) {
-        eval(bquote(expect_equal(vals$VS.prf, .(VS.prf), tolerance = abs(absTolerance / .(VS.prf)))))
-        # OR: contract$Values$reserves[t + 1, "PremiumFreeSumInsured"]
-    }
-}
-
-
-
-
-#' Generate testthat output for unit-testing a tarif implementation
-#'
-#' This function calculates the required reference values for the given
-#' insurance contract as required by the Austrian regulation (LV-VMGLV, "LV
-#' Versicherungsmathematische Grundlagen Verordnung") and generates the
-#' code for unit-testing the contract with these values. The code printed
-#' can be directly copied into a unit test file.
-#'
-#' @param contract The insurance contract to calculate and generate unit-testing code.
-#'                 If an InsuranceTarif object is given, a new contract with default
-#'                 values is generated.
-#' @param t Time for which to calculate all values (except premium-free values)
-#' @param prf Time of premium waiver (premium-free)
-#' @param t_prf Time for which to calculated all values after the premium waiver
-#' @param ... Further parameters for generating the contract for a tariff object
-#'
-#' @examples
-#' library(MortalityTables)
-#' mortalityTables.load("Austria_Annuities_AVOe2005R")
-#' # A trivial deferred annuity tariff with no costs:
-#' tariff = InsuranceTarif$new(name="Test Annuity", type="annuity",
-#'     mortalityTable = AVOe2005R.unisex, i=0.01)
-#' vmGlgExample.generateTest(tariff,
-#'     age = 35, YOB = 1981,
-#'     policyPeriod = 30, premiumPeriod = 15, deferralPeriod = 15,
-#'     sumInsured = 1000,
-#'     contractClosing = as.Date("2016-10-01")
-#' )
-#'
-#' @export
-vmGlgExample.generateTest = function(contract, prf = 10, t = 10, t_prf = 12, ...) {
-    if (getOption('LIC.debug.vmGlgExample.generateTest', FALSE)) {
-        browser();
-    }
-    cntr = deparse(substitute(contract));
-
-    vals = calcVmGlgExample(contract, prf = prf, t = t, t_prf = t_prf, ...);
-
-
-    code = paste0("test_that(\"", vals$TarifName, "\", {\n");
-    code = paste0(code, "\tcontract = InsuranceContract$new(\n\t\t", cntr, ",\n\t\t");
-    arguments = sapply(substitute(list(...))[-1], deparse);
-    code = paste0(code,
-                  paste(names(arguments), arguments, sep = " = ", collapse = ",\n\t\t")
-           );
-    code = paste0(code, "\n\t);\n")
-    code = paste0(code, "\t# showVmGlgExamples(contract, t = ", t, ", prf = ", prf, ", t_prf = ", t_prf, ");\n\n")
-    code = paste0(code, "\ttestVmGlgExample(\n\t\tcontract, \n\t\tt = ", t, ", prf = ", prf, ", t_prf = ", t_prf, ",\n")
-
-    check.keys = c("net", "Zillmer", "gross", "written", "savings", "risk",
-                   "ZillmerRes", "ZillmerRes.prf", "VwKostenRes", "VwKostenRes.prf",
-                   "Bilanzreserve", "Praemienuebertrag",
-                   "Rueckkaufsreserve", "Rueckkaufswert", "Abschlusskostenruecktrag",
-                   "Rueckkaufswert.prf", "VS.prf");
-
-    # Subsetting a list creates NULL entries for missing keys => filter them out
-    # E.g. single-premium contracts do not have any premium-free values, so they are NULL.
-    cmpvals = Filter(Negate(is.null), vals[check.keys]);
-    check.str =  paste(
-        names(cmpvals),
-        sprintf("%.2f", cmpvals),
-        sep = " = ", collapse = ", \n\t\t");
-    code = paste0(code, "\t\t", check.str, ",\n\tabsTolerance = 0.01\n\t);\n");
-    code = paste0(code, "})\n");
-    cat(code);
-}
-
-
-
diff --git a/README.md b/README.md
index b96611f2849df091967b4b44c1d36bbabf6668b4..91f3a67eefcd282ae180fb90dc69941365e1d574 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,4 @@
 # The *LifeInsuranceContracts* Package For Traditional Life Insurance with Guarantee and Profit Participation
 R package implementing general life insurance contracts
 
-This package R6 classes to model traditional life insurance
-    contracts like annuities, whole life insurances or endowments. All relevant
-    quantities like premium decomposition, reserves and benefits over the whole
-    contract period are calculated and potentially exported to excel. Mortalities
-    are given using the MortalityTables package.
+This package has been renamed to LifeInsureR, please use that new name instead of LifeInsuranceContracts!
diff --git a/inst/Beispiele/Example_Endowment.R b/inst/Beispiele/Example_Endowment.R
deleted file mode 100644
index 0791875aaeea9280ab080b041b3a14404ce064c5..0000000000000000000000000000000000000000
--- a/inst/Beispiele/Example_Endowment.R
+++ /dev/null
@@ -1,117 +0,0 @@
-library(LifeInsuranceContracts)
-library(MortalityTables)
-library(lubridate)
-mortalityTables.load("Austria_Census")
-
-################################################################### #
-#              DEFINITION TARIF                                  ####
-################################################################### #
-#
-# Beispieltarif:
-#    endowment with regular premiums
-#    death benefit = survival benefit
-#    Costs: Alpha: 4% of premium sum up-front (2,5% Zillmer)
-#           Beta:  5% of each premium paid
-#           Gamma: 0,1% of sum insured per year over the whole contract maturity
-#           Unitcosts: 10 EUR + 5% Premium Sum (max. 50 EUR), during premium period
-################################################################### #
-
-costs.Bsp = initializeCosts();
-costs.Bsp[["alpha", "SumPremiums", "once"]] = 0.04;
-costs.Bsp[["Zillmer", "SumPremiums", "once"]] = 0.025; # deutsche Beschränkung der Zillmerung
-costs.Bsp[["beta", "GrossPremium", "PremiumPeriod"]] = 0.05;
-costs.Bsp[["gamma", "SumInsured", "PolicyPeriod"]] = 0.001;
-
-
-initializeCosts(alpha = 0.04, Zillmer = 0.025, beta = 0.05, gamma.contract = 0.001)
-
-
-costs.Bsp.Unterjaehrigkeit = list("1" = 0.0, "2" = 0.01, "4" = 0.015, "12" = 0.02);
-
-# Stückkosten: 10EUR + 5% PS, maximal 50
-costs.Bsp.Stueckkosten       = function (params, values) { min(50, 10 + 0.05*values$premiums[["gross"]]) }
-
-
-surrender.Bsp = function(surrenderReserve, params, values) {
-  n = params$ContractData$policyPeriod - params$ContractData$blockStart;
-  # Rückkaufsabschlag linear fallend von 10 auf 0%:
-  sf = c(rep(0, params$ContractData$blockStart), 1 - 0.1 * (1 - (0:n)/n));
-  surrenderReserve * sf
-}
-
-Tarif.Bsp = InsuranceTarif$new(
-  name = "Example Tariff - Standard Endowment",
-  type = "endowment",
-  tarif = "BSP",
-  desc = "Gemischte Versicherung (Standardtarif)",
-  premiumPeriod = 1,
-  #alphaRefundLinear = FALSE,
-
-  mortalityTable = mort.AT.census.2011.unisex,
-  i = 0.005,
-  costs = costs.Bsp,
-  Costs = costs.Bsp,
-  unitcosts = costs.Bsp.Stueckkosten,
-
-  premiumFrequencyOrder = -1, # Unterjährige Prämienzahlung wird nicht im BW berücksichtigt, sondern durch Prämienaufschlag
-  premiumFrequencyLoading = costs.Bsp.Unterjaehrigkeit,
-  premiumRefund = 0,
-  tax = 0.04,
-
-  surrenderValueCalculation = surrender.Bsp
-);
-
-################################################################### #
-# Example contract with dynamiocs                               ####
-################################################################### #
-
-
-contract.Bsp = InsuranceContract$
-  new(
-    Tarif.Bsp,
-    age = 35, policyPeriod = 15, premiumPeriod = 15,
-    premiumFrequency = 12,
-    sumInsured = 100000,
-    contractClosing = as.Date("2020-07-01"),
-    id = "Hauptvertrag"
-  )$
-  addDynamics(t = 5, NewSumInsured = 200000, id = "Dynamik 1", i = 0.05, age = 70)$
-  addDynamics(t = 10, NewSumInsured = 250000, id = "Dynamik 2", i = 0.01);
-
-options('LIC.debug.premiumCalculation' = TRUE)
-contract.Bsp$premiumWaiver(t = 13)
-
-options('LIC.debug.premiumCalculation' = FALSE)
-# exportInsuranceContractExample(contract.Bsp, t = 5);
-# showVmGlgExamples(contract.Bsp, t = 10)
-#
-# exportInsuranceContract.xlsx(contract.Bsp, filename = "BEISPIEL_Contract.xlsx")
-#
-#
-# contract.Bsp$Values$cashFlowsBasic
-# contract.Bsp$Values$cashFlows
-# contract.Bsp$Values$cashFlowsCosts
-# contract.Bsp$Values$presentValues
-# # contract.U17_3J$Values$presentValuesCosts
-# contract.Bsp$Values$premiumSum
-# contract.Bsp$Values$premiums
-# contract.Bsp$Values$premiumComposition
-# contract.Bsp$Values$reserves
-
-
-################################################################### #
-# Testing premium waivers                                        ####
-################################################################### #
-
-
-contract.Bsp.waiver = InsuranceContract$
-  new(
-    Tarif.Bsp,
-    age = 35, policyPeriod = 15, premiumPeriod = 15,
-    premiumFrequency = 12,
-    sumInsured = 100000,
-    contractClosing = as.Date("2020-07-01"),
-    id = "Hauptvertrag"
-  )$premiumWaiver(t = 5)
-exportInsuranceContract.xlsx(contract.Bsp.waiver, filename = "BEISPIEL_Contract_PrWaiver.xlsx")
-
diff --git a/inst/Beispiele/Example_WholeLife_L71-U.R b/inst/Beispiele/Example_WholeLife_L71-U.R
deleted file mode 100644
index 40101f35b3bdae55a6c2cd6245e108bf04fe2ecc..0000000000000000000000000000000000000000
--- a/inst/Beispiele/Example_WholeLife_L71-U.R
+++ /dev/null
@@ -1,41 +0,0 @@
-library(magrittr)
-library(MortalityTables)
-library(LifeInsuranceContracts)
-mortalityTables.load("Austria_Census")
-
-Tarif.L71U = InsuranceTarif$new(
-    name = "L71-U",
-    type = "wholelife",
-    tarif = "DeathPlus - Short Term Life Insurance",
-    desc = "Term Life insurance (5 years) with constant sum insured and regular premiums",
-    policyPeriod = 5, premiumPeriod = 5,  # premiumPeriod not needed, defaults to maturity
-
-    mortalityTable = mortalityTable.mixed(
-        table1 = mort.AT.census.2011.male, weight1 = 0.65,
-        table2 = mort.AT.census.2011.female, weight2 = 0.35
-    ),
-    i = 0.005,
-    tax = 0.04,
-    costs = initializeCosts(alpha = 0.05, gamma = 0.01, gamma.paidUp = 0.01, unitcosts = 10),
-    surrenderValueCalculation = function(surrenderReserve, params, values) {
-        surrenderReserve * 0.9
-    }
-);
-
-contract.L71U  = InsuranceContract$new(
-    Tarif.L71U,
-    age = 35,
-    contractClosing = as.Date("2020-08-18"),
-    sumInsured = 100000);
-
-contract.L71U$Values$premiums
-contract.L71U$Values$reserves
-
-contract.L71U = contract.L71U$premiumWaiver(t = 3)
-contract.L71U$Values$reserves
-contract.L71U$Values$premiumCoefficients
-
-
-
-exportInsuranceContract.xlsx(contract.L71U, "L71U.xlsx")
-openXL("L71U.xlsx")
diff --git a/inst/rstudio/templates/project/LifeInsuranceContracts.dcf b/inst/rstudio/templates/project/LifeInsuranceContracts.dcf
deleted file mode 100644
index ce4aeb5dccbb2eaaa4c5f4e94a5d013ecef73085..0000000000000000000000000000000000000000
--- a/inst/rstudio/templates/project/LifeInsuranceContracts.dcf
+++ /dev/null
@@ -1,10 +0,0 @@
-Binding: create_LIC_project
-Title: LifeInsuranceContracts Implementation
-Subtitle: Company-specific product definitions using the LifeInsuranceContracts package
-OpenFiles: RechnungGesamtbestand.R
-Caption: Company-specific LifeInsuranceContracts product implementation
-
-Parameter: Company
-Widget: TextInput
-Label: Company (letters only, no spaces, special characters etc.)
-
diff --git a/inst/rstudio/templates/project/LifeInsuranceContracts/.Rbuildignore b/inst/rstudio/templates/project/LifeInsuranceContracts/.Rbuildignore
deleted file mode 100644
index 0e18abd9d5ca74e9fc4b7d8717c88d5629e80c97..0000000000000000000000000000000000000000
--- a/inst/rstudio/templates/project/LifeInsuranceContracts/.Rbuildignore
+++ /dev/null
@@ -1,8 +0,0 @@
-^.*\.Rproj$
-^\.Rproj\.user$
-^Polizzeninfos/2020-
-^Polizzeninfos/2021-
-^Polizzeninfos/2022-
-^\.RData$
-^\.git$
-^Vergleichsrechner/
diff --git a/inst/rstudio/templates/project/LifeInsuranceContracts/.gitignore b/inst/rstudio/templates/project/LifeInsuranceContracts/.gitignore
deleted file mode 100644
index 3865c7eb6383ee0cc1222356af5092c5c4c6442e..0000000000000000000000000000000000000000
--- a/inst/rstudio/templates/project/LifeInsuranceContracts/.gitignore
+++ /dev/null
@@ -1,6 +0,0 @@
-.Rproj.user
-.Rhistory
-.RData
-.Ruserdata
-Ergebnisse_Gesamtbestand_Vergleichsrechnung
-20*_Nachrechnung/
diff --git a/inst/rstudio/templates/project/LifeInsuranceContracts/DESCRIPTION b/inst/rstudio/templates/project/LifeInsuranceContracts/DESCRIPTION
deleted file mode 100644
index 1b35ed472b0ec1b52c36aa6f712571cbf707bcde..0000000000000000000000000000000000000000
--- a/inst/rstudio/templates/project/LifeInsuranceContracts/DESCRIPTION
+++ /dev/null
@@ -1,28 +0,0 @@
-Package: LifeInsuranceContractsXXXCOMPANYXXX
-Type: Package
-Title: LifeInsuranceContract Implementation for XXXCOMPANYXXX
-Version: 0.1
-Date: 2023-12-31
-Description: Implementation of XXXCOMPANYXXX life insurance products.
-License: Proprietory (using XXXCOMPANYXXX's tariff plans)
-Authors@R: c(person("Firstname", "Lastname", role = c("aut", "cre"),
-                    email = "email@example.com"))
-Author: Firstname Lastname [aut, cre]
-Maintainer: Firstname Lastname <email@example.com>
-Depends: R (>= 3.1.0), 
-    LifeInsuranceContracts, 
-    MortalityTables,
-    here
-Encoding: UTF-8
-LazyData: true
-Recommends:
-    openxlsx
-URL:
-BugReports:
-RoxygenNote: 7.2.3
-Collate: 
-    'XXXCOMPANYXXX_General.R'
-    'XXXCOMPANYXXX_Tarif1.R'
-Suggests: 
-    testthat (>= 3.0.0)
-Config/testthat/edition: 3
diff --git a/inst/rstudio/templates/project/LifeInsuranceContracts/NAMESPACE b/inst/rstudio/templates/project/LifeInsuranceContracts/NAMESPACE
deleted file mode 100644
index 6ae926839dd1829f1016a96f766d970ff184ad97..0000000000000000000000000000000000000000
--- a/inst/rstudio/templates/project/LifeInsuranceContracts/NAMESPACE
+++ /dev/null
@@ -1,2 +0,0 @@
-# Generated by roxygen2: do not edit by hand
-
diff --git a/inst/rstudio/templates/project/LifeInsuranceContracts/R/XXXCOMPANYXXX_General.R b/inst/rstudio/templates/project/LifeInsuranceContracts/R/XXXCOMPANYXXX_General.R
deleted file mode 100644
index c571c783c40dadf7afed9c18b317319cdacb4320..0000000000000000000000000000000000000000
--- a/inst/rstudio/templates/project/LifeInsuranceContracts/R/XXXCOMPANYXXX_General.R
+++ /dev/null
@@ -1,197 +0,0 @@
-library(tidyverse)
-
-##########################################################################m#
-# Datenstruktur für Tarife                                              ####
-##########################################################################m#
-
-# Idea / approach taken from the `memoise` package (In-memory cache)
-# XXXCOMPANYXXX.Tariffs.init = function() {
-#     tariffs = new.env(TRUE, emptyenv())
-#     tariff_set = function(key, value) {
-#         assign(key, value, envir = tariffs)
-#     }
-#     tariff_get = function(key) {
-#         get(key, envir = tariffs, inherits = FALSE)
-#     }
-#     tariff_exists = function(key) {
-#         exists(key, envir = tariffs)
-#     }
-#     list(
-#         get = tariff_get,
-#         set = tariff_set,
-#         exists =
-#     )
-# }
-#' @export
-XXXCOMPANYXXX.Tariffs = c()
-
-#' @export
-XXXCOMPANYXXX.register = function(Tarif, Produkt, GV = NULL, AVB = NULL) {
-    if (is.null(Produkt)) {
-        warning("Product name missing in call to XXXCOMPANYXXX.register!");
-        return();
-    }
-    locked = FALSE
-    # TODO: Unlocking does not work => Once the package is built/installed,
-    #       new products/tariffs cannot be added via XXXCOMPANYXXX.register.
-    #       => Figure out a way to store all registered tariffs in a list
-    #       that is not locked / that can be unlocked!
-    if ("package:LifeInsuranceContractsXXXCOMPANYXXX" %in% search()) {
-        pkgenv = as.environment("package:LifeInsuranceContractsXXXCOMPANYXXX")
-        locked = bindingIsLocked("XXXCOMPANYXXX.Tariffs", pkgenv)
-        # if (locked) {
-            # unlockBinding("XXXCOMPANYXXX.Tariffs", pkgenv)
-            # locked = bindingIsLocked("XXXCOMPANYXXX.Tariffs", pkgenv)
-        # }
-        # nsenv = as.environment("namespace:LifeInsuranceContractsXXXCOMPANYXXX")
-        # locked = bindingIsLocked("XXXCOMPANYXXX.Tariffs", pkgenv)
-        # if (locked) {
-        #     unlockBinding("XXXCOMPANYXXX.Tariffs", pkgenv)
-        #     locked = bindingIsLocked("XXXCOMPANYXXX.Tariffs", pkgenv)
-        # }
-    }
-    # assign("XXXCOMPANYXXX.Tariffs", 123, -1, as.environment("package:LifeInsuranceContractsXXXCOMPANYXXX"))
-    # if (locked) {
-        # warning("")
-    # }
-    # unlockBinding("XXXCOMPANYXXX.Tariffs", as.environment("package:LifeInsuranceContractsXXXCOMPANYXXX"))
-    # unlockBinding(XXXCOMPANYXXX.Tariffs, pryr::where("XXXCOMPANYXXX.Tariffs"))
-    if (!locked && !is.null(GV) && !is.null(AVB)) {
-        XXXCOMPANYXXX.Tariffs[[paste0(Produkt, "/GV", GV, "/AVB", AVB)]] <<- Tarif
-    }
-    if (!locked && !is.null(GV)) {
-        XXXCOMPANYXXX.Tariffs[[paste0(Produkt, "/GV", GV)]] <<- Tarif
-    }
-    if (!locked && !is.null(AVB)) {
-        XXXCOMPANYXXX.Tariffs[[paste0(Produkt, "/AVB", AVB)]] <<- Tarif
-    }
-    Tarif
-}
-#' @export
-XXXCOMPANYXXX.Tariff = function(Produkt, GV = NULL, AVB = NULL) {
-    if (is.null(Produkt)) {
-        warning("Tariff name missing in call to XXXCOMPANYXXX.Tariff!");
-        return(NULL);
-    }
-    if (is.null(GV) && is.null(AVG)) {
-        warning("Both profit class and terms indicator missing in call to XXXCOMPANYXXX.Tariff!");
-        return(NULL);
-    }
-    id = Produkt;
-    if (!is.null(GV)) {
-        id = paste0(id, "/GV", GV);
-    }
-    if (!is.null(AVB)) {
-        id = paste0(id, "/AVB", AVB);
-    }
-    XXXCOMPANYXXX.Tariffs[[id]]
-}
-
-
-##########################################################################m#
-# GEWINNBETEILIGUNGSSÄTZE                                               ####
-##########################################################################m#
-
-
-XXXCOMPANYXXX.Gesamtverzinsung = c(
-    `2000` = 0.07,
-    `2005` = 0.05,
-    `2006` = 0.045,
-    `2005` = 0.04,
-    `2006` = 0.035,
-    `2007` = 0.03,
-    `2012` = 0.025,
-    `2015` = 0.02,
-    `2020` = 0.0175,
-    `2023` = 0.015
-)
-
-
-##########################################################################m#
-# STERBETAFELN                                                          ####
-##########################################################################m#
-
-
-mortalityTables.load("Austria_Census")
-mortalityTables.load("Austria_Annuities_EROMF")
-mortalityTables.load("Austria_Annuities_AVOe2005R")
-mortalityTables.load("Austria_Annuities_AVOe1996R")
-
-
-##########################################################################m#
-# Österr. Volkssterbetafel 2000/02                                      ####
-
-#' @export
-XXXCOMPANYXXX.Sterbetafel2001 = function(params, ...) {
-    if (params$ContractData$sex == "female") {
-        mort.AT.census.2001.female
-    } else {
-        mort.AT.census.2001.male
-    }
-}
-
-#' @export
-XXXCOMPANYXXX.Sterbetafel2001.unisex = mortalityTable.mixed(
-    name = "ÖVSt 2000/02 unisex 70:30",
-    table1 = mort.AT.census.2001.male, weight1 = 70,
-    table2 = mort.AT.census.2001.female, weight2 = 30
-)
-
-
-
-
-
-##########################################################################m#
-# Rententafel AVÖ 1996-R                                                ####
-
-#' @export
-XXXCOMPANYXXX.AVOe1996R.AV = function(params, ...) {
-    if (params$ContractData$sex == "female") {
-        AVOe1996R.male.av325
-    } else {
-        AVOe1996R.female.av325
-    }
-}
-
-
-
-
-
-
-##########################################################################
-# RÜCKKAUFSFORMELN                                                      ####
-##########################################################################m#
-
-#' @export
-XXXCOMPANYXXX.surrender.increasing90 = function(surrenderReserve, params, values) {
-    n = params$ContractData$policyPeriod;
-    surrenderReserve * (0.9 + 0.08*pmax(((0:n) - 3) / (n - 3), 0))
-}
-
-
-##########################################################################m#
-# KOSTENFORMELN                                                         ####
-##########################################################################m#
-
-
-
-##########################################################################m#
-# RABATTFORMELN                                                         ####
-##########################################################################m#
-
-
-
-##########################################################################m#
-# TECHNISCHES ALTER                                                     ####
-##########################################################################m#
-
-#' z.B. Frauen werden um 5 Jahre verjüngt, Mindestalter 20
-#' etc.
-
-
-
-
-##########################################################################m#
-# TARIFSPEZIFIKA (HOOKS) der XXXCOMPANYXXX                                    ####
-##########################################################################m#
-
diff --git a/inst/rstudio/templates/project/LifeInsuranceContracts/R/XXXCOMPANYXXX_Gewinnplan1.R b/inst/rstudio/templates/project/LifeInsuranceContracts/R/XXXCOMPANYXXX_Gewinnplan1.R
deleted file mode 100644
index c583001e9afcee14451f822875ab15b99cc27ec3..0000000000000000000000000000000000000000
--- a/inst/rstudio/templates/project/LifeInsuranceContracts/R/XXXCOMPANYXXX_Gewinnplan1.R
+++ /dev/null
@@ -1,42 +0,0 @@
-#' @include XXXCOMPANYXXX_General.R
-
-############################################################################~#
-#  XXXCOMPANYXXX Gewinnplan 1                                             ####
-#  Profits:                                                               ####
-#    * Interest profit: (profit rate - guaranteed interest)*reserve       ####
-#    * Terminal profit: once/twice the last interest profit assignment    ####
-############################################################################~#
-
-
-#' @export
-XXXCOMPANYXXX.Gewinnplan1 = ProfitParticipation$new(
-  name = "XXXCOMPANYXXX Gewinnplan 1, Version 1",
-  profitComponents = c("interest", "terminal"),
-  profitClass = "1",
-
-  waitingPeriod = 3,
-
-  guaranteedInterest = 0.03,
-  interestProfitRate = pmax(XXXCOMPANYXXX.Gesamtverzinsung - 0.03, 0),
-  totalInterest = XXXCOMPANYXXX.Gesamtverzinsung,
-  getTerminalBonusRate = function(res, rates, params, values) {
-    # Schlussgewinn (Vielfaches des letzten Zinsgewinns)
-    # lfd. Prämie: LZ<20: 1x, LZ>=20: 2x
-    if (params$ContractData$policyPeriod < 20) {
-      1
-    } else {
-      2
-    }
-  },
-
-  getInterestOnProfits = PP.rate.interestProfitPlusGuarantee,
-
-  getInterestProfitBase = PP.base.contractualReserve,
-  getTerminalBonusBase = PP.base.totalProfitAssignment,
-
-  calculateSurvivalBenefit = function(profits, rates, ...) { profits[,"regularBonus"] * (1 + rates$guaranteedInterest + rates$interestProfitRate) + profits[,"terminalBonus"]},
-  calculateDeathBenefitAccrued  = PP.benefit.Profit,
-  calculateSurrenderBenefitAccrued = PP.benefit.Profit,
-  calculatePremiumWaiverBenefitAccrued = PP.benefit.Profit,
-  calculatePremiumWaiverBenefitTerminal = PP.benefit.None
-);
diff --git a/inst/rstudio/templates/project/LifeInsuranceContracts/R/XXXCOMPANYXXX_Tarif1.R b/inst/rstudio/templates/project/LifeInsuranceContracts/R/XXXCOMPANYXXX_Tarif1.R
deleted file mode 100644
index 22311d8f2540a963564d4919d629062a6e887424..0000000000000000000000000000000000000000
--- a/inst/rstudio/templates/project/LifeInsuranceContracts/R/XXXCOMPANYXXX_Tarif1.R
+++ /dev/null
@@ -1,37 +0,0 @@
-#' @include XXXCOMPANYXXX_General.R
-
-
-##############################################################################m##
-#     Tarif1
-##############################################################################m##
-
-# XXXCOMPANYXXX Versicherung, Tarif 1
-# Typ: Endowment with level death and survival benefits, level premiums
-# Guaranteed interest: i=3%, Mortality rates: XXXCOMPANYXXX.Sterbetafel2001.unisex
-
-XXXCOMPANYXXX.costs = initializeCosts(
-    alpha = 0.04, Zillmer = 0.025,
-    beta = 0.02,
-    gamma = 0.002,
-    gamma.paidUp = 0.005
-)
-
-#' @export
-XXXCOMPANYXXX.Tarif1 = InsuranceTarif$new(
-    name = "Tarif1",
-    type = "endowment",
-    tarif = "Endowment Comfort",
-    desc = "Endowment with level death and survival benefits, level premiums, guaranteed interest 3%",
-
-    mortalityTable = XXXCOMPANYXXX.Sterbetafel2001.unisex,
-    i = 0.03,
-    tax = 0.04,
-    costs = XXXCOMPANYXXX.costs,
-    premiumFrequencyLoading = freqCharge(3, 2, 1, 0),
-
-    surrenderValueCalculation = XXXCOMPANYXXX.surrender.increasing90,
-    profitParticipationScheme = XXXCOMPANYXXX.Gewinnplan1
-) %>%
-    XXXCOMPANYXXX.register("Tarif1", GV = "1");
-
-
diff --git a/inst/rstudio/templates/project/LifeInsuranceContracts/R/XXXCOMPANYXXX_Tarif2.R b/inst/rstudio/templates/project/LifeInsuranceContracts/R/XXXCOMPANYXXX_Tarif2.R
deleted file mode 100644
index 18ae9aad65c3a2c7997cb69b399abf0d21df3c74..0000000000000000000000000000000000000000
--- a/inst/rstudio/templates/project/LifeInsuranceContracts/R/XXXCOMPANYXXX_Tarif2.R
+++ /dev/null
@@ -1,46 +0,0 @@
-#' @include XXXCOMPANYXXX_General.R
-
-
-##############################################################################m##
-#     Tarif2
-##############################################################################m##
-
-# XXXCOMPANYXXX Versicherung, Tarif2
-# Whole life insurance
-
-XXXCOMPANYXXX.costs2 = initializeCosts(
-    alpha = 0.035,
-    gamma = 0.005,
-    gamma.paidUp = 0.005
-)
-
-#' @export
-XXXCOMPANYXXX.Tarif2 = InsuranceTarif$new(
-    name = "Tarif2",
-    type = "wholelife",
-    tarif = "Death Comfort",
-    desc = "Whole life insurance with single premium, guaranteed interest 3%",
-
-    mortalityTable = XXXCOMPANYXXX.Sterbetafel2001.unisex,
-    i = 0.03,
-    tax = 0.04,
-    costs = XXXCOMPANYXXX.costs2,
-    premiumFrequencyLoading = freqCharge(3, 2, 1, 0),
-
-    sumRebate = function(params, values) {
-        SI = params$ContractData$sumInsured
-        if(SI >= 1000000) {
-            0.002
-        } else if (500000 <= SI) {
-            0.001
-        } else if (200000 <= SI) {
-            0.0005
-        } else {
-            0
-        }
-    },
-    surrenderValueCalculation = XXXCOMPANYXXX.surrender.increasing90
-) %>%
-    XXXCOMPANYXXX.register("Tarif2", GV = "2");
-
-
diff --git a/inst/rstudio/templates/project/LifeInsuranceContracts/XXXCOMPANYXXXRechnungGesamtbestand.R b/inst/rstudio/templates/project/LifeInsuranceContracts/XXXCOMPANYXXXRechnungGesamtbestand.R
deleted file mode 100644
index 25b7095d3ce86c7b25cdd4bbf6b96df6871cc021..0000000000000000000000000000000000000000
--- a/inst/rstudio/templates/project/LifeInsuranceContracts/XXXCOMPANYXXXRechnungGesamtbestand.R
+++ /dev/null
@@ -1,561 +0,0 @@
-# This file was created from a template provided by the LifeInsuranceContracts
-# package. It's purpose is to read in a set of contract data and calculate the
-# corresponding reserves (e.g. to validate the official numbers in the financial
-# statements).
-#
-# Steps:
-#   1. Implement the corresponding products in the files in the R/ subdirectory.
-#      Use the LifeInsuranceContracts documentation available at
-#      https://cran.r-project.org/web/packages/LifeInsuranceContracts/vignettes/using-the-lifeinsurancecontracts-package.html
-#   2. Install the package (using the "Install" button in RStudio's "Build" pane)
-#   3. Set up the mapping of the columns of the contract data source to the package's arguments.
-#      The columns of the input data can be directly mapped to named arguments in LifeInsuranceContract$new(..) calls.
-#   4. If some columns need manual modifications (e.g. sex or frequencies
-#      expressed with other values than the package expects), update the
-#      VTmodify.* functions below correspondingly.
-#   5. Update the column types in the readXXXCOMPANYXXXBestand(..) function. This helps
-#      preventing errors, as these columns are always cast to the required type.
-#   6. The calculate_contract(..) function might need to some adjustments /
-#      modifications, in particular when modified contracts, premiums waivers,
-#      additional tariffs / single-payment add-ons etc. are present.
-#   7. Depending on which columns / data are available in the company-provided
-#      contract data, the column modifications / calculations of other reserves,
-#      etc. at the end of the calculate_portfolio(...) function might need to
-#      be adjusted.
-#   8. Update the `files` and `outfile` variables to point to the input files
-#      ("Bestandsdaten") and the output file name
-#   9. Call the calculate_portfolio function on the contract data set (potentially
-#      filtered to some subsets to prevent performance issues)
-#
-#  Typically, a call to calculate a portfolio and store the results in a dedicated
-#  (Excel) output file is:
-#      results = NULL; results = calculate_portfolio(bestandinfos.all,
-#           tarif = c("ProdName1", "ProdName2"), GV = c("123"), debug =TRUE)
-#      results %>%
-#           openxlsx::write.xlsx(outfile("Prods-1-2"), asTable = TRUE,
-#                  overwrite = TRUE, creator = "Your Name",
-#                  sheetName = "Vergleichsrechnung", tabColour = "#FFE600")
-#      openXL(outfile("Prods-1-2"))
-#
-#
-#
-# General Overview of the calculation procedure
-#   1. The contract data are read in from the file names provided in the `files`
-#      list and stored in the data.frame called `bestandinfos.all`.
-#        a. Each file is read using the function `readXXXCOMPANYXXXBestand`.
-#        b. The `readXXXCOMPANYXXXBestand` function uses read_excel to read in the raw data,
-#           then ensures the defined columns have the proper data type.
-#        c. The columns are renamed according to the mapping in `colMapping`
-#        d. All contracts are sorted by `Polizzennummer`
-#        e. Additional modifications are done by the function `VTmodify.general`.
-#        f. Further custom modifications can be manually added either in readXXXCOMPANYXXXBestand or in VTmodify.general
-#   2. All contracts are calculated by a call to `calculate_portfolio`. The arguments
-#      tarif and GV can be used to restrict the calculation only to certain
-#      products and/or profit classes. Additionally, n_max can be used to
-#      calculate only the first n_max contracts.
-#      The `calculate_portfolio` function does its work with the following steps:
-#        a. The portfolio data is filtered with the given tariff, GV, skip, n_max arguments
-#        b. Only the relevant columns of the portfolio data are taken, some
-#           sanity checks (sumInsured > 0, premiumFrequency >= 0) are applied.
-#        c. Grouping happens by column SliceID. This allows multiple portfolio
-#           data rows to be combined to one contract with several slices / sum
-#           increases, which are calculated as one contract (see section "10.3
-#           Dynamic Increases" of the LifeInsuranceContracts vignette). If each
-#           slice / dynamic increase is supposed to be calculated individually
-#           and independent from the main contract / other increases, then the
-#           column mapped to the SliceID column needs to have a different value
-#           for each portfolio data row. If SliceID uses contract numbers, all
-#           dynamics, etc. belonging to the same contract number will be combined
-#           and calculated using $addDynamics
-#        d. Each contract (entries with distinct SliceID value) is calculated in
-#           a loop using the by_slice function, which calls the calculate_contract
-#           function for each contract.
-#   3. The `calculate_contract` function calculates one individual contract, with
-#      the individual columns of the portfolio data passed as named parameters
-#      to the function.
-#        a. A progress message is printed (if applicable)
-#        b. All slices are arranged by date, with the slice starting first
-#           assumed to be the main contract part.
-#        c. For the main contract, an instance of the LifeInsuranceContract
-#           (with the given tariff / product) is created and all values of the
-#           contract are automatically calculated by the package by default.
-#        d. All additional slices (e.g. dynamic increases) with the same SliceID
-#           are added using the $addDynamics method of the LifeInsuranceContract
-#           class. The slice start date and duration are adjusted correspondingly.
-#        e. The reserves are extracted from the contract and stored in the final
-#           data.frame
-#        z. If debug=TRUE, a column is added to the resulting data.frame containing the R code to reproduce with full contract.
-#    4. The calculate_portfolio combines the data.frames returned for each
-#       contract's calculate_contract call into one large data frame, adds some
-#       derived columns and returns the data frame as result of the calculations.
-#
-#
-#
-# COLUMN MAPPING
-# --------------
-# The following columns / named parameters are typically used by a LifeInsuranceTariff
-# implementation or the concrete contract as a LifeInsuranceContract object. Most
-# parameters are not mandatory.
-# Additional arguments / columns are possible and will be preserved, even if
-# they are not used by the contract.
-#   * `Polizzennummer`
-#   * `SliceID`
-#   * `balanceSheetDate`
-#   * `tarif`
-#   * `GV`
-#   * `i`
-#   * `sex`
-#   * `age`
-#   * `contractClosing`
-#   * `sliceDate`
-#   * `policyPeriod`
-#   * `premiumPeriod`
-
-#   * `premiumFrequency`
-#   * `annuityFrequency`
-#   * `sumInsured`
-
-# Columns used for comparison with the calculated values:
-#   * `Bruttoprämie`
-#   * `Sparprämie`
-#   * `Risikoprämie`
-#   * `Kostenprämie`
-#   * `Bilanzreserve`
-#   * `Gewinnreserve`
-#   * `Prämienübertrag`
-
-################################################################################
-
-
-library(here)
-library(lubridate)
-library(readxl)
-library(magrittr)
-library(purrr)
-library(purrrlyr)
-library(openxlsx)
-library(tictoc)
-library(tidyverse)
-library(LifeInsuranceContractsXXXCOMPANYXXX)
-mortalityTables.load("Austria_*")
-
-
-
-########################################################################m#
-# Database structure definitions / mapping                            ####
-########################################################################m#
-
-colMapping = c(
-    # Polizzen- und Tarifdefinition
-    `Polizzennummer` = "PolNr",
-    `SliceID` = "PolNr",          # Grouping will happen by SliceID
-    `balanceSheetDate` = "Datum",
-    `tarif` = "Produkt",          # Used to search for the LifeInsuranctTarif object
-    `GV` = "Gewinnverband",
-
-    # Parameter des Vertrags
-    `i` = "Garantiezins",
-    `sex` = "Geschlecht",
-    `age` = "Eintrittsalter",     # Alternatively, birth can be given
-    # `birthDate` = "GebDat",
-    `contractClosing` = "Abschluss",
-    `sliceDate` = "Abschluss",
-    `policyPeriod` = "LZ",
-
-    `premiumFrequency` = "ZW",
-    `sumInsured` = "vs",
-    `initialCapital` = "Anfangskapital",
-    `costWaiver` = "Kostenverzicht",
-
-    # Kontrollgrößen (lt. Geschäftsplan abgeleitet)
-
-    `Bruttoprämie` = "BPr",
-    `Sparprämie` = "SparPr",
-    `Risikoprämie` = "RisikoPr",
-    `Kostenprämie` = "KostenPr",
-
-    # Deckungskapital am jeweiligen Jahrestag der Versicherung
-    `DKt` = "VK",
-    `DKt+1` = "VK1",
-    `DKt+2` = "VK2",
-
-    # Bilanzwerte
-    `Bilanzreserve` = "BilRes",
-    `Gewinnreserve` = "GewRes",
-    `Bilanz-Verwaltungskostenreserve` = "VerwKostRes",
-    `Netto-Bilanzreserve` = "NettoBilRes"#,
-    # `Prämienübertrag` = "???"
-)
-colNamesRelevant = names(colMapping) %>% `[<-`(., . == "", NA_character_) %>% coalesce(colMapping)
-
-Problempolizzen = c()
-
-
-
-########################################################################m#
-# Helper functions                                                    ####
-########################################################################m#
-
-cleanDate = function(dt) {
-    if (is.POSIXct(dt) || is.POSIXlt(dt) || is.Date(dt) || is.logical(dt))
-        as.Date(dt)
-    else if (is.numeric(dt))
-        as.Date(dt, origin = "1899-12-30")
-    else if (is.character(dt)) {
-        warning("date column was read in as string: ", dt)
-        Reduce(c, map(dt, function(d) {
-            # browser()
-            if (is.character(d) && !is.na(d) && str_detect(d, "^[0-9]+$"))
-                d = as.numeric(d)
-            if (is.numeric(d))
-                return(as.Date(d, origin = "1899-12-30"))
-            as.Date(d)
-        }))
-    }
-}
-
-
-
-VTmodify.general = function(data) {
-    #browser()
-
-    data %>%
-        separate(tarif, into = c("tarif", "Produkt"), sep = "[ ]+", extra = "merge", fill = "left") %>%
-        mutate(
-            sex = recode(
-                as.character(sex),
-                "M" = "male", "W" = "female", "F" = "female", "U" = "unisex",
-                "m" = "male", "w" = "female", "f" = "female", "u" = "unisex",
-                `0` = "male", `1` = "female", .default = "unisex"),
-            premiumFrequency = recode(
-                as.character(premiumFrequency),
-                "J" = 1, "H" = 2, "V" = 4, "M" = 12, "E" = 0, .default = 1),
-            policyPeriod = round(time_length(difftime(policyPeriod, contractClosing), "years")),
-
-            # TODO: Apply further adjustments to the input data, e.g.
-            # costWaiver = ifelse(costWaiver == "N", 0, 1),
-            # sumRebate = -sumRebate,
-            # sumInsured = if_else(VS == 0, Rentenhoehe, VS),
-
-            # TODO: Rabatte, etc.
-
-            id = paste0(tarif, "/GV", GV)
-        )
-}
-
-
-########################################
-readXXXCOMPANYXXXBestand = function(file, sheet = 1, ...) {
-    charColumns = c(
-        "tarif", "GV"
-    )
-    dateColumns = c(
-        "balanceSheetDate",
-        "contractClosing",
-        "sliceDate",
-        "birthData"
-    );
-    percentColumns = c(
-        "i"
-    )
-    permilleColumns = c(
-
-    )
-    numericColumns = c(
-        "policyPeriod", "age",
-        "sumInsured", "initialCapital"
-    );
-    mapping = colMapping[names(colMapping) != ""]
-
-    # browser()
-    data = read_excel(file, sheet = sheet, ..., na = c("", "01.01.0100", "01.01.1000", "-328716", -328716)) %>%
-        # Apply all renamings from colMapping:
-        select(all_of(mapping), !all_of(mapping)) %>%
-        mutate(
-            across(any_of(dateColumns), cleanDate),
-            across(any_of(numericColumns), as.numeric),
-            across(any_of(charColumns), as.character),
-            across(any_of(percentColumns), function(x) { as.numeric(x)/100 }),
-            across(any_of(permilleColumns), function(x) { as.numeric(x)/1000 })
-        ) %>%
-        arrange(Polizzennummer) %>%   # Sortiere Verträge nach Polizzennummer
-        VTmodify.general()
-    data
-
-}
-
-
-###############################################################m#
-## Definitionen: Kontrollrechnung der Deckungsrückstellung   ####
-###############################################################m#
-
-CountPol = 0
-CountSlice = 0
-
-calculate_contract = function(ctr.data, balanceSheetDate = as.Date("2023-12-31"), progress = 100, tariffs = XXXCOMPANYXXX.Tariffs, debug = FALSE, ...) {
-    # browser()
-    CountPol <<- CountPol + 1
-    CountSlice <<- CountSlice + NROW(ctr.data)
-    # browser()
-    if (CountPol %% progress == 0) {
-        print(paste0(CountPol, "/", CountSlice, ": Vertrag Nr. ", ctr.data[[1, "Polizzennummer"]], ", Tarif:", ctr.data[[1, "tarif"]], " GV", ctr.data[[1, "GV"]], ", ", NROW(ctr.data), " Scheiben"))
-    }
-
-    # Main part is the slice that
-    #       a) starts first.
-    # If two slices start at the same time, main part is
-    #       b) the one with an initialCapital, or
-    #       c) the one with the longest premium period (to exclude single payments from being the main part) or
-    #       d) the highest sum insured
-    ctr.data = ctr.data %>% arrange(sliceDate, desc(initialCapital), desc(premiumPeriod), desc(sumInsured))
-    mainPart.orig = head(ctr.data, 1)
-    mainPart.begin = mainPart.orig$sliceDate
-
-    # Simplification: Adjust main part so  the contract end is always a full number of
-    # years away (otherwise the reserves towards the end will be off considerably)
-    #    if (!is.na(mainPart.orig$Vertragsende)) {
-    #        mainPart.begin = mainPart.orig$sliceDate %>%
-    #            `month<-`(month(mainPart.orig$Vertragsende))
-    #    }
-    # Changes in the current year might move the date after the balance sheet
-    # date => as a workaround let the contract begin last year!
-    while (mainPart.begin > balanceSheetDate) {
-        year(mainPart.begin) = year(mainPart.begin) - 1
-    }
-
-    # If main part begins after contract, adjust the contract date to the main part's begin
-    # Also recalculate the policy period from the (potentially changed) start and end dates of the main slice
-    ctr.data = ctr.data %>%
-        mutate(contractClosing = mainPart.begin)
-
-    mainPart = head(ctr.data, 1) #%>%
-    #        mutate(policyPeriod = year(Vertragsende) - year(contractClosing))
-    dynamics = tail(ctr.data, -1)
-    # browser()
-
-    # Calculate main part
-    args = as.list(mainPart)
-    tarifName = args$tarif;
-    tarifID = paste0(tarifName, "/", args$GV);
-    args$tarif = XXXCOMPANYXXX.Tariff(tarifName, args$GV)
-
-    if (is.null(args$tarif)) {
-        warning("Unable to find Tarif for Product/GV", tarifID)
-        return(
-            data.frame(tarif = "?", mainPart.orig, Scheiben = NROW(ctr.data), date = balanceSheetDate, time = 0, Zillmer = 0, gamma = 0, `Balance Sheet Reserve` = 0, `unearned Premiums` = 0)
-        )
-    }
-
-    ###################
-    # Tariff-specific adjustments to the input data:
-    #------------------
-    # TODO: Implement all required tariff-specific adjustments here
-
-    if (debug) {
-        dbg.args = args;
-        dbg.args$tarif = NULL;
-
-        arguments = sapply(substitute(list(...))[-1], deparse);
-        prepare.dbg.args = function(x) {
-            if (is.function(x)) {paste(deparse(x), collapse = "\n\t\t")}
-            else if (is.expression(x)) {as.character(x)}
-            else if (is.na(x)) {x}
-            else if (is.numeric(x)) {x}
-            else if (is.character(x)) {deparse(as.character(x))}
-            else if (is.Date(x)) {paste0("as.Date(\"", x, "\")")}
-            else if (is.list(x)) {deparse(x)}
-            else x
-        }
-
-        code = paste0(
-            "InsuranceContract$new(\n\t",
-            paste(
-                c(
-                    paste0("XXXCOMPANYXXX.Tariff(\"", tarifName, "\", ", dbg.args$GV, ")"), # ? und 117
-                    paste(paste0("`", names(dbg.args), "`"), map(dbg.args, prepare.dbg.args), sep = " = ", collapse = ",\n\t"),
-                    paste0("balanceSheetDate = as.Date(\"", balanceSheetDate, "\")"),
-                    paste(names(arguments), arguments, sep = " = ", collapse = ",\n\t")
-                ),
-                collapse = ", \n\t"
-            ),
-            ")");
-    }
-    contract  = do.call(
-        InsuranceContract$new,
-        c(args, list(balanceSheetDate = balanceSheetDate, ...))
-    )
-
-    # Loop through all dynamics and call contract$addDynamics
-    by_row(dynamics, function(dyn, ...) {
-        # Vereinfachte Annahme: Dynamik ist immer am Jahrestag der Versicherung => Vergleiche nur Vertrags- mit Scheibenbeginnjahr
-        # TODO: Einmal-Zuzahlungen müssen erkannt und anders gehandhabt werden!
-        t = year(dyn$sliceDate) - year(dyn$contractClosing)
-        contract$addDynamics(t = t, SumInsuredDelta = dyn$sumInsured)
-        if (debug) {
-            code <<- paste0(code, "$\naddDynamics(t = ", t, ", SumInsuredDelta = ", dyn$sumInsured, ")")
-        }
-    }, ...)
-
-
-    Bilanzreserve = contract$Values$reservesBalanceSheet %>% `colnames<-`(c("Datum", "t", "Res.Netto.EY", "Res.Zillmer.EY", "Res.VwK.EY", "BilRes.EY", "PÜ.EY"))
-    BilDRSt = Bilanzreserve %>% filter(Datum == balanceSheetDate)
-    if (debug) {
-        BilDRSt$code = code
-    }
-    t = which(Bilanzreserve$Datum == balanceSheetDate)
-
-    data.frame(
-        tarif = contract$tarif$name,
-        mainPart.orig,
-        Scheiben = NROW(ctr.data),
-
-        # TODO: Weitere Vergleichswerte zurückliefern
-        Premium.net.Cmp = contract$Values$premiumComposition[[t, "net"]],
-        Premium.Zillmer.Cmp = contract$Values$premiumComposition[[t, "Zillmer"]],
-        Premium.gross.Cmp = contract$Values$premiumComposition[[t, "gross"]],
-        Premium.written.Cmp = contract$Values$premiumComposition[[t, "charged"]] - contract$Values$premiumComposition[[1, "tax"]],
-        Premium.savings.Cmp = contract$Values$premiumComposition[[t, "savings"]],
-        Premium.risk.Cmp = contract$Values$premiumComposition[[t, "risk"]],
-        Premium.alphaZ.Cmp = contract$Values$premiumComposition[[t, "alpha.Zillmer"]],
-        Premium.costs.Cmp = "TODO",
-        Premium.gamma.Cmp = contract$Values$premiumComposition[[t, "gamma"]],
-        Premium.sumRebate.Cmp = -contract$Values$premiumComposition[[t, "rebate.sum"]],
-
-        DKt.Cmp = contract$Values$reserves[[t, "contractual"]],
-        `DKt+1.Cmp` = if (t+1 > NROW(contract$Values$reserves)) 0 else contract$Values$reserves[[t+1, "contractual"]],
-        `DKt+2.Cmp` = if (t+2 > NROW(contract$Values$reserves)) 0 else contract$Values$reserves[[t+2, "contractual"]],
-
-        BilDRSt)
-}
-
-
-calculate_portfolio = function(bestand, tarif = NULL, GV = NULL, n_max = Inf, skip = 0, progress = 25, debug = FALSE, ...) {
-    # browser()
-    if (!missing(tarif) && !is.null(tarif)) {
-        bestand = filter(bestand, tarif %in% !!tarif)
-    }
-    if (!missing(GV) && !is.null(GV)) {
-        bestand = filter(bestand, GV %in% !!GV)
-    }
-    if (!missing(skip) && !is.null(skip) && skip > 0) {
-        bestand = tail(bestand, -skip)
-    }
-    if (!missing(n_max) && !is.null(n_max) && n_max < Inf && n_max>0) {
-        bestand = head(bestand, n_max)
-    }
-
-    input = bestand %>%
-        select(all_of(colNamesRelevant)) %>%
-        filter(sumInsured > 0, premiumFrequency >= 0) %>%  # <- Sanity Checks!
-        # group_by(Polizzennummer)
-        group_by(SliceID)
-
-    CountPol <<- 0
-    CountSlice <<- 0
-    tic()
-    # browser()
-    Werte.berechnet = input %>%
-        by_slice(calculate_contract, balanceSheetDate = ymd("2021-12-31"), .collate = "rows", progress = progress, debug = debug, ...)
-    toc()
-
-    Werte.berechnet %>%
-        mutate(
-            across(any_of(
-                c("contractClosing", "sliceDate", "premiumWaiverDate", "date", "birthDate")
-            ), as.Date, origin = "1970-01-01")) %>%
-        mutate(
-            # TODO: Implement comparisons to all values given in the XXXCOMPANYXXX portfolio file!
-            #date = as.Date(date, origin = "1970-01-01"),
-            BilRes.VU = bestand$Bilanzreserve, #`Bilanzreserve`, #+ `Bilanz.Verwaltungskostenreserve` ,#+ `Reserve.prämienfrei`,
-            Fehlbetrag = BilRes.Cmp - BilRes.VU,
-            `abs.FB` = abs(Fehlbetrag),
-            `rel.FB` = Fehlbetrag / BilRes.Cmp,
-            # `abs.FB NP` = abs(`Premium.net` - `Nettoprämie`),
-            `abs.FB BP` = abs(`Premium.gross.Cmp` - `Bruttoprämie`),
-            # `Monate verschoben` = (month(Vertragsende) != month(sliceDate)),
-            exclude = c(""),
-            Grund = c(""),
-            Bilanzdaten = NULL
-        )
-}
-
-
-
-
-
-###############################################################m#
-## Bestände einlesen                                         ####
-###############################################################m#
-
-files = c(
-    # here("Polizzeninfos", "2021-YE", "Einzelposten_2112.xlsx")
-    here("Polizzeninfos", "2022-YE", "Einzelposten_2212.xlsx")
-)
-outfile = function(tarif) { here(paste0("XXXCOMPANYXXX_2022-YE_Vergleichsrechnung", paste(tarif, collapse = "_", sep= "_"), ".xlsx"))}
-
-bestandinfos.all = bind_rows(map(unique(unname(unlist(files))), readXXXCOMPANYXXXBestand, skip = 0, guess_max = 99999, n_max = 99999))
-bestandinfos.all %<>%
-    filter(SATZTYP != "3A")
-
-# Filter out all problematic contracts
-bestandinfos = bestandinfos.all %>%
-    filter(!Polizzennummer %in% Problempolizzen)
-
-
-
-## PLAUSICHECKS auf Bestandsinfo:   ####
-
-# Gesamtzahl verschiedene Polizzen
-bestandinfos.all$Polizzennummer %>% unique %>% length
-bestandinfos$Polizzennummer %>% unique %>% length
-
-# 1) Schnelle übersicht über Anzahl Scheiben pro Vertrag
-bestandinfos %>%
-    group_by(Polizzennummer) %>%
-    summarize(n = n()) %>%
-    group_by(n) %>% summarize(Anzahl = n())
-bestandinfos %>%
-    group_by(Polizzennummer) %>%
-    summarize(n = n()) %>%
-    ggplot(aes(x = n)) + geom_histogram(binwidth = 1) +
-    stat_bin(aes(y=..count.., label=..count..), geom= "text", vjust=-.5)
-
-# 2) Überblick über Verträge, deren Scheiben alle nach Vertragsbeginn beginnen (Vertragsänderungen)
-
-
-# 3) Prämienfreigestellte Verträge:
-#     -) Scheiben, die ab Abschluss prämienfrei sind
-#     -) Haben HV und alle Scheiben denselben Prf-Zeitpunkt?
-
-# 4) Basic sanity checks: VS<0, keine Prämienzahlung
-bestandinfos %>% filter(premiumFrequency < 1)
-bestandinfos %>% filter(sumInsured <= 0)
-bestandinfos %>% filter(sliceDate < contractClosing)
-
-
-bestandinfos %>%
-    group_by(Polizzennummer, GV) %>%
-    summarize(Anzahl = n()) %>%
-    filter(Anzahl>1)
-
-
-##############################################################################m#
-##
-##  CALCULATION                                                             ####
-##
-##############################################################################m#
-
-
-# Calculate Tarif1 and Tarif2 => Copy and adjust for each run / company-specific implementation
-
-results = NULL;
-results = calculate_portfolio(bestandinfos.all,
-    tarif = c("Tarif1", "Tarif2"),
-    #GV = c("108", "109", "111", "113", "115", "117"),
-    progress = 1, n_max = 9999, debug =TRUE)
-results %>%
-    openxlsx::write.xlsx(outfile("Tarif-1-2"), asTable = TRUE, overwrite = TRUE, sheetName = "Vergleichsrechnung", tabColour = "#80FF8F")
-openXL(outfile("Tarif-1-2"))
-
-
-
diff --git a/inst/rstudio/templates/project/LifeInsuranceContracts/tests/testthat.R b/inst/rstudio/templates/project/LifeInsuranceContracts/tests/testthat.R
deleted file mode 100644
index e0b550c9a2eefca1d3d9c0fb0261a46943339c86..0000000000000000000000000000000000000000
--- a/inst/rstudio/templates/project/LifeInsuranceContracts/tests/testthat.R
+++ /dev/null
@@ -1,4 +0,0 @@
-library(testthat)
-library(LifeInsuranceContractsXXXCOMPANYXXX)
-
-test_check("LifeInsuranceContractsXXXCOMPANYXXX")
diff --git a/inst/rstudio/templates/project/LifeInsuranceContracts/tests/testthat/.gitignore b/inst/rstudio/templates/project/LifeInsuranceContracts/tests/testthat/.gitignore
deleted file mode 100644
index 66e54ae32f6a2693464817ee3ac5fc2fb3daaacf..0000000000000000000000000000000000000000
--- a/inst/rstudio/templates/project/LifeInsuranceContracts/tests/testthat/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-testthat-problems.rds
diff --git a/inst/rstudio/templates/project/LifeInsuranceContracts/tests/testthat/test-Tarif1.R b/inst/rstudio/templates/project/LifeInsuranceContracts/tests/testthat/test-Tarif1.R
deleted file mode 100644
index dc411b5150efa46a7f29c0ff639b6e59cc4afadd..0000000000000000000000000000000000000000
--- a/inst/rstudio/templates/project/LifeInsuranceContracts/tests/testthat/test-Tarif1.R
+++ /dev/null
@@ -1,41 +0,0 @@
-# LifeInsuranceContracts::vmGlgExample.generateTest(
-#     XXXCOMPANYXXX.Tarif1,
-#     age=35, policyPeriod=30, sumInsured=100000,
-#     contractClosing = as.Date("2000-07-01"))
-
-
-test_that("Tarif1", {
-    contract = InsuranceContract$new(
-        XXXCOMPANYXXX.Tarif1,
-        age = 35,
-        policyPeriod = 30,
-        sumInsured = 100000,
-        contractClosing = as.Date("2000-07-01")
-    );
-    exportInsuranceContract.xlsx(contract, here("test-Tarif1.xlsx"))
-    openxlsx::openXL(here("test-Tarif1.xlsx"))
-    # showVmGlgExamples(contract, t = 10, prf = 10, t_prf = 12);
-
-    testVmGlgExample(
-        contract,
-        t = 10, prf = 10, t_prf = 12,
-        net = 2208.00,
-        Zillmer = 2308.67,
-        gross = 2621.51,
-        written = 2726.37,
-        savings = 2126.58,
-        risk = 182.10,
-        ZillmerRes = 23118.57,
-        ZillmerRes.prf = 19931.70,
-        VwKostenRes = -0.00,
-        VwKostenRes.prf = 2245.90,
-        Bilanzreserve = 24560.53,
-        Praemienuebertrag = 1310.76,
-        Rueckkaufsreserve = 23118.57,
-        Rueckkaufswert = 21286.21,
-        Abschlusskostenruecktrag = 0.00,
-        Rueckkaufswert.prf = 22177.59,
-        VS.prf = 33014.59,
-        absTolerance = 0.01
-    );
-})
diff --git a/inst/rstudio/templates/project/LifeInsuranceContracts/tests/testthat/test-Tarif2.R b/inst/rstudio/templates/project/LifeInsuranceContracts/tests/testthat/test-Tarif2.R
deleted file mode 100644
index d3e6585c8724461544579d713a9d2d1b202f059a..0000000000000000000000000000000000000000
--- a/inst/rstudio/templates/project/LifeInsuranceContracts/tests/testthat/test-Tarif2.R
+++ /dev/null
@@ -1,40 +0,0 @@
-# LifeInsuranceContracts::vmGlgExample.generateTest(
-#     XXXCOMPANYXXX.Tarif2,
-#     age=35, policyPeriod = 85, sumInsured=100000,
-#     contractClosing = as.Date("2000-07-01"),
-#     t = 40)
-
-
-test_that("Tarif2", {
-    contract = InsuranceContract$new(
-        XXXCOMPANYXXX.Tarif2,
-        age = 35,
-        policyPeriod = 85,
-        sumInsured = 1e+05,
-        contractClosing = as.Date("2000-07-01")
-    );
-    # showVmGlgExamples(contract, t = 40, prf = 10, t_prf = 12);
-
-    testVmGlgExample(
-        contract,
-        t = 40, prf = 10, t_prf = 12,
-        net = 1210.13,
-        Zillmer = 1210.13,
-        gross = 1930.16,
-        written = 2007.37,
-        savings = -137.47,
-        risk = 1347.60,
-        ZillmerRes = 63074.49,
-        ZillmerRes.prf = 10471.41,
-        VwKostenRes = -0.00,
-        VwKostenRes.prf = 2659.34,
-        Bilanzreserve = 63949.81,
-        Praemienuebertrag = 965.08,
-        Rueckkaufsreserve = 63074.49,
-        Rueckkaufswert = 63074.49,
-        Abschlusskostenruecktrag = 0.00,
-        Rueckkaufswert.prf = 13130.75,
-        VS.prf = 80461.07,
-        absTolerance = 0.01
-    );
-})
diff --git a/man/CalculationSingleEnum-class.Rd b/man/CalculationSingleEnum-class.Rd
deleted file mode 100644
index ed8e8db53fd75487c8da0b8bf1d3d488968e8106..0000000000000000000000000000000000000000
--- a/man/CalculationSingleEnum-class.Rd
+++ /dev/null
@@ -1,30 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/HelperFunctions.R
-\docType{class}
-\name{CalculationSingleEnum-class}
-\alias{CalculationSingleEnum-class}
-\alias{CalculationEnum}
-\title{Enum to define how much of a contract needs to be calculated automatically.}
-\description{
-Enum to define how much of a contract needs to be calculated automatically.
-}
-\details{
-When an \link{InsuranceContract} object is created, all time series are immediately
-calculated. However, sometimes, one only needs part of the values, so it
-would be a waste of resources to calculate e.g. all future reserves and
-profit participation, if only premiums are of interest.
-
-Possible values are:
-\itemize{
-\item "all"
-\item "probabilities"
-\item "cashflows"
-\item "presentvalues"
-\item "premiums"
-\item "absvalues"
-\item "reserves"
-\item "premiumcomposition"
-\item "profitparticipation"
-\item "history"
-}
-}
diff --git a/man/InsuranceContract.ParameterDefaults.Rd b/man/InsuranceContract.ParameterDefaults.Rd
deleted file mode 100644
index c8fe4b31e92f74f71d39d40d1908f5e2873b8195..0000000000000000000000000000000000000000
--- a/man/InsuranceContract.ParameterDefaults.Rd
+++ /dev/null
@@ -1,336 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/InsuranceParameters.R
-\docType{data}
-\name{InsuranceContract.ParameterDefaults}
-\alias{InsuranceContract.ParameterDefaults}
-\title{Default parameters for the InsuranceContract class.}
-\format{
-The parameter list is a list of lists with the following structure:
-
-Sublists:
-\itemize{
-\item \code{$ContractData} ... Contract-specific data (policy period,
-closing, age, sum insured, premium payments, etc.)
-\item \code{$ContractState} ... Current contract state (paid-up, surrender
-penalty already applied, alpha costs already (partially) refunded)
-\item \code{$ActuarialBases} ... Actuarial bases for the contract
-calculation (mortality/invalidity table, guaranteed interest,
-surrender penalty, etc.)
-\item \code{$Costs}, \code{$minCosts} ... Expenses charged to the contract (see \code{\link[=initializeCosts]{initializeCosts()}})
-\item \code{$Loadings} ... Loadings, rebates and other charges of the
-tariff / contract (tax, unit costs, surcharge for no medial exam, premium/benefit frequency loading)
-\item \code{$Features} ... Peculiarities of the tariff (to enable
-non-standard formulas for certain company-specific historical
-"glitches" in the tariff definitions.)
-\item \code{$ProfitParticipation} ... Profit scheme and profit participation
-rates (default values, can be overwritten per profit scenario)
-\item \code{$Hooks} ... Hook functions to allow modification of various
-calculation aspects (e.g. modify the default cash flows after
-their setup)
-}
-\subsection{Elements of sublist \code{InsuranceContract.ParameterDefault$ContractData}}{
-
-These values are typically set per contract and not by the tariff. Notable
-exceptions are the contract duration in some instances and the premiumPeriod=1
-for single-premium contracts.
-
-\describe{
-\item{\code{$id}}{ID of the contract (to distinguish individual parts in
-contracts with multiple parts, e.g. dynamic increases),
-default = "Hauptvertrag"}
-\item{\code{$sumInsured}}{Sum insured, default = 100,000}
-\item{\code{$premium}}{Premium, given to determine the sumInsured (default: NULL)}
-\item{\code{$initialCapital}}{Reserve/Capital that is already available
-at contract inception, e.g. from a previous contract. No tax
-or acquisition costs are applied to this capital.}
-\item{\code{$YOB (deprecated)}}{Year of birth of the insured, used to determine the
-age for the application of the mortality table}
-\item{\code{$birthDate}}{Date  of birth of the insured, used to determine the
-age for the application of the mortality table. Alternatively,
-the year alone can be passed as \code{YOB}.}
-\item{\code{$age}}{Age of the insured}
-\item{\code{$technicalAge}}{Technical age of the insured (when the age
-for the application of the mortality table does not coincide
-with the real age)}
-\item{\code{$ageDifferences}}{Vector of age differences to the first
-insured for contracts with multiple insured (i.e. joint-lives)}
-\item{\code{$sex}}{Sex of the insured, to allow gender-specific prixing
-(e.g. different mortalities or age modification), default="unisex",
-Type is \link{SexEnum}}
-\item{\code{$policyPeriod}}{Policy Duration (in years)}
-\item{\code{$premiumPeriod}}{Premium payment period (in year), for
-single-premium contracts, \code{premiumPeriod = 1}. Default is
-\code{policyPeriod}, i.e. regular premiums during the whole
-contract period}
-\item{\code{$deferralPeriod}}{deferral period for annuities, i.e. the
-period survival payments start only after this period, typically
-the retirement age.  This applies mostly to tariffs of type
-annuity, although deferral periods are possible (but not common)
-for all other types of insurance, too.}
-\item{\code{$guaranteedPeriod}}{guaranteed annuity payment period. The
-annuity pays out for this period, even if the insured dies.
-This applies only to tariffs of type annuity.}
-\item{\code{$contractClosing}}{The date (variable of type \link{Date}) when
-the coverage of the contract starts (not neccessarily equal to
-the date when the contract was signed). Typically generated by
-a call to \code{\link[=as.Date]{as.Date()}}. The year is relevant to derive the age
-of the insured, while month and day are relevant for the
-interpolation of the balance sheet reserves}
-\item{\code{$blockStart}}{For contracts with multiple blocks (e.g.
-multiple dynamic increases, where each increase is modelled
-like a separate contract), this variable holds the offset of
-the current contract block relative to the main contract block.
-The main block starts a 0, dynamic increases start later! This
-value is only used by the parent block (i.e. $t=0$ of the child
-is aligned with $t=blockStart$ of the parent block.}
-\item{\code{$premiumPayments}}{Whether premiums are paid in advance
-(default) or arrears. Value is of type \link{PaymentTimeEnum}
-with possible values "in advance" and "in arrears"}
-\item{\code{$benefitPayments}}{Whether recurring benefits (e.g. annuities)
-are paid in advance (default) or arrears. Value is of type
-\link{PaymentTimeEnum} with possible values "in advance" and
-"in arrears"}
-\item{\code{$premiumFrequency}}{Number of premium payments per year, default is 1.}
-\item{\code{$benefitFrequency}}{Number of benefit payments per year, default is 1.}
-\item{\code{$premiumRefund}}{Proportion of (gross) premiums refunded on
-death (including additional risk, e.g. 1.10 = 110\% of paid premiums)}
-\item{\code{$premiumRefundPeriod}}{The period, during which the premium
-refund on death applies. By default, deferred contracts will
-refund premiums only during the deferral period, all other
-contracts during the whole contract. Default is
-\code{premiumRefundPeriod.default}}
-\item{\code{$premiumIncrease}}{The yearly growth factor of the premium,
-i.e. 1.05 means +5\% increase each year; a vector describes the
-premiums for all years}
-\item{\code{$annuityIncrease}}{The yearly growth factor of the annuity
-payments, i.e. 1.05 means +5\% increase each year; a vector
-describes the annuity unit payments for all years}
-\item{\code{$deathBenefit}}{The yearly relative death benefit (relative
-to the initial sum insured); Can be set to a \code{function(len,
-              params, values)}, e.g. \code{deathBenefit = deathBenefit.linearDecreasing}}
-\item{\code{$benefitParameter}}{(optional) Tariff-specific parameter to
-indicate special benefit conditions (e.g. for non-constant benefits
-the initial starting value, or a minimum benefit, etc.). This
-parameter is not used automatically, but needs to be processed
-by a custom \code{$deathBenefit} function.}
-
-\item{\code{$costWaiver}}{The fraction of the costs that are waived (only
-those cost components that are defined to be waivable, i.e. by
-defining a corresponding \code{$minCosts}). Linearly interpolates
-between \code{$Costs} and \code{$minCosts}, if the latter is set.
-Otherwise is has no effect.}
-\item{\code{$attributes}}{Additional custom attributes (as a named list),
-which can be used for particular behaviour of different contracts
-or contract slices.}
-}
-}
-
-\subsection{Elements of sublist \code{InsuranceContract.ParameterDefault$ContractState}}{
-
-Contract-specific status variables holding the status of the contract.
-
-\describe{
-\item{\code{$premiumWaiver}}{Whether the contract is paid-up.}
-\item{\code{$surrenderPenalty}}{Whether a surrender penalty still applies
-(e.g. because it has already been applied during a contract change,
-or because due to legal reasons it can no longer be applied)}
-\item{\code{$alphaRefunded}}{Whether alpha costs have (at least partially)
-been refunded (e.g. when a contract is changed or paid-up). Default
-is not yet refunded.}
-}
-}
-
-\subsection{Elements of sublist \code{InsuranceContract.ParameterDefault$ActuarialBases}}{
-
-Tarif-specific actuarial calculation parameters of the contract. Typically,
-these values are set by the tariff, but can be overridden by contract (e.g.
-while prototyping a new product or a product change).
-
-\describe{
-\item{\code{$mortalityTable}}{The \link{mortalityTable} object describing the
-mortality of the insured}
-\item{\code{$invalidityTable}}{For contracts with invalidity benefits,
-the \link{mortalityTable} object describing the probabilities of
-invalidity}
-\item{\code{$invalidityEndsContract}}{For contracts with invalidity
-benefits, whether a payment of an invalidity benefit ends the
-contract.}
-\item{\code{$i}}{Guaranteed yearly interest rate, default is 0.00, i.e. 0\%}
-\item{\code{$balanceSheetDate}}{The day/month when balance sheet reserves
-are calculated. Value of type \link{Date}, typically generated with
-\code{\link[=as.Date]{as.Date()}}. The year is actually irrelevant, only the day and
-month are relevant.}
-\item{\code{$balanceSheetMethod}}{How to interpolate the balance sheet
-reserves (at the balandeSheetDate) from the yearly contractual
-reserves. Either a string "30/360", "act/act", "act/360", "act/365"
-or a function with signature \code{balanceSheetMethod(params, contractDates, balanceDates)}
-that returns a vector of coefficients for each year to
-interpolate the reserves available at the given \code{contractDates}
-for the desired \code{balanceDates}}
-\item{\code{$unearnedPremiumsMethod}}{How to calculate the unearned
-premiums (considering the balance sheet date and the premium
-frequency). A function with signature \code{unearnedPremiumsMethod(params, dates)}}
-\item{\code{$surrenderValueCalculation}}{A function describing the surrender
-value calculation. If NULL, the full reserve will be used as
-surrender value. If given, it must be a function with signature
-\code{function(SurrenderReserve, params, values)}.}
-\item{\code{$premiumWaiverValueCalculation}}{A function describing the
-reserve used to derive the premium-free sum insured. If NULL,
-the surrender value will be used. If given, it must be a function
-with signature \code{function(SurrenderReserve, params, values)}}
-\item{\code{$premiumFrequencyOrder}}{Order of the approximation for
-payments within the year (unless an extra frequency loading is
-used => then leave this at 0)}
-\item{\code{$benefitFrequencyOrder}}{Order of the approximation for
-payments within the year (unless an extra frequency loading is
-used => then leave this at 0)}
-}
-}
-
-\subsection{Elements of sublist \code{InsuranceContract.ParameterDefault$Costs}}{
-
-Definition of contractual costs charged to the contract. See \code{\link[=initializeCosts]{initializeCosts()}}.
-
-\describe{
-\item{\code{$Costs}}{The full cost defined for the contract / tariff,
-usually set with \code{\link[=initializeCosts]{initializeCosts()}} and \code{\link[=setCost]{setCost()}}}
-\item{\code{$minCosts}}{The minimum costs defined for the contract / tariff
-that cannot be waived. Either an explicit cost definition structure
-generated by \code{\link[=initializeCosts]{initializeCosts()}} and \code{\link[=setCost]{setCost()}}, or a
-\verb{function(params, values, costs)}, where the full costs are passed
-as third parameter, so the function can modify only those cost parts
-that can be waived at all. }
-}
-}
-
-\subsection{Elements of sublist \code{InsuranceContract.ParameterDefault$Loadings}}{
-
-\describe{
-\item{\code{$ongoingAlphaGrossPremium}}{Acquisition cost that increase the gross premium}
-\item{\code{$tax}}{insurance tax, factor on each premium paid, default is 4\%, i.e. \code{i=0.04}}
-\item{\code{$unitcosts}}{Annual unit cost for each policy, absolute value (can be a function)}
-\item{\code{$security}}{Additional security loading on all benefit payments, factor on all benefits}
-\item{\code{$noMedicalExam}}{Loading when no medicial exam is done, \% of SumInsured}
-\item{\code{$noMedicalExamRelative}}{Loading when no medicial exam is done, \% of gross premium}
-\item{\code{$sumRebate}}{gross premium reduction for large premiums, \% of SumInsured}
-\item{\code{$extraRebate}}{gross premium reduction for any reason, \% of SumInsured}
-\item{\code{$premiumRebate}}{gross premium reduction for large premiums, \% of gross premium}
-\item{\code{$partnerRebate}}{Rebate on premium with all surcharges and
-rebates when more than one contract is written with identical
-parameters. Sums with advanceBonusInclUnitCost and premiumRebate.}
-\item{\code{$extraChargeGrossPremium}}{extra charges on gross premium
-(smoker, leisure activities, BMI too high, etc.)}
-\item{\code{$benefitFrequencyLoading}}{Loading on the benefit for premium
-payment frequencies of more than once a year. Format is
-\code{list("1" = 0.0, "2" = 0.0, "4" = 0.0, "12" = 0.0)}}
-\item{\code{$premiumFrequencyLoading}}{Loading on the premium for premium
-payment frequencies of more than once a year. Format is
-\code{list("1" = 0.0, "2" = 0.0, "4" = 0.0, "12" = 0.0)}}
-\item{\code{$alphaRefundPeriod}}{How long the acquisition costs should be
-(partially) refunded in case of surrender or premium waiver.}
-\item{\code{$commissionPeriod}}{Period, over which the acquisition costs
-are charged to the contract (if not fully up-front or over the
-whole contract period). This has only an effect for cost definitions
-with duration "CommissionPeriod". Default is 5 years.}
-}
-}
-
-\subsection{Elements of sublist \code{InsuranceContract.ParameterDefault$Features}}{
-
-\describe{
-\item{\code{$zillmering}}{Whether the contract uses Zillmering (and bases
-reserves on the Zillmer reserve as opposed to the adequate
-reserve) (default: TRUE)}
-\item{\code{$betaGammaInZillmer}}{Whether beta and gamma-costs should be
-included in the Zillmer premium calculation}
-\item{\code{$alphaRefundLinear}}{Whether the refund of alpha-costs on
-surrender is linear in t or follows the NPV of an annuity}
-\item{\code{$useUnearnedPremiums}}{Whether unearned premiums should be
-reported in the balance sheet reserves. Otherwise, a premium
-paid at the beginning of the period is added to the reserve at
-that time for balance-sheet purposes.
-For regular premiums, the default is TRUE, i.e. the balance-sheet
-reserve at time $t$ does not include the premium paid at time
-$t$, but unearned premiums are included in the balance sheet
-reserves. For single-premium contracts, there are no "unearned"
-premiums, but the initial single premium is added to the reserve
-immediately for balance-sheet purposes. In particular, the
-balance sheet reserve at time $t=0$ is not 0, but the
-premium paid. In turn, no unearned premiums are applied.}
-\item{\code{$surrenderIncludesCostsReserves}}{Whether (administration)
-cost reserves are paid out on surrender (i.e. included in the
-surrender value before surrender penalties are applied)}
-\item{\code{$unitcostsInGross}}{Whether unit costs are included in the
-gross premium calculation or added after gross premiums. (default: FALSE)}
-\item{\code{$absPremiumRefund}}{Constant death benefit (typically premium
-refund of a previous contract), relative to the sum insured.}
-\item{\code{$alphaCostsCommission}}{Whether alpha costs over the commision
-period are given as their actual yearly value ("actual"), or
-whether the given value is the sum ("sum") or the present value
-("presentvalue") over the whole commission period.}
-}
-}
-
-\subsection{Elements of sublist \code{InsuranceContract.ParameterDefault$ProfitParticipation}}{
-
-Parameters describing the profit participation (instance of \link{ProfitParticipation})
-Most element descrive some kind of profit rate (which can vary in time),
-while the bases, on which they are applied is defined in the profit scheme.
-
-\describe{
-\item{\code{$advanceProfitParticipation}}{Advance profit participation
-rate (percentage rebate of the gross premium)}
-\item{\code{$advanceProfitParticipationInclUnitCost}}{Advance profit
-participation rate (percentage rebate on the gross premium after all surcharges and unit costs.}
-\item{\code{$waitingPeriod}}{Waiting period of the profit sharing (e.g.
-no profit in the first two years of a contract, or similar)}
-\item{\code{$guaranteedInterest}}{Individual contract-specific overrides
-of the guaranteed interest rate (i.e. not keyed by year)}
-\item{\code{$interestProfitRate}}{Interest profit rate (guaranteed interest
-rate + interest profit rate = total credited rate)}
-\item{\code{$totalInterest}}{Total credited rate (guarantee + interest profit)}
-\item{\code{$mortalityProfitRate}}{Mortality Profit rate}
-\item{\code{$expenseProfitRate}}{Expense profit rate}
-\item{\code{$sumProfitRate}}{Sum profit rate (for high sumInsured)}
-\item{\code{$terminalBonusRate}}{Terminal bonus rate (non-terminal-bonus
-fund, but "old" Austrian terminal bonus)}
-\item{\code{$terminalBonusFundRate}}{Terminal bonus fund rate}
-\item{\code{$profitParticipationScheme}}{Profit participation scheme (object of class \link{ProfitParticipation})}
-\item{\code{$profitComponents}}{Profit components of the profit scheme. List containing one or more of \code{c("interest", "risk", "expense", "sum", "terminal")}}
-\item{\code{$profitClass}}{String describing the profit class the tariff
-is assigned to. Profit classes are used to bundle similar
-contracts (e.g. following similar risks) together. Profit
-participation rates are defined at the level of profit classes.}
-\item{\code{$profitRates}}{General, company-wide profit rates, key columns are year and profitClass}
-\item{\code{$scenarios}}{profit participation scenarios (list of overridden parameters for each scenario)}
-}
-}
-
-\subsection{Elements of sublist \code{InsuranceContract.ParameterDefault$Hooks}}{
-
-\describe{
-\item{\code{$adjustCashFlows}}{Function with signature \code{function(x, params, values, ...)} to adjust the benefit/premium cash flows after their setup.}
-\item{\code{$adjustCashFlowsCosts}}{Function with signature \code{function(x, params, values, ...)} to adjust the costs cash flows after their setup.}
-\item{\code{$adjustCosts}}{Function with signature \code{function(costs, params, values, ...)} to adjust the tariff costs after their setup (e.g. contract-specific conditions/waivers, etc.).}
-\item{\code{$adjustMinCosts}}{Function with signature \code{function(minCosts, costs, params, values, ...)} to adjust the tariff minimum (unwaivable) costs after their setup (e.g. contract-specific conditions/waivers, etc.).}
-\item{\code{$adjustPresentValues}}{Adjust the present value vectors that are later used to derive premiums and reserves. \code{function(presentValues, params, values)}}
-\item{\code{$adjustPresentValuesCosts}}{Adjust the present value cost vectors used to derive premiums and reserves. \code{function(presentValuesCosts, params, values)}}
-\item{\code{$adjustPremiumCoefficients}}{Function with signature \code{function(coeff, type, premiums, params, values, premiumCalculationTime)} to adjust the coefficients for premium calculation after their default setup. Use cases are e.g. term-fix tariffs where the Zillmer premium term contains the administration cost over the whole contract, but not other gamma- or beta-costs.}
-\item{\code{$adjustPremiums}}{Adjust the resulting premiums. \code{function(premiums = list(premiums, coefficients, sumInsured), params, values)}}
-\item{\code{$adjustPVForReserves}}{Adjust the absolute present value vectors used to derive reserves (e.g. when a sum rebate is subtracted from the gamma-cost reserves without influencing the premium calculation). \code{function(absPV, params, values)}}
-\item{\code{$premiumRebateCalculation}}{Calculate the actual premium rebate from the rebate rate (e.g. when the premium rate is given as a yearly cost reduction applied to a single-premium contract). \code{function(premiumRebateRate, params = params, values = values)}}
-}
-}
-}
-\usage{
-InsuranceContract.ParameterDefaults
-}
-\description{
-A new contract will be
-pre-filled with these values, and values passed in the constructor (or with
-other setter functions) will override these values.
-}
-\examples{
-InsuranceContract.ParameterDefaults
-}
-\keyword{datasets}
diff --git a/man/InsuranceContract.ParameterStructure.Rd b/man/InsuranceContract.ParameterStructure.Rd
deleted file mode 100644
index e02511618bc07ea13ac930e92c1a763a8fa23343..0000000000000000000000000000000000000000
--- a/man/InsuranceContract.ParameterStructure.Rd
+++ /dev/null
@@ -1,19 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/InsuranceParameters.R
-\docType{data}
-\name{InsuranceContract.ParameterStructure}
-\alias{InsuranceContract.ParameterStructure}
-\title{Full insurance contract parameter structure.}
-\format{
-An object of class \code{list} of length 9.
-}
-\usage{
-InsuranceContract.ParameterStructure
-}
-\description{
-All values are filled with NULL,
-so the functions \code{\link{InsuranceContract.ParametersFill}} and
-\code{\link{InsuranceContract.ParametersFallback}} can be used to override
-existing parameters or to provide default values for unset (NULL) entries.
-}
-\keyword{datasets}
diff --git a/man/InsuranceContract.ParametersFallback.Rd b/man/InsuranceContract.ParametersFallback.Rd
deleted file mode 100644
index c5b50e621d53ccf4a044190fff0dbba5c9ce861b..0000000000000000000000000000000000000000
--- a/man/InsuranceContract.ParametersFallback.Rd
+++ /dev/null
@@ -1,22 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/InsuranceParameters.R
-\name{InsuranceContract.ParametersFallback}
-\alias{InsuranceContract.ParametersFallback}
-\title{Use fallback values for missing contract parameters}
-\usage{
-InsuranceContract.ParametersFallback(params, fallback, ppParameters = TRUE)
-}
-\arguments{
-\item{params}{Current, explicitly set contract parameters. All NULL values
-will be filled with the corresponding entry from \code{fallback}.}
-
-\item{fallback}{Fallback values that will be used when the corresponding
-entry in \code{params} is NULL.}
-
-\item{ppParameters}{Whether profit participation parameters should also be
-filled (default is TRUE)}
-}
-\description{
-Provide default values for the insurance contract parameters if any of the
-parameters is not explicitly set.
-}
diff --git a/man/InsuranceContract.ParametersFill.Rd b/man/InsuranceContract.ParametersFill.Rd
deleted file mode 100644
index cedd6db9ac3dbcd37ae9a4cc9c2a51ee0df4ad96..0000000000000000000000000000000000000000
--- a/man/InsuranceContract.ParametersFill.Rd
+++ /dev/null
@@ -1,25 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/InsuranceParameters.R
-\name{InsuranceContract.ParametersFill}
-\alias{InsuranceContract.ParametersFill}
-\title{Initialize the insurance contract parameters from passed arguments}
-\usage{
-InsuranceContract.ParametersFill(
-  params = InsuranceContract.ParameterStructure,
-  costs = NULL,
-  minCosts = NULL,
-  ...
-)
-}
-\arguments{
-\item{params}{Initial values of the insurance contract parameters. (default: empty parameter structure)}
-
-\item{costs, minCosts, ...}{Values for any of the entries in the insurance contract
-parameter structure. These values take precedence over the
-initial parameters provided in \code{params}.}
-}
-\description{
-Initialize the insurance contract parameters from the passed
-arguments. Arguments not given are left unchanged. If no existing parameter
-structure is given, an empty (i.e. all NULL entries) structure is used.
-}
diff --git a/man/InsuranceContract.Rd b/man/InsuranceContract.Rd
deleted file mode 100644
index 6c44951ab005960ab47abccd6253f0c0a84b7993..0000000000000000000000000000000000000000
--- a/man/InsuranceContract.Rd
+++ /dev/null
@@ -1,808 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/InsuranceContract.R
-\name{InsuranceContract}
-\alias{InsuranceContract}
-\title{Base Class for Insurance Contracts}
-\description{
-Base Class for Insurance Contracts
-
-Base Class for Insurance Contracts
-}
-\details{
-R6 class that models a complete, general insurance contract.
-The corresponding tariff and the profit participation scheme, as well as
-all other relevant contract parameters (if not defined by the tariff or
-explicitly overridden by the contract) can be given in the constructor.
-}
-\section{Usage}{
-The typical usage of this class is to simply call
-\ifelse{html}{\href{#method-new}{\code{InsuranceContract$new()}}}{\code{InsuranceContract$new()()}}.
-
-All parameters from the \link{InsuranceContract.ParameterDefaults} can be passed
-to the constructor of the class (i.e. the \ifelse{html}{\href{#method-new}{\code{InsuranceContract$new()}}}{\code{InsuranceContract$new()()}}-call).
-Parameters not explicitly given, will be taken from the tariff or as a fall-back
-mechanism from the \link{InsuranceContract.ParameterDefaults} defaults.
-
-Immediately upon construction, all premiums, reserves and cash flows for the
-whole contract period are calculated and can be accessed via the \code{Values}
-field of the object.
-}
-
-\section{Calculation approach: Valuation}{
-The calculation of all contract values is controlled by the function
-\ifelse{html}{\href{#method-calculateContract}{\code{InsuranceContract$calculateContract()}}}{\code{InsuranceContract$calculateContract()()}} (using methods of the \link{InsuranceTarif}
-object) and follows the following logic:
-\enumerate{
-\item First the \strong{contingent (unit) cash flows} and the \strong{transition probbilities}
-are determined.
-\item The \strong{actuarial equivalence principle} states that at time of inception, the
-(net and gross) premium must be determined in a way that the present value
-of the future benefits and costs minus the present value of the future premiums
-must be equal, i.e. in expectation the future premiums ove the whole lifetime
-of the contract will exactly cover the benefits and costs. Similarly, at all
-later time steps, the difference between these two present values needs to be
-reserved (i.e. has already been paid by the customer by previous premiums).
-\item This allows the premiums to be calculated by first calculating the \strong{present
-values} for all of the \strong{benefit and costs cash flow} vectors.
-\item The formulas
-to calculate the gross, Zillmer and net \strong{premiums} involve simple linear
-combinations of these present values, so the \strong{coefficients of these formulas}
-are determined next.
-\item With the coefficients of the premium formulas calculated, all \strong{premiums
-can be calculated} (first the gross premium, because due to potential gross
-premium refunds in case of death, the formula for the net premium requires
-the gross premium, which the formula for the gross premium involves no other
-type of premuim).
-\item With premiums determined, all unit cash flows and unit present values can
-now be expressed in monetary terms / as \strong{absolute cash flows} (i.e. the actual Euro-amount that flows
-rather than a percentage).
-\item As described above, the difference between the present values of premiums
-and present values of benefits and costs is defined as the required amount
-of reserves, so the \strong{reserves (net, gross, administration cost, balance sheet)}
-and all values derived from them (i.e. surrender value, sum insured in case of
-premium waiver, etc.) are calculated.
-\item The \strong{decomposition of the premium} into parts dedicated to specific purposes
-(tax, rebates, net premium, gross premium, Zillmer premium, cost components,
-risk premium, savings premium, etc.) can be done once the reserves are
-ready (since e.g. the savings premium is defined as the difference of
-discounted reserves at times $t$ and $t+1$).
-\item If the contract has \strong{(discretionary or obligatory) profit sharing}B mechanisms
-included, the corresponding \link{ProfitParticipation} object can calculate that
-profit sharing amounts, once all guaranteed values are calculated. This can
-also be triggered manually (with custom profit sharing rates) by calling
-the methods \ifelse{html}{\href{#method-profitScenario}{\code{InsuranceContract$profitScenario()}}}{\code{InsuranceContract$profitScenario()()}}]
-or \ifelse{html}{\href{#method-addProfitScenario}{\code{InsuranceContract$addProfitScenario()}}}{\code{InsuranceContract$addProfitScenario()()}}.
-}
-}
-
-\section{Calculation approach: Cash Flows}{
-An insurance contract is basically defined by the (unit) cash flows it produces:
-\itemize{
-\item \strong{Premium payments} (in advance or in arrears) at each timestep
-\item \strong{Survival payments} at each timestep
-\item \strong{Guaranteed payments} at each timestep
-\item \strong{Death benefits} at each timestep
-\item \strong{Disease benefits} at each timestep
-}
-Together with the transition probabilities (mortalityTable parameter)
-the present values can be calculated, from which the premiums follow and
-finally the reserves and a potential profit sharing.
-
-For example, a \emph{\strong{term life insurance with regular premiums}} would have the following
-cash flows:
-\itemize{
-\item premium cash flows: 1, 1, 1, 1, 1, ...
-\item survival cash flows: 0, 0, 0, 0, 0, ...
-\item guaranteed cash flows: 0, 0, 0, 0, 0, ...
-\item death benefit cash flows: 1, 1, 1, 1, 1, ...
-}
-
-A \emph{\strong{single-premium term life insurance}} would look similar, except for the premiums:
-\itemize{
-\item premium cash flows: 1, 0, 0, 0, 0, ...
-}
-
-A \emph{\strong{pure endowment}} has no death benefits, but a survival benefit of 1 at the
-maturity of the contract:
-\itemize{
-\item premium cash flows: 1, 1, 1, 1, 1, ...
-\item survival cash flows: 0, 0, ..., 0, 1
-\item guaranteed cash flows: 0, 0, 0, 0, 0, ...
-\item death benefit cash flows: 0, 0, 0, 0, 0, ...
-}
-
-An \emph{\strong{endowment}} has also death benefits during the contract duration:
-\itemize{
-\item premium cash flows: 1, 1, 1, 1, 1, ...
-\item survival cash flows: 0, 0, ..., 0, 1
-\item guaranteed cash flows: 0, 0, 0, 0, 0, ...
-\item death benefit cash flows: 1, 1, 1, 1, 1, ...
-}
-
-A \emph{\strong{(deferred) annuity}B} has premium cash flows only during the deferral peroid
-and only survival cash flows during the annuity payment phase. Often, in case
-of death during the deferral period, all premiums paid are refunded as a death
-benefit.:
-\itemize{
-\item premium cash flows: 1, 1, ...,  1, 0, 0, 0, ...
-\item survival cash flows: 0, 0, ..., 0, 1, 1, 1,...
-\item guaranteed cash flows: 0, 0, 0, 0, 0, ...
-\item death benefit cash flows: 1, 2, 3, 4, 5, ..., 0, 0, ...
-}
-
-A \emph{\strong{terme-fix insurance}} has a guaranteed payment at maturity, even if the insured
-has already died. The premiums, however, are only paid until death (which is
-not reflected in the contingent cash flows, but rather in the transition
-probabilities):
-\itemize{
-\item premium cash flows: 1, 1, 1, 1, ...,  1
-\item survival cash flows: 0, 0, 0, 0, ..., 0
-\item guaranteed cash flows: 0, 0, 0, ..., 0, 1
-\item death benefit cash flows: 0, 0, 0, 0, ..., 0
-}
-
-The \code{InsuranceContract$new()} function creates a new
-insurance contract for the given tariff, using the parameters passed
-to the function (and the defaults specified in the tariff).
-
-As soon as this function is called, the contract object calculates
-all time series (cash flows, premiums, reserves, profit participation)
-for the whole contract duration.
-
-The most important parameters that are typically passed to the
-constructor are:
-\itemize{
-\item \code{age} ... Age of the insured person (used to derive mortalities / transition probabilities)
-\item \code{policyPeriod} ... Maturity of the policy (in years)
-\item \code{premiumPeriod} ... How long premiums are paid (\code{premiumPeriod = 1}
-for single-premium contracts, \code{premiumPeriod} equals
-\code{policyPeriod} for regular premium payments for the whole
-contract period, while other premium payment durations indicate
-premium payments only for shorter periods than the whole contract
-duration. Contract extensions without any premium payments are
-indicated by \code{premiumPeriod}=0). Default is equal to
-\code{policyPeriod}
-\item \code{sumInsured} ... The sum insured (i.e. survival benefit for
-endowments, death benefit for whole/term life insurances,
-annuity payments for annuities)
-\item \code{contractClosing} ... Date of the contract beginning (typically
-created using something like \code{as.Date("2020-08-01")})
-\item \code{YOB} ... Year of birth of the insured (for cohort mortality
-tables). If not given, YOB is derived from \code{age} and
-\code{contractClosing}.
-\item \code{deferralPeriod} ... Deferral period for deferred annuities
-(i.e. when annuity payments start at a future point in time).
-Default is 0.
-\item \code{premiumFrequency} ... How many premium payments per year are
-made (e.g. 1 for yearly premiums, 4 for quarterly premiumd,
-12 for monthly premium payments). Default is 1 (yearly premiums).
-}
-
-While these are the most common and most important parameters, all
-parameters can be overwritten on a per-contract basis, even those
-that are defined by the tariff. For a full list and explanation of all
-parameters, see \link{InsuranceContract.ParameterDefaults}.
-
-The \code{InsuranceContract$addHistorySnapshot()} function
-adds the current (or the explicitly given) state of the contract
-(parameters, calculated values, tarif, list of all contract blocks)
-to the history list (available in the \code{history} field of the
-contract, i.e. \code{InsuranceContract$history}).
-
-Contracts with multiple contract blocks (typically either
-contracts with dynamic increases, sum increases or protection riders)
-are constructed by instantiating the child block (e.g. a single
-dynamic increase or the rider) independently with its own (shorter)
-duration and then inserting it into the parent contract with this
-function at the given time.
-
-If no \link{InsuranceContract} object is passed as \code{block}, a copy
-of the parent is created with overriding parameters given in \code{...}.
-
-This method adds a new contract block describing a dynamic
-or sum increase (increasing the sum insured at a later time
-$t$ than contract inception). This increase is modelled by a
-separate \link{InsuranceContract} object with the sum difference
-as its own \code{sumInsured}.
-
-\if{html}{\out{<div class="sourceCode">}}\preformatted{     By default, all parameters are taken from the main contract,
-     with the maturity adjusted to match the original contract's
-     maturity.
-
-     The main contract holds all child blocks, controls their
-     valueation and aggregates all children's values to the
-     total values of the overall contract.
-}\if{html}{\out{</div>}}
-
-When a contract expires, this function adds a follow-up contract
-(with either the same or a different tariff), using the existing
-reserve as \code{additionalCapital} at inception.
-Technically, a child block using the new contract data of the extension
-is added to the original contract. The over-all contract values are then
-the sum of the original contract (providing values until expiration)
-and the extension (providing values after the extension).
-
-This method calculates all contract values (potentially
-starting from and preserving all values before a later time
-\code{valuesFrom}). This function is not meant to be called
-directly, but internally, whenever a contract is created or
-modified.
-
-\if{html}{\out{<div class="sourceCode">}}\preformatted{     There is, however, a legitimate case to call this function
-     when a contract was initially created with a value of
-     \code{calculate} other than "all", so not all values of the
-     contract were calculated. When one later needs more values
-     than were initially calculated, this function can be called.
-     However, any contract changes might need to be rolled back
-     and reapplied again afterwards. So even in this case it is
-     probably easier to create the contract object from scratch
-     again.
-}\if{html}{\out{</div>}}
-
-This function is an internal function for contracts with
-multiple child blocks (dynamic increases, sum increases, riders).
-It takes the values from all child blocks and calculates the
-overall values from all child blocks aggregated.
-
-\if{html}{\out{<div class="sourceCode">}}\preformatted{   This function should not be called manually.
-}\if{html}{\out{</div>}}
-
-This function modifies the contract at time $t$ so that
-no further premiums are paid (i.e. a paid-up contract) and the
-\code{sumInsured} is adjusted according to the existing reserves.
-
-This function calculates one profit scenario with the
-provided profit participation parameters (all parameters
-not given in the call are taken from their values of the
-contract, profit participation scheme or tariff).
-
-This function calculates one profit scenario with the
-provided profit participation parameters (all parameters
-not given in the call are taken from their values of the
-contract, profit participation scheme or tariff). The results
-are stored in a list of profit scenarios inside the contract.
-
-\if{html}{\out{<div class="sourceCode">}}\preformatted{    This function can be chained to calculate and add multiple
-    profit scenarios.
-}\if{html}{\out{</div>}}
-}
-
-\examples{
-# TODO
-
-
-## ------------------------------------------------
-## Method `InsuranceContract$addHistorySnapshot`
-## ------------------------------------------------
-
-# TODO
-
-## ------------------------------------------------
-## Method `InsuranceContract$addBlock`
-## ------------------------------------------------
-
-# TODO
-
-## ------------------------------------------------
-## Method `InsuranceContract$addDynamics`
-## ------------------------------------------------
-
-# TODO
-
-## ------------------------------------------------
-## Method `InsuranceContract$addExtension`
-## ------------------------------------------------
-
-# TODO
-
-## ------------------------------------------------
-## Method `InsuranceContract$premiumWaiver`
-## ------------------------------------------------
-
-# TODO
-
-## ------------------------------------------------
-## Method `InsuranceContract$profitScenario`
-## ------------------------------------------------
-
-# TODO
-
-## ------------------------------------------------
-## Method `InsuranceContract$addProfitScenario`
-## ------------------------------------------------
-
-# TODO
-}
-\section{Public fields}{
-\if{html}{\out{<div class="r6-fields">}}
-\describe{
-\item{\code{tarif}}{The \link{InsuranceTarif} underlying this contract. The tarif is the abstract
-product description (i.e. defining the type of insurance, fixing tpyes
-of benefits, specifying costs, guaranteed interest rate, mortality tables,
-potential profit sharing mechanisms, etc.), while the contract holds
-the individual parts like age, sum insured, contract duration, premium
-payment frequency, etc.}
-
-\item{\code{parent}}{A pointer to the parent contract. Some contracts consist of multiple
-parts (e.g. a main savings contract with a dread-disease rider, or
-a contract with multiple dynamic increases). These are internally
-represented by one \link{InsuranceContract} object per contract part, plus
-one contract object combining them and deriving combined premiums,
-reserves and profit participation. The child contracts (i.e. the
-objects representing the individual parts) have a pointer to their
-parent, while the overall contract holds a list of all its child contract parts.}
-
-\item{\code{ContractParameters}}{Insurance contract parameters explicitly specified in the contract
-(i.e. parameters that are NOT taken from the tariff of the defaults).}
-
-\item{\code{Parameters}}{Full set of insurance contract parameters applying to this contract.
-The set of parameters is a combination of explicitly given (contract-specific)
-values, parameters determined by the tariff and default values.}
-
-\item{\code{Values}}{List of all contract values (cash flows, present values, premiums,
-reserves, premium decomposition, profit participation, etc.). These
-values will be calculated and filled when the contract is created
-and updated whenever the contract is changed.}
-
-\item{\code{blocks}}{For contracts with multiple contract parts: List of all tariff blocks
-(independently calculated \link{InsuranceContract} objects, that are combined
-to one contract, e.g. dynamic/sum increases). If this field is empty,
-this object describes a contract block (calculated as a stand-alone
-tariff), otherwise it will simply be the sum of its blocks (adjusted
-to span the same time periods)}
-
-\item{\code{history}}{A list keeping track of all contract changes (including the whole
-contract state and its values before the change).}
-
-\item{\code{dummy.public}}{dummy field to allow a trailing comma after the previous field/method}
-}
-\if{html}{\out{</div>}}
-}
-\section{Methods}{
-\subsection{Public methods}{
-\itemize{
-\item \href{#method-InsuranceContract-new}{\code{InsuranceContract$new()}}
-\item \href{#method-InsuranceContract-addHistorySnapshot}{\code{InsuranceContract$addHistorySnapshot()}}
-\item \href{#method-InsuranceContract-addBlock}{\code{InsuranceContract$addBlock()}}
-\item \href{#method-InsuranceContract-addDynamics}{\code{InsuranceContract$addDynamics()}}
-\item \href{#method-InsuranceContract-addExtension}{\code{InsuranceContract$addExtension()}}
-\item \href{#method-InsuranceContract-calculateContract}{\code{InsuranceContract$calculateContract()}}
-\item \href{#method-InsuranceContract-consolidateBlocks}{\code{InsuranceContract$consolidateBlocks()}}
-\item \href{#method-InsuranceContract-premiumWaiver}{\code{InsuranceContract$premiumWaiver()}}
-\item \href{#method-InsuranceContract-profitScenario}{\code{InsuranceContract$profitScenario()}}
-\item \href{#method-InsuranceContract-addProfitScenario}{\code{InsuranceContract$addProfitScenario()}}
-\item \href{#method-InsuranceContract-clone}{\code{InsuranceContract$clone()}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceContract-new"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceContract-new}{}}}
-\subsection{Method \code{new()}}{
-Create a new insurance contract (for the given tariff/product) and calculate all time series
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceContract$new(
-  tarif,
-  parent = NULL,
-  calculate = "all",
-  profitid = "default",
-  ...
-)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{tarif}}{The \link{InsuranceTarif} object describing the Tariff/Product
-and providing defaults for the parameters.}
-
-\item{\code{parent}}{For contracts with multiple contract blocks (dynamic
-increases, sum increases, riders), each child is created with
-a pointer to its parent. NULL for single-block contracts or
-for the overall-contract of a multi-block contract. This
-parameter is used internally, but should not be used in
-user-written code.}
-
-\item{\code{calculate}}{how much of the contract's time series need to be
-calculated. See \link{CalculationEnum} for all possible values. This
-is usefull to prevent calculation of e.g. reserves and profit
-participation, when one only wants to create a grid of premiums.}
-
-\item{\code{profitid}}{The ID of the default profit participation scenario.
-The default profit participation scenario uses the default
-values passed, while further scenarios can be added by
-\ifelse{html}{\href{#method-addProfitScenario}{\code{InsuranceContract$addProfitScenario()}}}{\code{InsuranceContract$addProfitScenario()()}}.}
-
-\item{\code{...}}{Further parameters (age, sum insured, contract closing /
-begin, premium payment details, etc.) of the contract, which
-can also override parameters defined at the tariff-level.
-Possible values are all sub-fields of the
-\link{InsuranceContract.ParameterDefaults} data structure.}
-}
-\if{html}{\out{</div>}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceContract-addHistorySnapshot"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceContract-addHistorySnapshot}{}}}
-\subsection{Method \code{addHistorySnapshot()}}{
-Add the current state of the contract to the history list
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceContract$addHistorySnapshot(
-  time = 0,
-  comment = "Initial contract values",
-  type = "Contract",
-  params = self$Parameters,
-  values = self$Values,
-  tarif = self$tarif,
-  blocks = self$blocks
-)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{time}}{the time described by the snapshot}
-
-\item{\code{comment}}{a comment to store together with the contract state}
-
-\item{\code{type}}{The type of action that caused a history snapshot to
-be stored. Typical values are "Contract" to describe the initial
-contract, "Premium Waiver" or "Dynamic Increase".}
-
-\item{\code{params}}{The set of params to be stored in the history snapshot
-(default is \code{self$Parameters}, if not explicitly given)}
-
-\item{\code{values}}{The calculated time series of all contract values
-calculated so far. Default is \code{self$Values}, if not
-explicitly given}
-
-\item{\code{tarif}}{The underlying \link{InsuranceTarif} object describing the
-Product/Tariff. Default is \code{self$tarif}, if not explicitly given.}
-
-\item{\code{blocks}}{The list of all contract children for contracts with
-multiple insurance blocks (e.g. dynamic increases, riders, etc.)}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Examples}{
-\if{html}{\out{<div class="r example copy">}}
-\preformatted{# TODO
-}
-\if{html}{\out{</div>}}
-
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceContract-addBlock"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceContract-addBlock}{}}}
-\subsection{Method \code{addBlock()}}{
-Add a child contract block (e.g. a dynamic increase or a rider) to an insurance contract
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceContract$addBlock(
-  id = NULL,
-  block = NULL,
-  t = block$Values$int$blockStart,
-  comment = paste0("Additional block at time t=", t),
-  blockType = "Dynamics",
-  ...
-)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{id}}{The identifier of the child block to be inserted}
-
-\item{\code{block}}{The \link{InsuranceContract} object describing the child block.
-If NULL (or not given at all), a copy of the parent will be
-created.}
-
-\item{\code{t}}{Then the child block starts, relative to the parent block.
-The child block is calculated independently (with time 0
-describing its own start), so when aggregating all values from
-the individual blocks to overall values for the whole contract,
-the child's values need to be translated to the parent contracts's
-time frame using this parameter}
-
-\item{\code{comment}}{The comment to use in the history snapshot.}
-
-\item{\code{blockType}}{The type of block to be added (e.g. Dynamics, Extension,
-etc.). Can be any (short) string.}
-
-\item{\code{...}}{parameters to be passed to \ifelse{html}{\href{#method-new}{\code{InsuranceContract$new()}}}{\code{InsuranceContract$new()()}} when
-\code{block} is not given and a copy of the parent should be
-created with overrides.}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Examples}{
-\if{html}{\out{<div class="r example copy">}}
-\preformatted{# TODO
-}
-\if{html}{\out{</div>}}
-
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceContract-addDynamics"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceContract-addDynamics}{}}}
-\subsection{Method \code{addDynamics()}}{
-Add a dynamic increase with the same parameters as the main contract part
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceContract$addDynamics(t, NewSumInsured, SumInsuredDelta, id, ...)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{t}}{The time within the main contract when the sum increase happens.
-The \link{InsuranceContract} object describing the dynamic increase
-will still internally start at its own time 0, but the
-aggregation by the main contract will correctly offset to
-the time $t$ within the main contract.}
-
-\item{\code{NewSumInsured}}{The over-all new sum insured (sum of original
-contract and all dynamica increaeses). The \code{sumInsured}
-of the new dynamic increase block will be determined as the
-difference of the old and new overall sum insured. Alternatively,
-it can directly be given as the \code{SumInsuredDelta}
-argument instead.}
-
-\item{\code{SumInsuredDelta}}{The sum insured of only the dynamic increase,
-i.e. the sumInsured of the dynamic contract block only. The
-overall sum insured will increase by this amount. Only one of
-\code{NewSumInsured} and \code{SumInsuredDelta} is needed,
-the other one will be calculated accordingly. If both are
-given, the \code{SumInsuredDelta} will take precedence.}
-
-\item{\code{id}}{The identifier of the contract block describing the dynamic
-increase. This is a free-form string that should be unique
-within the list of child blocks. It will be displayed in the
-Excel export feature and in the history snapshot list.}
-
-\item{\code{...}}{Paramters to override in the dynamic block. By default,
-all parameters of the main contract block will be used, but
-they can be overridden per dynamic increase block.}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Examples}{
-\if{html}{\out{<div class="r example copy">}}
-\preformatted{# TODO
-}
-\if{html}{\out{</div>}}
-
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceContract-addExtension"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceContract-addExtension}{}}}
-\subsection{Method \code{addExtension()}}{
-Add a contract extension after the contract has ended
-(existing reserve is used as initial capital of the follow-up contract).
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceContract$addExtension(
-  id = NULL,
-  t = NULL,
-  comment = paste0("Contract extension at time t=", t),
-  ...
-)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{id}}{The identifier of the child block to be inserted}
-
-\item{\code{t}}{The time of the extension (relative to the parent block),
-by default contract expiration of the parent block.
-The extension is calculated independently (with time 0
-describing its own start), but using the existing reserve as
-initialCapital and the parent's parameters as fall-back values.}
-
-\item{\code{comment}}{The comment to use in the history snapshot.}
-
-\item{\code{...}}{Additional parameters to be passed to
-\ifelse{html}{\href{#method-new}{\code{InsuranceContract$new}}}{\code{InsuranceContract$new}} to create the contract
-extension object.}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Examples}{
-\if{html}{\out{<div class="r example copy">}}
-\preformatted{# TODO
-}
-\if{html}{\out{</div>}}
-
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceContract-calculateContract"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceContract-calculateContract}{}}}
-\subsection{Method \code{calculateContract()}}{
-Calculate all time series of the contract from the parameters
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceContract$calculateContract(
-  calculate = "all",
-  valuesFrom = 0,
-  premiumCalculationTime = 0,
-  preservePastPV = TRUE,
-  additionalCapital = 0,
-  recalculatePremiums = TRUE,
-  recalculatePremiumSum = TRUE,
-  history_comment = NULL,
-  history_type = "Contract"
-)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{calculate}}{Which values to calculate. See \link{CalculationEnum}}
-
-\item{\code{valuesFrom}}{Calculate only values starting from this time step
-on (all values before that time will be preserved). This is
-required when a contract is changed significantly (potentially
-even switching to a new tariff), so that the calculation bases
-for previous periods are no longer available.}
-
-\item{\code{premiumCalculationTime}}{The time point when the premium should
-be re-calculated (including existing reserves) based on the
-actuarial equivalence principle. All reserves will be based on
-these new premiums.}
-
-\item{\code{preservePastPV}}{Whether present value before the recalculation
-time \code{valuesFrom} should be preserved or recalculated.
-When they are recalculated, the present values are consistent
-to the new cash flows over the whole contract period, but
-they no longer represent the actual contract state at these
-times. If values are not recalculated, the reserves at each
-time step represent the proper state at that point in time.}
-
-\item{\code{additionalCapital}}{The capital that is added to the contract
-(e.g. capital carried over from a previous contract) at the
-premium calculation time.}
-
-\item{\code{recalculatePremiums}}{Whether the premiums should be recalculated
-at time \code{premiumCalculationTime} at all.}
-
-\item{\code{recalculatePremiumSum}}{Whether to recalculate the overall premium
-sum when the premium is recalculated.}
-
-\item{\code{history_comment}}{The comment for the history snapshot entry}
-
-\item{\code{history_type}}{The type (free-form string) to record in the history snapshot}
-}
-\if{html}{\out{</div>}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceContract-consolidateBlocks"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceContract-consolidateBlocks}{}}}
-\subsection{Method \code{consolidateBlocks()}}{
-Aggregate values from all child contract blocks (if any)
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceContract$consolidateBlocks(valuesFrom = 0)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{valuesFrom}}{The time from when to aggragate values. Values before
-that time will be left unchanged.}
-}
-\if{html}{\out{</div>}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceContract-premiumWaiver"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceContract-premiumWaiver}{}}}
-\subsection{Method \code{premiumWaiver()}}{
-Stop premium payments and re-calculate sumInsured of the paid-up contract
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceContract$premiumWaiver(t, ...)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{t}}{Time of the premium waiver.}
-
-\item{\code{...}}{Further parameters (currently unused)}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Examples}{
-\if{html}{\out{<div class="r example copy">}}
-\preformatted{# TODO
-}
-\if{html}{\out{</div>}}
-
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceContract-profitScenario"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceContract-profitScenario}{}}}
-\subsection{Method \code{profitScenario()}}{
-Calculate one profit scenario and return all values
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceContract$profitScenario(...)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{...}}{Scenario-specific profit sharing parameters, overriding
-the default values. Typically, adjusted profit rates are required
-in a profitScenario.}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Returns}{
-a data.frame holding all profit participation values (rates,
-bases for the different profit types, profit allocations,
-terminal bonus funds, profit in case of death/surrender/premium waiver)
-}
-\subsection{Examples}{
-\if{html}{\out{<div class="r example copy">}}
-\preformatted{# TODO
-}
-\if{html}{\out{</div>}}
-
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceContract-addProfitScenario"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceContract-addProfitScenario}{}}}
-\subsection{Method \code{addProfitScenario()}}{
-Calculate one profit scenario and store it in the contract
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceContract$addProfitScenario(id, ...)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{id}}{The unique ID of the profit scenario. Will be used as key
-in the list of profit scenarios and printed out in the Excel
-export.}
-
-\item{\code{...}}{Scenario-specific profit sharing parameters, overriding
-the default values. Typically, adjusted profit rates are required
-in a profitScenario.}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Examples}{
-\if{html}{\out{<div class="r example copy">}}
-\preformatted{# TODO
-}
-\if{html}{\out{</div>}}
-
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceContract-clone"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceContract-clone}{}}}
-\subsection{Method \code{clone()}}{
-The objects of this class are cloneable with this method.
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceContract$clone(deep = FALSE)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{deep}}{Whether to make a deep clone.}
-}
-\if{html}{\out{</div>}}
-}
-}
-}
diff --git a/man/InsuranceContract.Values.Rd b/man/InsuranceContract.Values.Rd
deleted file mode 100644
index 41dfe5b6e493d3d561b384a1ed1ac0fc258d6a8b..0000000000000000000000000000000000000000
--- a/man/InsuranceContract.Values.Rd
+++ /dev/null
@@ -1,16 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/InsuranceParameters.R
-\docType{data}
-\name{InsuranceContract.Values}
-\alias{InsuranceContract.Values}
-\title{Data structure (filled only with NULL) for insurance contract class member values.}
-\format{
-An object of class \code{list} of length 16.
-}
-\usage{
-InsuranceContract.Values
-}
-\description{
-Data structure (filled only with NULL) for insurance contract class member values.
-}
-\keyword{datasets}
diff --git a/man/InsuranceTarif.Rd b/man/InsuranceTarif.Rd
deleted file mode 100644
index e6dd304e3b942eb5df3b5db1ae243431232f2d50..0000000000000000000000000000000000000000
--- a/man/InsuranceTarif.Rd
+++ /dev/null
@@ -1,1186 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/InsuranceTarif.R
-\name{InsuranceTarif}
-\alias{InsuranceTarif}
-\title{Base class for traditional Insurance Tarifs (with fixed guarantee, profit
-sharing and no unit-linked component)}
-\description{
-The class \code{InsuranceTarif} provides the code and general
-framework to implement contract-independent functionality of a life insurance
-product.
-}
-\details{
-This is a base class for holding contract-independent values and
-providing methods to calculate cash flows, premiums, etc. Objects of this
-class do NOT contain contract-specific values like age, death probabilities,
-premiums, reserves, etc. Rather, they are the calculation kernels that will
-be called by the \code{\link{InsuranceContract}} objects to make the actual,
-tariff-specific calculations.
-
-Most methods of this class are not meant to be called manually, but are supposed
-to be called by the InsuranceContract object with contract-specific information.
-The only methods that are typically used for defining an insurance tariff are
-the constructor \href{#method-new}{\code{InsuranceTarif$new()}} and the cloning method
-\href{#method-createModification}{\code{InsuranceTarif$createModification()}}.
-All other methods should never be called manually.
-
-However, as overriding private methods is not possible in an R6 class, all the
-methods need to be public to allow overriding them in derived classes.
-}
-\examples{
-# Define an insurance tariff for 10-year endowments, using a guaranteed interest
-# rate of 1\% and the Austrian population mortality table of the census 2011.
-# Premiums are paid monthly in advance during the whole contract period.
-MortalityTables::mortalityTables.load("Austria_Census")
-# Cost structure:
-#   - 4\% up-front acquisition costs (of premium sum)
-#   - 1\% collection cost of each premium paid
-#   - 1\%o yearly administration cost (of the sum insured) as long as premiums are paid
-#   - 2\%o yearly administration cost for paid-up contracts
-#   - 10 Euro yearly unit costs (as long as premiums are paid)
-costs.endw = initializeCosts(alpha = 0.04, beta = 0.01, gamma = 0.001,
-    gamma.paidUp = 0.002, gamma.premiumfree = 0.002, unitcosts = 10)
-
-endowment.AT1 = InsuranceTarif$new(
-    name = "Endow AT 1\%", type = "endowment", tarif = "Austrian Endowment",
-    desc = "An endowment for Austrian insured with 1\% interest and no profit participation",
-    ContractPeriod = 10,
-    i = 0.01, mortalityTable = mort.AT.census.2011.unisex,
-    costs = costs.endw, premiumFrequency = 12)
-
-# The instantiation of the actual contract will provide the contract specific
-# information and immediately calculate all further values:
-ctr.end.AT1 = InsuranceContract$new(tarif = endowment.AT1,
-    contractClosing = as.Date("2020-07-01"), age = 42)
-
-# All values for the contract are already calculated during construction and
-# stored in the ctr.end.AT1$Values list:
-ctr.end.AT1$Values$basicData
-ctr.end.AT1$Values$transitionProbabilities
-ctr.end.AT1$Values$cashFlowsCosts
-ctr.end.AT1$Values$presentValues
-ctr.end.AT1$Values$premiums
-ctr.end.AT1$Values$reserves
-ctr.end.AT1$Values$premiumComposition
-# etc.
-
-## ------------------------------------------------
-## Method `InsuranceTarif$new`
-## ------------------------------------------------
-
-MortalityTables::mortalityTables.load("Austria_Annuities_AVOe2005R")
-tarif.male = InsuranceTarif$new(name = "Annuity Males", type = "annuity",
-    i = 0.01, mortalityTable = AVOe2005R.male)
-
-## ------------------------------------------------
-## Method `InsuranceTarif$createModification`
-## ------------------------------------------------
-
-MortalityTables::mortalityTables.load("Austria_Annuities_AVOe2005R")
-tarif.male = InsuranceTarif$new(name = "Annuity Males", type = "annuity",
-    i = 0.01, mortalityTable = AVOe2005R.male)
-tarif.unisex = tarif.male$createModification(name = "Annuity unisex",
-    mortalityTable = AVOe2005R.unisex)
-
-## ------------------------------------------------
-## Method `InsuranceTarif$getParameters`
-## ------------------------------------------------
-
-tarif.male = InsuranceTarif$new(name = "Annuity Males", type = "annuity",
-    i = 0.01, mortalityTable = AVOe2005R.male)
-tarif.male$getParameters()
-}
-\section{Public fields}{
-\if{html}{\out{<div class="r6-fields">}}
-\describe{
-\item{\code{name}}{The tariff's unique name. Will also be used as the key for exported data.}
-
-\item{\code{tarif}}{The tariff's public name (typically a product name), not necessarily unique.}
-
-\item{\code{desc}}{A short human-readable description of the tariff and its main features.}
-
-\item{\code{tariffType}}{An enum specifying the main characteristics of the tarif.
-Possible values are:
-\describe{
-\item{annuity}{Whole life or term annuity (periodic survival benefits)
-with flexible payouts (constand, increasing, decreasing, arbitrary,
-etc.)}
-\item{wholelife}{A whole or term life insurance with only death benefits.
-The benefit can be constant, increasing, decreasing, described by
-a function, etc.}
-\item{endowment}{An  endowment with death and survival benefits,
-potentially with different benefits.}
-\item{pureendowment}{A pure endowment with only a survival benefit at
-the end of the contract. Optionally, in case of death, all or part
-of the premiums paid may be refunded.}
-\item{terme-fix}{A terme-fix insurance with a fixed payout at the end
-of the contract, even if the insured dies before that time.
-Premiums are paid until death of the insured.}
-\item{dread-disease}{A dread-disease insurance, which pays in case of
-a severe illness (typically heart attacks, cancer, strokes, etc.),
-but not in case of death.}
-\item{endowment + dread-disease}{A combination of an endowment and a
-temporary dread-disease insurance. Benefits occur either on death,
-severe illness or survival, whichever comes first.}
-}}
-
-\item{\code{Parameters}}{A data structure (nested list) containing all relevant
-parameters describing a contract, its underlying tariff, the profit
-participation scheme etc. See \link{InsuranceContract.ParameterStructure} for
-all fields.}
-
-\item{\code{dummy}}{Dummy field to allow commas after the previous method}
-}
-\if{html}{\out{</div>}}
-}
-\section{Methods}{
-\subsection{Public methods}{
-\itemize{
-\item \href{#method-InsuranceTarif-new}{\code{InsuranceTarif$new()}}
-\item \href{#method-InsuranceTarif-createModification}{\code{InsuranceTarif$createModification()}}
-\item \href{#method-InsuranceTarif-getParameters}{\code{InsuranceTarif$getParameters()}}
-\item \href{#method-InsuranceTarif-getInternalValues}{\code{InsuranceTarif$getInternalValues()}}
-\item \href{#method-InsuranceTarif-getAges}{\code{InsuranceTarif$getAges()}}
-\item \href{#method-InsuranceTarif-getTransitionProbabilities}{\code{InsuranceTarif$getTransitionProbabilities()}}
-\item \href{#method-InsuranceTarif-getCostValues}{\code{InsuranceTarif$getCostValues()}}
-\item \href{#method-InsuranceTarif-getPremiumCF}{\code{InsuranceTarif$getPremiumCF()}}
-\item \href{#method-InsuranceTarif-getAnnuityCF}{\code{InsuranceTarif$getAnnuityCF()}}
-\item \href{#method-InsuranceTarif-getDeathCF}{\code{InsuranceTarif$getDeathCF()}}
-\item \href{#method-InsuranceTarif-getBasicCashFlows}{\code{InsuranceTarif$getBasicCashFlows()}}
-\item \href{#method-InsuranceTarif-getCashFlows}{\code{InsuranceTarif$getCashFlows()}}
-\item \href{#method-InsuranceTarif-getCashFlowsCosts}{\code{InsuranceTarif$getCashFlowsCosts()}}
-\item \href{#method-InsuranceTarif-presentValueCashFlows}{\code{InsuranceTarif$presentValueCashFlows()}}
-\item \href{#method-InsuranceTarif-presentValueCashFlowsCosts}{\code{InsuranceTarif$presentValueCashFlowsCosts()}}
-\item \href{#method-InsuranceTarif-getAbsCashFlows}{\code{InsuranceTarif$getAbsCashFlows()}}
-\item \href{#method-InsuranceTarif-getAbsPresentValues}{\code{InsuranceTarif$getAbsPresentValues()}}
-\item \href{#method-InsuranceTarif-presentValueBenefits}{\code{InsuranceTarif$presentValueBenefits()}}
-\item \href{#method-InsuranceTarif-getPremiumCoefficients}{\code{InsuranceTarif$getPremiumCoefficients()}}
-\item \href{#method-InsuranceTarif-sumInsuredCalculation}{\code{InsuranceTarif$sumInsuredCalculation()}}
-\item \href{#method-InsuranceTarif-premiumCalculation}{\code{InsuranceTarif$premiumCalculation()}}
-\item \href{#method-InsuranceTarif-reserveCalculation}{\code{InsuranceTarif$reserveCalculation()}}
-\item \href{#method-InsuranceTarif-getBalanceSheetReserveFactor}{\code{InsuranceTarif$getBalanceSheetReserveFactor()}}
-\item \href{#method-InsuranceTarif-reserveCalculationBalanceSheet}{\code{InsuranceTarif$reserveCalculationBalanceSheet()}}
-\item \href{#method-InsuranceTarif-calculateProfitParticipation}{\code{InsuranceTarif$calculateProfitParticipation()}}
-\item \href{#method-InsuranceTarif-reservesAfterProfit}{\code{InsuranceTarif$reservesAfterProfit()}}
-\item \href{#method-InsuranceTarif-getBasicDataTimeseries}{\code{InsuranceTarif$getBasicDataTimeseries()}}
-\item \href{#method-InsuranceTarif-premiumDecomposition}{\code{InsuranceTarif$premiumDecomposition()}}
-\item \href{#method-InsuranceTarif-calculateFutureSums}{\code{InsuranceTarif$calculateFutureSums()}}
-\item \href{#method-InsuranceTarif-calculatePresentValues}{\code{InsuranceTarif$calculatePresentValues()}}
-\item \href{#method-InsuranceTarif-evaluateFrequencyLoading}{\code{InsuranceTarif$evaluateFrequencyLoading()}}
-\item \href{#method-InsuranceTarif-clone}{\code{InsuranceTarif$clone()}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-new"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-new}{}}}
-\subsection{Method \code{new()}}{
-Initialize a new tariff object
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$new(
-  name = NULL,
-  type = "wholelife",
-  tarif = "Generic Tarif",
-  desc = "Description of tarif",
-  ...
-)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{name}}{The unique name / ID of the tariff}
-
-\item{\code{type}}{An enum specifying the main characteristics of the tarif. See \link{TariffTypeEnum}}
-
-\item{\code{tarif}}{The tariff's public name to be stored in the \code{tarif} field.}
-
-\item{\code{desc}}{A short human-readable description to be stored in the \code{desc} field.}
-
-\item{\code{...}}{Parameters for the \link{InsuranceContract.ParameterStructure},
-defining the characteristics of the tariff.}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-The constructor function defines a tariff and generates the
-corresponding data structure, which can then be used with the \link{InsuranceContract}
-class to define an actual contract using the tariff.
-
-The arguments passed to this function will be stored inside the
-\code{Parameters} field of the class, inside one of the lists sublists.
-The parameters are stacked from different layers (higher levels override
-default values from lower layers):
-\itemize{
-\item InsuranceContract object (parameters passed directly to the individual
-contract)
-\item ProfitParticipation object (parameters for profit participation, passed
-to the definition of the profit plan, which is used for the tarif
-definition or the contract)
-\item InsuranceTarif object (parameters passed to the definition of the tariff
-that was used for the contract)
-\item Defaults taken from \link{InsuranceContract.ParameterStructure}
-}
-
-The general implementation of this parameter layering means that (a) a tariff
-can already provide default values for contracts (e.g. a default maturity,
-default sum insured, etc) and (b) individual contracts can override all
-parameters defined with the underlying tariff. In particular the latter
-feature has many use-cases in prototyping: E.g. when you have a tariff
-with a guaranteed interest rate of 1\\% and a certain mortality table,
-one can immediately instantiate a contract with an updated interest rate
-or mortality table for comparison. There is no need to re-implement a
-tariff for such comparisons, as long as only parameters are changed.
-}
-
-\subsection{Examples}{
-\if{html}{\out{<div class="r example copy">}}
-\preformatted{MortalityTables::mortalityTables.load("Austria_Annuities_AVOe2005R")
-tarif.male = InsuranceTarif$new(name = "Annuity Males", type = "annuity",
-    i = 0.01, mortalityTable = AVOe2005R.male)
-}
-\if{html}{\out{</div>}}
-
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-createModification"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-createModification}{}}}
-\subsection{Method \code{createModification()}}{
-create a copy of a tariff with certain parameters changed
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$createModification(
-  name = NULL,
-  tarif = NULL,
-  desc = NULL,
-  tariffType = NULL,
-  ...
-)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{name}}{The unique name / ID of the tariff}
-
-\item{\code{tarif}}{The tariff's public name to be stored in the \code{tarif} field.}
-
-\item{\code{desc}}{A short human-readable description to be stored in the \code{desc} field.}
-
-\item{\code{tariffType}}{An enum specifying the main characteristics of the tarif.
-See \link{TariffTypeEnum}}
-
-\item{\code{...}}{Parameters for the \link{InsuranceContract.ParameterStructure},
-defining the characteristics of the tariff.}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-This method \code{createModification} returns a copy of the tariff
-with all given arguments changed in the tariff's \code{InsuranceTarif$Parameters}
-parameter list.
-
-As InsuranceTarif is a R6 class with reference logic, simply assigning
-the object to a new variable does not create a copy, but references the
-original tariff object. To create an actual copy, one needs to call this
-method, which first clones the whole object and then adjusts all parameters
-to the values passed to this method.
-}
-
-\subsection{Examples}{
-\if{html}{\out{<div class="r example copy">}}
-\preformatted{MortalityTables::mortalityTables.load("Austria_Annuities_AVOe2005R")
-tarif.male = InsuranceTarif$new(name = "Annuity Males", type = "annuity",
-    i = 0.01, mortalityTable = AVOe2005R.male)
-tarif.unisex = tarif.male$createModification(name = "Annuity unisex",
-    mortalityTable = AVOe2005R.unisex)
-}
-\if{html}{\out{</div>}}
-
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-getParameters"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-getParameters}{}}}
-\subsection{Method \code{getParameters()}}{
-Retrieve the parameters for this tariff (can be overridden
-for each contract)
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$getParameters()}\if{html}{\out{</div>}}
-}
-
-\subsection{Examples}{
-\if{html}{\out{<div class="r example copy">}}
-\preformatted{tarif.male = InsuranceTarif$new(name = "Annuity Males", type = "annuity",
-    i = 0.01, mortalityTable = AVOe2005R.male)
-tarif.male$getParameters()
-}
-\if{html}{\out{</div>}}
-
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-getInternalValues"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-getInternalValues}{}}}
-\subsection{Method \code{getInternalValues()}}{
-Get some internal parameters cached (length of data.frames,
-policy periods cut at max.age, etc.)
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$getInternalValues(params, ...)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{...}}{currently unused}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-This methos is not meant to be called explicitly, but rather used
-by the InsuranceContract class. It returns a list of maturities and ages
-relevant for the contract-specific calculations
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-getAges"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-getAges}{}}}
-\subsection{Method \code{getAges()}}{
-Calculate the contract-relevant age(s) given a certain
-parameter data structure (contract-specific values)
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$getAges(params)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-This method is not meant to be called explicitly, but rather used
-by the InsuranceContract class. It returns the relevant ages during the
-whole contract period
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-getTransitionProbabilities"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-getTransitionProbabilities}{}}}
-\subsection{Method \code{getTransitionProbabilities()}}{
-Calculate the transition probabilities from the contract-specific
-parameters passed as \code{params} and the already-calculated contract
-values \code{values}
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$getTransitionProbabilities(params, values)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (in the \code{contract$Values}
-list) then this method is called by the contract object}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Not to be called directly, but implicitly by the \link{InsuranceContract} object.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-getCostValues"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-getCostValues}{}}}
-\subsection{Method \code{getCostValues()}}{
-Obtain the cost structure from the cost parameter and the
-given paremeter set
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$getCostValues(params)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{params}}{The parameters of the contract / tariff}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Not to be called directly, but implicitly by the \link{InsuranceContract} object.
-The cost parameter can be either an array of costs (generated by \code{\link[=initializeCosts]{initializeCosts()}})
-or a function with parameters \code{param} and \code{values}(=NULL) returning
-an array of the required dimensions. This function makes sures that the
-latter function is actually evaluated.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-getPremiumCF"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-getPremiumCF}{}}}
-\subsection{Method \code{getPremiumCF()}}{
-Returns the unit premium cash flow for the whole contract period.
-\itemize{
-\item For constant premiums it will be rep(1, premiumPeriod),
-\item for single premiums it will be c(1, 0, 0, ...),
-\item for increasing premiums it will be (1+increase)^(0:(premiumPeriod-1))
-and 0 after the premium period
-}
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$getPremiumCF(len, params, values)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{len}}{The desired length of the returned data frame (the number of contract periods desire)}
-
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (in the \code{contract$Values}
-list) then this method is called by the contract object}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Not to be called directly, but implicitly by the \link{InsuranceContract} object.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-getAnnuityCF"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-getAnnuityCF}{}}}
-\subsection{Method \code{getAnnuityCF()}}{
-Returns the unit annuity cash flow (guaranteed and contingent) for
-the whole annuity payment period (after potential deferral period)
-\itemize{
-\item For constant annuity it will be rep(1, annuityPeriod),
-\item for increasing annuities it will be (1+increase)^(0:(premiumPeriod-1))
-and 0 after the premium period
-}
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$getAnnuityCF(len, params, values)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{len}}{The desired length of the returned data frame (the number of contract periods desire)}
-
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (in the \code{contract$Values}
-list) then this method is called by the contract object}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Not to be called directly, but implicitly by the \link{InsuranceContract} object.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-getDeathCF"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-getDeathCF}{}}}
-\subsection{Method \code{getDeathCF()}}{
-Returns the unit death cash flow for the whole protection
-period (after potential deferral period!)
-\itemize{
-\item For constant death benefit it will be rep(1, policyPeriod),
-\item for linearly decreasing sum insured it will be (policyPeriod:0)/policyPeriod
-}
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$getDeathCF(len, params, values)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{len}}{The desired length of the returned data frame (the number of contract periods desire)}
-
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (in the \code{contract$Values}
-list) then this method is called by the contract object}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Not to be called directly, but implicitly by the \link{InsuranceContract} object.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-getBasicCashFlows"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-getBasicCashFlows}{}}}
-\subsection{Method \code{getBasicCashFlows()}}{
-Returns the basic (unit) cash flows associated with the type
-of insurance given in the InsuranceTarif's \code{tariffType} field
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$getBasicCashFlows(params, values)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (in the \code{contract$Values}
-list) then this method is called by the contract object}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Not to be called directly, but implicitly by the \link{InsuranceContract} object.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-getCashFlows"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-getCashFlows}{}}}
-\subsection{Method \code{getCashFlows()}}{
-Returns the cash flows for the contract given the parameters
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$getCashFlows(params, values)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (in the \code{contract$Values}
-list) then this method is called by the contract object}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Not to be called directly, but implicitly by the \link{InsuranceContract} object.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-getCashFlowsCosts"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-getCashFlowsCosts}{}}}
-\subsection{Method \code{getCashFlowsCosts()}}{
-Returns the cost cash flows of the contract given the contract
-and tariff parameters
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$getCashFlowsCosts(params, values)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (in the \code{contract$Values}
-list) then this method is called by the contract object}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Not to be called directly, but implicitly by the \link{InsuranceContract} object.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-presentValueCashFlows"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-presentValueCashFlows}{}}}
-\subsection{Method \code{presentValueCashFlows()}}{
-Returns the present values of the cash flows of the contract
-(cash flows already calculated and stored in the \code{cashFlows} data.frame)
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$presentValueCashFlows(params, values)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (in the \code{contract$Values}
-list) then this method is called by the contract object}
-
-\item{\code{cashFlows}}{data.frame of cash flows calculated by a call to \href{#method-getCashFlows}{\code{InsuranceTarif$getCashFlows()}}}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Not to be called directly, but implicitly by the \link{InsuranceContract} object.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-presentValueCashFlowsCosts"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-presentValueCashFlowsCosts}{}}}
-\subsection{Method \code{presentValueCashFlowsCosts()}}{
-Calculates the present values of the cost cash flows of the
-contract (cost cash flows alreay calculated by \href{#method-getCashFlowsCosts}{\code{InsuranceTarif$getCashFlowsCosts()}}
-and stored in the \code{values} list
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$presentValueCashFlowsCosts(params, values, presentValues)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (in the \code{contract$Values}
-list) then this method is called by the contract object}
-
-\item{\code{presentValues}}{The present values of the insurance claims (without costs)}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Not to be called directly, but implicitly by the \link{InsuranceContract} object.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-getAbsCashFlows"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-getAbsCashFlows}{}}}
-\subsection{Method \code{getAbsCashFlows()}}{
-Calculate the cash flows in monetary terms of the insurance contract
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$getAbsCashFlows(params, values)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (in the \code{contract$Values}
-list) then this method is called by the contract object}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Once the premiums of the insurance contracts are calculated, all
-cash flows can also be expressed in absolute terms. This function
-calculates these time series in monetary terms, once the premiums
-are calculated by the previous functions of this class.
-
-This method is NOT to be called directly, but implicitly by the \link{InsuranceContract} object.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-getAbsPresentValues"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-getAbsPresentValues}{}}}
-\subsection{Method \code{getAbsPresentValues()}}{
-Calculate the absolute present value time series of the insurance contract
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$getAbsPresentValues(params, values)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (in the \code{contract$Values}
-list) then this method is called by the contract object}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Once the premiums of the insurance contracts are calculated, all
-present values can also be expressed in absolute terms. This function
-calculates these time series in monetary terms, once the premiums and the
-unit-benefit present values are calculated by the previous functions of
-this classe.
-
-This method is NOT to be called directly, but implicitly by the \link{InsuranceContract} object.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-presentValueBenefits"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-presentValueBenefits}{}}}
-\subsection{Method \code{presentValueBenefits()}}{
-Calculate the absolute present value time series of the
-benefits of the insurance contract
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$presentValueBenefits(params, values)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (in the \code{contract$Values}
-list) then this method is called by the contract object}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Once the premiums of the insurance contracts are calculated, all
-present values can also be expressed in absolute terms. This function
-calculates these time series of the benefits present values in monetary
-terms, once the premiums and the unit-benefit present values are calculated
-by the previous functions of this classe.
-
-This method is NOT to be called directly, but implicitly by the \link{InsuranceContract} object.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-getPremiumCoefficients"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-getPremiumCoefficients}{}}}
-\subsection{Method \code{getPremiumCoefficients()}}{
-Calculate the linear coefficients of the premium calculation formula for the insurance contract
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$getPremiumCoefficients(
-  type = "gross",
-  coeffBenefits,
-  coeffCosts,
-  premiums,
-  params,
-  values,
-  premiumCalculationTime = values$int$premiumCalculationTime
-)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{type}}{The premium that is supposed to be calculated ("gross", "Zillmer", "net")}
-
-\item{\code{coeffBenefits}}{(empty) data structure of the benefit coefficients.
-The actual values have no meaning, this parameter is only used to
-derive the required dimensions}
-
-\item{\code{coeffCosts}}{(empty) data structure of the cost coefficients. The
-actual values have no meaning, this parameter is only used to
-derive the required dimensions}
-
-\item{\code{premiums}}{The premium components that have already been calculated
-(e.g. for net and Zillmer, the gross premium has already been
-calculated to allow modelling the premium refund)}
-
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (in the \code{contract$Values}
-list) then this method is called by the contract object}
-
-\item{\code{premiumCalculationTime}}{The time when the premiums should be
-(re-)calculated according to the equivalence principle. A time 0
-means the initial premium calculation at contract closing, later
-premium calculation times can be used to re-calculate the new
-premium after a contract change (possibly including an existing reserve)}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Not to be called directly, but implicitly by the \link{InsuranceContract} object.
-When \code{getPremiumCoefficients} is called, the \code{values$premiums}
-array has NOT yet been filled! Instead, all premiums already calculated
-(and required for the premium coefficients) are passed in the \code{premiums}
-argument.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-sumInsuredCalculation"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-sumInsuredCalculation}{}}}
-\subsection{Method \code{sumInsuredCalculation()}}{
-Calculate the sumInsured of the InsuranceContract given the
-parameters and premiums given and teh , present values already calculated and
-stored in the \code{params} and \code{values} lists.
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$sumInsuredCalculation(
-  params,
-  values,
-  calculationTime = values$int$premiumCalculationTime
-)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (in the \code{contract$Values}
-list) then this method is called by the contract object}
-
-\item{\code{calculationTime}}{the time when the sumInsured should be recalculated from the given premium}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Not to be called directly, but implicitly by the \link{InsuranceContract} object.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-premiumCalculation"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-premiumCalculation}{}}}
-\subsection{Method \code{premiumCalculation()}}{
-Calculate the premiums of the InsuranceContract given the
-parameters, present values and premium cofficients already calculated and
-stored in the \code{params} and \code{values} lists.
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$premiumCalculation(
-  params,
-  values,
-  premiumCalculationTime = values$int$premiumCalculationTime
-)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (in the \code{contract$Values}
-list) then this method is called by the contract object}
-
-\item{\code{premiumCalculationTime}}{The time when the premiums should be
-(re-)calculated according to the equivalence principle. A time 0
-means the initial premium calculation at contract closing, later
-premium calculation times can be used to re-calculate the new
-premium after a contract change (possibly including an existing reserve)}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Not to be called directly, but implicitly by the \link{InsuranceContract} object.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-reserveCalculation"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-reserveCalculation}{}}}
-\subsection{Method \code{reserveCalculation()}}{
-Calculate the reserves of the InsuranceContract given the
-parameters, present values and premiums already calculated and stored in
-the \code{params} and \code{values} lists.
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$reserveCalculation(params, values)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (in the \code{contract$Values}
-list) then this method is called by the contract object}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Not to be called directly, but implicitly by the \link{InsuranceContract} object.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-getBalanceSheetReserveFactor"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-getBalanceSheetReserveFactor}{}}}
-\subsection{Method \code{getBalanceSheetReserveFactor()}}{
-Calculate the (linear) interpolation factors for the balance
-sheet reserve (Dec. 31) between the yearly contract closing dates
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$getBalanceSheetReserveFactor(method, params, years = 1)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{method}}{The method for the balance sheet interpolation (30/360, act/act, act/360, act/365 or a function)}
-
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{years}}{how many years to calculate (for some usances, the factor
-is different in leap years!)}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Not to be called directly, but implicitly by the \link{InsuranceContract} object.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-reserveCalculationBalanceSheet"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-reserveCalculationBalanceSheet}{}}}
-\subsection{Method \code{reserveCalculationBalanceSheet()}}{
-Calculate the reserves for the balance sheets at Dec. 31 of each
-year by interpolation from the contract values calculated for
-the yearly reference date of the contract
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$reserveCalculationBalanceSheet(params, values)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (in the \code{contract$Values}
-list) then this method is called by the contract object}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Not to be called directly, but implicitly by the \link{InsuranceContract} object.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-calculateProfitParticipation"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-calculateProfitParticipation}{}}}
-\subsection{Method \code{calculateProfitParticipation()}}{
-Calculate the profit participation given the contract
-parameters and the already calculated reserves of the contract.
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$calculateProfitParticipation(params, ...)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{...}}{Additional parameters for the profit participation calculation, passed
-through to the profit participation scheme's \href{../../LifeInsuranceContracts/html/ProfitParticipation.html#method-getProfitParticipation}{\code{ProfitParticipation$getProfitParticipation()}}}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Not to be called directly, but implicitly by the \link{InsuranceContract} object.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-reservesAfterProfit"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-reservesAfterProfit}{}}}
-\subsection{Method \code{reservesAfterProfit()}}{
-Calculate the reserves after profit participation for the given profit scenario
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$reservesAfterProfit(profitScenario, params, values, ...)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{profitScenario}}{The ID of the profit scenario for which to calculate the reserves}
-
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (in the \code{contract$Values}
-list) then this method is called by the contract object}
-
-\item{\code{...}}{TODO}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Not to be called directly, but implicitly by the \link{InsuranceContract} object.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-getBasicDataTimeseries"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-getBasicDataTimeseries}{}}}
-\subsection{Method \code{getBasicDataTimeseries()}}{
-Return the time series of the basic contract
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$getBasicDataTimeseries(params, values)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (in the \code{contract$Values}
-list) then this method is called by the contract object}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Not to be called directly, but implicitly by the \link{InsuranceContract} object.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-premiumDecomposition"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-premiumDecomposition}{}}}
-\subsection{Method \code{premiumDecomposition()}}{
-Calculate the time series of the premium decomposition of the contract
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$premiumDecomposition(params, values)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (in the \code{contract$Values}
-list) then this method is called by the contract object}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Details}{
-Not to be called directly, but implicitly by the \link{InsuranceContract} object.
-All premiums, reserves and present values have already been calculated.
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-calculateFutureSums"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-calculateFutureSums}{}}}
-\subsection{Method \code{calculateFutureSums()}}{
-Generic function to calculate future sums of the values
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$calculateFutureSums(cf, ...)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{cf}}{The time series, for which future sums at all times are desired}
-
-\item{\code{...}}{currently unused}
-}
-\if{html}{\out{</div>}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-calculatePresentValues"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-calculatePresentValues}{}}}
-\subsection{Method \code{calculatePresentValues()}}{
-Calculate all present values for a given time series. The
-mortalities are taken from the contract's parameters.
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$calculatePresentValues(cf, params, values)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{cf}}{The time series, for which future present values at all
-times are desired}
-
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (in the \code{contract$Values}
-list) then this method is called by the contract object}
-
-\item{\code{...}}{currently unused}
-}
-\if{html}{\out{</div>}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-evaluateFrequencyLoading"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-evaluateFrequencyLoading}{}}}
-\subsection{Method \code{evaluateFrequencyLoading()}}{
-Calculate the premium frequency loading, i.e. the surcharge
-on the premium for those cases where the premium is not paid yearly.
-Return values can be either a numeric value or a named list with all
-possible premium frequencies as keys.
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$evaluateFrequencyLoading(loading, frequency, params, values)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{loading}}{The premiumFrequencyLoading parameter of the Contract or Tariff to be evaluated}
-
-\item{\code{frequency}}{The premiumFrequency parameter of the contract}
-
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (in the \code{contract$Values}
-list) then this method is called by the contract object}
-}
-\if{html}{\out{</div>}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-InsuranceTarif-clone"></a>}}
-\if{latex}{\out{\hypertarget{method-InsuranceTarif-clone}{}}}
-\subsection{Method \code{clone()}}{
-The objects of this class are cloneable with this method.
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{InsuranceTarif$clone(deep = FALSE)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{deep}}{Whether to make a deep clone.}
-}
-\if{html}{\out{</div>}}
-}
-}
-}
diff --git a/man/PVfactory.Rd b/man/PVfactory.Rd
deleted file mode 100644
index 8b0306caeb85535084ba52a71c1bfc1ebbf84a65..0000000000000000000000000000000000000000
--- a/man/PVfactory.Rd
+++ /dev/null
@@ -1,224 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/HelperFunctions.R
-\name{PVfactory}
-\alias{PVfactory}
-\title{PVfactory (R6Class for present values with arbitrary dimensions)}
-\description{
-PVfactory (R6Class for present values with arbitrary dimensions)
-
-PVfactory (R6Class for present values with arbitrary dimensions)
-}
-\details{
-provides functions to calculate present values for survival, death, dread
-disease, invalidity and guaranteed benefits in various dimensions
-}
-\section{Methods}{
-\subsection{Public methods}{
-\itemize{
-\item \href{#method-PVfactory-new}{\code{PVfactory$new()}}
-\item \href{#method-PVfactory-guaranteed}{\code{PVfactory$guaranteed()}}
-\item \href{#method-PVfactory-survival}{\code{PVfactory$survival()}}
-\item \href{#method-PVfactory-death}{\code{PVfactory$death()}}
-\item \href{#method-PVfactory-disease}{\code{PVfactory$disease()}}
-\item \href{#method-PVfactory-afterDeath}{\code{PVfactory$afterDeath()}}
-\item \href{#method-PVfactory-clone}{\code{PVfactory$clone()}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-PVfactory-new"></a>}}
-\if{latex}{\out{\hypertarget{method-PVfactory-new}{}}}
-\subsection{Method \code{new()}}{
-Initialize the present value factory with defaults for qx, interest and multiple payments per year
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{PVfactory$new(qx, m = 1, mCorrection = list(alpha = 1, beta = 0), v = 1)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{qx}}{the vector of mortality / death probabilities}
-
-\item{\code{m}}{the number of yearly payments}
-
-\item{\code{mCorrection}}{the list of alpha/beta to correct present values for multiple payments per year}
-
-\item{\code{v}}{the discount factor (1 / (1+i))}
-}
-\if{html}{\out{</div>}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-PVfactory-guaranteed"></a>}}
-\if{latex}{\out{\hypertarget{method-PVfactory-guaranteed}{}}}
-\subsection{Method \code{guaranteed()}}{
-Present values of guaranteed benefits (paid in advance or arrears, possible multiple times per year)
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{PVfactory$guaranteed(
-  advance = NULL,
-  arrears = NULL,
-  start = 0,
-  ...,
-  m = private$m,
-  mCorrection = private$mCorrection,
-  v = private$v
-)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{advance}}{the payment cashflows in advance}
-
-\item{\code{arrears}}{the payment cashflows in arrears}
-
-\item{\code{start}}{the time index, where the PV calculation should be based}
-
-\item{\code{...}}{other parameters (currently not used, for future use)}
-
-\item{\code{m}}{the number of yearly payments}
-
-\item{\code{mCorrection}}{the list of alpha/beta to correct present values for multiple payments per year}
-
-\item{\code{v}}{the discount factor (1 / (1+i))}
-}
-\if{html}{\out{</div>}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-PVfactory-survival"></a>}}
-\if{latex}{\out{\hypertarget{method-PVfactory-survival}{}}}
-\subsection{Method \code{survival()}}{
-Present values of survival benefits (paid in advance or arrears, possible multiple times per year)
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{PVfactory$survival(
-  advance = NULL,
-  arrears = NULL,
-  start = 0,
-  ...,
-  m = private$m,
-  mCorrection = private$mCorrection,
-  v = private$v
-)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{advance}}{the payment cashflows in advance}
-
-\item{\code{arrears}}{the payment cashflows in arrears}
-
-\item{\code{start}}{the time index, where the PV calculation should be based}
-
-\item{\code{...}}{other parameters (currently not used, for future use)}
-
-\item{\code{m}}{the number of yearly payments}
-
-\item{\code{mCorrection}}{the list of alpha/beta to correct present values for multiple payments per year}
-
-\item{\code{v}}{the discount factor (1 / (1+i))}
-}
-\if{html}{\out{</div>}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-PVfactory-death"></a>}}
-\if{latex}{\out{\hypertarget{method-PVfactory-death}{}}}
-\subsection{Method \code{death()}}{
-Present values of death benefits
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{PVfactory$death(benefits, start = 0, ..., v = private$v)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{benefits}}{the vector of death / invalidity / disease benefits}
-
-\item{\code{start}}{the time index, where the PV calculation should be based}
-
-\item{\code{...}}{other parameters (currently not used, for future use)}
-
-\item{\code{v}}{the discount factor (1 / (1+i))}
-}
-\if{html}{\out{</div>}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-PVfactory-disease"></a>}}
-\if{latex}{\out{\hypertarget{method-PVfactory-disease}{}}}
-\subsection{Method \code{disease()}}{
-Present values of disease benefits
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{PVfactory$disease(benefits, start = 0, ..., v = private$v)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{benefits}}{the vector of death / invalidity / disease benefits}
-
-\item{\code{start}}{the time index, where the PV calculation should be based}
-
-\item{\code{...}}{other parameters (currently not used, for future use)}
-
-\item{\code{v}}{the discount factor (1 / (1+i))}
-}
-\if{html}{\out{</div>}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-PVfactory-afterDeath"></a>}}
-\if{latex}{\out{\hypertarget{method-PVfactory-afterDeath}{}}}
-\subsection{Method \code{afterDeath()}}{
-Present values of guaranteed benefits after death (paid in advance or arrears, possible multiple times per year)
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{PVfactory$afterDeath(
-  advance = NULL,
-  arrears = NULL,
-  start = 0,
-  ...,
-  m = private$m,
-  mCorrection = private$mCorrection,
-  v = private$v
-)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{advance}}{the payment cashflows in advance}
-
-\item{\code{arrears}}{the payment cashflows in arrears}
-
-\item{\code{start}}{the time index, where the PV calculation should be based}
-
-\item{\code{...}}{other parameters (currently not used, for future use)}
-
-\item{\code{m}}{the number of yearly payments}
-
-\item{\code{mCorrection}}{the list of alpha/beta to correct present values for multiple payments per year}
-
-\item{\code{v}}{the discount factor (1 / (1+i))}
-}
-\if{html}{\out{</div>}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-PVfactory-clone"></a>}}
-\if{latex}{\out{\hypertarget{method-PVfactory-clone}{}}}
-\subsection{Method \code{clone()}}{
-The objects of this class are cloneable with this method.
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{PVfactory$clone(deep = FALSE)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{deep}}{Whether to make a deep clone.}
-}
-\if{html}{\out{</div>}}
-}
-}
-}
diff --git a/man/PaymentTimeSingleEnum-class.Rd b/man/PaymentTimeSingleEnum-class.Rd
deleted file mode 100644
index 9c2d66b39fa2bef96ce8554f9c118775ae36dbc5..0000000000000000000000000000000000000000
--- a/man/PaymentTimeSingleEnum-class.Rd
+++ /dev/null
@@ -1,17 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/HelperFunctions.R
-\docType{class}
-\name{PaymentTimeSingleEnum-class}
-\alias{PaymentTimeSingleEnum-class}
-\alias{PaymentTimeEnum}
-\title{Enum to describe when a benefit or premium payment is due (in advance or in arrears)}
-\description{
-Enum to describe when a benefit or premium payment is due (in advance or in arrears)
-}
-\details{
-Currently, only two values are allowed;
-\itemize{
-\item "in advance"
-\item "in arrears"
-}
-}
diff --git a/man/ProfitComponentsMultipleEnum-class.Rd b/man/ProfitComponentsMultipleEnum-class.Rd
deleted file mode 100644
index e0d0f521929d078326f12942d9f72d344c2a1e5f..0000000000000000000000000000000000000000
--- a/man/ProfitComponentsMultipleEnum-class.Rd
+++ /dev/null
@@ -1,37 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/HelperFunctions.R
-\docType{class}
-\name{ProfitComponentsMultipleEnum-class}
-\alias{ProfitComponentsMultipleEnum-class}
-\alias{ProfitComponentsEnum}
-\title{Enum to define the different components of profit participation.}
-\description{
-Enum to define the different components of profit participation.
-}
-\details{
-Profit participation schemes typically consist of different components,
-which are calculated independently. Typical components are interest profit
-to distribute investment gains to the customer, risk profit and expense profit
-to return security margins in the biometric risk and the expenses to the customer
-and sum profit, which aplies to contracts with higher sums insured, where
-charged expenses are calculated from the sum insured, while the actual
-expenses are more or less constant. Thus, high contracts are charged more,
-which causes profits that are returned as sum profit.
-
-As a special case, part of the profits can be stored in a terminal bonus
-reserve and only distributed on maturity (or potentially on death), but
-not on surrender. Some (older) profit participation schemes add an independently
-calculated bonus on maturity (e.g. twice the total profit assignment of the
-last year) at maturity to give customers an additional incentive not to
-surrender a contract.
-
-Possible values are (multiple can be given):
-\itemize{
-\item "interest"
-\item "risk"
-\item "expense"
-\item "sum"
-\item "terminal"
-\item "TBF"
-}
-}
diff --git a/man/ProfitParticipation.Rd b/man/ProfitParticipation.Rd
deleted file mode 100644
index 40edd9bd5951d7d6910138b8e1f7c34eb8d993f0..0000000000000000000000000000000000000000
--- a/man/ProfitParticipation.Rd
+++ /dev/null
@@ -1,371 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/ProfitParticipation.R
-\name{ProfitParticipation}
-\alias{ProfitParticipation}
-\title{Base Class for Profit Participation Schemes}
-\description{
-Base Class for Profit Participation Schemes
-
-Base Class for Profit Participation Schemes
-}
-\details{
-Base class for Profit Participation schemes  (holding contract-independent values and
-providing methods to calculate the profit participation values from the given
-reserves).
-
-The profit participation object is typically not used directly, but rather
-defined once and then passed on to an \link{InsuranceTarif} or \link{InsuranceContract}
-object, where it will be used internally when profit participation is
-calculated.
-
-This class provides the technical implementation of a profit plan for traditional
-life insurance contracts with a guaranteed component (calculated before the
-profit scheme comes into play) and a discretionary profit on top.
-
-This function is called when a new profit participation scheme
-is created with a call to \code{ProfitParticipation$new(...)}. Possible
-parameters to the \code{new}-Call are all parameters from the \code{ProfitParticipation} sublist of the
-\link{InsuranceContract.ParameterStructure} parameter
-structure (which are understood as template values that can be overridden
-per contract or even per profit participation scenario) and the components
-of the \code{Functions} field defining the functions to calculate the individual
-components of the profit participation (rates, calculation bases, calculation, benefits)
-
-This method \code{createModification} returns a copy of the profit scheme
-with all given arguments changed in the schmes's \code{Parameters}
-parameter list.
-
-As ProfitParticipation is a R6 class with reference logic, simply assigning
-the object to a new variable does not create a copy, but references the
-original profit scheme object. To create an actual copy, one needs to call this
-method, which first clones the whole object and then adjusts all parameters
-to the values passed to this method.
-
-The \link{InsuranceContract}'s param structure \link{InsuranceContract.ParameterStructure}
-contains the field \code{params$ProfitParticipation$advanceProfitParticipation},
-which can either be numeric rate for advance profit participation, or
-a function with signature \code{function(params, values, ...)} that
-returns the advance profit participation rate when called with the
-contract's parameters and the values calculated so far (cash flows and premiums)
-
-The \link{InsuranceContract}'s param structure \link{InsuranceContract.ParameterStructure}
-contains the field \code{params$ProfitParticipation$advanceProfitParticipationInclUnitCost},
-which can either be numeric rate for advance profit participation, or
-a function with signature \code{function(params, values, ...)} that
-returns the advance profit participation rate when called with the
-contract's parameters and the values calculated so far (cash flows and premiums)
-
-This function provides an easy way to modify the whole set of
-profit rates after their initial setup. Possible applications are waiting
-periods, which can be implemented once for all rates rather than inside
-each individual calculation period.
-}
-\section{Public fields}{
-\if{html}{\out{<div class="r6-fields">}}
-\describe{
-\item{\code{name}}{The human-readable name of the profit plan.}
-
-\item{\code{Parameters}}{Parameter template for profit-participation-specific
-parameters, i.e. the \code{ProfitParticipation} element of the
-\link{InsuranceContract.ParameterStructure} data structure.
-
-All elements defined in the profit scheme can be overriden per contract
-in the call to \code{[InsuranceContract]$new} or even in the explicit
-call to \ifelse{html}{\href{../../LifeInsuranceContracts/html/InsuranceContract.html#method-profitScenario}{\code{InsuranceContract$profitScenario()}}}{\code{InsuranceContract$profitScenario()()}}
-or \ifelse{html}{\href{../../LifeInsuranceContracts/html/InsuranceContract.html#method-addProfitScenario}{\code{InsuranceContract$addProfitScenario()}}}{\code{InsuranceContract$addProfitScenario()()}}.}
-
-\item{\code{Functions}}{list of functions defined to calculate the individual
-components. For each of the profit components
-\itemize{
-\item interest profit
-\item risk profit
-\item expense profit
-\item sum profit
-\item terminal bonus
-\item terminal bonus fund
-}
-a rate,  a profit base and a calculation function can be defined, by assigning one of the pre-defined
-\link{ProfitParticipationFunctions} or proving your own function with signature
-\code{function(rates, params, values, ...)}. Additionally, for each of the
-benefit types (survival, death, surrender, premium waiver) a function can
-be provided to calculate the benefit stemming from profit participation.}
-
-\item{\code{dummy}}{Dummy to allow commas in the previous method}
-}
-\if{html}{\out{</div>}}
-}
-\section{Methods}{
-\subsection{Public methods}{
-\itemize{
-\item \href{#method-ProfitParticipation-new}{\code{ProfitParticipation$new()}}
-\item \href{#method-ProfitParticipation-setParameters}{\code{ProfitParticipation$setParameters()}}
-\item \href{#method-ProfitParticipation-setFunctions}{\code{ProfitParticipation$setFunctions()}}
-\item \href{#method-ProfitParticipation-setFallbackParameters}{\code{ProfitParticipation$setFallbackParameters()}}
-\item \href{#method-ProfitParticipation-createModification}{\code{ProfitParticipation$createModification()}}
-\item \href{#method-ProfitParticipation-getAdvanceProfitParticipation}{\code{ProfitParticipation$getAdvanceProfitParticipation()}}
-\item \href{#method-ProfitParticipation-getAdvanceProfitParticipationAfterUnitCosts}{\code{ProfitParticipation$getAdvanceProfitParticipationAfterUnitCosts()}}
-\item \href{#method-ProfitParticipation-setupRates}{\code{ProfitParticipation$setupRates()}}
-\item \href{#method-ProfitParticipation-adjustRates}{\code{ProfitParticipation$adjustRates()}}
-\item \href{#method-ProfitParticipation-getProfitParticipation}{\code{ProfitParticipation$getProfitParticipation()}}
-\item \href{#method-ProfitParticipation-clone}{\code{ProfitParticipation$clone()}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-ProfitParticipation-new"></a>}}
-\if{latex}{\out{\hypertarget{method-ProfitParticipation-new}{}}}
-\subsection{Method \code{new()}}{
-Create a new profit participation scheme
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{ProfitParticipation$new(name = NULL, ...)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{name}}{The name of the profit scheme (typicall the name of the profit plan and its version)}
-
-\item{\code{...}}{profit participation parameters to be stored in the
-\verb{Parameters field or calculation functions to be stored in the }Functions`
-field}
-}
-\if{html}{\out{</div>}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-ProfitParticipation-setParameters"></a>}}
-\if{latex}{\out{\hypertarget{method-ProfitParticipation-setParameters}{}}}
-\subsection{Method \code{setParameters()}}{
-Store all passed parameters in the \code{Parameters} field
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{ProfitParticipation$setParameters(...)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{...}}{any of the named fields defined in the \code{ProfitParticipation} sublist of the
-\link{InsuranceContract.ParameterStructure}. All other arguments will be ignored}
-}
-\if{html}{\out{</div>}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-ProfitParticipation-setFunctions"></a>}}
-\if{latex}{\out{\hypertarget{method-ProfitParticipation-setFunctions}{}}}
-\subsection{Method \code{setFunctions()}}{
-Store all passed functions in the \code{Functions} field
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{ProfitParticipation$setFunctions(...)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{...}}{any of the functions defined in the \code{Functions} field. All other
-arguments will be ignored}
-}
-\if{html}{\out{</div>}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-ProfitParticipation-setFallbackParameters"></a>}}
-\if{latex}{\out{\hypertarget{method-ProfitParticipation-setFallbackParameters}{}}}
-\subsection{Method \code{setFallbackParameters()}}{
-Fill all missing parameters with the default fall-back values
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{ProfitParticipation$setFallbackParameters()}\if{html}{\out{</div>}}
-}
-
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-ProfitParticipation-createModification"></a>}}
-\if{latex}{\out{\hypertarget{method-ProfitParticipation-createModification}{}}}
-\subsection{Method \code{createModification()}}{
-create a copy of a profit scheme with certain parameters changed
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{ProfitParticipation$createModification(name = NULL, ...)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{name}}{The new name for the cloned \link{ProfitParticipation} object}
-
-\item{\code{...}}{Parameters for the \link{InsuranceContract.ParameterStructure},
-defining the characteristics of the tariff.}
-}
-\if{html}{\out{</div>}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-ProfitParticipation-getAdvanceProfitParticipation"></a>}}
-\if{latex}{\out{\hypertarget{method-ProfitParticipation-getAdvanceProfitParticipation}{}}}
-\subsection{Method \code{getAdvanceProfitParticipation()}}{
-Calculate and return the advance profit participation (to be
-applied on the actuarial gross premium)
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{ProfitParticipation$getAdvanceProfitParticipation(params, values, ...)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (guaranteed component of the
-insurance contract, including cash flows, premiums, reserves etc.).}
-
-\item{\code{...}}{optional parameters, to be passed to the advanceProfitParticipation
-field of the parameter structure (if that is a function)}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Returns}{
-Return either one numerical value (constant for the whole premium payment period)
-of a vector of numerical values for the whole contract period
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-ProfitParticipation-getAdvanceProfitParticipationAfterUnitCosts"></a>}}
-\if{latex}{\out{\hypertarget{method-ProfitParticipation-getAdvanceProfitParticipationAfterUnitCosts}{}}}
-\subsection{Method \code{getAdvanceProfitParticipationAfterUnitCosts()}}{
-Calculate and return the advance profit participation (to be
-applied after unit costs are added to the gross premium)
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{ProfitParticipation$getAdvanceProfitParticipationAfterUnitCosts(
-  params,
-  values,
-  ...
-)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (guaranteed component of the
-insurance contract, including cash flows, premiums, reserves etc.).}
-
-\item{\code{...}}{optional parameters, to be passed to the advanceProfitParticipationInclUnitCost
-field of the parameter structure (if that is a function)}
-}
-\if{html}{\out{</div>}}
-}
-\subsection{Returns}{
-Return either one numerical value (constant for the whole premium payment period)
-of a vector of numerical values for the whole contract period
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-ProfitParticipation-setupRates"></a>}}
-\if{latex}{\out{\hypertarget{method-ProfitParticipation-setupRates}{}}}
-\subsection{Method \code{setupRates()}}{
-Set up the data.frame containing the profit participation rates
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{ProfitParticipation$setupRates(params, values, ...)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (guaranteed component of the
-insurance contract, including cash flows, premiums, reserves etc.).}
-
-\item{\code{...}}{additional parameters passed to the profit calculation functions
-stored in the \code{Functions} field.}
-}
-\if{html}{\out{</div>}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-ProfitParticipation-adjustRates"></a>}}
-\if{latex}{\out{\hypertarget{method-ProfitParticipation-adjustRates}{}}}
-\subsection{Method \code{adjustRates()}}{
-Adjust the data.frame of profit participation rates after their setup
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{ProfitParticipation$adjustRates(rates, params, values)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{rates}}{data.frame of profit paticipation rates}
-
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (guaranteed component of the
-insurance contract, including cash flows, premiums, reserves etc.).}
-}
-\if{html}{\out{</div>}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-ProfitParticipation-getProfitParticipation"></a>}}
-\if{latex}{\out{\hypertarget{method-ProfitParticipation-getProfitParticipation}{}}}
-\subsection{Method \code{getProfitParticipation()}}{
-Calculation the full time series of profit participation for
-the given contract values
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{ProfitParticipation$getProfitParticipation(
-  calculateFrom = 0,
-  profitScenario = NULL,
-  params,
-  values,
-  ...
-)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{calculateFrom}}{The time from which to start calculating the profit
-participation. When a contract is changed at some time t (possibly even
-changing the profit scheme), all future profit participation needs to be
-re-calculated from that time on, without changing past profit participation.
-All values before \code{calculateFrom} will not be calculated.}
-
-\item{\code{profitScenario}}{profit participation values from a previous calculation
-(NULL if profit calculation is to be calculated from the contract inception).
-Values before \code{calculateFrom} will be used from this data.frame.}
-
-\item{\code{params}}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{\code{values}}{Contract values calculated so far (guaranteed component of the
-insurance contract, including cash flows, premiums, reserves etc.).}
-
-\item{\code{...}}{additional parameters to be passed to \href{../../LifeInsuranceContracts/html/ProfitParticipation.html#method-setupRates}{\code{ProfitParticipation$setupRates()}}}
-}
-\if{html}{\out{</div>}}
-}
-}
-\if{html}{\out{<hr>}}
-\if{html}{\out{<a id="method-ProfitParticipation-clone"></a>}}
-\if{latex}{\out{\hypertarget{method-ProfitParticipation-clone}{}}}
-\subsection{Method \code{clone()}}{
-The objects of this class are cloneable with this method.
-\subsection{Usage}{
-\if{html}{\out{<div class="r">}}\preformatted{ProfitParticipation$clone(deep = FALSE)}\if{html}{\out{</div>}}
-}
-
-\subsection{Arguments}{
-\if{html}{\out{<div class="arguments">}}
-\describe{
-\item{\code{deep}}{Whether to make a deep clone.}
-}
-\if{html}{\out{</div>}}
-}
-}
-}
diff --git a/man/ProfitParticipationFunctions.Rd b/man/ProfitParticipationFunctions.Rd
deleted file mode 100644
index c1d6db13d4946b2997d740f6130114cff7641884..0000000000000000000000000000000000000000
--- a/man/ProfitParticipationFunctions.Rd
+++ /dev/null
@@ -1,270 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/ProfitParticipation_Functions.R
-\name{ProfitParticipationFunctions}
-\alias{ProfitParticipationFunctions}
-\alias{PP.base.NULL}
-\alias{PP.base.PreviousZillmerReserve}
-\alias{PP.base.ZillmerReserveT2}
-\alias{PP.base.contractualReserve}
-\alias{PP.base.previousContractualReserve}
-\alias{PP.base.meanContractualReserve}
-\alias{PP.base.ZillmerRiskPremium}
-\alias{PP.base.sumInsured}
-\alias{PP.base.totalProfitAssignment}
-\alias{PP.rate.interestProfit}
-\alias{PP.rate.riskProfit}
-\alias{PP.rate.expenseProfit}
-\alias{PP.rate.sumProfit}
-\alias{PP.rate.terminalBonus}
-\alias{PP.rate.terminalBonusFund}
-\alias{PP.rate.interestProfitPlusGuarantee}
-\alias{PP.rate.interestProfit2PlusGuarantee}
-\alias{PP.rate.totalInterest}
-\alias{PP.rate.totalInterest2}
-\alias{PP.rate.interestProfit2}
-\alias{getTerminalBonusReserve}
-\alias{PP.calculate.RateOnBase}
-\alias{PP.calculate.RateOnBaseMin0}
-\alias{PP.calculate.RatePlusGuaranteeOnBase}
-\alias{PP.calculate.RateOnBaseSGFFactor}
-\alias{sumProfits}
-\alias{PP.benefit.ProfitPlusTerminalBonusReserve}
-\alias{PP.benefit.Profit}
-\alias{PP.benefit.ProfitPlusGuaranteedInterest}
-\alias{PP.benefit.ProfitPlusTotalInterest}
-\alias{PP.benefit.ProfitPlusHalfTotalInterest}
-\alias{PP.benefit.ProfitPlusHalfGuaranteedInterest}
-\alias{PP.benefit.ProfitPlusInterestMinGuaranteeTotal}
-\alias{PP.benefit.ProfitPlusHalfInterestMinGuaranteeTotal}
-\alias{PP.benefit.ProfitGuaranteeSupporting}
-\alias{PP.benefit.TerminalBonus5YearsProRata}
-\alias{PP.benefit.TerminalBonus5Years}
-\alias{PP.benefit.TerminalBonus}
-\alias{PP.benefit.None}
-\title{Helper functions for profit participation}
-\usage{
-PP.base.NULL(rates, params, values, ...)
-
-PP.base.PreviousZillmerReserve(rates, params, values, ...)
-
-PP.base.ZillmerReserveT2(rates, params, values, ...)
-
-PP.base.contractualReserve(rates, params, values, ...)
-
-PP.base.previousContractualReserve(rates, params, values, ...)
-
-PP.base.meanContractualReserve(rates, params, values, ...)
-
-PP.base.ZillmerRiskPremium(rates, params, values, ...)
-
-PP.base.sumInsured(rates, params, values, ...)
-
-PP.base.totalProfitAssignment(res, ...)
-
-PP.rate.interestProfit(rates, ...)
-
-PP.rate.riskProfit(rates, ...)
-
-PP.rate.expenseProfit(rates, ...)
-
-PP.rate.sumProfit(rates, ...)
-
-PP.rate.terminalBonus(rates, ...)
-
-PP.rate.terminalBonusFund(rates, ...)
-
-PP.rate.interestProfitPlusGuarantee(rates, ...)
-
-PP.rate.interestProfit2PlusGuarantee(rates, ...)
-
-PP.rate.totalInterest(rates, ...)
-
-PP.rate.totalInterest2(rates, ...)
-
-PP.rate.interestProfit2(rates, ...)
-
-getTerminalBonusReserve(
-  profits,
-  rates,
-  terminalBonus,
-  terminalBonusAccount,
-  params,
-  values,
-  ...
-)
-
-PP.calculate.RateOnBase(base, rate, waiting, rates, params, values, ...)
-
-PP.calculate.RateOnBaseMin0(base, rate, waiting, rates, params, values, ...)
-
-PP.calculate.RatePlusGuaranteeOnBase(
-  base,
-  rate,
-  waiting,
-  rates,
-  params,
-  values,
-  ...
-)
-
-PP.calculate.RateOnBaseSGFFactor(
-  base,
-  rate,
-  waiting,
-  rates,
-  params,
-  values,
-  ...
-)
-
-sumProfits(profits, cols)
-
-PP.benefit.ProfitPlusTerminalBonusReserve(profits, ...)
-
-PP.benefit.Profit(profits, ...)
-
-PP.benefit.ProfitPlusGuaranteedInterest(profits, rates, ...)
-
-PP.benefit.ProfitPlusTotalInterest(profits, rates, params, values)
-
-PP.benefit.ProfitPlusHalfTotalInterest(profits, ...)
-
-PP.benefit.ProfitPlusHalfGuaranteedInterest(profits, rates, ...)
-
-PP.benefit.ProfitPlusInterestMinGuaranteeTotal(profits, rates, ...)
-
-PP.benefit.ProfitPlusHalfInterestMinGuaranteeTotal(profits, rates, ...)
-
-PP.benefit.ProfitGuaranteeSupporting(profits, rates, params, values, ...)
-
-PP.benefit.TerminalBonus5YearsProRata(profits, params, ...)
-
-PP.benefit.TerminalBonus5Years(profits, params, ...)
-
-PP.benefit.TerminalBonus(profits, params, ...)
-
-PP.benefit.None(profits, ...)
-}
-\arguments{
-\item{rates}{data.frame of profit rates}
-
-\item{params}{Contract-specific, full set of parameters of the contract
-(merged parameters of the defaults, the tariff, the profit participation
-scheme and the contract)}
-
-\item{values}{Contract values calculated so far (guaranteed component of the
-insurance contract, including cash flows, premiums, reserves etc.).}
-
-\item{...}{Other values that might be used for the calculation (currently unused)}
-
-\item{res}{the data.frame of reserves.}
-
-\item{profits}{The array of profit participation component values}
-
-\item{terminalBonus}{The terminal bonus calculated}
-
-\item{terminalBonusAccount}{The terminal bonus account (like a bank account,
-where terminal bonuses are accrued, potentiall discounted from the maturity)}
-
-\item{base}{The profit calculation base, on which the rate is to be applied}
-
-\item{rate}{The profit participation rate}
-
-\item{waiting}{A possible waiting period}
-
-\item{cols}{The columns of the profit values array to be summed (columns given that do not exist in the profits array are ignired)}
-}
-\description{
-Various helper functions for the \code{ProfitParticipation} class that
-provide the building blocks for the individual components of profit participation,
-the rates and how the assigned profit is calculated.
-}
-\section{Functions}{
-\itemize{
-\item \code{PP.base.NULL()}: Basis for profit: NONE (i.e. always returns 0)
-
-\item \code{PP.base.PreviousZillmerReserve()}: Basis for profit: Previous Zillmer reserve (no administration cost reserve)
-
-\item \code{PP.base.ZillmerReserveT2()}: Basis for profit: Zillmer reserve (no administration cost reserve) at time t-2
-
-\item \code{PP.base.contractualReserve()}: Basis for profit: Contractual reserve (including administration costs) at time t
-
-\item \code{PP.base.previousContractualReserve()}: Basis for profit: Contractual reserve (including administration costs) at time t-1
-
-\item \code{PP.base.meanContractualReserve()}: Basis for profit: Contractual reserve (including administration costs) averaged over t and t-1
-
-\item \code{PP.base.ZillmerRiskPremium()}: Basis for risk/mortality profit: Zillmer Risk Premium of the past year
-
-\item \code{PP.base.sumInsured()}: Basis for expense/sum profit: sum insured
-
-\item \code{PP.base.totalProfitAssignment()}: Basis for Terminal Bonus Fund Assignment: total profit assignment of the year
-
-\item \code{PP.rate.interestProfit()}: Returns the array of interest profit rates (keyed by year)
-
-\item \code{PP.rate.riskProfit()}: Returns the array of risk profit rates (keyed by year)
-
-\item \code{PP.rate.expenseProfit()}: Returns the array of expense profit rates (keyed by year)
-
-\item \code{PP.rate.sumProfit()}: Returns the array of sum profit rates (keyed by year)
-
-\item \code{PP.rate.terminalBonus()}: Returns the array of terminal bonus rates (keyed by year)
-
-\item \code{PP.rate.terminalBonusFund()}: Returns the array of terminal bonus rates (keyed by year) as the terminal bonus fund ratio
-
-\item \code{PP.rate.interestProfitPlusGuarantee()}: Rate for interest on past profits: total credited rate, but at least the guarantee
-
-\item \code{PP.rate.interestProfit2PlusGuarantee()}: Rate for interest on past profits: total creditedrate2, but at least the guarantee
-
-\item \code{PP.rate.totalInterest()}: Rate for interest on past profits: total interest rate
-
-\item \code{PP.rate.totalInterest2()}: Rate for interest on past profits: second total interest rate
-
-\item \code{PP.rate.interestProfit2()}: Rate for interest on past profits: second interest profit rate (not including guaranteed interest), keyed by year
-
-\item \code{getTerminalBonusReserve()}: Calculate the terminal bonus reserve.
-
-\item \code{PP.calculate.RateOnBase()}: Calculate profit by a simple rate applied on the basis (with an optional waiting vector of values 0 or 1)
-
-\item \code{PP.calculate.RateOnBaseMin0()}: Calculate profit by a simple rate applied on the basis (with an optional waiting vector of values 0 or 1), bound below by 0
-
-\item \code{PP.calculate.RatePlusGuaranteeOnBase()}: Calculate profit by a rate + guaranteed interest applied on the basis (with an optional waiting vector of values 0 or 1)
-
-\item \code{PP.calculate.RateOnBaseSGFFactor()}: Calculate profit by a simple rate applied on the basis (with only (1-SGFFactor) put into profit participation, and an optional waiting vector of values 0 or 1)
-
-\item \code{sumProfits()}: Extract the given columns of the profit participation array of values and sum
-them up. Columns that do not exist, because the profit scheme does not
-provide the corresponding profit component will be silently ignored.
-This allows generic benefit calculation functions to be written that do
-not need to distinguish e.g. whether an old-style terminal bonus or a terminal
-bonus fund is provided.
-
-This function is not meant to be called directly, but within a profit benefit
-calculation function.
-
-\item \code{PP.benefit.ProfitPlusTerminalBonusReserve()}: Calculate survival benefit as total profit amount plus the terminal bonus reserve
-
-\item \code{PP.benefit.Profit()}: Calculate benefit as total profit accrued so far
-
-\item \code{PP.benefit.ProfitPlusGuaranteedInterest()}: Calculate accrued death benefit as total profit with (guaranteed) interest for one year
-
-\item \code{PP.benefit.ProfitPlusTotalInterest()}: Calculate accrued death benefit as total profit with total interest (interest on profit rate) for one year
-
-\item \code{PP.benefit.ProfitPlusHalfTotalInterest()}: Calculate accrued benefit as total profit with total interest (interest on profit rate) for half a year
-
-\item \code{PP.benefit.ProfitPlusHalfGuaranteedInterest()}: Calculate death benefit as total profit with (guaranteed) interest for one year
-
-\item \code{PP.benefit.ProfitPlusInterestMinGuaranteeTotal()}: Calculate accrued benefit as total profit with interest for one year (max of guarantee and total interest)
-
-\item \code{PP.benefit.ProfitPlusHalfInterestMinGuaranteeTotal()}: Calculate accrued benefit as total profit with interest for half a year (max of guarantee and total interest)
-
-\item \code{PP.benefit.ProfitGuaranteeSupporting()}: Calculate accrued benefit as regular profit, but used to cover initial Zillmerization
-
-\item \code{PP.benefit.TerminalBonus5YearsProRata()}: Calculate benefit from terminal bonus as 1/n parts of the terminal bonus reserve during the last 5 years
-
-\item \code{PP.benefit.TerminalBonus5Years()}: Terminal bonus is only paid out during the last 5 years of the contract (but never during the first 10 years)
-
-\item \code{PP.benefit.TerminalBonus()}: Calculate benefit from terminal bonus (full bonus), either old-style terminal bonus reserve or Terminal Bonus Fund (TBF)
-
-\item \code{PP.benefit.None()}: No benefit paid out
-
-}}
diff --git a/man/SexSingleEnum-class.Rd b/man/SexSingleEnum-class.Rd
deleted file mode 100644
index 8d28e94c8d841d3c0058ae95ab6617dc30c18bfa..0000000000000000000000000000000000000000
--- a/man/SexSingleEnum-class.Rd
+++ /dev/null
@@ -1,18 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/HelperFunctions.R
-\docType{class}
-\name{SexSingleEnum-class}
-\alias{SexSingleEnum-class}
-\alias{SexEnum}
-\title{Enum to describe possible sexes in an insurance contract or tariff.}
-\description{
-Enum to describe possible sexes in an insurance contract or tariff.
-}
-\details{
-Currently, the only possible values are:
-\itemize{
-\item "unisex"
-\item "male"
-\item "female"
-}
-}
diff --git a/man/TariffTypeSingleEnum-class.Rd b/man/TariffTypeSingleEnum-class.Rd
deleted file mode 100644
index 36a4539c09991d65c184f590554dfba9ca187e3c..0000000000000000000000000000000000000000
--- a/man/TariffTypeSingleEnum-class.Rd
+++ /dev/null
@@ -1,32 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/InsuranceTarif.R
-\docType{class}
-\name{TariffTypeSingleEnum-class}
-\alias{TariffTypeSingleEnum-class}
-\alias{TariffTypeEnum}
-\title{An enum specifying the main characteristics of the tarif.}
-\description{
-Possible values are:
-\describe{
-\item{annuity}{Whole life or term annuity (periodic survival benefits)
-with flexible payouts (constand, increasing, decreasing, arbitrary,
-etc.)}
-\item{wholelife}{A whole or term life insurance with only death benefits.
-The benefit can be constant, increasing, decreasing, described by
-a function, etc.}
-\item{endowment}{An  endowment with death and survival benefits,
-potentially with different benefits.}
-\item{pureendowment}{A pure endowment with only a survival benefit at
-the end of the contract. Optionally, in case of death, all or part
-of the premiums paid may be refunded.}
-\item{terme-fix}{A terme-fix insurance with a fixed payout at the end
-of the contract, even if the insured dies before that time.
-Premiums are paid until death of the insured.}
-\item{dread-disease}{A dread-disease insurance, which pays in case of
-a severe illness (typically heart attacks, cancer, strokes, etc.),
-but not in case of death.}
-\item{endowment + dread-disease}{A combination of an endowment and a
-temporary dread-disease insurance. Benefits occur either on death,
-severe illness or survival, whichever comes first.}
-}
-}
diff --git a/man/age.exactRounded.Rd b/man/age.exactRounded.Rd
deleted file mode 100644
index 71ae22f31416cc8ff7db132101bd9fc38b2f7524..0000000000000000000000000000000000000000
--- a/man/age.exactRounded.Rd
+++ /dev/null
@@ -1,18 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/HelperFunctions.R
-\name{age.exactRounded}
-\alias{age.exactRounded}
-\title{Calculate the age of the insured based on exact age at contract closing, rounded
-to the nearest birthday.}
-\usage{
-age.exactRounded(params, values)
-}
-\arguments{
-\item{params}{The parameters of the contract.}
-
-\item{values}{Unused by default (already calculated values of the contract)}
-}
-\description{
-Calculate the age of the insured based on exact age at contract closing, rounded
-to the nearest birthday.
-}
diff --git a/man/age.yearDifference.Rd b/man/age.yearDifference.Rd
deleted file mode 100644
index b972916c306f66b0347e650b19202110b394ee27..0000000000000000000000000000000000000000
--- a/man/age.yearDifference.Rd
+++ /dev/null
@@ -1,18 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/HelperFunctions.R
-\name{age.yearDifference}
-\alias{age.yearDifference}
-\title{Calculate the age of the insured based on the difference of the bith year and
-contract closing year.}
-\usage{
-age.yearDifference(params, values)
-}
-\arguments{
-\item{params}{The parameters of the contract.}
-
-\item{values}{Unused by default (already calculated values of the contract)}
-}
-\description{
-Calculate the age of the insured based on the difference of the bith year and
-contract closing year.
-}
diff --git a/man/applyHook.Rd b/man/applyHook.Rd
deleted file mode 100644
index e1e336d0ee8e0bddb6153f5256402fa622ff14a9..0000000000000000000000000000000000000000
--- a/man/applyHook.Rd
+++ /dev/null
@@ -1,23 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/HelperFunctions.R
-\name{applyHook}
-\alias{applyHook}
-\title{If \code{hook} is a function, apply it to \code{val}, otherwise return \code{val} unchanged}
-\usage{
-applyHook(hook, val, ...)
-}
-\arguments{
-\item{hook}{(optional) function to apply to \code{val} and the other parameters}
-
-\item{val}{The value to which the hook is applied (ifgiven)}
-
-\item{...}{optional parameters passed to the hook function (if it is a function)}
-}
-\description{
-If \code{hook} is a function, apply it to \code{val}, otherwise return \code{val} unchanged
-}
-\examples{
-applyHook(NULL, 3) # returns 3 unchanged
-applyHook(function(x) 2*x, 3) # applies the function, returns 6
-applyHook(`+`, 3, 1) # returns 4
-}
diff --git a/man/contractGrid.Rd b/man/contractGrid.Rd
deleted file mode 100644
index 43967b72d651028e581dcb3d38c787439645a1a6..0000000000000000000000000000000000000000
--- a/man/contractGrid.Rd
+++ /dev/null
@@ -1,80 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/contractGrid.R
-\name{contractGrid}
-\alias{contractGrid}
-\alias{contractGridPremium}
-\title{Create a grid of InsuranceContract objects or premiums with each axis representing one varying parameter}
-\usage{
-contractGrid(
-  axes = list(age = seq(20, 60, 10), policyPeriod = seq(5, 35, 5)),
-  YOB = NULL,
-  observationYear = NULL,
-  ...
-)
-
-contractGridPremium(
-  contractGrid = NULL,
-  premium = "written",
-  .fun = function(cntr) {
-     cntr$Values$premiums[[premium]]
- },
-  ...
-)
-}
-\arguments{
-\item{axes}{List of paramters spanning the dimensions of the grid.}
-
-\item{YOB}{optional year of bith. If missing, the \code{observationYear} and the contract's age}
-
-\item{observationYear}{The observation year, for which the grid shall be calculated. If given, the YOB is calculated from it, otherwise the contract's YOB is used}
-
-\item{...}{In \code{contractGrid}: Additional parameters to be passed to \ifelse{html}{\href{../../LifeInsuranceContracts/html/InsuranceContract.html#method-new}{\code{InsuranceContract$new()}}}{\code{InsuranceContract$new()()}}; In \code{contractGridPremium}: Additional parameters to be passed to \code{contractGrid}.}
-
-\item{contractGrid}{(optional) existing contract grid from which to derive
-premiums. If not given, \link{contractGrid} is called with all parameters, so
-\code{...} should contain an \code{axes} argument in that case.}
-
-\item{premium}{The type of premium to derive (key of the \code{contract$Values$premiums} list.}
-
-\item{.fun}{The function to extract the desired premium from a contract
-object. By default it accesses the premium vector and extracts the
-type of premium given in the \code{premium} parameter. One can,
-however pass any other extractor function to access e.g. reserves,
-cash flows etc. at any desired time.}
-}
-\description{
-The function \code{contractGrid} creates a (two- or multi-dimensional) grid
-of InsuranceContract objects, where each axis represents one of the insurance
-parameters varying as given in the \code{axes} argument (as a named list).
-
-The function \code{contractGridPremium} returns a grid of premiums as requested in
-the \code{premium} parameter rather than the full InsuranceContract objects.
-It is a convenience wrapper around \code{contractGrid} and is recommended if
-one is only interested in a grid of one particular value (typically some
-kind of premium).
-The function \code{contractGridPremium} can also be used on an existing
-\code{contractGrid}-generated grid of contracts to extract grid of numerical
-values of the specified premiums. If no contract grid is passed to
-\code{contractGridPremium}, \code{contractGrid} will be called to create it.
-}
-\details{
-The function \code{contractGrid} will return the full \link{InsuranceContract}
-objects, so apply can later be used to extract premiums, reserves and other
-values to display in a grid. For this feature, one can also use the convenience
-function \code{contractGridPremium}.
-
-The \code{axes} list describing the parameters changing along the axes of the
-resulting grid is internally expanded with \code{\link[=expand.grid]{expand.grid()}}. The resulting flat
-list of parameter (together with the fixed parameters passed as \code{...})
-is then passed to the \ifelse{html}{\href{../../LifeInsuranceContracts/html/InsuranceContract.html#method-new}{\code{InsuranceContract$new()}}}{\code{InsuranceContract$new()()}} call to create the corresponding
-contract object.
-
-To create the human-readable row-/columnnames of the resulting array,
-the function \code{\link[=makeContractGridDimname]{makeContractGridDimname()}} for each value of the axes, allowing
-human-readable representations e.g. of a tariff or a mortality table as
-the dimension label.
-}
-\examples{
-# TODO
-
-}
diff --git a/man/costValuesAsDF.Rd b/man/costValuesAsDF.Rd
deleted file mode 100644
index babe964cea3390e2bebfec26e9aba4ba976c246a..0000000000000000000000000000000000000000
--- a/man/costValuesAsDF.Rd
+++ /dev/null
@@ -1,19 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/exportInsuranceContract_xlsx.R
-\name{costValuesAsDF}
-\alias{costValuesAsDF}
-\title{Convert the multi-dimensional costs array to a data.frame for output to a file}
-\usage{
-costValuesAsDF(costValues)
-}
-\arguments{
-\item{costValues}{Cost definition data structure}
-}
-\description{
-Convert the cost values array to a tx15 matrix
-}
-\details{
-Not to be called directly, but implicitly by the \link{InsuranceContract} object.
-Convert the array containing cost values like cashflows, present
-values, etc. (objects of dimension tx5x3) to a matrix with dimensions (tx15)
-}
diff --git a/man/costs.baseAlpha.Rd b/man/costs.baseAlpha.Rd
deleted file mode 100644
index 63cca08a9df78b88be1792bfd1e2cf157777f3a8..0000000000000000000000000000000000000000
--- a/man/costs.baseAlpha.Rd
+++ /dev/null
@@ -1,19 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/InsuranceParameters.R
-\name{costs.baseAlpha}
-\alias{costs.baseAlpha}
-\title{Helper function to define base costs with base alpha, but otherwise unchanged costs}
-\usage{
-costs.baseAlpha(alpha)
-}
-\arguments{
-\item{alpha}{The minimum alpha / Zillmer cost that cannot be waived}
-}
-\description{
-Returns a function that sets base alpha (and Zillmer) costs to the given value,
-but otherwise uses the full costs defined by the Costs parameter.
-}
-\details{
-This function can be set as minCosts parameter for a tariff and makes sure
-that only alpha costs are modified / waived, but no other costs.
-}
diff --git a/man/costs.scaleAlpha.Rd b/man/costs.scaleAlpha.Rd
deleted file mode 100644
index 36e3ff21745a93c132b4b7e361804fc86d955864..0000000000000000000000000000000000000000
--- a/man/costs.scaleAlpha.Rd
+++ /dev/null
@@ -1,20 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/InsuranceParameters.R
-\name{costs.scaleAlpha}
-\alias{costs.scaleAlpha}
-\title{Helper function to modify alpha costs of an insurance contract individually}
-\usage{
-costs.scaleAlpha(scale)
-}
-\arguments{
-\item{scale}{The scale for  alpha / Zillmer cost}
-}
-\description{
-Returns a function that modifies alpha (and Zillmer) costs by the given scale,
-but otherwise uses the full costs defined by the Costs parameter.
-}
-\details{
-This function can be set as adjustCosts or adjustMinCosts hook parameters
-for a tariff or contract and can be used to apply cost adjustments on a
-per-contract basis.
-}
diff --git a/man/costsDisplayTable.Rd b/man/costsDisplayTable.Rd
deleted file mode 100644
index 684111ca4d656de06a52e8ea41cbaf1e0b0e88cb..0000000000000000000000000000000000000000
--- a/man/costsDisplayTable.Rd
+++ /dev/null
@@ -1,14 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/InsuranceParameters.R
-\name{costsDisplayTable}
-\alias{costsDisplayTable}
-\title{Helper function to display all cost definitions in a concise table}
-\usage{
-costsDisplayTable(costs)
-}
-\arguments{
-\item{costs}{The cost structure to be displayed in a concise table style.}
-}
-\description{
-Returns a data.frame with columns
-}
diff --git a/man/deathBenefit.annuityDecreasing.Rd b/man/deathBenefit.annuityDecreasing.Rd
deleted file mode 100644
index 8eb7ac1b9e66ba91107409c88380272118fd9ab2..0000000000000000000000000000000000000000
--- a/man/deathBenefit.annuityDecreasing.Rd
+++ /dev/null
@@ -1,31 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/HelperFunctions.R
-\name{deathBenefit.annuityDecreasing}
-\alias{deathBenefit.annuityDecreasing}
-\title{Describes the death benefit of a decreasing whole life insurance (after a possible deferall period)}
-\usage{
-deathBenefit.annuityDecreasing(interest)
-}
-\arguments{
-\item{interest}{The interest rate of the loan, which is underlying the insurance.}
-}
-\description{
-The death benefit will be the full sumInsured for the first year after the
-deferral period and then decrease like an annuity to 0 at the end of the policyPeriod.
-This can be used with the \code{deathBenefit} parameter for insurance
-contracts, but should not be called directly.
-}
-\details{
-This function is a mere generator function, which takes the interest rate and
-generates a function that describes a decreasing annuity.
-
-The generated function has the following parameters:
-\describe{
-\item{len}{The desired length of the Cash flow vector (can be shorter than
-the policyPeriod, if q_x=1 before the end of the contract, e.g.
-for life-long insurances)}
-\item{params}{The full parameter set of the insurance contract (including
-all inherited values from the tariff and the profit participation)}
-\item{values}{The values calculated from the insurance contract so far}
-}
-}
diff --git a/man/deathBenefit.linearDecreasing.Rd b/man/deathBenefit.linearDecreasing.Rd
deleted file mode 100644
index b4f84ee64f35d21a2a9801f0b508a47a457036a2..0000000000000000000000000000000000000000
--- a/man/deathBenefit.linearDecreasing.Rd
+++ /dev/null
@@ -1,24 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/HelperFunctions.R
-\name{deathBenefit.linearDecreasing}
-\alias{deathBenefit.linearDecreasing}
-\title{Describes the death benefit of a linearly decreasing whole life insurance (after a possible deferall period)}
-\usage{
-deathBenefit.linearDecreasing(len, params, values)
-}
-\arguments{
-\item{len}{The desired length of the Cash flow vector (can be shorter than
-the policyPeriod, if q_x=1 before the end of the contract, e.g.
-for life-long insurances)}
-
-\item{params}{The full parameter set of the insurance contract (including
-all inherited values from the tariff and the profit participation)}
-
-\item{values}{The values calculated from the insurance contract so far}
-}
-\description{
-The death benefit will be the full sumInsured for the first year after the
-deferral period and then decrease linearly to 0 at the end of the policyPeriod.
-This can be used with the \code{deathBenefit} parameter for insurance
-contracts, but should not be called directly.
-}
diff --git a/man/exportInsuranceContract.xlsx.Rd b/man/exportInsuranceContract.xlsx.Rd
deleted file mode 100644
index 7dad96fab80a227d308ca45719f8e08da566de23..0000000000000000000000000000000000000000
--- a/man/exportInsuranceContract.xlsx.Rd
+++ /dev/null
@@ -1,41 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/exportInsuranceContract_xlsx.R
-\name{exportInsuranceContract.xlsx}
-\alias{exportInsuranceContract.xlsx}
-\title{Export an insurance act object tocontract (object of class \link{InsuranceContract}) to an Excel file}
-\usage{
-exportInsuranceContract.xlsx(contract, filename)
-}
-\arguments{
-\item{contract}{The insurance contract to export}
-
-\item{filename}{Target Excel filename for export}
-}
-\description{
-Export an insurance act object tocontract (object of class \link{InsuranceContract}) to an Excel file
-}
-\details{
-The function \code{exportInsuranceContract.xlsx} exports an object
-of class \link{InsuranceContract} to an Excel file. All basic data, as well as
-the time series of (absolute and unit) cash flows, reserves, premiums, premium
-composition and all profit participation scenarios are exported to the file
-in nicely looking tables.
-
-No new calculations are done in this function. It only prints out the values
-stored in \code{contract$Values}.
-}
-\examples{
-library("MortalityTables")
-mortalityTables.load("Austria_Annuities_AVOe2005R")
-# A trivial deferred annuity tariff with no costs:
-tariff = InsuranceTarif$new(name = "Test Annuity", type = "annuity", tarif = "Annuity 1A",
-    mortalityTable = AVOe2005R.unisex, i=0.01)
-contract = InsuranceContract$new(
-    tariff,
-    age = 35, YOB = 1981,
-    policyPeriod = 30, premiumPeriod = 15, deferralPeriod = 15,
-    sumInsured = 1000,
-    contractClosing = as.Date("2016-10-01")
-);
-\dontrun{exportInsuranceContract.xlsx(contract, "Example_annuity_contract.xlsx")}
-}
diff --git a/man/exportInsuranceContractExample.Rd b/man/exportInsuranceContractExample.Rd
deleted file mode 100644
index f8a59beabfbcd605529f357aed2b228b90d605a8..0000000000000000000000000000000000000000
--- a/man/exportInsuranceContractExample.Rd
+++ /dev/null
@@ -1,65 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/exportInsuranceContractExample.R
-\name{exportInsuranceContractExample}
-\alias{exportInsuranceContractExample}
-\title{Export the example calculations of an insurance contract}
-\usage{
-exportInsuranceContractExample(
-  contract,
-  prf = 10,
-  outdir = ".",
-  basename = NULL,
-  extraname = NULL,
-  ...
-)
-}
-\arguments{
-\item{contract}{The \code{\link{InsuranceContract}} object to be exported}
-
-\item{prf}{The time of the premium waiver}
-
-\item{outdir}{The output directory (the file names are not configurable)}
-
-\item{basename}{The base output filename (sans .xlsx). If missing, a name of
-the form 2020-08-01_TARIFNAME_EXTRANAME_RZ0.01_x35_YoB1977_LZ45_PrZ20_VS100000
-is used. If given, the main contract without modification will be
-exported to basename.xlsx, while the example with premium waiver will be
-exported to basename_PremiumWaiver_t10.xlsx and the text file containing
-the examples required by the LV-VMGV is exported to basename_VmGlg.txt.}
-
-\item{extraname}{If basename is not given, this allows a suffix to distinguish
-multiple exports.}
-
-\item{...}{Further parameters (passed on to \code{\link{showVmGlgExamples}})}
-}
-\description{
-Export the given contract to excel (full history/timeseries of all cash
-flows, reserves, premiums, etc.) and to a text file (sample calculation
-required by the Austrian regulation).
-}
-\details{
-Three output files are generated:
-\itemize{
-\item {DATE}_{TARIFF}_Example.xlsx: Full history/timeseries
-\item {DATE}_{TARIFF}_Example_PremiumWaiver_t10.xlsx: Full history/timeseries
-after a premium waiver at the given time \code{prf}
-\item {DATE}_{TARIFF}_Examples_VmGlg.txt: Example calculation required for the
-Austrian regulation (LV-VMGLV)
-}
-}
-\examples{
-library("MortalityTables")
-mortalityTables.load("Austria_Annuities_AVOe2005R")
-# A trivial deferred annuity tariff with no costs:
-tariff = InsuranceTarif$new(name="Test Annuity", type="annuity", tarif = "Annuity 1A",
-    mortalityTable = AVOe2005R.unisex, i=0.01)
-contract = InsuranceContract$new(
-    tariff,
-    age = 35, YOB = 1981,
-    policyPeriod = 30, premiumPeriod = 15, deferralPeriod = 15,
-    sumInsured = 1000,
-    contractClosing = as.Date("2016-10-01")
-);
-\dontrun{exportInsuranceContractExample(contract, prf = 10)}
-
-}
diff --git a/man/fallbackFields.Rd b/man/fallbackFields.Rd
deleted file mode 100644
index 6cde187fefd0f19ae14e823342f8482836b0c827..0000000000000000000000000000000000000000
--- a/man/fallbackFields.Rd
+++ /dev/null
@@ -1,18 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/HelperFunctions.R
-\name{fallbackFields}
-\alias{fallbackFields}
-\title{Replace missing values in ields by default fallback values}
-\usage{
-fallbackFields(fields, valuelist)
-}
-\arguments{
-\item{fields}{existing list}
-
-\item{valuelist}{list of fields to replace in \code{fields}. Only keys that are missing in \code{fields} are added, no existing fields in \code{fields} are overwritten}
-}
-\description{
-Replace all missing values in fields (either missing or NA) with
-their corresponding values from fallback. Members in fallback that are missing
-in fields are inserted
-}
diff --git a/man/fillFields.Rd b/man/fillFields.Rd
deleted file mode 100644
index 3845bfdbc4bb8967c8b2008d0d4f706c3a79b584..0000000000000000000000000000000000000000
--- a/man/fillFields.Rd
+++ /dev/null
@@ -1,19 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/HelperFunctions.R
-\name{fillFields}
-\alias{fillFields}
-\title{Overwrite all existing fields with default values given}
-\usage{
-fillFields(fields, valuelist)
-}
-\arguments{
-\item{fields}{existing list}
-
-\item{valuelist}{list of fields to replace in \code{fields}. Only keys that exist in \code{fields} are overwritten, no new fields are added to \code{fields}}
-}
-\description{
-Overwrite all existing fields in the first argument with
-values given in valuelist. Members of valuelist that are not yet in
-fields are ignored. This allows a huge valuelist to be used to fill
-fields in multiple lists with given structure.
-}
diff --git a/man/fillNAgaps.Rd b/man/fillNAgaps.Rd
deleted file mode 100644
index c330f85cc0d4019be8163f8461239a29ae952dfb..0000000000000000000000000000000000000000
--- a/man/fillNAgaps.Rd
+++ /dev/null
@@ -1,29 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/HelperFunctions.R
-\name{fillNAgaps}
-\alias{fillNAgaps}
-\title{Replace all \code{NA} entries of a vector with the previous non-NA value}
-\usage{
-fillNAgaps(x, firstBack = FALSE)
-}
-\arguments{
-\item{x}{The vector where NA-values should be filled by repeating the last preceeding non-NA value}
-
-\item{firstBack}{if \code{TRUE}, leading NAs are replaced by the first non-NA
-value in the vector, otherwise leading NAs are left untouched.}
-}
-\description{
-Sometimes one has a vector with some gaps (\code{NA}) values, which cause
-problems for several numeric functions. This function \code{fillNAgaps} fills
-these missing values by inserting the last preceeding non-NA-value. Leading
-NA values (at the start of the vector will not be modified). If the
-argument \code{firstBack = TRUE}, leading \code{NA}-values are replaced by
-the first non-NA value.
-Trailing NAs are always replaced by the last previous NA-value.
-}
-\details{
-This code was taken from the R Cookbook:
-http://www.cookbook-r.com/Manipulating_data/Filling_in_NAs_with_last_non-NA_value/
-LICENSE (from that page): The R code is freely available for use without any restrictions.
-In other words: you may reuse the R code for any purpose (and under any license).
-}
diff --git a/man/filterProfitRates.Rd b/man/filterProfitRates.Rd
deleted file mode 100644
index b6a8b2677d88795601948f474ccac4492903817a..0000000000000000000000000000000000000000
--- a/man/filterProfitRates.Rd
+++ /dev/null
@@ -1,16 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/ProfitParticipation.R
-\name{filterProfitRates}
-\alias{filterProfitRates}
-\title{Filter the whole data.frame of profit rates for the given profit classes}
-\usage{
-filterProfitRates(rates, classes)
-}
-\arguments{
-\item{rates}{data.frame containing all profit rates for multiple profit classes}
-
-\item{classes}{the profit classes, for which rates should be extracted}
-}
-\description{
-This is a rather trivial helper function, which just calls \code{\link[dplyr:filter]{dplyr::filter()}}.
-}
diff --git a/man/freqCharge.Rd b/man/freqCharge.Rd
deleted file mode 100644
index cdf33b55c4cd76dcaf9982b1aa27c950360c2194..0000000000000000000000000000000000000000
--- a/man/freqCharge.Rd
+++ /dev/null
@@ -1,38 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/HelperFunctions.R
-\name{freqCharge}
-\alias{freqCharge}
-\title{Defines a frequency charge (surcharge for monthly/quarterly/semiannual) premium payments}
-\usage{
-freqCharge(monthly = 0, quarterly = 0, semiannually = 0, yearly = 0)
-}
-\arguments{
-\item{monthly}{Surcharge for monthly premium payments}
-
-\item{quarterly}{Surcharge for quarterly premium payments}
-
-\item{semiannually}{Surcharge for semi-annual premium payments}
-
-\item{yearly}{Surcharge for yearly premium payments (optiona, default is no surcharge)}
-}
-\description{
-Tariffs are typically calculated with yearly premium installments. When
-premiums are paid more often then one a year (in advance), the insurance
-receives part of the premium later (or not at all in case of death), so a
-surcharge for premium payment frequencies higher than yearly is applied to
-the  premium, typically in the form of a percentage of the premium.
-
-This function generates the internal data structure to define surcharges for
-monthly, quarterly and semiannual premium payments. The given surcharges can
-be either given as percentage points (e.g. 1.5 means 1.5\% = 0.015) or as
-fractions of 1 (i.e. 0.015 also means 1.5\% surcharge). The heuristics applied
-to distinguish percentage points and fractions is that all values larger than 0.1
-are understood as percentage points and values 0.1 and lower are understood
-as fractions of 1.
-As a consequence, a frequency charge of 10\% or more MUST be given as percentage points.
-
-Currently, the frequency charges are internally represented as a named list,
-\code{list("1" = 0, "2" = 0.01, "4" = 0.02, "12" = 0.03)}, but that might
-change in the future, so it is advised to use this function rather than
-explicitly using the named list in your code.
-}
diff --git a/man/head0.Rd b/man/head0.Rd
deleted file mode 100644
index a71e9cb6406bc2632f975589742a2225a95c6647..0000000000000000000000000000000000000000
--- a/man/head0.Rd
+++ /dev/null
@@ -1,24 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/HelperFunctions.R
-\name{head0}
-\alias{head0}
-\title{Set all entries of the given vector to 0 up until index 'start'}
-\usage{
-head0(v, start = 0, value.start = 0)
-}
-\arguments{
-\item{v}{the vector to modify}
-
-\item{start}{how many leading elements to zero out}
-
-\item{value.start}{the value to insert before the start index.}
-}
-\value{
-the vector \code{v} with the first \code{start} elements replaced by 0.
-}
-\description{
-Set all entries of the given vector to 0 up until index 'start'
-}
-\examples{
-head0(1:10, 3)
-}
diff --git a/man/initializeCosts.Rd b/man/initializeCosts.Rd
deleted file mode 100644
index 372e32576ed7eae2f06c93ae3f44c60c0738b870..0000000000000000000000000000000000000000
--- a/man/initializeCosts.Rd
+++ /dev/null
@@ -1,93 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/InsuranceParameters.R
-\name{initializeCosts}
-\alias{initializeCosts}
-\title{Initialize or modify a data structure for the definition of \link{InsuranceTarif} costs}
-\usage{
-initializeCosts(
-  costs,
-  alpha,
-  Zillmer,
-  alpha.commission,
-  beta,
-  gamma,
-  gamma.paidUp,
-  gamma.premiumfree,
-  gamma.contract,
-  gamma.afterdeath,
-  gamma.fullcontract,
-  unitcosts,
-  unitcosts.PolicyPeriod
-)
-}
-\arguments{
-\item{costs}{(optional) existing cost structure to duplicate / use as a starting point}
-
-\item{alpha}{Alpha costs (charged once, relative to sum of premiums)}
-
-\item{Zillmer}{Zillmer costs (charged once, relative to sum of premiums)}
-
-\item{alpha.commission}{Alpha costs (charged during the commission period,
-relative to sum of premiums; Use the \code{commissionPeriod}
-and \code{alphaCostsCommission} contract parameters
-to set the length of the commission period and whether
-the \code{alpha.commission} val´ue is understood as yearly
-cost or the sum or present value of the commission
-charges over the whole commission period)}
-
-\item{beta}{Collection costs (charged on each gross premium, relative to gross premium)}
-
-\item{gamma}{Administration costs while premiums are paid (relative to sum insured)}
-
-\item{gamma.paidUp}{Administration costs for paid-up contracts (relative to sum insured)}
-
-\item{gamma.premiumfree}{Administration costs for planned premium-free period (reltaive to sum insured)}
-
-\item{gamma.contract}{Administration costs for the whole contract period (relative to sum insured)}
-
-\item{gamma.afterdeath}{Administration costs after the insured person has dies (for term-fix insurances)}
-
-\item{gamma.fullcontract}{Administration costs for the full contract period,
-even if the insured has already dies (for term-fix insurances)}
-
-\item{unitcosts}{Unit costs (absolute monetary amount, during premium period)}
-
-\item{unitcosts.PolicyPeriod}{Unit costs (absolute monetary amount, during full contract period)}
-}
-\description{
-Initialize a cost matrix with dimensions: {CostType, Basis, Period}, where:
-\describe{
-\item{CostType:}{alpha, Zillmer, beta, gamma, gamma_nopremiums, unitcosts}
-\item{Basis:}{SumInsured, SumPremiums, GrossPremium, NetPremium, Benefits, Constant}
-\item{Period:}{once, PremiumPeriod, PremiumFree, PolicyPeriod, CommissionPeriod}
-}
-This cost structure can then be modified for non-standard costs using the \code{\link[=setCost]{setCost()}} function.
-The main purpose of this structure is to be passed to \link{InsuranceContract} or
-\link{InsuranceTarif} definitions.
-}
-\examples{
-# empty cost structure (only 0 costs)
-initializeCosts()
-
-# the most common cost types can be given in initializeCosts()
-initializeCosts(alpha = 0.04, Zillmer = 0.025, beta = 0.05, gamma.contract = 0.001)
-
-# The same cost structure manually
-costs.Bsp = initializeCosts();
-costs.Bsp[["alpha", "SumPremiums", "once"]] = 0.04;
-costs.Bsp[["Zillmer", "SumPremiums", "once"]] = 0.025;
-costs.Bsp[["beta", "GrossPremium", "PremiumPeriod"]] = 0.05;
-costs.Bsp[["gamma", "SumInsured", "PolicyPeriod"]] = 0.001;
-
-# The same structure using the setCost() function:
-library(magrittr)
-costs.Bsp = initializeCosts() \%>\%
-  setCost("alpha", "SumPremiums", "once", 0.04) \%>\%
-  setCost("Zillmer", "SumPremiums", "once", 0.025) \%>\%
-  setCost("beta", "GrossPremium", "PremiumPeriod", 0.05) \%>\%
-  setCost("gamma", "SumInsured", "PolicyPeriod", 0.001)
-
-
-
-
-}
diff --git a/man/isRegularPremiumContract.Rd b/man/isRegularPremiumContract.Rd
deleted file mode 100644
index f204dbae4e3ececbeed52762c336f7f5559f80e5..0000000000000000000000000000000000000000
--- a/man/isRegularPremiumContract.Rd
+++ /dev/null
@@ -1,16 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/HelperFunctions.R
-\name{isRegularPremiumContract}
-\alias{isRegularPremiumContract}
-\title{Determine whether a contract (given all parameters) is a contract with regular premiums}
-\usage{
-isRegularPremiumContract(params, values)
-}
-\arguments{
-\item{params}{The parameters of the contract.}
-
-\item{values}{Unused by default (already calculated values of the contract)}
-}
-\description{
-Regular premium contracts are identified by the parameter \code{premiumPeriod > 1}.
-}
diff --git a/man/isSinglePremiumContract.Rd b/man/isSinglePremiumContract.Rd
deleted file mode 100644
index b69cc80c59bb10a46f92e22dd9eb4160c051b5ee..0000000000000000000000000000000000000000
--- a/man/isSinglePremiumContract.Rd
+++ /dev/null
@@ -1,16 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/HelperFunctions.R
-\name{isSinglePremiumContract}
-\alias{isSinglePremiumContract}
-\title{Determine whether a contract (given all parameters) is a single-premium contract or with regular premiums}
-\usage{
-isSinglePremiumContract(params, values)
-}
-\arguments{
-\item{params}{The parameters of the contract.}
-
-\item{values}{Unused by default (already calculated values of the contract)}
-}
-\description{
-Single premium contracts are identified by the parameter \code{premiumPeriod = 1}.
-}
diff --git a/man/makeContractGridDimname.Rd b/man/makeContractGridDimname.Rd
deleted file mode 100644
index b09d322c857251bfdc07f3e8df0397778f38f059..0000000000000000000000000000000000000000
--- a/man/makeContractGridDimname.Rd
+++ /dev/null
@@ -1,47 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/contractGrid.R
-\name{makeContractGridDimname}
-\alias{makeContractGridDimname}
-\alias{makeContractGridDimnames}
-\title{Create human-readable labels for the dimensions in a \code{\link[=contractGrid]{contractGrid()}}}
-\usage{
-makeContractGridDimname(value)
-
-makeContractGridDimnames(axes)
-}
-\arguments{
-\item{value}{the value along the axis, for which a name should be generated}
-
-\item{axes}{the axes with all names, for which a name should be generated}
-}
-\description{
-The function \code{makeContractGridDimname} generates a short, human-readable
-dimension label for the entries along the axes of a \code{\link[=contractGrid]{contractGrid()}}.
-The default is to use the \code{value} unchanged as the row-/columnname, but
-for some parameter values (like a \link{InsuranceTarif} or \link{mortalityTable})
-a custom method of this function is needed to create the (short) human-readable
-representation for the axes in the grid.
-
-The function \code{makeContractGridDimnames} generate proper
-dimnames for all entries of the axes of a \code{\link[=contractGrid]{contractGrid()}} by calling
-\code{makeContractGridDimname} on each of the axes' values
-}
-\section{Functions}{
-\itemize{
-\item \code{makeContractGridDimname()}: Create a short, human-readable dimensional name for an object (default S3 method)
-
-\item \code{makeContractGridDimnames()}: Generate proper dimnames for all entries of the axes of a \code{\link[=contractGrid]{contractGrid()}}
-
-}}
-\examples{
-library(MortalityTables)
-mortalityTables.load("Austria_Census")
-
-makeContractGridDimname(mort.AT.census.2011.unisex)
-
-makeContractGridDimnames(axes = list(
-    age = seq(30,60,10),
-    mortalityTable = c(mort.AT.census.2011.unisex, mort.AT.census.2011.male,
-                       mort.AT.census.2011.female))
-)
-}
diff --git a/man/pad0.Rd b/man/pad0.Rd
deleted file mode 100644
index 5bba7c95a2ffa20156b7be0278a019f46500409b..0000000000000000000000000000000000000000
--- a/man/pad0.Rd
+++ /dev/null
@@ -1,39 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/HelperFunctions.R
-\name{pad0}
-\alias{pad0}
-\title{Pad a vector with 0 to a desired length}
-\usage{
-pad0(v, l, value = 0, start = 0, value.start = 0)
-}
-\arguments{
-\item{v}{the vector to pad with 0}
-
-\item{l}{the desired (resulting) length of the vector}
-
-\item{value}{the value to pad with (if padding is needed). Default to 0, but
-can be overridden to pad with any other value.}
-
-\item{start}{the first \code{start} values are always set to 0 (default is 0,
-can be changed using the \code{value.start} argument),
-the vector \code{v} starts only after these leading zeroes. The number of
-leading zeroes counts towards the desired length}
-
-\item{value.start}{the value to insert before the start index.}
-}
-\value{
-returns the vector \code{v} padded to length \code{l} with value \code{value} (default 0).
-}
-\description{
-Pad a vector with 0 to a desired length
-}
-\examples{
-pad0(1:5, 7)   # Pad to length 7 with zeroes
-pad0(1:5, 3)   # no padding, but cut at length 3
-
-# 3 leading zeroes, then the vector start (10 elements of vector, no additional padding needed):
-pad0(1:10, 13, start = 3)
-
-# padding with value other than zero:
-pad0(1:5, 7, value = "pad")
-}
diff --git a/man/padLast.Rd b/man/padLast.Rd
deleted file mode 100644
index 7997f186a1fcc58a5cc2e145365f6ef03ad5e7aa..0000000000000000000000000000000000000000
--- a/man/padLast.Rd
+++ /dev/null
@@ -1,23 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/HelperFunctions.R
-\name{padLast}
-\alias{padLast}
-\title{Pad the vector \code{v} to length \code{l} by repeating the last entry of the
-vector.}
-\usage{
-padLast(v, ...)
-}
-\arguments{
-\item{v}{the vector to pad by repeating the last element}
-
-\item{...}{arguments passed through to \code{pad0}}
-}
-\description{
-This function is just a trivial wrapper around \code{pad0} and only calls \code{\link[=pad0]{pad0()}}
-with the last element of the vector as padding value instead of the default 0.
-}
-\examples{
-padLast(1:5, 7) # 5 is repeated twice
-padLast(1:5, 3) # no padding needed
-
-}
diff --git a/man/premiumRefundPeriod.default.Rd b/man/premiumRefundPeriod.default.Rd
deleted file mode 100644
index 6b04c5241e7e56e60a6bb68624fde33207bb070f..0000000000000000000000000000000000000000
--- a/man/premiumRefundPeriod.default.Rd
+++ /dev/null
@@ -1,19 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/HelperFunctions.R
-\name{premiumRefundPeriod.default}
-\alias{premiumRefundPeriod.default}
-\title{Default premium refund period: for deferred contracts the deferral period, otherwise the whole contract}
-\usage{
-premiumRefundPeriod.default(params, values)
-}
-\arguments{
-\item{params}{The full parameter set of the insurance contract (including
-all inherited values from the tariff and the profit participation)}
-
-\item{values}{The values calculated from the insurance contract so far}
-}
-\description{
-If a premium refund is set for the tariff, the default is the full contract
-period, except for deferred contracts (typically deferred life annuities),
-for which the deferral period is the refund period.
-}
diff --git a/man/rollingmean.Rd b/man/rollingmean.Rd
deleted file mode 100644
index de7fe2086f7dc4b541abc5f107e79befdb74e210..0000000000000000000000000000000000000000
--- a/man/rollingmean.Rd
+++ /dev/null
@@ -1,17 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/HelperFunctions.R
-\name{rollingmean}
-\alias{rollingmean}
-\title{Calculate the rolling mean of length 2}
-\usage{
-rollingmean(x)
-}
-\arguments{
-\item{x}{vector of values, for which the rolling mean is calculated}
-}
-\description{
-Calculate the rolling mean of length 2
-}
-\examples{
-rollingmean(1:10)
-}
diff --git a/man/setCost.Rd b/man/setCost.Rd
deleted file mode 100644
index 840e7ad9928de177466956e729cac1b7a26d9752..0000000000000000000000000000000000000000
--- a/man/setCost.Rd
+++ /dev/null
@@ -1,44 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/InsuranceParameters.R
-\name{setCost}
-\alias{setCost}
-\title{Update one component of an \link{InsuranceTarif}'s cost structure}
-\usage{
-setCost(costs, type, basis = "SumInsured", frequency = "PolicyPeriod", value)
-}
-\arguments{
-\item{costs}{The cost definition matrix (usually created by \code{\link[=initializeCosts]{initializeCosts()}})}
-
-\item{type}{The cost type (alpha, Zillmer, beta, gamma, gamma_nopremiums, unitcosts)}
-
-\item{basis}{The basis fo which the cost rate is applied (default is SumInsured)}
-
-\item{frequency}{How often / during which period the cost is charged (once, PremiumPeriod, PremiumFree, PolicyPeriod, FullContract)}
-
-\item{value}{The new cost value to set for the given type, basis and frequency}
-}
-\value{
-The modified cost structure
-}
-\description{
-Insurance tariff costs are defined by a cost matrix with dimensions: {CostType, Basis, Period}, where:
-\describe{
-\item{CostType:}{alpha, Zillmer, beta, gamma, gamma_nopremiums, unitcosts}
-\item{Basis:}{SumInsured, SumPremiums, GrossPremium, NetPremium, Constant}
-\item{Period:}{once, PremiumPeriod, PremiumFree, PolicyPeriod, AfterDeath, FullContract}
-}
-After creation (using the function \code{\link[=initializeCosts]{initializeCosts()}}), the funciton \code{setCost}
-can be used to modify a single entry. While \code{\link[=initializeCosts]{initializeCosts()}} provides arguments
-to set the most common types of cost parameters in one call, the \code{setCost}
-function allows to modify any cost parameter.
-}
-\details{
-This function modifies a copy of the cost structure and returns it, so this
-function can be chained as often as desired and final return value will contain
-all cost modifications.
-}
-\examples{
-costs = initializeCosts()
-setCost(costs, "alpha", "SumPremiums", "once", 0.05)
-
-}
diff --git a/man/showVmGlgExamples.Rd b/man/showVmGlgExamples.Rd
deleted file mode 100644
index 7ce4288f4f4694756a6f92ac53db61cc6d39a045..0000000000000000000000000000000000000000
--- a/man/showVmGlgExamples.Rd
+++ /dev/null
@@ -1,46 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/showVmGlgExamples.R
-\name{showVmGlgExamples}
-\alias{showVmGlgExamples}
-\title{Display insurance contract calculation example}
-\usage{
-showVmGlgExamples(contract, prf = 10, t = 10, t_prf = 12, file = "", ...)
-}
-\arguments{
-\item{contract}{The insurance contract to calculate and show}
-
-\item{prf}{Time of premium waiver (premium-free)}
-
-\item{t}{Time for which to show all values (except premium-free values)}
-
-\item{t_prf}{Time for which to show all values after the premium waiver}
-
-\item{file}{If given, outputs all information to the file rather than the console}
-
-\item{...}{Further parameters for generating the contract for a tariff object}
-}
-\description{
-Display the values of the example calculation of the given insurance contract
-as required by the Austrian regulation (LV-VMGLV, "LV
-Versicherungsmathematische Grundlagen Verordnung").
-}
-\examples{
-library(MortalityTables)
-mortalityTables.load("Austria_Annuities_AVOe2005R")
-# A trivial deferred annuity tariff with no costs:
-tariff = InsuranceTarif$new(name="Test Annuity", type="annuity",
-    mortalityTable = AVOe2005R.unisex, i=0.01)
-contract = InsuranceContract$new(
-    tariff,
-    age = 35, YOB = 1981,
-    policyPeriod = 30, premiumPeriod = 15, deferralPeriod = 15,
-    sumInsured = 1000,
-    contractClosing = as.Date("2016-10-01")
-);
-showVmGlgExamples(contract)
-
-# Optionally output to a file rather than the console:
-\dontrun{
-showVmGlgExamples(contract, file = "annuity-example.txt")
-}
-}
diff --git a/man/testVmGlgExample.Rd b/man/testVmGlgExample.Rd
deleted file mode 100644
index 2e68a94f99aafbe3cdc4af88f1f1a2b82fc083f3..0000000000000000000000000000000000000000
--- a/man/testVmGlgExample.Rd
+++ /dev/null
@@ -1,96 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/showVmGlgExamples.R
-\name{testVmGlgExample}
-\alias{testVmGlgExample}
-\title{Perform unit tests of given standard values of the insurance contract example}
-\usage{
-testVmGlgExample(
-  contract,
-  prf = 10,
-  t = 10,
-  t_prf = 12,
-  net,
-  Zillmer,
-  gross,
-  written,
-  savings,
-  risk,
-  ZillmerRes,
-  ZillmerRes.prf,
-  VwKostenRes,
-  VwKostenRes.prf,
-  Bilanzreserve,
-  Praemienuebertrag,
-  Rueckkaufsreserve,
-  Rueckkaufswert,
-  Abschlusskostenruecktrag,
-  Rueckkaufswert.prf,
-  VS.prf,
-  absTolerance = 0.015,
-  ...
-)
-}
-\arguments{
-\item{contract}{The insurance contract to calculate and check}
-
-\item{prf}{Time of premium waiver (premium-free)}
-
-\item{t}{Time for which to check all values (except premium-free values)}
-
-\item{t_prf}{Time for which to check all values after the premium waiver}
-
-\item{net, Zillmer, gross, written, savings, risk, ZillmerRes, ZillmerRes.prf, VwKostenRes, VwKostenRes.prf, Bilanzreserve, Praemienuebertrag, Rueckkaufsreserve, Rueckkaufswert, Abschlusskostenruecktrag, Rueckkaufswert.prf, VS.prf}{Values as printed out by showVmGlgExamples}
-
-\item{absTolerance}{If non-NULL, will ignore small floating point differences. It uses same algorithm as all.equal()}
-
-\item{...}{Further parameters for generating the contract for a tariff object}
-}
-\description{
-Check the values of the example calculation of the given insurance contract
-as required by the Austrian regulation (LV-VMGLV, "LV
-Versicherungsmathematische Grundlagen Verordnung").
-Missing params not passed to the function call will be silently ignored and
-not cause unit test failures.
-}
-\details{
-The easiest way to write unit-tests is using the function \code{vmGlgExample.generateTest}
-}
-\examples{
-library(MortalityTables)
-mortalityTables.load("Austria_Annuities_AVOe2005R")
-
-\dontrun{
-test_that("Testtarif", {
-    # A trivial deferred annuity tariff with no costs:
-    tariff = InsuranceTarif$new(name="Test Annuity", type="annuity",
-        mortalityTable = AVOe2005R.unisex, i=0.01)
-    contract = InsuranceContract$new(
-        tariff,
-        age = 35, YOB = 1981,
-        policyPeriod = 30, premiumPeriod = 15, deferralPeriod = 15,
-        sumInsured = 1000,
-        contractClosing = as.Date("2016-10-01")
-    );
-
-    testVmGlgExample(
-        contract, t = 10,
-        net = 850.09, # NOT_CHECKED: Zillmer = 950.09,
-        gross = 850.09,
-        written = 884.09,
-        savings = 857.09, risk = -7.00,
-        ZillmerRes = 9011.40,
-        ZillmerRes.prf = 9205.96,
-        VwKostenRes = 0.00,
-        VwKostenRes.prf = 0.00,
-        Bilanzreserve = 9250.35,
-        Praemienuebertrag = 212.52,
-        Rueckkaufsreserve = 9011.40,
-        Rueckkaufswert = 9011.40,
-        Abschlusskostenruecktrag = 0.00,
-        Rueckkaufswert.prf = 9205.96,
-        VS.prf = 685.12
-    )
-})
-}
-
-}
diff --git a/man/valueOrFunction.Rd b/man/valueOrFunction.Rd
deleted file mode 100644
index 9b09a76bd5f4b7e80cca8049dd1c8605d7f4d188..0000000000000000000000000000000000000000
--- a/man/valueOrFunction.Rd
+++ /dev/null
@@ -1,22 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/HelperFunctions.R
-\name{valueOrFunction}
-\alias{valueOrFunction}
-\title{If \code{val} is a function, evaluate it, otherwise return \code{val}}
-\usage{
-valueOrFunction(val, ...)
-}
-\arguments{
-\item{val}{Function or value}
-
-\item{...}{Argument passed to \code{val} if it is a function}
-}
-\description{
-If \code{val} is a function, evaluate it, otherwise return \code{val}
-}
-\examples{
-valueOrFunction(3) # returns 3
-valueOrFunction(`+`, 1, 2) # also returns 3
-A = `+`
-valueOrFunction(A, 1, 2)
-}
diff --git a/man/vmGlgExample.generateTest.Rd b/man/vmGlgExample.generateTest.Rd
deleted file mode 100644
index ab53b8e01478d7af5c4f1590bad224912dbea0de..0000000000000000000000000000000000000000
--- a/man/vmGlgExample.generateTest.Rd
+++ /dev/null
@@ -1,42 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/showVmGlgExamples.R
-\name{vmGlgExample.generateTest}
-\alias{vmGlgExample.generateTest}
-\title{Generate testthat output for unit-testing a tarif implementation}
-\usage{
-vmGlgExample.generateTest(contract, prf = 10, t = 10, t_prf = 12, ...)
-}
-\arguments{
-\item{contract}{The insurance contract to calculate and generate unit-testing code.
-If an InsuranceTarif object is given, a new contract with default
-values is generated.}
-
-\item{prf}{Time of premium waiver (premium-free)}
-
-\item{t}{Time for which to calculate all values (except premium-free values)}
-
-\item{t_prf}{Time for which to calculated all values after the premium waiver}
-
-\item{...}{Further parameters for generating the contract for a tariff object}
-}
-\description{
-This function calculates the required reference values for the given
-insurance contract as required by the Austrian regulation (LV-VMGLV, "LV
-Versicherungsmathematische Grundlagen Verordnung") and generates the
-code for unit-testing the contract with these values. The code printed
-can be directly copied into a unit test file.
-}
-\examples{
-library(MortalityTables)
-mortalityTables.load("Austria_Annuities_AVOe2005R")
-# A trivial deferred annuity tariff with no costs:
-tariff = InsuranceTarif$new(name="Test Annuity", type="annuity",
-    mortalityTable = AVOe2005R.unisex, i=0.01)
-vmGlgExample.generateTest(tariff,
-    age = 35, YOB = 1981,
-    policyPeriod = 30, premiumPeriod = 15, deferralPeriod = 15,
-    sumInsured = 1000,
-    contractClosing = as.Date("2016-10-01")
-)
-
-}
diff --git a/tests/testthat.R b/tests/testthat.R
deleted file mode 100644
index ec93ddba512575a0df2746f0163477cddbc05496..0000000000000000000000000000000000000000
--- a/tests/testthat.R
+++ /dev/null
@@ -1,7 +0,0 @@
-library(testthat)
-library(LifeInsuranceContracts)
-library(MortalityTables)
-mortalityTables.load("Austria_Census")
-mortalityTables.load("Austria_Annuities_AVOe2005R")
-
-test_check("LifeInsuranceContracts")
diff --git a/tests/testthat/test-CF-Annuity-Deferred.R b/tests/testthat/test-CF-Annuity-Deferred.R
deleted file mode 100644
index 7afdbec750bd2f80a47bc9afb4546c1d6e1a2ec9..0000000000000000000000000000000000000000
--- a/tests/testthat/test-CF-Annuity-Deferred.R
+++ /dev/null
@@ -1,41 +0,0 @@
-test_that("Deferred Annuity Cash Flows", {
-    library(MortalityTables)
-    mortalityTables.load("Austria_Annuities_AVOe2005R")
-
-    Tarif.DefAnnuity = InsuranceTarif$new(
-        name = "Example Tariff - Deferred Annuity",
-        type = "annuity",
-        tarif = "Life1",
-        desc = "A deferred annuity (life-long payments start at age 65) with reg. premiums",
-
-        policyPeriod = function(params, values) { 120 - params$ContractData$age},
-        deferralPeriod = function(params, values) { 65 - params$ContractData$age},
-        premiumPeriod = function(params, values) { 65 - params$ContractData$age},
-        premiumRefund = 1,
-
-        mortalityTable = AVOe2005R.unisex,
-        i = 0.005
-    )
-    Contract.DefAnnuity = InsuranceContract$new(
-        tarif = Tarif.DefAnnuity,
-        age = 40, YOB = 1980,
-        sumInsured = 1200,
-        contractClosing = as.Date("2020-09-01"),
-        calculate = "cashflows"
-    )
-    expect_equal(Contract.DefAnnuity$Parameters$ContractData$policyPeriod, 80)
-    expect_equal(Contract.DefAnnuity$Parameters$ContractData$deferralPeriod, 25)
-    expect_equal(Contract.DefAnnuity$Parameters$ContractData$premiumPeriod, 25)
-
-
-    expect_true(all(Contract.DefAnnuity$Values$cashFlows %>% dplyr::select(-premiums_advance, -survival_advance, -death_GrossPremium, -death_Refund_past) == 0))
-
-    # 25 years premium cash flow
-    expect_equal(Contract.DefAnnuity$Values$cashFlows$premiums_advance, c(rep(1, 25), rep(0, 56)))
-    # premium payment start after 25 years
-    expect_equal(Contract.DefAnnuity$Values$cashFlows$survival_advance, c(rep(0, 25), rep(1, 55),0))
-    # premium payment start after 25 years
-    expect_equal(Contract.DefAnnuity$Values$cashFlows$death_GrossPremium, c(1:25, rep(0, 56)))
-    # death refund flag
-    expect_equal(Contract.DefAnnuity$Values$cashFlows$death_Refund_past, c(rep(1, 25), rep(0, 56)))
-})
diff --git a/tests/testthat/test-CF-Annuity.R b/tests/testthat/test-CF-Annuity.R
deleted file mode 100644
index 512d3640d71b096100464e281c2d6250b25af23a..0000000000000000000000000000000000000000
--- a/tests/testthat/test-CF-Annuity.R
+++ /dev/null
@@ -1,34 +0,0 @@
-test_that("Annuity Cash Flows", {
-    library(MortalityTables)
-    mortalityTables.load("Austria_Annuities_AVOe2005R")
-
-    Tarif.Annuity = InsuranceTarif$new(
-        name = "Example Tariff - Immediate Annuity",
-        type = "annuity",
-        tarif = "Ann1",
-        desc = "An annuity with single-premium",
-        premiumPeriod = 1,
-
-        mortalityTable = AVOe2005R.unisex,
-        i = 0.005
-    )
-    Contract.Annuity = InsuranceContract$new(
-        tarif = Tarif.Annuity,
-        age = 65, YOB = 1955,
-        sumInsured = 1200,
-        policyPeriod = 55,
-        contractClosing = as.Date("2020-09-01"),
-        calculate = "cashflows"
-    )
-    expect_equal(Contract.Annuity$Parameters$ContractData$policyPeriod, 55)
-    expect_equal(Contract.Annuity$Parameters$ContractData$deferralPeriod, 0)
-    expect_equal(Contract.Annuity$Parameters$ContractData$premiumPeriod, 1)
-
-
-    expect_true(all(Contract.Annuity$Values$cashFlows %>% select(-premiums_advance, -survival_advance) == 0))
-
-    # 1 year premium cash flow
-    expect_equal(Contract.Annuity$Values$cashFlows$premiums_advance, c(1, rep(0, 55)))
-    # premium payment start immediately for the whole contract period
-    expect_equal(Contract.Annuity$Values$cashFlows$survival_advance, c(rep(1, 55), 0))
-})
diff --git a/tests/testthat/test-CF-DreadDisease.R b/tests/testthat/test-CF-DreadDisease.R
deleted file mode 100644
index 4f5562deedc4674703cf6348414534efd7e3a635..0000000000000000000000000000000000000000
--- a/tests/testthat/test-CF-DreadDisease.R
+++ /dev/null
@@ -1,80 +0,0 @@
-test_that("Dread-Disease Cash Flows", {
-    library(MortalityTables)
-    mortalityTables.load("Austria_Census")
-
-    # An example dread-disease tariff, morbidity is assumed linearly increasing with age
-    ddTable = mortalityTable.period(name = "Linear dread-disease table",
-                                    ages = 0:100, deathProbs = 0:100/500)
-    Tarif.DreadDisease = InsuranceTarif$new(
-        name = "Example Tariff - Dread-Disease",
-        type = "dread-disease",
-        tarif = "DD1",
-        desc = "A dread disease insurance with a lump-sum payment upon diagnosis",
-
-        sumInsured = 50000,
-        mortalityTable = mort.AT.census.2011.unisex,
-        invalidityTable = ddTable,
-        i = 0.005
-    )
-
-    Contract.DreadDisease = InsuranceContract$new(
-        tarif = Tarif.DreadDisease,
-        age = 40, policyPeriod = 20,
-        sumInsured = 10000,
-        contractClosing = as.Date("2020-09-01"),
-        calculate = "cashflows"
-    )
-    expect_equal(Contract.DreadDisease$Parameters$ContractData$policyPeriod, 20)
-    expect_equal(Contract.DreadDisease$Parameters$ContractData$deferralPeriod, 0)
-    expect_equal(Contract.DreadDisease$Parameters$ContractData$premiumPeriod, 20)
-
-
-    expect_true(all(Contract.DreadDisease$Values$cashFlows %>% select(-premiums_advance, -disease_SumInsured) == 0))
-
-    expect_equal(Contract.DreadDisease$Values$cashFlows$premiums_advance, c(rep(1, 20), 0))
-    expect_equal(Contract.DreadDisease$Values$cashFlows$disease_SumInsured, c(rep(1, 20), 0))
-})
-
-""
-test_that("Endowment + Dread-Disease Cash Flows", {
-    library(MortalityTables)
-    mortalityTables.load("Austria_Census")
-
-    # An example dread-disease tariff, morbidity is assumed linearly increasing with age
-    ddTable = mortalityTable.period(name = "Linear dread-disease table",
-                                    ages = 0:100, deathProbs = 0:100/500)
-    Tarif.EndowDreadDisease = InsuranceTarif$new(
-        name = "Example Tariff - Endowment + Dread-Disease",
-        type = "endowment + dread-disease",
-        tarif = "EnDD1",
-        desc = "An endowment and dread disease insurance with a lump-sum payment upon diagnosis",
-
-        sumInsured = 50000,
-        mortalityTable = mort.AT.census.2011.unisex,
-        invalidityTable = ddTable,
-        invalidityEndsContract = TRUE,
-        i = 0.005
-    )
-
-    Contract.EndowDreadDisease = InsuranceContract$new(
-        tarif = Tarif.EndowDreadDisease,
-        age = 40, policyPeriod = 20,
-        sumInsured = 10000,
-        contractClosing = as.Date("2020-09-01"),
-        calculate = "cashflows"
-    )
-    expect_equal(Contract.EndowDreadDisease$Parameters$ContractData$policyPeriod, 20)
-    expect_equal(Contract.EndowDreadDisease$Parameters$ContractData$deferralPeriod, 0)
-    expect_equal(Contract.EndowDreadDisease$Parameters$ContractData$premiumPeriod, 20)
-
-
-    expect_true(all(Contract.EndowDreadDisease$Values$cashFlows %>% select(-premiums_advance, -survival_advance, -death_SumInsured, -death_PremiumFree, -disease_SumInsured) == 0))
-
-    expect_equal(Contract.EndowDreadDisease$Values$cashFlows$premiums_advance, c(rep(1, 20), 0))
-    expect_equal(Contract.EndowDreadDisease$Values$cashFlows$survival_advance, c(rep(0, 20), 1))
-    expect_equal(Contract.EndowDreadDisease$Values$cashFlows$death_SumInsured, c(rep(1, 20), 0))
-    expect_equal(Contract.EndowDreadDisease$Values$cashFlows$disease_SumInsured, c(rep(1, 20), 0))
-    expect_equal(Contract.EndowDreadDisease$Values$cashFlows$death_PremiumFree, c(rep(1, 20), 0))
-
-})
-
diff --git a/tests/testthat/test-CF-Endowment-SP.R b/tests/testthat/test-CF-Endowment-SP.R
deleted file mode 100644
index 113bf85a5d0d1017b017595b7ebcc224161e8aa6..0000000000000000000000000000000000000000
--- a/tests/testthat/test-CF-Endowment-SP.R
+++ /dev/null
@@ -1,32 +0,0 @@
-test_that("Endowment Cash Flows", {
-    library(MortalityTables)
-    mortalityTables.load("Austria_Census")
-
-    Tarif.Endowment.SP = InsuranceTarif$new(
-        name = "Example Tariff - Endowment Single Premium",
-        type = "endowment",
-        tarif = "E1-SP",
-        desc = "An endowment with single premiums (standard tariff)",
-        premiumPeriod = 1,
-        mortalityTable = mort.AT.census.2011.unisex,
-        i = 0.005
-    )
-    Contract.Endowment.SP = InsuranceContract$new(
-        tarif = Tarif.Endowment.SP,
-        age = 40, policyPeriod = 20,
-        sumInsured = 10000,
-        contractClosing = as.Date("2020-09-01"),
-        calculate = "cashflows"
-    )
-    expect_equal(Contract.Endowment.SP$Parameters$ContractData$policyPeriod, 20)
-    expect_equal(Contract.Endowment.SP$Parameters$ContractData$deferralPeriod, 0)
-    expect_equal(Contract.Endowment.SP$Parameters$ContractData$premiumPeriod, 1)
-
-
-    expect_true(all(Contract.Endowment.SP$Values$cashFlows %>% select(-premiums_advance, -survival_advance, -death_SumInsured, -death_PremiumFree) == 0))
-
-    expect_equal(Contract.Endowment.SP$Values$cashFlows$premiums_advance, c(1, rep(0, 20)))
-    expect_equal(Contract.Endowment.SP$Values$cashFlows$survival_advance, c(rep(0, 20), 1))
-    expect_equal(Contract.Endowment.SP$Values$cashFlows$death_SumInsured, c(rep(1, 20),0))
-    expect_equal(Contract.Endowment.SP$Values$cashFlows$death_PremiumFree, c(rep(1, 20), 0))
-})
diff --git a/tests/testthat/test-CF-Endowment.R b/tests/testthat/test-CF-Endowment.R
deleted file mode 100644
index 65715c7837f62c7f406b42dd6ee42d0acd9674da..0000000000000000000000000000000000000000
--- a/tests/testthat/test-CF-Endowment.R
+++ /dev/null
@@ -1,32 +0,0 @@
-test_that("Endowment Cash Flows", {
-    library(MortalityTables)
-    mortalityTables.load("Austria_Census")
-
-    Tarif.Endowment = InsuranceTarif$new(
-        name = "Example Tariff - Endowment",
-        type = "endowment",
-        tarif = "E1-RP",
-        desc = "An endowment with regular premiums (standard tariff)",
-
-        mortalityTable = mort.AT.census.2011.unisex,
-        i = 0.005
-    )
-    Contract.Endowment = InsuranceContract$new(
-        tarif = Tarif.Endowment,
-        age = 40, policyPeriod = 20,
-        sumInsured = 10000,
-        contractClosing = as.Date("2020-09-01"),
-        calculate = "cashflows"
-    )
-    expect_equal(Contract.Endowment$Parameters$ContractData$policyPeriod, 20)
-    expect_equal(Contract.Endowment$Parameters$ContractData$deferralPeriod, 0)
-    expect_equal(Contract.Endowment$Parameters$ContractData$premiumPeriod, 20)
-
-
-    expect_true(all(Contract.Endowment$Values$cashFlows %>% select(-premiums_advance, -survival_advance, -death_SumInsured, -death_PremiumFree) == 0))
-
-    expect_equal(Contract.Endowment$Values$cashFlows$premiums_advance, c(rep(1, 20), 0))
-    expect_equal(Contract.Endowment$Values$cashFlows$survival_advance, c(rep(0, 20), 1))
-    expect_equal(Contract.Endowment$Values$cashFlows$death_SumInsured, c(rep(1, 20),0))
-    expect_equal(Contract.Endowment$Values$cashFlows$death_PremiumFree, c(rep(1, 20), 0))
-})
diff --git a/tests/testthat/test-CF-Life.R b/tests/testthat/test-CF-Life.R
deleted file mode 100644
index 714f6e0197e55f64bf1419f91b80f05a8e0bdced..0000000000000000000000000000000000000000
--- a/tests/testthat/test-CF-Life.R
+++ /dev/null
@@ -1,32 +0,0 @@
-test_that("Term Life Cash Flows", {
-    library(MortalityTables)
-    mortalityTables.load("Austria_Census")
-
-    Tarif.Life = InsuranceTarif$new(
-        name = "Example Tariff - Whole/Term Life",
-        type = "wholelife",
-        tarif = "Life1",
-        desc = "A whole or term life insurance with regular premiums",
-
-        mortalityTable = mort.AT.census.2011.unisex,
-        i = 0.005
-    )
-
-    Contract.Life = InsuranceContract$new(
-        tarif = Tarif.Life,
-        age = 40, policyPeriod = 20,
-        sumInsured = 10000,
-        contractClosing = as.Date("2020-09-01"),
-        calculate = "cashflows"
-    )
-    expect_equal(Contract.Life$Parameters$ContractData$policyPeriod, 20)
-    expect_equal(Contract.Life$Parameters$ContractData$deferralPeriod, 0)
-    expect_equal(Contract.Life$Parameters$ContractData$premiumPeriod, 20)
-
-
-    expect_true(all(Contract.Life$Values$cashFlows %>% select(-premiums_advance, -death_SumInsured, -death_PremiumFree) == 0))
-
-    expect_equal(Contract.Life$Values$cashFlows$premiums_advance, c(rep(1, 20), 0))
-    expect_equal(Contract.Life$Values$cashFlows$death_SumInsured, c(rep(1, 20), 0))
-    expect_equal(Contract.Life$Values$cashFlows$death_PremiumFree, c(rep(1, 20), 0))
-})
diff --git a/tests/testthat/test-CF-PureEndowment.R b/tests/testthat/test-CF-PureEndowment.R
deleted file mode 100644
index e51077889b16bab7d00883d2d4d1245c9aaa73fc..0000000000000000000000000000000000000000
--- a/tests/testthat/test-CF-PureEndowment.R
+++ /dev/null
@@ -1,33 +0,0 @@
-test_that("Pure Endowment Cash Flows", {
-    library(MortalityTables)
-    mortalityTables.load("Austria_Census")
-
-    Tarif.PureEnd = InsuranceTarif$new(
-        name = "Example Tariff - Pure Endowment",
-        type = "pureendowment",
-        tarif = "PE1-RP",
-        desc = "A pure endowment with regular premiums (standard tariff)",
-
-        mortalityTable = mort.AT.census.2011.unisex,
-        i = 0.005,
-        premiumRefund = 1
-    )
-    Contract.PureEnd = InsuranceContract$new(
-        tarif = Tarif.PureEnd,
-        age = 40, policyPeriod = 20,
-        sumInsured = 10000,
-        contractClosing = as.Date("2020-09-01"),
-        calculate = "cashflows"
-    )
-    expect_equal(Contract.PureEnd$Parameters$ContractData$policyPeriod, 20)
-    expect_equal(Contract.PureEnd$Parameters$ContractData$deferralPeriod, 0)
-    expect_equal(Contract.PureEnd$Parameters$ContractData$premiumPeriod, 20)
-
-
-    expect_true(all(Contract.PureEnd$Values$cashFlows %>% select(-premiums_advance, -survival_advance, -death_GrossPremium, -death_Refund_past) == 0))
-
-    expect_equal(Contract.PureEnd$Values$cashFlows$premiums_advance, c(rep(1, 20), 0))
-    expect_equal(Contract.PureEnd$Values$cashFlows$survival_advance, c(rep(0, 20), 1))
-    expect_equal(Contract.PureEnd$Values$cashFlows$death_GrossPremium, c(1:20,0))
-    expect_equal(Contract.PureEnd$Values$cashFlows$death_Refund_past, c(rep(1, 20), 0))
-})
diff --git a/tests/testthat/test-CF-TermeFixe.R b/tests/testthat/test-CF-TermeFixe.R
deleted file mode 100644
index d103657244082cae2cbee76b43673b83251eeb39..0000000000000000000000000000000000000000
--- a/tests/testthat/test-CF-TermeFixe.R
+++ /dev/null
@@ -1,30 +0,0 @@
-test_that("Termfix Cash Flows", {
-    library(MortalityTables)
-    mortalityTables.load("Austria_Census")
-
-    Tarif.Termfix = InsuranceTarif$new(
-        name = "Example Tariff - Terme Fixe",
-        type = "terme-fix",
-        tarif = "TF",
-        desc = "A termfix insurance with regular premiums",
-
-        mortalityTable = mort.AT.census.2011.unisex,
-        i = 0.005
-    )
-    Contract.Termfix = InsuranceContract$new(
-        tarif = Tarif.Termfix,
-        age = 40, policyPeriod = 20,
-        sumInsured = 10000,
-        contractClosing = as.Date("2020-09-01"),
-        calculate = "cashflows"
-    )
-    expect_equal(Contract.Termfix$Parameters$ContractData$policyPeriod, 20)
-    expect_equal(Contract.Termfix$Parameters$ContractData$deferralPeriod, 0)
-    expect_equal(Contract.Termfix$Parameters$ContractData$premiumPeriod, 20)
-
-
-    expect_true(all(Contract.Termfix$Values$cashFlows %>% select(-premiums_advance, -guaranteed_advance) == 0))
-
-    expect_equal(Contract.Termfix$Values$cashFlows$premiums_advance, c(rep(1, 20), 0))
-    expect_equal(Contract.Termfix$Values$cashFlows$guaranteed_advance, c(rep(0, 20), 1))
-})
diff --git a/tests/testthat/test-Cost-Initialization.R b/tests/testthat/test-Cost-Initialization.R
deleted file mode 100644
index da277efe48aef462f817a38df372bd3e318d63d3..0000000000000000000000000000000000000000
--- a/tests/testthat/test-Cost-Initialization.R
+++ /dev/null
@@ -1,28 +0,0 @@
-test_that("multiplication works", {
-    c1 = initializeCosts(
-        alpha = 0.04,
-        Zillmer = 0.025,
-        beta = 0.05,
-        gamma = 0.0005,
-        gamma.paidUp = 0.001,
-        gamma.premiumfree = 0.00075,
-        gamma.contract = 0.002,
-        unitcosts = 10,
-        unitcosts.PolicyPeriod = 12
-    )
-
-    # the above is the short form of:
-    c2 = initializeCosts()
-    c2[["alpha", "SumPremiums", "once"]] = 0.04
-    c2[["Zillmer", "SumPremiums", "once"]] = 0.025
-    c2[["beta", "GrossPremium", "PremiumPeriod"]] = 0.05
-    c2[["gamma", "SumInsured", "PremiumPeriod"]] = 0.0005
-    c2[["gamma_nopremiums", "SumInsured", "PolicyPeriod"]] = 0.001
-    c2[["gamma", "SumInsured", "PremiumFree"]] = 0.00075
-    c2[["gamma", "SumInsured", "PolicyPeriod"]] = 0.002
-    c2[["unitcosts", "Constant", "PremiumPeriod"]] = 10
-    c2[["unitcosts", "Constant", "PolicyPeriod"]] = 12
-
-    expect_equal(c1, c2)
-    expect_equal(c1, initializeCosts(c1))
-})
diff --git a/tests/testthat/test-PVfactory.R b/tests/testthat/test-PVfactory.R
deleted file mode 100644
index 82385867eb7216cefdb7b4dad62d364b7874cdbc..0000000000000000000000000000000000000000
--- a/tests/testthat/test-PVfactory.R
+++ /dev/null
@@ -1,90 +0,0 @@
-test_that("multiplication works", {
-    library(MortalityTables)
-    mortalityTables.load("Austria_Census")
-
-    # Sample data: Austrian population mortality, interest 3%
-    ags = 40:100
-    v = 1/1.03
-    qx = deathProbabilities(mort.AT.census.2011.unisex, ages = ags)
-    qq = data.frame(x = ags, qx = qx, ix = 0, px = 1 - qx)
-    pvf = PVfactory$new(qx = qq, m = 1, v = v)
-    # For invalidity, simply use half the death prob (split qx into qx and ix, leave px unchanged!)
-    qqI = qq
-    qqI$ix = qqI$qx/2
-    qqI$qx = qqI$ix
-    pvfI = PVfactory$new(qx = qqI, m = 1, v = v)
-
-    #################################### #
-    # Cash Flow Definitions
-    #################################### #
-    # Single payment after 10 years
-    cf1 = c(rep(0, 10), 1)
-    # Annual payments for 10 years
-    cfN = rep(1, 10)
-
-    #################################### #
-    # Guaranteed  PV
-    #################################### #
-    PV1adv = v^(10:0)
-    PV1arr = v^(11:1)
-    PVNadv = (1 - v^(10:1))/(1-v)
-    PVNarr = v * PVNadv
-
-    # Check basic present values for correctness (one-dimensional CF vector)
-    expect_equal(as.vector(pvf$guaranteed(advance = cf1)), PV1adv)
-    expect_equal(as.vector(pvf$guaranteed(arrears = cf1)), PV1arr)
-    expect_equal(as.vector(pvf$guaranteed(advance = cfN)), PVNadv)
-    expect_equal(as.vector(pvf$guaranteed(arrears = cfN)), PVNarr)
-
-    # Same cash flows, either understood paid in advance at next timestep or in arrears of previous timestep => same present values
-    expect_equal(c(pvf$guaranteed(advance = c(1,cfN))), 1 + c(pvf$guaranteed(arrears = cfN), 0))
-
-    # Check cash flow arrays
-    # PV of single payment is v^(n-t), PV of annuity is (1-v^(n-t))/(1-v)
-    # Use CF array with those two cash flows
-    cf2d = array(c(cf1, cfN, 0), dim = c(length(cf1),2))
-    expect_equal(pvf$guaranteed(advance = cf2d), array(c(PV1adv, PVNadv, 0), dim = c(length(cf1), 2)))
-
-    # two-dimensional cashflows at each time => 3-dimensional tensor
-    cf3d = array(c(cf1, cfN, 0, cf1, cfN, 0, cfN, 0, cf1), dim = c(length(cf1), 2, 3))
-    expect_equal(pvf$guaranteed(advance = cf3d), array(c(PV1adv, PVNadv, 0, PV1adv, PVNadv, 0, PVNadv, 0, PV1adv), dim = c(length(cf1), 2, 3)))
-
-
-
-    #################################### #
-    # Survival PV
-    #################################### #
-    PV1adv.sv = Reduce(`*`, 1-qx[1:10], init = 1, right = TRUE, accumulate = TRUE) * (v^(10:0))
-    PV1arr.sv = head(Reduce(`*`, 1-qx[1:11], init = 1, right = TRUE, accumulate = TRUE), -1) * (v^(11:1))
-    PVNadv.sv = head(Reduce(function(p, pv1) {pv1 * v * p + 1}, 1-qx[1:10], init = 0, right = TRUE, accumulate = TRUE), -1)
-    PVNarr.sv = head(Reduce(function(p, pv1) { v * p * (1 + pv1)}, 1-qx[1:10], init = 0, right = TRUE, accumulate = TRUE), -1)
-
-    # check basic PV
-    expect_equal(as.vector(pvf$survival(advance = cf1)), PV1adv.sv)
-    expect_equal(as.vector(pvf$survival(arrears = cf1)), PV1arr.sv)
-    expect_equal(as.vector(pvf$survival(advance = cfN)), PVNadv.sv)
-    expect_equal(as.vector(pvf$survival(arrears = cfN)), PVNarr.sv)
-
-    # Check cash flow arrays
-    expect_equal(pvf$survival(advance = cf2d), array(c(PV1adv.sv, PVNadv.sv, 0), dim = c(length(cf1), 2)))
-    expect_equal(pvf$survival(arrears = cf2d), array(c(PV1arr.sv, PVNarr.sv, 0), dim = c(length(cf1), 2)))
-
-    # two-dimensional cashflows at each time => 3-dimensional tensor
-    expect_equal(pvf$survival(advance = cf3d), array(c(PV1adv.sv, PVNadv.sv, 0, PV1adv.sv, PVNadv.sv, 0, PVNadv.sv, 0, PV1adv.sv), dim = c(length(cf1), 2, 3)))
-    expect_equal(pvf$survival(arrears = cf3d), array(c(PV1arr.sv, PVNarr.sv, 0, PV1arr.sv, PVNarr.sv, 0, PVNarr.sv, 0, PV1arr.sv), dim = c(length(cf1), 2, 3)))
-
-
-
-    #################################### #
-    # Death PV
-    #################################### #
-    PVN.death = head(Reduce(function(q, pv1) {q * v + (1 - q) * v * pv1}, qx[1:10], init = 0, right = TRUE, accumulate = TRUE), -1)
-    expect_equal(as.vector(pvf$death(benefits = cfN)), PVN.death)
-
-    #################################### #
-    # Disease PV
-    #################################### #
-    # Death and disease probabilities are equal, so the PV should be equal. If death() is implemented correctly, this can detect errors in
-    expect_equal(pvfI$disease(benefits = cfN), pvfI$death(benefits = cfN))
-
-})
diff --git a/tests/testthat/test-SumInsured-calculated.R b/tests/testthat/test-SumInsured-calculated.R
deleted file mode 100644
index 92c88748d374b564dd0750fffe487f5f68791768..0000000000000000000000000000000000000000
--- a/tests/testthat/test-SumInsured-calculated.R
+++ /dev/null
@@ -1,46 +0,0 @@
-test_that("Calculation of sumInsured from premium", {
-    library(MortalityTables)
-    mortalityTables.load("Austria_Census")
-
-    Tarif.EndowmentSI = InsuranceTarif$new(
-        name = "Example Tariff - Endowment",
-        type = "endowment",
-        tarif = "E1-RP",
-        desc = "An endowment with regular premiums (standard tariff)",
-
-        mortalityTable = mort.AT.census.2011.unisex,
-        cost = initializeCosts(alpha = 0.04, gamma.contract = 0.0005, unitcosts = 10),
-        i = 0.03
-    )
-    Contract.sumInsured = InsuranceContract$new(
-        tarif = Tarif.EndowmentSI,
-        age = 40, policyPeriod = 20,
-        sumInsured = 10000,
-        contractClosing = as.Date("2020-09-01")
-    )
-    Contract.premium = InsuranceContract$new(
-        tarif = Tarif.EndowmentSI,
-        age = 40, policyPeriod = 20,
-        premium = Contract.sumInsured$Values$premiums[["written"]],
-        contractClosing = as.Date("2020-09-01")
-    )
-    Contract.premium_beforetax = InsuranceContract$new(
-        tarif = Tarif.EndowmentSI,
-        age = 40, policyPeriod = 20,
-        premium = c(written_beforetax = Contract.sumInsured$Values$premiums[["written_beforetax"]]),
-        contractClosing = as.Date("2020-09-01")
-    )
-    Contract.premium_gross = InsuranceContract$new(
-        tarif = Tarif.EndowmentSI,
-        age = 40, policyPeriod = 20,
-        premium = c(gross = Contract.sumInsured$Values$premiums[["gross"]]),
-        contractClosing = as.Date("2020-09-01")
-    )
-
-    # All four contracts above should result in the same sumInsured:
-    expect_equal(Contract.premium$Parameters$ContractData$sumInsured, Contract.sumInsured$Parameters$ContractData$sumInsured)
-    expect_equal(Contract.premium_beforetax$Parameters$ContractData$sumInsured, Contract.sumInsured$Parameters$ContractData$sumInsured)
-    expect_equal(Contract.premium_gross$Parameters$ContractData$sumInsured, Contract.sumInsured$Parameters$ContractData$sumInsured)
-    expect_equal(Contract.sumInsured$Parameters$ContractData$sumInsured, Contract.premium$Parameters$ContractData$sumInsured)
-
-})
diff --git a/tests/testthat/test-extendContract.R b/tests/testthat/test-extendContract.R
deleted file mode 100644
index e0a9f0f287e7c3dbdb37666ba541753e59d6a2e8..0000000000000000000000000000000000000000
--- a/tests/testthat/test-extendContract.R
+++ /dev/null
@@ -1,47 +0,0 @@
-test_that("Extend contract by $addExtension", {
-    library(MortalityTables)
-    mortalityTables.load("Austria_Census")
-
-    Tarif.EndowmentA = InsuranceTarif$new(
-        name = "Example Tariff - Endowment 1981",
-        type = "endowment",
-        tarif = "E1-RP81",
-        desc = "An endowment with regular premiums (standard tariff)",
-
-        mortalityTable = mort.AT.census.1981.male,
-        cost = initializeCosts(alpha = 0.04, gamma.contract = 0.0005, unitcosts = 10),
-        i = 0.03
-    )
-    Tarif.EndowmentB = Tarif.EndowmentA$createModification(
-        name = "Example Tariff - Endowment 2001",
-        tarif = "E1-RP01",
-        mortalityTable = mort.AT.census.2001.male,
-        cost = initializeCosts(alpha = 0.024, gamma.contract = 0.00075, unitcosts = 20),
-        i = 0.01)
-
-    ContractA = InsuranceContract$new(
-        tarif = Tarif.EndowmentA,
-        age = 40, policyPeriod = 20,
-        sumInsured = 10000,
-        contractClosing = as.Date("2000-07-01")
-    )
-
-
-    # premium-free extension
-    ContractB = ContractA$clone()$addExtension(id = "Verlängerung1", contractPeriod = 5, premiumPeriod = 0)
-    expect_equal(ContractB$blocks$Verlängerung1$Parameters$ContractData$sumInsured, 15117.03896)
-
-
-    # extension with given sumInsured resulting in 0 premiums
-    ContractC = ContractA$clone()$addExtension(id = "Verlängerung1", contractPeriod = 5, sumInsured = 15117.03896)
-    expect_equal(ContractC$blocks$Verlängerung1$Values$premiums[["gross"]], 0, tolerance = 1e-06)
-
-    # extension with increased sumInsured: real premiums are charged, reserves start from the existing reserve:
-    ContractD = ContractA$clone()$addExtension(id = "Verlängerung1", contractPeriod = 5, sumInsured = 20000)
-    expect_equal(ContractD$blocks$Verlängerung1$Values$premiums[["written"]], 315.109)
-    expect_equal(ContractD$blocks$Verlängerung1$Values$reserves[["0", "contractual"]], 10000)
-
-    # extension with increased sumInsured and different tariff: check whether interest rate has really changed
-    ContractE = ContractA$clone()$addExtension(id = "Verlängerung1", contractPeriod = 5, sumInsured = 20000, tarif = Tarif.EndowmentB)
-    expect_equal(unname(ContractE$Values$basicData[c(1,20,30,40), "InterestRate"]), c(0.03, 0.03, 0.01, 0.01))
-})
diff --git a/tests/testthat/test-premiumRefundPeriod.R b/tests/testthat/test-premiumRefundPeriod.R
deleted file mode 100644
index 40bb1fe89de459691b0398ebdbac47b4f6011184..0000000000000000000000000000000000000000
--- a/tests/testthat/test-premiumRefundPeriod.R
+++ /dev/null
@@ -1,55 +0,0 @@
-test_that("premiumRefundPeriod", {
-    library(MortalityTables)
-    mortalityTables.load("Austria_Annuities_AVOe2005R")
-
-    #--------------------------------------------------------------------------- -
-    # For deferred contracts, premium refund applies during deferral only by default
-    #--------------------------------------------------------------------------- -
-    Tarif.DefAnnuity = InsuranceTarif$new(
-        type = "annuity",
-
-        policyPeriod = function(params, values) { 120 - params$ContractData$age},
-        deferralPeriod = function(params, values) { 65 - params$ContractData$age},
-        premiumPeriod = function(params, values) { 65 - params$ContractData$age},
-        premiumRefund = 1,
-        mortalityTable = AVOe2005R.unisex
-    )
-    Contract.DefAnnuity = InsuranceContract$new(
-        tarif = Tarif.DefAnnuity,
-        age = 40, YOB = 1980,
-        sumInsured = 1200,
-        contractClosing = as.Date("2020-09-01"),
-        calculate = "cashflows"
-    )
-    expect_equal(Contract.DefAnnuity$Parameters$ContractData$policyPeriod, 80)
-    expect_equal(Contract.DefAnnuity$Parameters$ContractData$deferralPeriod, 25)
-    expect_equal(Contract.DefAnnuity$Parameters$ContractData$premiumPeriod, 25)
-    expect_equal(Contract.DefAnnuity$Parameters$ContractData$premiumRefundPeriod, 25)
-
-    # premium refund only during the frist 25 years (linearly increasing), then 0
-    expect_equal(Contract.DefAnnuity$Values$cashFlows[,"death_GrossPremium"], c(1:25, rep(0, 81-25)))
-    expect_equal(Contract.DefAnnuity$Values$cashFlows[,"death_Refund_past"], c(rep(1, 25), rep(0, 81-25)))
-
-
-
-    #--------------------------------------------------------------------------- -
-    # For all other contracts without deferral period, refund period is whole contract
-    #--------------------------------------------------------------------------- -
-    Tarif.PureEnd = InsuranceTarif$new(
-        type = "pureendowment",
-
-        policyPeriod = 25,
-        premiumRefund = 1,
-        mortalityTable = AVOe2005R.unisex
-    )
-    Contract.PureEnd = InsuranceContract$new(
-        tarif = Tarif.PureEnd,
-        age = 40, YOB = 1980,
-        sumInsured = 10000,
-        contractClosing = as.Date("2020-09-01"),
-        calculate = "cashflows"
-    )
-    # premium refund during the whole contract (25 years), the last year is the survival date without any death benefits
-    expect_equal(Contract.PureEnd$Values$cashFlows[,"death_GrossPremium"], c(1:25, 0))
-    expect_equal(Contract.PureEnd$Values$cashFlows[,"death_Refund_past"], c(rep(1, 25), 0))
-})
diff --git a/vignettes/.gitignore b/vignettes/.gitignore
deleted file mode 100644
index 097b241637da023174b0f2e3715bd0291d9ded37..0000000000000000000000000000000000000000
--- a/vignettes/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-*.html
-*.R
diff --git a/vignettes/creating-company-specific-implementations-as-package.Rmd b/vignettes/creating-company-specific-implementations-as-package.Rmd
index e7982e81adbf94f880b1be058468dec15639c391..c1830bf09d8912373ab866958957b049b0fb7fa4 100644
--- a/vignettes/creating-company-specific-implementations-as-package.Rmd
+++ b/vignettes/creating-company-specific-implementations-as-package.Rmd
@@ -16,273 +16,8 @@ vignette: >
   %\VignetteIndexEntry{Creating Company-Specific LifeInsuranceContracts Implementations (using an RStudio Package Template)}
   %\VignetteEncoding{UTF-8}
   %\VignetteEngine{knitr::rmarkdown}
-editor_options: 
-  markdown: 
-    wrap: 72
 ---
 
-```{r setup, echo = FALSE, message=FALSE}
-knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
-library(knitr)
-library(kableExtra)
-library(LifeInsuranceContracts)
-library(dplyr)
-library(tibble)
-library(lubridate)
-options(scipen=5)
+This package has been renamed from LifeInsuranceContracts to **LifeInsureR**!
 
-library(pander)
-```
-
-The LifeInsuranceContracts package provides a full-featured framework to
-model classical life insurance contracts (non-unit linked). This is
-typically sufficient to implement simple example calculations or
-validate a single contract or tariff by a single individual.
-
-However, when working for a company (either from inside the company or
-as an external consultant), one typically wants the implementation to be
-nicely structured, easily available for the whole team and still have
-the chance to improve the implementation. This can be achieved by
-encapsulating the company-specific tariff implementations in an R
-package that provides and exports the individual products of the
-company.
-
-The LifeInsuranceContracts package even provides an RStudio project
-template to create a new skeleton of a company-specific implementation
-to use as the foundation of such an implementation.
-
-# Creating an RStudio project from the template
-
-The `LifeInsuranceContracts` package provides an RStudio project
-template that sets up a package for a company-specific tariff
-implementation. After installing the package, simply create a new
-RStudio project from the template:
-
-![Menu item "File -\> New
-Project\..."](images/01_RStudio_ProjectTemplate_new.png){width="61%"}
-
-![Select "New
-Directory"](images/02_RStudio_ProjectTemplate_new.png){width="61%"}
-
-![Use the "LifeInsuranceContracts Implementation" project type![Name the
-directory and provide the company
-name](images/04_RStudio_ProjectTemplate_projectSettings.png){width="61%"}](images/03_RStudio_ProjectTemplate_selectTemplate.png){width="61%"}
-
-The resulting RStudio project will have the following file structure:
-
-![Package file structure generated by the project
-template](images/05_RStudio_ProjectTemplate_fileStructure.png)
-
--   The `DESCRIPTION` file provides the package name and its settings
-    (author, explanation, dependencies, etc.). This is typically the
-    first file to update.
-
--   The `NAMESPACE` file will be automatically handled by roxygen
-
--   The files in the `R/` subdirectory contain the tariff / product
-    definitions, i.e. they implement the `LifeInsuranceTarif` objects
-    for each product. The `*_General.R` file contains general
-    definitions, like mortality tables, parameter / cost sets, surrender
-    penalty functions, etc. and is typically sourced from each tariff's
-    implementation file.
-
--    The files in the `tests/testthat/` directory are unit tests for the
-    testthat package. Typically, you will use the example prescribed (by
-    the regulator) in the official tariff definitions as test cases, so
-    that the implementation will always correspond to the official
-    documents.
-
-# Implementing a full portfolio calculation
-
-Once the individual products are implemented in the R/ directory, one
-typical application is to use them for batch-testing the contract
-administration or financial statement system.
-
-To automate this, the template `[MyCompany]RechnungGesamtbestand.R` is
-provided in the project's top-level directory. It's purpose is to read
-in a set of contract data and calculate the corresponding reserves (e.g.
-to validate the official numbers in the financial statements).
-
-## Steps to implement batch-testing a whole (sub-)portfolio
-
-1.  Implement the corresponding products in the files in the `R/`
-    subdirectory. Use the LifeInsuranceContracts documentation available
-    at
-    <https://cran.r-project.org/web/packages/LifeInsuranceContracts/vignettes/using-the-lifeinsurancecontracts-package.html>
-
-2.  Install the package (using the "Install" button in RStudio's "Build"
-    pane)
-
-3.  Set up the mapping of the columns of the contract data source to the
-    package's arguments. The columns of the input data can be directly
-    mapped to named arguments in `LifeInsuranceContract$new(..)` calls.
-
-4.  If some columns need manual modifications (e.g. sex or frequencies
-    expressed with other values than the package expects), update the
-    `VTmodify.*` functions correspondingly.
-
-5.  Update the column types in the `readXXXCOMPANYXXXBestand(..)`
-    function. This helps preventing errors, as these columns are always
-    cast to the required type.
-
-6.  The `calculate_contract(..)` function might need to some adjustments
-    / modifications, in particular when modified contracts, premiums
-    waivers, additional tariffs / single-payment add-ons etc. are
-    present.
-
-7.  Depending on which columns / data are available in the
-    company-provided contract data, the column modifications /
-    calculations of other reserves, etc. at the end of the
-    `calculate_portfolio(…)` function might need to be adjusted.
-
-8.  Update the `files` and `outfile` variables to point to the input
-    files ("Bestandsdaten") and the output file name
-
-9.  Call the `calculate_portfolio` function on the contract data set
-    (potentially filtered to some subsets to prevent performance issues)
-
-Typically, a call to calculate a portfolio and store the results in a
-dedicated (Excel) output file is:
-
-```{r CalculatePortfolio,echo=TRUE,eval=FALSE}
-results = NULL;
-results = calculate_portfolio(bestandinfos.all,
-    tarif = c("ProdName1", "ProdName2"), GV = c("123"), debug =TRUE)
-openxlsx::write.xlsx(results, outfile("Prods-1-2"), 
-    asTable = TRUE, overwrite = TRUE, sheetName = "Vergleichsrechnung")
-openXL(outfile("Prods-1-2"))
-```
-
-## General Overview of the batch-calculation procedure 
-
-1.  The contract data are read in from the filenames provided in the
-    `files` list and stored in the data.frame called `bestandinfos.all`.
-
-    1.  Each file is read using the function `readXXXCOMPANYXXXBestand`.
-
-    2.  The `readXXXCOMPANYXXXBestand` function uses read_excel to read
-        in the raw data, then ensures the defined columns have the
-        proper data type.
-
-    3.  The columns are renamed according to the mapping in `colMapping`
-
-    4.  All contracts are sorted by `Polizzennummer`
-
-    5.  Additional modifications are done by the function
-        `VTmodify.general`.
-
-    6.  Further custom modifications can be manually added either in
-        `readXXXCOMPANYXXXBestand` or in `VTmodify.general`
-
-2.  All contracts are calculated by a call to `calculate_portfolio`. The
-    arguments `tarif` and `GV` can be used to restrict the calculation
-    only to certain products and/or profit classes. Additionally,
-    `n_max` can be used to calculate only the first `n_max` contracts.
-    The `calculate_portfolio` function does its work with the following
-    steps:
-
-    1.  The portfolio data is filted with the given tariff, GV, skip,
-        n_max arguments
-
-    2.  Only the relevant columns of the portfolio data are taken, some
-        sanity checks (sumInsured \> 0, premiumFrequency \>= 0) are
-        applied.
-
-    3.  Grouping happens by column `SliceID`. This allows multiple
-        portfolio data rows to be combined to one contract with several
-        slices / sum increases, which are calculated as one contract
-        (see section "10.3 Dynamic Increases" of the
-        LifeInsuranceContracts vignette). If each slice / dynamic
-        increase is supposed to be calculated individually and
-        independent from the main contract / other increases, then the
-        column mapped to the `SliceID` column needs to have a different
-        value for each portfolio data row. If `SliceID` uses contract
-        numbers, all dynamics, etc. belonging to the same contract
-        number will be combined and calculated using `$addDynamics`
-
-    4.  Each contract (entries with distinct `SliceID` value) is
-        calculated in a loop using the `by_slice` function, which calls
-        the `calculate_contract` function for each contract.
-
-3.  The `calculate_contract` function calculates one individual
-    contract, with the individual columns of the portfolio data passed
-    as named parameters to the function.
-
-    1.  A progress message is printed (if applicable)
-
-    2.  All slices are arranged by date, with the slice starting first
-        assumed to be the main contract part.
-
-    3.  For the main contract, an instance of the
-        `LifeInsuranceContract` (with the given tariff / product) is
-        created and all values of the contract are automatically
-        calculated by the package by default.
-
-    4.  All additional slices (e.g. dynamic increases) with the same
-        `SliceID` are added using the `$addDynamics` method of the
-        `LifeInsuranceContract` class. The slice start date and duration
-        are adjusted correspondingly.
-
-    5.  The reserves are extracted from the contract and stored in the
-        final `data.frame` z. If `debug=TRUE`, a column is added to the
-        resulting data.frame containing the R code to reproduce with
-        full contract.
-
-    6.  The `calculate_portfolio` combines the `data.frame`s returned
-        for each contract's `calculate_contract` call into one large
-        data frame, adds some derived columns and returns the data frame
-        as result of the calculations.
-
-## Column Mapping
-
-The following columns / named parameters are typically used by a
-`LifeInsuranceTariff` implementation or the concrete contract as a
-`LifeInsuranceContract` object. Most parameters are not mandatory.
-Additional arguments / columns are possible and will be preserved, even
-if they are not used by the contract.
-
--   `Polizzennummer`
-
--   `SliceID`
-
--   `balanceSheetDate`
-
--   `tarif`
-
--   `GV`
-
--   `i`
-
--   `sex`
-
--   `age`
-
--   `contractClosing`
-
--   `sliceDate`
-
--   `policyPeriod`
-
--   `premiumPeriod`
-
--   `premiumFrequency`
-
--   `annuityFrequency`
-
--   `sumInsured`
-
-Columns used for comparison with the calculated values:
-
--   `Bruttoprämie`
-
--   `Sparprämie`
-
--   `Risikoprämie`
-
--   `Kostenprämie`
-
--   `Bilanzreserve`
-
--   `Gewinnreserve`
-
--   `Prämienübertrag`
+For the documentation, see <https://cran.r-project.org/web/packages/LifeInsureR/vignettes/using-the-lifeinsurer-package.html>!
diff --git a/vignettes/images/01_RStudio_ProjectTemplate_new.png b/vignettes/images/01_RStudio_ProjectTemplate_new.png
deleted file mode 100644
index 1d17a679958ada8fe63ecd10f2f0d3008794fcd1..0000000000000000000000000000000000000000
Binary files a/vignettes/images/01_RStudio_ProjectTemplate_new.png and /dev/null differ
diff --git a/vignettes/images/02_RStudio_ProjectTemplate_new.png b/vignettes/images/02_RStudio_ProjectTemplate_new.png
deleted file mode 100644
index ba76420ef8ac75202e1e189b056754c41de7ed4e..0000000000000000000000000000000000000000
Binary files a/vignettes/images/02_RStudio_ProjectTemplate_new.png and /dev/null differ
diff --git a/vignettes/images/03_RStudio_ProjectTemplate_selectTemplate.png b/vignettes/images/03_RStudio_ProjectTemplate_selectTemplate.png
deleted file mode 100644
index 4ce31e7ade7b082a66247a3709d8b5701980b259..0000000000000000000000000000000000000000
Binary files a/vignettes/images/03_RStudio_ProjectTemplate_selectTemplate.png and /dev/null differ
diff --git a/vignettes/images/04_RStudio_ProjectTemplate_projectSettings.png b/vignettes/images/04_RStudio_ProjectTemplate_projectSettings.png
deleted file mode 100644
index 9ac947cb71b2a56be2e0dacfba83c1647d205dd1..0000000000000000000000000000000000000000
Binary files a/vignettes/images/04_RStudio_ProjectTemplate_projectSettings.png and /dev/null differ
diff --git a/vignettes/images/05_RStudio_ProjectTemplate_fileStructure.png b/vignettes/images/05_RStudio_ProjectTemplate_fileStructure.png
deleted file mode 100644
index 96de59c51dcda3532156b5026f0b382aa11becaa..0000000000000000000000000000000000000000
Binary files a/vignettes/images/05_RStudio_ProjectTemplate_fileStructure.png and /dev/null differ
diff --git a/vignettes/using-the-lifeinsurancecontracts-package.Rmd b/vignettes/using-the-lifeinsurancecontracts-package.Rmd
index cdaed0e1ded7fadc601b1b31b5b22848a88c615b..13331421c8b3168241f107d7f79b900112fc6aa0 100644
--- a/vignettes/using-the-lifeinsurancecontracts-package.Rmd
+++ b/vignettes/using-the-lifeinsurancecontracts-package.Rmd
@@ -19,2282 +19,7 @@ vignette: >
   %\VignetteEncoding{UTF-8}
 ---
 
+This package has been renamed from LifeInsuranceContracts to LifeInsureR! 
 
-```{r setup, echo = FALSE, message=FALSE}
-knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
-library(knitr)
-library(kableExtra)
-library(LifeInsuranceContracts)
-library(dplyr)
-library(tibble)
-library(lubridate)
-options(scipen=5)
-
-library(pander)
-
-panderOptions('round', 2)
-panderOptions('digits', 12)
-panderOptions('keep.trailing.zeros', TRUE)
-panderOptions('table.split.table', 120)
-
-kableTable = function(grd, ...) {
-  grd %>% 
-    kable(...) %>% 
-    add_header_above(header = c(1, dim(grd)[[2]]) %>% `names<-`(names(dimnames(grd))), align = "c") %>%
-    kable_styling(bootstrap_options = c("striped", "hover", "condensed", "responsive"), full_width = F) %>%
-    column_spec(1, bold = T, border_right = T)
-}
-
-```
-
-
-The LifeInsuranceContracts package provides a full-featured framework to model classical life insurance contracts (non-unit linked). Mathematically, a general life insurance contracts can be defined using death and survival (and disability) benefit vectors to define the cash flows and calculate all premiums and reserves recursively. This powerful approach is taken by the LifeInsuranceContracts package to provide the most flexible contract modelling framework in R.
-
-# General Overview of the Concepts
-
-An insurance contract is described by three different objects;
-
-* `InsuranceContract`: The object describing the actual contract with all 
-  contract-specific parameters (age, maturity, sum insured, etc.).
-* `InsuranceTarif`: The general (contract-independent) description of the
-  insurance product (benefits, present values / reserves, premium calculation,
-  premium waivers, surrender value, reserve calculation, premium decomposition).
-  It does not store any values (only tarif-provided default values for the 
-  insurance contract), but provides all calculation functions. The implementation
-  is based on a general approach using cash flows (depending on the type of 
-  insurance). Once the cash flows (survival, death and guaranteed) are defined
-  for all time steps, all further calculations are idential for all different 
-  kinds of life insurance.
-* ` ProfitParticipation`: For contracts with profit sharing mechanisms, this
-  object describes the profit participation (like the `InsuranceTarif` object
-  describes the guaranteed payments) and us used by the `InsuranceContract` 
-  object.
-
-
-The tariff and the profit scheme are purely descriptional and their creation does
-not trigger any calculations. 
-However, when one creates a contract for a given tariff, the following steps are 
-done to calculate all values relevant for the contract:
-
-* Extract the transition probabilities (mortality)
-* Set up all cash flow time series (premiums, guaranteed payments, survival payments, death payments, disease payments, charged cost cash flows)
-* Calculate all present values for each time for all the cash flows (benefits, premiums and costs)
-* Use the actuarial equivalence principle and the present values at time $t=0$ to calculate the premium of the contract
-* Express all cash flows also in absolute (monetary) terms
-* Calculate the reserves at every moment
-* Calculate the premium decomposition
-* Apply the (optional) profit participation scheme with the given profit scenario
-* Optionally apply contract changes (premiums waivers, dynamic) and further profit scenarios
-
-All steps after the cash flow setup are implemented in a very generic way, as 
-the cash flows fully determine an insurance contract and as soon as the cash 
-flows are fixed, the valuation and reserve calculation can be expressed in 
-terms of expected present values of the cash flows only.
-
-While this might at first seem a bit complicated, it allows for very generic
-implementations of life insurance products and contracts.
-
-
-# A simple example: Term life insurance
-
-To understand how the package implements life insurance contracts, let us look
-at a simple example:
-
-## Product description
-
-Term Life Insurance 
-
-* Public product name '**DeathPlus - Short Term Life Insurance**', Internal ID '**L71-U**'
-* Only **death benefits**, no survival benefits
-* **Mortality table**: Austrian 2010/12 census table unisex (mixed 65:35 from the male:female tables)
-* **Guaranteed interest rate**: 0.5%
-* Default contract duration: 5 years (to keep the example short)
-* **Regular premium** payments (constant premiums) during the whole contract
-<!-- * premiums paid more often than once a year in advance get the following surcharge: -->
-<!--     * yearly premiums: 0% surcharge -->
-<!--     * half-yearly premiums: 1% surcharge -->
-<!--     * quarterly premiums: 1.5% surcharge -->
-<!--     * monthly premiums: 2% surcharge -->
-
-**Costs**:
-
-* Aquisition costs: 5\% of the total premium sum
-* Administration cost: 1% of the sum insured per year (both during premium payments as well as for paid-up contracts)
-* Unit costs: 10 Euro per year (fixed) during premium payments
-* Tax: 4% insurance tax (default)
-
-Surrender Value:
-
-* Reserve minus 10% surrender penalty, also applied on premium waiver
-
-
-## Tariff implementation (InsuranceTarif)
-
-```{r SimpleExampleRiskTarif, warning=F, results="hide", message = F}
-library(magrittr)
-library(MortalityTables)
-library(LifeInsuranceContracts)
-mortalityTables.load("Austria_Census")
-
-Tarif.L71U = InsuranceTarif$new(
-    name = "L71-U",
-    type = "wholelife",
-    tarif = "DeathPlus - Short Term Life Insurance",
-    desc = "Term Life insurance (5 years) with constant sum insured and regular premiums",
-    policyPeriod = 5, premiumPeriod = 5,  # premiumPeriod not needed, defaults to maturity
-
-    mortalityTable = mortalityTable.mixed(
-      table1 = mort.AT.census.2011.male, weight1 = 0.65, 
-      table2 = mort.AT.census.2011.female, weight2 = 0.35
-    ),
-    i = 0.005, 
-    tax = 0.04, 
-    costs = initializeCosts(alpha = 0.05, gamma = 0.01, gamma.paidUp = 0.01, unitcosts = 10),
-    surrenderValueCalculation = function(surrenderReserve, params, values) { 
-      surrenderReserve * 0.9 
-    }
-);
-```
-
-## Creating a contract
-
-With the above product / tariff definition, it is now easy to instantiate 
-one particular contract for this tariff. All we need to do is pass the tariff
-and the corresponding contract-specific information (mainly age, sum insured
-and contract closing) to the `InsuranceContract` object:
-
-```{r SimpleExampleRiskContract}
-contract.L71U  = InsuranceContract$new(
-  Tarif.L71U, 
-  age = 35, 
-  contractClosing = as.Date("2020-08-18"), 
-  sumInsured = 100000);
-```
-
-Just creating the contract will already calculate all cash flows, present values,
-premiums, reserves, etc. for the whole contract period. They can be accessed 
-through the `contract.L71U$Values` list.
-
-A full list of all possible arguments can be found in the section [All possible parameters and their default values].
-
-
-Once the contract is created, all values can be accessed like this:
-
-```{r SimpleExampleRiskValuesPremCode, eval=F}
-contract.L71U$Values$premiums
-```
-```{r SimpleExampleRiskValuesPremCodeOut, echo=F}
-contract.L71U$Values$premiums %>% kable
-```
-```{r SimpleExampleRiskValuesResCode, eval=F}
-contract.L71U$Values$reserves
-```
-```{r SimpleExampleRiskValuesResOut, echo=F}
-contract.L71U$Values$reserves %>% pander()
-```
-
-Looking back at the definition of the tariff, the only spot where the type of
-insurance actually came in was the `type` argument of the `InsuranceTarif`
-definition. This is one of the most important flags and is central to correct
-implementation of a tarif. On the other hand, all it does is to cause different
-vectors of survival, death and guaranteed cash flows. Once the cash flows are 
-determined, the insurance contract and tariff does not need the insurance type
-any more.
-
-In our term life example, the insurance contract's unit cash flows are 1 for death 
-benefits (both when premiums are paid and when the contract is paid-up) and for
-premiums in advance. All other cash flows (guaranteed, survival or disease cash 
-flows) are zero. Similarly, the cost structure described above and implemented
-by the `LifeInsuranceContracts::initializeCosts()` function defines all cost cash
-flows, which are the starting point for all further calculations (only relevant 
-columns of the data.frame are shown):
-
-```{r SimpleExampleRiskCFCode, eval=F}
-contract.L71U$Values$cashFlows
-```
-```{r SimpleExampleRiskCFOut, echo=F}
-contract.L71U$Values$cashFlows %>% select(starts_with('premiums'), starts_with('death'), -death_Refund_past ) %>% pander()
-```
-```{r SimpleExampleRiskCFCostCode, eval=F}
-contract.L71U$Values$cashFlowsCosts[,,,"survival"]
-```
-```{r SimpleExampleRiskCFCostOut, echo=F, results="asis"}
-for (base in dimnames(contract.L71U$Values$cashFlowsCosts)[[3]]) {
-  cat("* ,,\"", base, "\"\n", sep = "")
-  cat(contract.L71U$Values$cashFlowsCosts[,,base, "survival"] %>% pander(round = 4, style = "rmarkdown"))
-}
-```
-
-Once these unit cash flows are set, all insurance contracts are handled identically.
-First, present values of each of the cash flows are calculated, from which 
-the premiums can be calculated by the equivalence principle.
-
-```{r SimpleExampleRiskPVCode, eval=F}
-contract.L71U$Values$presentValues
-```
-```{r SimpleExampleRiskPVOut, echo=F}
-contract.L71U$Values$presentValues %>% as.data.frame() %>% select(starts_with('premiums'), starts_with('death'), -death_Refund_past ) %>% pander(round=5)
-```
-```{r SimpleExampleRiskPVCostCode, eval=F}
-contract.L71U$Values$presentValuesCosts
-```
-```{r SimpleExampleRiskPVCostOut, echo=F, results="asis"}
-for (base in dimnames(contract.L71U$Values$presentValuesCosts)[[3]]) {
-  cat("* ,,\"", base, "\"\n", sep = "")
-  cat(contract.L71U$Values$presentValuesCosts[,,base,"survival" ] %>% pander(round = 4, style = "rmarkdown"))
-}
-```
-```{r SimpleExampleRiskPVPremCode, eval=F}
-contract.L71U$Values$premiums
-```
-```{r SimpleExampleRiskPVPremOut, echo=F}
-contract.L71U$Values$premiums %>% data.frame() %>% pander()
-```
-
-The actual calculation of the premiums has to be in the order gross premium, 
-Zillmer premiuem, then net premium. The reason for this particular order is that
-some tariffs have a gross premium refund in case of death. So to calculate the
-net premium, the gross premium is required. 
-
-The premiums allow the unit cash flows and present values to be converted to 
-monetary terms (fields `contract.L71U$Values$absCashFlows` and 
-`contract.L71U$Values$absPresentValues`). Also, the reserves of the 
-contract can be calculated.
-
-```{r SimpleExampleRiskPremiumsCode, eval=F}
-contract.L71U$Values$reserves
-```
-```{r SimpleExampleRiskPremiumsOut, echo=F}
-contract.L71U$Values$reserves %>% pander(digits=2)
-```
-
-Also, the premium composition into costs, risk premium, savings premium and 
-other components is possible.
-
-```{r SimpleExampleRiskPremiumCompositionCode, eval=F}
-contract.L71U$Values$premiumComposition
-```
-```{r SimpleExampleRiskPremiumCompositionOut, echo=F}
-contract.L71U$Values$premiumComposition %>% as.data.frame() %>% select(-loading.frequency, -rebate.premium, -rebate.partner, -profit.advance, -rebate.sum, -charge.noMedicalExam, -premium.risk.actual, -premium.risk.security, -risk.disease, -premium.risk.disease.actual, -premium.risk.disease.security, -starts_with('Zillmer')) %>% pander()
-```
-
-
-
-
-As we see, the whole history and future of the contract is calculated as soon 
-as it is created. It is, however, also possible to modify a contract later on,
-e.g. by stopping premium payments and converting it to a paid-up contract.
-
-```{r SimpleExampleRiskConversionCode, eval=F}
-contract.L71U.prf = contract.L71U$premiumWaiver(t = 3)
-contract.L71U.prf$Values$reserves
-```
-```{r SimpleExampleRiskConversionOut, echo=F}
-contract.L71U.prf = contract.L71U$premiumWaiver(t = 3)
-contract.L71U.prf$Values$reserves %>% pander()
-```
-
-
-
-## Creating tables with various parameters
-
-When prototyping a new product or creating marketing material, it is often needed
-to create tables of premiums, reserves, benefits or surrender values for different
-parameters (e.g. different ages, maturities and sums insured for the marketing 
-department, or different guaranteed interest rates, mortality tables or costs 
-for the product development group). 
-
-This can be easily done by the functions `contractGridPremium()` or `contractGrid()`.
-They take one argument `axes`, which gives the parameters for the axes of
-the table (more than two dimensions are possible!), while all other parameters
-are passed unchanged to `InsuranceContract$new()`.
-
-
-First, let us create a grid of premiums for different ages and maturities (for 
-sum insured 100,000 Euro):
-```{r SimpleExampleRiskPremiumGrid, eval=T, results="hide"}
-grd = contractGridPremium(
-  axes = list(age = seq(20, 80, 5), policyPeriod = seq(10, 40, 5)),
-  tarif = Tarif.L71U, 
-  contractClosing = as.Date("2020-08-18"), 
-  sumInsured = 100000
-)
-grd
-```
-```{r SimpleExampleRiskPremiumGridOut, echo = F}
-grd %>% kableTable(digits = 2)
-
-```
-
-One can also pass more than two dimensions to the axes:
-```{r SimpleExampleRiskPremiumGrid3D, results = "hide"}
-grd = contractGridPremium(
-  axes = list(age = seq(20, 80, 10), policyPeriod = seq(10, 40, 10), sumInsured = c(10000, 50000, 100000)),
-  tarif = Tarif.L71U, 
-  contractClosing = as.Date("2020-08-18")
-)
-grd
-```
-```{r SimpleExampleRiskPremiumGrid3DOut, echo=F, results="asis"}
-for (d in dimnames(grd)[[3]]) {
-  cat("\n", "* , , ", names(dimnames(grd))[[3]], "=",  d, "\n\n", sep = "")
-  # cat(grd[,,d ] %>% as.data.frame() %>% rownames_to_column("age \\|  policyPeriod") %>% pander(digits = 7, round = 2, style = "rmarkdown"))
-  cat(grd[,,d ] %>% kableTable(digits = 2), "\n")
-}
-
-```
-
-
-One can use any of the parameters of the `InsuranceContract$new()` call in the
-`axes` argument, even the `tarif` or `mortalityTable` parameters. 
-This means that one can create tables comparing different tariffs, or showing
-the effect of different life tables.
-
-In the following example, we use the tarif `Tarif.L71U`, but instead of the
-unisex table (mixed 65:35 from male:female tables), we use the male mortality tables
-of the Austrian census from 1870 to 2011 (with a contract period of 10 years fixed, and varying ages):
-
-```{r SimpleExampleRiskPremiumGridLifeTables, results = "hide"}
-grd = contractGridPremium(
-  axes = list(mortalityTable = mort.AT.census["m", ], age = seq(20, 80, 10)),
-  tarif = Tarif.L71U, 
-  sumInsured = 100000,
-  contractClosing = as.Date("2020-08-18")
-) 
-grd
-```
-```{r SimpleExampleRiskPremiumGridLifeTablesOUT, echo = F}
-grd %>% pander(round=1, digits=15, keep.trailing.zeros = T)
-```
-
-
-# All possible parameters
-
-All possible parameters of an insurance contract are stored in sub-lists of a a structure 
-`InsuranceContract.Parameters`. If not provided by the call to `InsuranceContract$new()`, 
-the values will be taken from either the `InsuranceTariff`'s default parameters, 
-the `ProfitParticipation`'s default parameters or the global defaults in the 
-`InsuranceContract.ParameterDefault`. The cascade or parameters is (from top to
-bottom):
-
-* explicit parameters passed to `InsuranceContract$addProfitScenario()` (applies 
-  only for the added profit scenario)
-* explicit parameters passed to `InsuranceContract$new()` or `InsuranceContract$clone()`
-* parameters set with the `ProfitParticipation`
-* parameters set with the `InsuranceTarif`
-* Default values set in `InsuranceContract.ParameterDefaults`
-
-In addition to the parameters listed below, the `InsuranceContract$new()`
-constructor function takes the following parameters
-
-\define{
-\item{tarif}{The `InsuranceTarif` object describing the tarif}
-\item{parent}{For contracts with multiple parts, children get passed a pointer to the parent}
-\item{calculate}{How much of the contract to calculate (by default everything will be calculated)}
-\item{profitid}{The profit ID for contracts with profit participation}
-}
-
-```{r}
-str(InsuranceContract.ParameterDefaults)
-```
-```{r, results="asis"}
-# pandoc.listRK(InsuranceContract.ParameterDefaults)
-```
-
-# Tarif and Contract Specification
-
-An insurance contract is modelled by the abstract product specification 
-(`InsuranceTarif` class) and the concrete (individualized) `InsuranceContract`. 
-
-* The `InsuranceTarif` object describes the product in abstract terms, holds
-  default parameters and provides all calculation functions for cash flows, 
-  present values, premiums and reserves (provided the contract's actual Parameters).
-  It does not, however, hold contract-specific data.
-* The `InsuranceContract` object holds the individual contract data (like age, contract 
-  closing date, sum insured, etc.) that override the tariff's defaults. It also 
-  holds a pointer to the insurance tariff and provides the general logic to
-  calculate all parts of an insurance contract by calling the corresponding 
-  functions of the tariff.
-
-The insurance contract and the underlying insurance tariff have the same possible 
-parameters in its constructors: The `InsuranceTarif` uses them to define defaults
-for contracts that use the tariff, while the parameters passed to the contract
-either provide the individually required data like age, sum insured or maturity, 
-or they can override the defaults provided by the tariff. In theory, one could
-even create a contract with an empty underlying tariff and provide all tariff-specific
-parameters also in the contract's `new` call.
-
-## Creating the tariff
-
-The `InsuranceTarif` class provides a way to define an abstract insurance product.
-The most important parameters to be passed in the  `InsuranceTarif$new()` call are:
-
-| | |
-|:-----|:----------|
-|**General settings for the Tariff** ||
-| `name`, `tarif`, `desc` | IDs and human-readable descriptions of the insurance product. They are just used as labels and array keys, but do not influence the calculations.|
-| `type` | the most important parameter, defining the type of life insurance product (endowment, pure endowment, annuity, whole life insurance, dread-disease insurance, etc.)|
-|**Actuarial Bases for the Tariff**  ||
-| `mortalityTable` | a `MortalityTable` Object (package "MortalityTables"), providing the transition probabilities (typically death probabilities, but potentially also morbidity in dread-disease insurances)|
-| `i` | Guaranteed interest rate|
-| `costs`, `unitcosts` | passed a data structure for all cost parameters (see below)|
-| `premiumFrequencyLoading` | surcharge for premium payments more often than yearly (as a named list)|
-| `premiumRefund` | how much of the (gross) premium paid is returned upon death (often provided e.g. in deferred annuities or pure endowments with no fixed death benefit)|
-| `tax` |insurance tax
-|**Benefit calculation** ||
-| `surrenderValueCalculation` | can be passed a hook function that calculates the surrender value given the current reserves at each time step|
-
-
-
-A typical call looks like the following for a pure endowment with gross premium
-refund upon death and a linearly decreasing surrender penalty:
-
-
-
-```{r TarifDefinition, message = F}
-Tarif.PureEnd = InsuranceTarif$new(
-  name = "Example Tariff - Pure Endowment",
-  type = "pureendowment",
-  tarif = "PE1-RP",
-  desc = "A pure endowment with regular premiums (standard tariff)",
-
-  mortalityTable = mort.AT.census.2011.unisex,
-  i = 0.005,
-  # Costs: 4% acquisition, where 2.5% are zillmered, 5\% of each premium as beta costs, 
-  #        1%o administration costs of the sum insured over the whole contract period
-  costs = initializeCosts(alpha = 0.04, Zillmer = 0.025, beta = 0.05, gamma.contract = 0.001, gamma.paidUp = 0.001),
-  unitcosts = 10,
-
-  # Yearly premiums get no surcharge, monthly premiums add +4%
-  premiumFrequencyLoading = list("1" = 0, "12" = 0.04),
-  premiumRefund = 1,  # Full gross premium refund upon death
-  tax = 0.04,         # 4% insurance tas
-
-  surrenderValueCalculation = function(surrenderReserve, params, values) {
-    n = params$ContractData$policyPeriod
-    # Surrender Penalty is 10% at the beginning and decreases linearly to 0%
-    surrenderReserve * (0.9 + 0.1 * (0:n)/n)
-  }
-)
-```
-
-Many parameters do not need to be given explicitly, but instead use sensible 
-defaults (like the `premiumPeriod`, which by default equals the whole contract 
-period, i.e. regular premium payments over the whole contract duration).
-
-To create a similar tariff with some changes, one can call the `createModification`
-method of the `InsuranceTarif` clas, which takes as arguments all insurance 
-parameters that should be changed for the new tarif. 
-
-To create a single-premium version of the pure endowment shown above, one can simply
-use a call like:
-
-```{r TarifDefinitionSP}
-Tarif.PureEnd.SP = Tarif.PureEnd$createModification(
-  name = "Example Tariff - Pure Endowment (SP)",
-  tarif = "PE1-SP",
-  desc = "A pure endowment with single premiums",
-  premiumPeriod = 1
-)
-```
-
-### Sample tariffs for the most common life insurance types
-
-For the examples in the remainder of this vignette, we can create some more
-example tariffs covering the most common types of life insurance. 
-
-
-**General definitions for all tariffs**
-```{r TarifDefinitions.All,message = F}
-library(MortalityTables)
-mortalityTables.load("Austria_Census")
-mortalityTables.load("Austria_Annuities_AVOe2005R")
-  # Costs: 4% acquisition, where 2.5% are zillmered, 5\% of each premium as beta costs, 
-  #        1%o acquisition costs of the sum insured over the whole contract period
-example.Costs = initializeCosts(
-  alpha = 0.04, Zillmer = 0.025, 
-  beta = 0.05, 
-  gamma.contract = 0.001, gamma.paidUp = 0.001
-)
-example.Surrender = function(surrenderReserve, params, values) {
-    n = params$ContractData$policyPeriod
-    # Surrender Penalty is 10% at the beginning and decreases linearly to 0%
-    surrenderReserve * (0.9 + 0.1 * (0:n)/n)
-}
-```
- 
-**Endowment**
-
-```{r TarifDefinitions.All.End}
-Tarif.Endowment = InsuranceTarif$new(
-  name = "Example Tariff - Endowment",
-  type = "endowment",
-  tarif = "EN1",
-  desc = "An endowment with regular premiums",
-
-  mortalityTable = mort.AT.census.2011.unisex,
-  i = 0.005,
-  costs = example.Costs,
-  unitcosts = 10,
-  tax = 0.04,         # 4% insurance tax
-  surrenderValueCalculation = example.Surrender
-)
-```
-
-**Whole / Term Life Insurance**
-```{r TarifDefinitions.All.Life}
-Tarif.Life = InsuranceTarif$new(
-  name = "Example Tariff - Whole/Term Life",
-  type = "wholelife",
-  tarif = "Life1",
-  desc = "A whole or term life insurance with regular premiums",
-
-  mortalityTable = mort.AT.census.2011.unisex,
-  i = 0.005,
-  costs = example.Costs,
-  unitcosts = 10,
-  tax = 0.04,         # 4% insurance tax
-  surrenderValueCalculation = example.Surrender
-)
-```
-
-**Immediate Annuity (single premium)**
-```{r TarifDefinitions.All.ImmAnnuity}
-Tarif.ImmAnnuity = InsuranceTarif$new(
-  name = "Example Tariff - Immediate Annuity",
-  type = "annuity",
-  tarif = "Ann1",
-  desc = "An annuity with single-premium",
-  premiumPeriod = 1,
-
-  mortalityTable = AVOe2005R.unisex,
-  i = 0.005,
-  costs = example.Costs,
-  tax = 0.04         # 4% insurance tax
-)
-```
-
-**Deferred Annuity**
-```{r TarifDefinitions.All.DefAnnuity}
-# Premium periods and deferral periods can also be given as a function of other
-# contract parameters (like the age at contract inception, etc.)
-Tarif.DefAnnuity = InsuranceTarif$new(
-  name = "Example Tariff - Deferred Annuity",
-  type = "annuity",
-  tarif = "Life1",
-  desc = "A deferred annuity (life-long payments start at age 65) with reg. premiums",
-
-  policyPeriod = function(params, values) { 120 - params$ContractData$age},
-  deferralPeriod = function(params, values) { 65 - params$ContractData$age},
-  premiumPeriod = function(params, values) { 65 - params$ContractData$age},
-    
-  mortalityTable = AVOe2005R.unisex,
-  i = 0.005,
-  costs = example.Costs,
-  tax = 0.04,         # 4% insurance tax
-  surrenderValueCalculation = example.Surrender
-)
-```
-
-**Dread-Disease Insurance**
-```{r TarifDefinitions.All.DD}
-# An example dread-disease tariff, morbidity is assumed linearly increasing with age
-ddTable = mortalityTable.period(name = "Linear dread-disease table", 
-                                ages = 0:100, deathProbs = 0:100/500)
-Tarif.DreadDisease = InsuranceTarif$new(
-  name = "Example Tariff - Dread-Disease",
-  type = "dread-disease",
-  tarif = "DD1",
-  desc = "A dread disease insurance with a lump-sum payment upon diagnosis",
-
-  sumInsured = 50000,
-  mortalityTable = mort.AT.census.2011.unisex,
-  invalidityTable = ddTable,
-  i = 0.005,
-  costs = example.Costs,
-  unitcosts = 10,
-  tax = 0.04,         # 4% insurance tax
-  surrenderValueCalculation = example.Surrender
-)
-```
-
-## Creating a contract
-
-While the tariff describes the general product features, the contract object
-holds the data of a concrete contract. All insurance parameters (see section 
-[All possible parameters and their default values]) can be given to override
-tarif defaults. 
-
-However, the most important and often used parameters are:
-
-|  |  |
-|:-----|:---------|
-|**Information about insuree** |
-| `age` |the age of the insured person at contract start
-| `YOB` | the year of birth of the insured person (`age`, `YOB` and `contractClosing` are redundant, at most two need to be given). YOB is only relevant for cohort mortality tables. For period life tables (which are independent of the birth year of the person), this parameter is not needed. |
-| `sex` | relevant for sex-specific life tables (common in the past) |
-|**Contract details** |
-| `sumInsured` | the benefit when the insured event happens. Typically the lump sum for whole life insurances or endowments, or the (yearly) payment for annuities |
-| `policyPeriod` | the duration of the whole contract |
-| `premiumPeriod` | how long premiums are paid (1 for single-premiumcontracts, equal to `policyPeriod` (default) for regular premiums) |
-| `premiumFrequency` | how often premiums are paid within a year (e.g.1 for yearly premiums, 4 for quarterly, 12 for monthly) |
-| `contractClosing` | the starting date of the contract |
-| `deathBenefit` | gives the factor of death benefit relative to the sum insured / survival benefit of endowments (1 means equal death and survival probabilities), can also be a function with non-constant values over time |
-| `noMedicalExam`, `noMedicalExamRelative`, `sumRebate`, `extraRebate`, `premiumRebate` | various types of rebates or charges. They can either be defined in general functional form in the tariff to apply to all contracts, or given individually for each contract. For the details, when each of these rebates are applied, check the formula reference document.|
-  
-
-
-For the pure endowments defined above, a typical contract would be created like
-this:
-
-```{r Contract}
-contract.PureEnd = InsuranceContract$new(
-    Tarif.PureEnd,
-    age = 50, policyPeriod = 20, 
-    premiumFrequency = 12,
-    sumInsured = 100000,
-    contractClosing = as.Date("2020-07-01")
-  )
-```
-
-```{r Contract.premiums,eval=F}
-contract.PureEnd$Values$premiums
-```
-
-```{r Contract.premiumsOUT, echo = F}
-contract.PureEnd$Values$premiums %>% kable(digits=4)
-```
-```{r Contract.premiumComposition,eval=F}
-contract.PureEnd$Values$premiumComposition
-```
-```{r Contract.premiumCompositionOUT, echo = F}
-contract.PureEnd$Values$premiumComposition %>% as.data.frame() %>% rowid_to_column("t") %>% mutate(t = t-1) %>% select(t, charged, tax, loading.frequency, gross, gamma, beta, alpha, alpha.noZillmer, alpha.Zillmer,  Zillmer, net, risk, savings) %>% pander
-```
-
-Due to the full premium refund in case of death, there is only very little 
-biometric risk involved. If the premium refund is not included in the contract,
-then we have a negative biometric risk over the whole period (i.e. negative 
-risk premium, because upon death the existing reserves is shared with the 
-collective). The premium refund can be overridden directly in the contract call:
-
-```{r ContractNoRefund}
-contract.PureEnd.NoRefund = InsuranceContract$new(
-    Tarif.PureEnd,
-    age = 50, policyPeriod = 20, 
-    premiumFrequency = 12,
-    sumInsured = 100000,
-    contractClosing = as.Date("2020-07-01"),
-    premiumRefund = 0
-  )
-
-```
-```{r Contract.premiumsCode, eval = F}
-cbind(`With refund` = contract.PureEnd$Values$premiums, `Without refund` = contract.PureEnd.NoRefund$Values$premiums)
-```{r Contract.premiumsOut, echo = F}
-cbind(`With refund` = contract.PureEnd$Values$premiums, `Without refund` = contract.PureEnd.NoRefund$Values$premiums) %>% pander
-```
-```{r Contract.riskpremiumsCode, eval = F}
-cbind(
-  `Gross premium with refund` = contract.PureEnd$Values$premiumComposition[,"gross"],
-  `Gross premium w/o refund` = contract.PureEnd.NoRefund$Values$premiumComposition[,"gross"],
-  `Risk premium with refund` = contract.PureEnd$Values$premiumComposition[,"risk"],
-  `Risk premium w/o refund` = contract.PureEnd.NoRefund$Values$premiumComposition[,"risk"]
-)
-
-```{r Contract.riskpremiumsOut, echo = F}
-cbind(
-  `Gross premium with refund` = contract.PureEnd$Values$premiumComposition[,"gross"],
-  `Gross premium w/o refund` = contract.PureEnd.NoRefund$Values$premiumComposition[,"gross"],
-  `Risk premium with refund` = contract.PureEnd$Values$premiumComposition[,"risk"],
-  `Risk premium w/o refund` = contract.PureEnd.NoRefund$Values$premiumComposition[,"risk"]
-) %>% as_tibble() %>% rowid_to_column("t") %>% mutate(t = t-1) %>% pander
-```
-
-
-To create a single-premium contract, one can either use the single-premium tarif
-defined above, or simply pass `premiumPeriod=1` to the call:
-
-```{r Contract.SP}
-contract.PureEnd.SP1 = InsuranceContract$new(
-    Tarif.PureEnd,
-    age = 40, policyPeriod = 45, premiumPeriod = 1,
-    sumInsured = 100000,
-    contractClosing = as.Date("2020-07-01")
-  )
-contract.PureEnd.SP2 = InsuranceContract$new(
-    Tarif.PureEnd.SP,
-    age = 40, policyPeriod = 45, # premiumPeriod already set by tariff!
-    sumInsured = 100000,
-    contractClosing = as.Date("2020-07-01")
-  )
-
-all_equal(contract.PureEnd.SP1$Values$reserves, contract.PureEnd.SP2$Values$reserves)
-
-```
-
-
-## Determining Sum Insured from the premium
-
-By default, the insurance contract is created for a given sum insured and the 
-premiums are calculated accordingly. Sometimes, the reverse is needed: The 
-premium (either actuarial gross premium, written premium before or after taxes) 
-is given and the corresponding sum insured should be determined automatically.
-
-The `InsuranceContract` constructor / parameter set has an additional field 
-`premium` to indicate the desired premium (written premium after tax by default) 
-from which the sum insured is then calculated:
-```{r PrescribePremium}
-# Premium calculated from sumInsured
-contract.End = InsuranceContract$new(
-  Tarif.Endowment, age = 35, policyPeriod = 10,
-  contractClosing = as.Date("2020-08-18"), 
-  sumInsured = 10000);
-
-# sumInsured derived from written premium
-contract.End.premium = InsuranceContract$new(
-  Tarif.Endowment, age = 35, policyPeriod = 10,
-  contractClosing = as.Date("2020-08-18"), 
-  premium = 1139.06);
-
-contract.End.premiumBeforeTax = InsuranceContract$new(
-  Tarif.Endowment, age = 35, policyPeriod = 10,
-  contractClosing = as.Date("2020-08-18"), 
-  premium = c(written_beforetax = 1095.25));
-
-contract.End.premiumGross = InsuranceContract$new(
-  Tarif.Endowment, age = 35, policyPeriod = 10,
-  contractClosing = as.Date("2020-08-18"), 
-  premium = c(gross = 1085.25));
-
-```
-```{r PrescribePremiumOUTPUT,echo = FALSE}
-bind_rows(
-  c(Contract = "contract.End", contract.End$Values$premiums[c("net", "Zillmer", "gross", "written_beforetax", "written")], sumInsured = contract.End$Parameters$ContractData$sumInsured),
-  c(Contract = "contract.End.premium", contract.End.premium$Values$premiums[c("net", "Zillmer", "gross", "written_beforetax", "written")], sumInsured = contract.End.premium$Parameters$ContractData$sumInsured),
-  c(Contract = "contract.End.premiumBeforeTax", contract.End.premiumBeforeTax$Values$premiums[c("net", "Zillmer", "gross", "written_beforetax", "written")], sumInsured = contract.End.premiumBeforeTax$Parameters$ContractData$sumInsured),
-  c(Contract = "contract.End.premiumGross", contract.End.premiumGross$Values$premiums[c("net", "Zillmer", "gross", "written_beforetax", "written")], sumInsured = contract.End.premiumGross$Parameters$ContractData$sumInsured)
-)
-```
-
-The final written premium can be directly passed as the `premium` argument. Other
-types of premium must be passed as a named number (i.e. a one-element vector with
-name "gross", "written_beforetax" or "written").
-
-If a premium is prescribed, a `sumInsured` must not be given. If both are given, 
-the sumInsured is used and the prescribed premium is silently ignored.
-
-The are cases, when the sumInsured cannot be derived from a prescribed premium.
-One relevant case is when a premium rebate depends on the sum insured, since in 
-this case we need the sumInsured to calculate the rebate and thus the premium.
-All rebates, add-ons and other parameters will temporarily use a sumInsured=1 
-during the calculation of the actual sumInsured!
-
-
-
-## Providing additional capital at contract inception
-
-Often, when a contract is changed significantly, this is modelled as a totally 
-new contract, with the existing reserve provided as additional one-time payment
-for the follow-up contract. This is different from a single-premium contract, 
-because the new contract can have regular premiums, just the existing reserve
-is used as the initial reserve of the new contract.
-
-The package provides the argument `initialCapital` to provide initial capital
-that is also included in the calculation of the premium of the contract.
-
-```{r InitialCapital}
-# Contract with initial capital of 5.000 EUR
-contract.Endow.initialCapital = InsuranceContract$new(
-  tarif = Tarif.Endowment,
-  sumInsured = 10000,
-  initialCapital = 5000,
-  age = 40, policyPeriod = 10,
-  contractClosing = as.Date("2020-09-01")
-)
-# For comparison: Contract without initial capital of 5.000 EUR
-contract.Endow = InsuranceContract$new(
-  tarif = Tarif.Endowment,
-  sumInsured = 10000,
-  age = 40, policyPeriod = 10,
-  contractClosing = as.Date("2020-09-01")
-)
-```
-Comparing the reserves, one can clearly see the initial capital used as initial reserve:
-
-```{r InitialCapitalOUTPUT}
-data.frame(
-  `Premium with initialCapital`= contract.Endow.initialCapital$Values$premiumComposition[,"charged"], 
-  `Premium without initialCapital`= contract.Endow$Values$premiumComposition[,"charged"], 
-  `Res.with initialCapital`= contract.Endow.initialCapital$Values$reserves[,"contractual"], 
-  `Res.without initialCapital`= contract.Endow$Values$reserves[,"contractual"]
-)
-```
-
-
-## Premium Waivers
-
-After a while, many customers do not want to pay premiums for the contract any 
-more and convert the contract to a paid-up contract. The unit benefit cash flows
-from that moment on stay the same, but the sum insured is adjusted, so that the 
-existing reserve is able to cover all future benefits and costs. Furthermore,
-paid-up contracts typically have differen costs / loadings. Additionally, the
-surrender penalty is usually applied to the reserve before the conversion.
-
-Waiving premiums and recalculating the sum insured is very easy, one just calls
-the method `InsuranceContract$premiumWaiver(t = ..)` on the existing contract.
-
-```{r Contract.PureEndPrf, results="hide"}
-contract.PureEnd.NoRefund.Prf = contract.PureEnd.NoRefund$clone()$premiumWaiver(t = 7)
-contract.PureEnd.NoRefund.Prf$Values$reserves
-```
-```{r Contract.PureEndPrfOUT, echo=F}
-contract.PureEnd.NoRefund.Prf$Values$reserves %>% pander
-```
-
-Notice that the contract changes are made directly to the contract ("reference semantics"). This is 
-different from the typical behavior of R, where any change to e.g. a data.frame 
-leaves the original data.frame intact and instead returns a modified copy.
-
-
-
-
-# Calculation Approach
-
-
-## Valuation
-
-The calculation of all contract values is controlled by the function
-`InsuranceContract$calculateContract()` (using methods of the `InsuranceTarif`
-object) and follows the following logic:
-
-1. First the **contingent (unit) cash flows** and the **transition probbilities**
-are determined.
-2. The **actuarial equivalence principle** states that at time of inception, the
-(net and gross) premium must be determined in a way that the present value
-of the future benefits and costs minus the present value of the future premiums
-must be equal, i.e. in expectation the future premiums ove the whole lifetime
-of the contract will exactly cover the benefits and costs. Similarly, at all
-later time steps, the difference between these two present values needs to be
-reserved (i.e. has already been paid by the customer by previous premiums).
-2. This allows the premiums to be calculated by first calculating the **present
-values** for all of the **benefit and costs cash flow** vectors.
-3. The formulas
-to calculate the gross, Zillmer and net **premiums** involve simple linear
-combinations of these present values, so the **coefficients of these formulas**
-are determined next.
-4. With the coefficients of the premium formulas calculated, all **premiums
-can be calculated** (first the gross premium, because due to potential gross
-premium refunds in case of death, the formula for the net premium requires
-the gross premium, which the formula for the gross premium involves no other
-type of premuim).
-5. With premiums determined, all unit cash flows and unit present values can
-now be expressed in monetary terms / as **absolute cash flows** (i.e. the actual 
-Euro-amount that flows rather than a percentage).
-6. As described above, the difference between the present values of premiums
-and present values of benefits and costs is defined as the required amount
-of reserves, so the **reserves (net, gross, administration cost, balance sheet)**
-and all values derived from them (i.e. surrender value, sum insured in case of
-premium waiver, etc.) are calculated.
-7. The **decomposition of the premium** into parts dedicated to specific purposes
-(tax, rebates, net premium, gross premium, Zillmer premium, cost components,
-risk premium, savings premium, etc.) can be done once the reserves are
-ready (since e.g. the savings premium is defined as the difference of
-discounted reserves at times $t$ and $t+1$).
-8. If the contract has **(discretionary or obligatory) profit sharing**B mechanisms
-included, the corresponding [ProfitParticipation] object can calculate that
-profit sharing amounts, once all guaranteed values are calculated. This can
-also be triggered manually (with custom profit sharing rates) by calling
-the methods `InsuranceContract$profitScenario()` or `InsuranceContract$addProfitScenario()`.
-
-
-## Cash Flows
-
-An insurance contract is basically defined by the (unit) cash flows it produces:
-\itemize{
-  \item **Premium payments** (in advance or in arrears) at each timestep
-  \item **Survival payments** at each timestep
-  \item **Guaranteed payments** at each timestep
-  \item **Death benefits** at each timestep
-  \item **Disease benefits** at each timestep
-}
-Together with the transition probabilities (mortalityTable parameter)
-the present values can be calculated, from which the premiums follow and
-finally the reserves and a potential profit sharing.
-
-For example, a _**term life insurance with regular premiums**_ would have the following
-cash flows:
-
-* premium cash flows: 1, 1, 1, 1, 1, ...
-* survival cash flows: 0, 0, 0, 0, 0, ...
-* guaranteed cash flows: 0, 0, 0, 0, 0, ...
-* death benefit cash flows: 1, 1, 1, 1, 1, ...
-
-A _**single-premium term life insurance**_ would look similar, except for the premiums:
-
-* premium cash flows: 1, 0, 0, 0, 0, ...
-
-A _**pure endowment**_ has no death benefits, but a survival benefit of 1 at the
-maturity of the contract:
-
-* premium cash flows: 1, 1, 1, 1, 1, ...
-* survival cash flows: 0, 0, ..., 0, 1
-* guaranteed cash flows: 0, 0, 0, 0, 0, ...
-* death benefit cash flows: 0, 0, 0, 0, 0, ...
-
-An _**endowment**_ has also death benefits during the contract duration:
-
-* premium cash flows: 1, 1, 1, 1, 1, ...
-* survival cash flows: 0, 0, ..., 0, 1
-* guaranteed cash flows: 0, 0, 0, 0, 0, ...
-* death benefit cash flows: 1, 1, 1, 1, 1, ...
-
-A _**(deferred) annuity**B_ has premium cash flows only during the deferral peroid
-and only survival cash flows during the annuity payment phase. Often, in case
-of death during the deferral period, all premiums paid are refunded as a death
-benefit.:
-
-* premium cash flows: 1, 1, ...,  1, 0, 0, 0, ...
-* survival cash flows: 0, 0, ..., 0, 1, 1, 1,...
-* guaranteed cash flows: 0, 0, 0, 0, 0, ...
-* death benefit cash flows: 1, 2, 3, 4, 5, ..., 0, 0, ...
-
-A _**terme-fix insurance**_ has a guaranteed payment at maturity, even if the insured
-has already died. The premiums, however, are only paid until death (which is
-not reflected in the contingent cash flows, but rather in the transition
-probabilities):
-
-* premium cash flows: 1, 1, 1, 1, ...,  1
-* survival cash flows: 0, 0, 0, 0, ..., 0
-* guaranteed cash flows: 0, 0, 0, ..., 0, 1
-* death benefit cash flows: 0, 0, 0, 0, ..., 0
-
-
-
-
-# Cost structure
-
-Costs of an insurance contracts can have various forms and bases.
-
-The `InsuranceContract` class provides all common types of costs:
-
-
-* Type of cost: Acquisition (Alpha-costs), Zillmer, Beta-costs, Administration (Gamma-costs during / after premiums and for paid-up contracts)
-* Basis for costs: SumInsured, Premium Sum, Gross Premium, Net Premium, Reserve, constant costs
-* Duration of costs: Once (up-front), during premium payments, after premium payments, during whole contract
-
-The cost structure generated by `initializeCosts()` is a three-dimensional array
-with the above-mentioned coordinates: 
-```{r costStructureDimensions}
-initializeCosts() %>% dimnames
-```
-
-The most common types of cost can be directly given in the call to `initializeCosts()`,
-but for some uncommon combinations, one can directly fill any of the fields in the
-three-dimensional array manually.
-```{r costExample, eval=F}
-initializeCosts(alpha = 0.04, Zillmer = 0.025, beta = 0.05, gamma.contract = 0.001)
-
-# the above is the short form of:
-costs.Bsp = initializeCosts()
-costs.Bsp[["alpha", "SumPremiums", "once"]] = 0.04
-costs.Bsp[["Zillmer", "SumPremiums", "once"]] = 0.025 # German Zillmer maximum
-costs.Bsp[["beta", "GrossPremium", "PremiumPeriod"]] = 0.05
-costs.Bsp[["gamma", "SumInsured", "PolicyPeriod"]] = 0.001
-```
-
-These costs parameters are immediately converted to the corresponding cash flows
-when the contract is created. In the above example of a pure endowment (with 
-premium waiver at time 7), the absolute cost cash flows are:
-
-```{r costCashFlowsCode, eval=F}
-contract.PureEnd.NoRefund$Values$absCashFlows
-```
-```{r costCashFlows, echo=F}
-contract.PureEnd.NoRefund$Values$absCashFlows[1:11,] %>% select(alpha, Zillmer, beta, gamma, gamma_nopremiums, unitcosts) %>% pander()
-```
-
-
-In addition to these standardized costs, which are included in the expense-loaded
-premium (sometimes also called the "(actuarial) gross premium"), there are certain
-loadings and rebates that are applied after the expense-loaded premium $BP_x$:
-
-$$P_x = \left\{ (BP_x + oUZu - SuRa) \cdot VS \cdot (1-VwGew) + unitC\right\} \cdot  \left(1-PrRa-VwGew_{StkK}-PartnerRa\right)\cdot \left(1+uz(k)\right) \cdot (1+tax)$$
-
-with the following surcharges and rebates:
-
-* $oUZu$ ... Surcharge for contracts without medical exam (parameter `noMedicalExam`)
-* $SuRa$ ... Sum rebate (depending on the sum insured) (parameter `sumRebate`)
-* $VwGew$ ... Advance profit participation (as premium rebate) (parameter `advanceProfitParticipation`)
-* $unitC$ ... Unit costs per year (only during premium payments) (parameter `unitcosts`)
-* $PrRa=PrRa(BP)$ ... Premium rebate (depending on premium amount) (parameter `premiumRebate`)
-* $VwGew_{StkK}$ ... Advance profit participation (as premium rebate, on premium after unit costs) (parameter `advanceProfitParticipationInclUnitCost`)
-* $PartnerRa$ ... Partner rebate on the premium (for multiple similar contracts) (parameter `partnerRebate`)
-* $uz(k)$ ... Frequency charge for monthly/quarterly/half-yearly premium payments instead of yearly premiums (parameter `premiumFrequencyLoading`)
-* $tax$ ... Insurance tax (0% in most countries, 4% or 11% in Austria) (parameter `tax`)
-
-
-
-
-## Frequency charges
-
-Typically, an insurance premium is calculated with yearly premiums paid in advance.
-If premiums are paid more often per year (Parameter `premiumFrequency` or 
-`benefitFrequency` set to a value larger than 1, typically 2 for half-yearly, 
-4 for quarterly, or 12 for monthly payments), part of the interest during the year
-is lost, as well as the premiums for the remainder of the year if the insured event
-happens. So usually there is some kind of extra charge included:
-
-* A frequency charge is added on the gross premium => Parameter `premiumFrequencyLoading` 
-  and `benefitFrequencyLoading` are set to a list with keys "1", "2", "4" and "12" 
-  and values that correspond to the extra charge (as a factor on the gross premium, 
-  i.e. a percentage).
-* The premium or benefit payments are calculated (approximately) as payments 
-  $k$-times per year using yearly death / incidence probabilities. This calculation
-  is typically using some approximations in $k$ => Parameter `premiumFrequencyOrder` 
-  and `benefitFrequencyOrder` set to a value larger than 0. 
-* Contracts with $k>1$ have higher cost loadings on the gross premium. => 
-  Parameter `costs` is implemented a function with signature $function(params, values)$, 
-  which accesses `params$ContractData$premiumFrequency` to return different expense
-  rates for different premium payment frequencies.
-* If the guaranteed interest rate is 0\%, the exact moment of payment during a year 
-  is irrelevant for the guaranteed values. However, if a yield larger than 0\% is
-  achieved, it is assigned to the contract via profit participation. So it makes
-  sense adjust profit participation rates depending on the premium frequency 
-  rather than modifying the premium. The higher the profit participation, the
-  higher the effect of the $k$-th yearly premium payments and the higher the 
-  modification of the rates can be. => Parameter `getInterestProfitRate` of
-  the profit scheme can be implemented as a function that modifies the 
-  rate depending on the premium or benefit frequency (similar to the cost adjustment 
-  mentioned in the previous item).
-
-```{r FrequencyCharges}
-Tarif.Life.FrequencyLoading = Tarif.Life$createModification(
-  name = "Term life (frequency loading)",
-  premiumFrequencyLoading = list("1" = 0.0, "2" = 0.01, "4" = 0.015, "12" = 0.02)
-)
-Tarif.Life.FrequencyApprox1 = Tarif.Life$createModification(
-  name = "Term life (k-th yearly, approx. 1.Ord.)",
-  premiumFrequencyOrder = 1
-)
-Tarif.Life.FrequencyApprox2 = Tarif.Life$createModification(
-  name = "Term life (k-th yearly, approx. 2.Ord.)",
-  premiumFrequencyOrder = 2
-)
-Tarif.Life.FrequencyApprox3 = Tarif.Life$createModification(
-  name = "Term life (k-th yearly, exact)",
-  premiumFrequencyOrder = Inf
-)
-
-Tarif.Life.FrequencyExpense = Tarif.Life$createModification(
-  name = "Term life (modified gamma costs)",
-  costs = function(params, values) {
-    switch (toString(params$ContractData$premiumFrequency),
-        "12" = initializeCosts(alpha = 0.04, Zillmer = 0.025,  beta = 0.05,  gamma.contract = 0.00127, gamma.paidUp = 0.001),
-        "4" = initializeCosts(alpha = 0.04, Zillmer = 0.025,  beta = 0.05,  gamma.contract = 0.00119, gamma.paidUp = 0.001),
-        "2" = initializeCosts(alpha = 0.04, Zillmer = 0.025,  beta = 0.05,  gamma.contract = 0.0011, gamma.paidUp = 0.001),
-        initializeCosts(alpha = 0.04, Zillmer = 0.025,  beta = 0.05,  gamma.contract = 0.001, gamma.paidUp = 0.001)
-    )
-  }
-)
-```
-
-Of course, the loadings and costs mentioned above are not necessarily mathematically 
-derived to offset the interest effect of k-th yearly payments. Rather, they are 
-often simply decided by the management. Thus, the three approaches implemented
-here can have quite different results:
-```{r FrequencyCharges.Grid}
-contractGridPremium(
-  axes = list(tarif = c(Tarif.Life.FrequencyLoading, Tarif.Life.FrequencyApprox1, 
-                        Tarif.Life.FrequencyApprox2, Tarif.Life.FrequencyApprox3, 
-                        Tarif.Life.FrequencyExpense),
-              premiumFrequency = c(1, 2, 4, 12)),
-  age = 40, policyDuration = 20,
-  sumInsured = 100000,
-  contractClosing = as.Date("2020-09-01")
-) %>% kableTable
-```
-
-
-
-## Security loadings
-
-Although most mortality tables and expense loadings already have a certain amount 
-of security margins included, often a tariff (mostly protection products) adds 
-an additional security loading directly to the net present value of the benedits.
-
-This can be easily implemented using the parameter `security`:
-
-```{r Protection.Security}
-contractGridPremium(
-  axes = list(age = seq(30, 60, 10), security = 10*(0:5)/100),
-  tarif = Tarif.Life,
-  policyDuration = 20,
-  sumInsured = 100000,
-  contractClosing = as.Date("2020-09-01")
-) %>% kableTable(digits = 2)
-```
-
-# Creating premium and contract grids
-
-When developing a new product or comparing different products, it is often
-required to create tables of premiums or reserves for a product/tarif where 
-just some of the parameters (like age, sum insured or maturity) change. 
-
-For this purpose, this package provides two functions to create two- or 
-higher-dimensional grids of contracts with each dimension representing one 
-of the parameters varying.
-
-* `contractGrid()` creates a (two- or higher-dimensional) grid of `InsuranceContract` object
-* `contractGridPremium()` creates a grid of the premiums
-
-The grid is defined by the `axes` argument to the `contractGrid()` call. This is
-a named list giving all parameters that should vary inside the grid. Any of the
-parameters of the `InsuranceContract$new()` constructor can be used in the axes.
-
-For example, one can compare multiple tariffs or multiple varying pararameters. 
-
-Let us look at the pure endowment above, which we implemented as a single-premium
-variant and a variant with regular premiums, both of which have a potential 
-(partial or full) premium refund in case of death. How do the premiums of these
-contracts compare and how do the premiums depend on the premium refund proportion?
-
-```{r Grid.Endowment.compare, results = "hide"}
-grd = contractGridPremium(
-  axes = list(tarif = c(Tarif.PureEnd, Tarif.Endowment, Tarif.PureEnd.SP), premiumRefund = c(0, 0.5, 1)),
-  age = 50, policyPeriod = 20,
-  sumInsured = 10000,
-  contractClosing = as.Date("2020-09-01")
-)
-grd
-```
-```{r Grid.Endowment.compareOUT, echo = F}
-grd %>% kableTable
-```
-
-The default implementation of `contractGridPremium` returns the written premium,
-but one can also choose other types of premiums to display, or even other 
-contract values (like reserves).
-
-If one needs to investigate multiple values, it is better to first create a grid
-of insurance contract objects and store it, so that the call to `contractGridPremium`
-does not have to re-calculate the same contracts over and over again, extract just
-one premium and discard the whole contract.
-
-```{r Grid.Endowment.compareOther}
-grd = contractGrid(
-  axes = list(tarif = c(Tarif.PureEnd, Tarif.Endowment, Tarif.PureEnd.SP), premiumRefund = c(0, 0.5, 1)),
-  age = 50, policyPeriod = 20,
-  sumInsured = 10000,
-  contractClosing = as.Date("2020-09-01")
-)
-```
-```{r Grid.Endowment.compareOtherG1, eval = F}
-# Compare net premiums without loadings:
-contractGridPremium(grd, premium = "net")
-```
-```{r Grid.Endowment.compareOtherG1Out, echo = F}
-contractGridPremium(grd, premium = "net") %>% kableTable
-```
-
-```{r Grid.Endowment.compareOtherG2, eval = F}
-# Compare premium sums over the whole contract period (all contracts have the same sumInsured)
-contractGridPremium(grd, .fun = function(c) {with(c$Values, 
-     unitPremiumSum * premiums["written"])
-})
-```
-```{r Grid.Endowment.compareOtherG2Out, echo = F}
-# Compare premium sums over the whole contract period (all contracts have the same sumInsured)
-contractGridPremium(grd, .fun = function(c) {with(c$Values, 
-     unitPremiumSum * premiums["written"])
-}) %>% kableTable(digits = 2)
-```
-
-```{r Grid.Endowment.compareOtherG3, eval = F}
-# Compare risk premiums at time t=10 (the 11th row of the premium decomposition)
-contractGridPremium(grd, .fun = function(c) {c$Values$premiumComposition[11, "risk"]})
-```
-```{r Grid.Endowment.compareOtherG3Out, echo = F}
-# Compare risk premiums at time t=10 (the 11th row of the premium decomposition)
-contractGridPremium(grd, .fun = function(c) {c$Values$premiumComposition[11, "risk"]}) %>% kableTable(digits = 2)
-```
-
-```{r Grid.Endowment.compareOtherG4, eval = F}
-# Compare present value of all benefits and refunds (without costs) at time t=0
-contractGridPremium(grd, .fun = function(c) {c$Values$absPresentValues[1, "benefitsAndRefund"]})
-```
-```{r Grid.Endowment.compareOtherG4Out, echo = F}
-# Compare present value of all benefits and refunds (without costs) at time t=0
-contractGridPremium(grd, .fun = function(c) {c$Values$absPresentValues[1, "benefitsAndRefund"]}) %>% kableTable(digits = 2)
-```
-
-
-
-
-Other useful examples of grid comparisons include e.g. the effect of the interest 
-rate and the mortality table on the premiums:
-
-```{r Grid.Protection, results ="hide"}
-grd = contractGridPremium(
-  axes = list(mortalityTable = mort.AT.census["m", -(1:10)], i = c(0, 0.005, 0.01), age = c(30, 45, 60), policyPeriod = c(10, 20)),
-  tarif = Tarif.Life,
-  contractClosing = as.Date("2020-09-01"),
-  sumInsured = 10000
-)
-grd
-```
-
-```{r Grid.ProtectionOUT, echo=F, results="asis"}
-for (a in dimnames(grd)[[3]]) {
-for (d in dimnames(grd)[[4]]) {
-  cat("\n", "* ", names(dimnames(grd))[[3]], "=",  a, ", ", names(dimnames(grd))[[4]], "=",  d, "\n\n", sep = "")
-  # cat(grd[,,d ] %>% as.data.frame() %>% rownames_to_column("age \\|  policyPeriod") %>% pander(digits = 7, round = 2, style = "rmarkdown"))
-  cat(grd[,, a, d] %>% kableTable(digits = 2), "\n")
-}
-}
-```
-
-
-# Exporting contract data to Excel
-
-The LifeInsuranceContracts package also provides a function to export a given 
-contract to a spreadsheet in Excel format:
-
-* `exportInsuranceContract.xlsx(contract, filename)`
-
-This function takes the contract and exports all data.frames in the contract's 
-`contract$Values` data list as separate tabs to a spreadsheet file. It also 
-adds some nice formatting and additional markup. For contracts with multiple
-contract blocks (e.g. dynamic increases / sum increases or riders), the main
-contract and all its child blocks are exported as well.
-
-The tab containing the premiums and the premium calculation coefficients even
-include the formulas, so one can in theory play around with the parameters to 
-see how the premium changes.
-
-If the contract has profit participation features and some profit scenarios have 
-been added, they are exported as well.
-
-Notice, however, that the Excel export is in general a static file containing 
-the current state of the contract and all its values (cash flows, present values,
-premiums, reserves, profit participation, etc.) as well as the most important
-parameters and an overview of the history of the contract.
-
-```{r ExcelExport,eval=F}
-contract.exportExample = contract.PureEnd.NoRefund$clone()$
-  addDynamics(t = 3, SumInsuredDelta = 10000)$
-  addDynamics(t = 5, SumInsuredDelta = 15000)$
-  addDynamics(t = 10, SumInsuredDelta = 15000)$
-  addDynamics(t = 14, SumInsuredDelta = 10000)
-exportInsuranceContract.xlsx(contract.exportExample, filename = "Example_PureEndowment_Dynamics.xlsx")
-```
-
-
-
-# Creating examples for the Austrian Financial Market Authority
-
-When introducing a new tariff, an Austrian insurance company has to submit
-a detailled mathematical description (so-called "Versicherungsmathematische 
-Grundlagen") of the tariff to the Financial Market Authority (FMA), which have
-to follow the [regulation on actuarial bases for life insurance -- LV-VMGV](https://www.ris.bka.gv.at/GeltendeFassung.wxe?Abfrage=Bundesnormen&Gesetzesnummer=20009298). The sections and contents
-of this document are strictly defined in the regulation, and in addition to the
-formulas of the tariff, an example contract has to be calculated with the following
-key parameters:
-
-* age 35, duration 30 years (15 years for protection tariffs)
-* sum insured 100 000 Euro / monthly annuity 1000 Euro for annuities
-* yearly premiums during the whole contract period (defereal period of 30 years for annuities)
-* intermediate values (reserves, etc.) have to be calculated at $t=10$.
-
-Given a tariff and a derived contract (with the above key parameters), this
-package provides two functions to calculate and print / export
-the required values either to the console / screen or to a file:
-
-* `showVmGlgExamples(contract, prf = 10, t = 10, t_prf = 12, file = "", ...)`
-* `exportInsuranceContractExample(contract, prf = 10, outdir = ".", basename=NULL, extraname = NULL, ...)`
-
-The function `showVmGlgExamples` calculates all required values for the actuarial
-bases document in the required order (including values after a premium waiver 
-at the given time). If a filename is given, the output is exported to that text file,
-otherwise it is simply printed out in the R console:
-
-```{r VmGlgExample}
-VMGL.contract = InsuranceContract$new(
-    Tarif.PureEnd,
-    age = 35, policyPeriod = 30, 
-    premiumFrequency = 1,
-    sumInsured = 100000,
-    contractClosing = as.Date("2020-07-01")
-  )
-
-showVmGlgExamples(VMGL.contract)
-```
-
-
-The `exportInsuranceContractExample` provides no new functionality, but combines 
-the Excel export feature and the regulatory example together. For a given contract
-it will create three files:
-
-* Excel export of the contract
-* Excel export of the contract with a premium waiver applied at the given time
-* The regulatory example (with premium waiver at the same time as in the Excel export) in a text file
-
-One can give a base name and an extra name to distinguish different calculations
-in the file names.
-
-
-# Contracts combining multiple contract layers / slices
-
-In real life, an insurance contract is not merely signed initially and then left 
-untouched until it expires or is surrendered. Rather, some contracts already have
-an automatic increase of the sumInsured or the premium (depending usually on some 
-kind of observed consumer price index) included in the contract. Other contracts
-have additional biometric riders like an additional death or disability cover. 
-Other contracts are extended after their expiration, using the existing reserve
-as a one-time payment (`initialCapital`) for the follow-up contract.
-
-In all these cases, the original contract can be calculated as an `InsuranceContract`, 
-but the additional dynamic increases, additional riders or extensions are mathematically
-calculated as separate contracts (potentiall using different tariffs / types of 
-insurance), although most parameters are shared from the original main contract.
-
-In addition to modelling one particular tariff, the LifeInsuranceContract class 
-can also act as a wrapper to bundle multiple related contracts / contract slices 
-together. The class provides several methods for this:
-* `$addDynamics(t, NewSumInsured, SumInsuredDelta, id, ...)`: 
-        Include (at time `t`) a dynamic increase of premium or sumInsured, but 
-        with the same basic parameters (age, tariff, maturity, 
-        interest rate, etc.) as the main contract. The increase can 
-        be given either as the new total sumInsured or as the 
-        increase in the sumInsured caused by that one increase. Other parameters
-        given as `...` are passed on to the `InsuranceContract$new` constructor
-        of the layer for the dynamic increase. This also means that one can
-        potentially override all parameters for the increase, including the 
-        tariff or the interest rate.
-* `$addExtension(t = NULL, policyPeriod, ...)`
-        After the original contracts maturity, append a follow-up contract (by 
-        default paid-up, i.e. no new premiums are paid) that uses the existing 
-        reserve as initial capital. By default, no further premiums are paid 
-        and the sumInsured is calculated from the existing reserve and the tariff
-        of the extension. One can, however, also provide either a sumInsured or 
-        a premium of the contract extension. In that case, the premium or the sumInsured
-        will be calculated, using the existing reserves as initialCapital.
-* `$addBlock(id = NULL, block = NULL, t, ...)`
-        Generic function to add a child block to the contract. If a block (object 
-        of type `LifeInsuranceContract` is passed, it is inserted and flagged as 
-        starting at time `t`. If no block is passed, a new insurance contract
-        is created using the arguments passed as `...`, combined with the
-        parameters of the main contract. If `t>0`, the child block starts later 
-        than the original contract. It is also possible that the child block extends
-        beyond the maturity of the original contract (e.g. contract extensions
-        are implemented this way).
-
-
-In these case, the main contract will have several child blocks (also
-LifeInsuranceContract objects), and the values of the main contract object will 
-be the aggregated values of all its children, rather than the results of a 
-calculation from an underlying tariff.
-
-## Dynamic increases
-
-To increase the sum insured or premium by a given value ()
-
-```{r contractLayers}
-# Contract with initial capital of 5.000 EUR
-ctr.dynInc = InsuranceContract$new(
-  tarif = Tarif.Endowment,
-  sumInsured = 10000,
-  age = 40, policyPeriod = 10,
-  contractClosing = as.Date("2020-09-01")
-)$
-  addDynamics(t = 1, SumInsuredDelta = 1000)$
-  addDynamics(t = 5, NewSumInsured = 15000)$
-  addDynamics(t = 8, SumInsuredDelta = 4000)
-
-
-ctr.dynInc$Values$basicData
-```
-As seen in this table, the sum insured increases and the premium with it. The 
-`PremiumPayment` column is no longer a 0/1-column indicating whether a premium is
-paid or not, but rather is the number of blocks/layers where a premium is paid.
-
-The individual blocks can be accessed with the `contract$blocks` list:
-```{r contractLayers.blocks}
-for (b in ctr.dynInc$blocks) {
-  cat(paste0("Block: ", b$Parameters$ContractData$id, ", starts at t=", b$Parameters$ContractData$blockStart, ", policyPeriod=", b$Parameters$ContractData$policyPeriod, "\n"))
-}
-```
-
-Each block is formally handled like a separate contract, each starting at its own time `t=0`.
-The over-all contract then takes care to correctly shift the child blocks to the
-time relative to the parent block, before aggregating the data:
-```{r contractLayers.blocks.data}
-ctr.dynInc$blocks$Hauptvertrag$Values$basicData
-ctr.dynInc$blocks$dyn1$Values$basicData
-ctr.dynInc$blocks$dyn2$Values$basicData
-ctr.dynInc$blocks$dyn3$Values$basicData
-```
-
-
-## General biometric riders
-
-Instead of adding a dynamic increase, which typically uses the same tariff as 
-the main contract, it is also possible to bundle e.g. a protection rider to a 
-saving product. The savings product and the protection rider are calculated 
-individually as child blocks, and the overall values of the contract are 
-obtained by aggregating the values from the two children (savings and protection
-part). Of course, in this scenario, the combined sumInsured of the overall contract 
-is not meaningful, but the sumInsured of the individual blocks is.
-
-```{r addBlock.rider}
-ctr.main = InsuranceContract$new(
-  tarif = Tarif.Endowment,
-  sumInsured = 10000,
-  age = 40, policyPeriod = 10,
-  contractClosing = as.Date("2020-09-01")
-)
-ctr.Rider = InsuranceContract$new(
-  tarif = Tarif.L71U, 
-  sumInsured = 100000, 
-  age = 40, policyPeriod = 10,
-  contractClosing = as.Date("2020-09-01")
-)
-ctr.main$addBlock(block = ctr.Rider)
-
-ctr.withRider = InsuranceContract$new(
-  tarif = Tarif.Endowment,
-  sumInsured = 10000,
-  age = 40, policyPeriod = 10,
-  contractClosing = as.Date("2020-09-01")
-)$
-  addBlock(tarif = Tarif.L71U, sumInsured = 100000, 
-           age = 40, policyPeriod = 10,
-           contractClosing = as.Date("2020-09-01"))
-```
-
-
-## Extending a contract beyond its maturity
-
-When a contract expires, many companies offer premium-free contract extensions,
-where the existing reserve is used as initial reserve for a follow-up contract
-(possibly with new terms and parameters like interest rate or mortalities).
-
-Instead of modifying the original contract and re-calculating it, it is easier 
-to model the extension as a new block with the existing reserve given as
-\code{initialCapital}. The extension will be calculated like a standalone-contract 
-and the overall contract will aggregate the values from the original contract
-and the extension. As the extension is a separate contract object, one can pass
-all contract parameters to the \code{$addExtension} method.
-
-The original premiumPeriod of the main contract is used, so by default the extension
-will be a premium-free extension, where the sumInsured is calculated from the 
-existing reserve and the benefits and costs of the extensions' tariff.
-
-To create a premium-free extension explicitly, one can pass \code{premiumPeriod=0} (which
-is the default anyway). To create an extension with regular (or single) premium
-payments, one can pass either a \code{sumInsured} or a \code{premium} to provide
-the sum insured and the premium and calculate the other from the given value
-
-```{r contractExtension}
-# original contract, expiring after 20 years
-ContractA = InsuranceContract$new(
-  tarif = Tarif.Endowment,
-  age = 40, policyPeriod = 20,
-  sumInsured = 10000,
-  contractClosing = as.Date("2000-07-01")
-)
-
-# premium-free extension
-ContractB = ContractA$clone()$
-  addExtension(id = "Verlängerung1", contractPeriod = 5, premiumPeriod = 0)
-# sumInsured calculated from existing reserve:
-ContractB$blocks$Verlängerung1$Parameters$ContractData$sumInsured
-ContractB$Values$basicData
-
-# extension with given sumInsured resulting in 0 (gross) premiums
-ContractC = ContractA$clone()$
-  addExtension(id = "Verlängerung1", contractPeriod = 5, sumInsured = 10723.07973354)
-ContractC$blocks$Verlängerung1$Values$premiums[["gross"]]
-ContractC$Values$basicData
-
-# extension with increased sumInsured: real premiums are charged, reserves start from the existing reserve:
-ContractD = ContractA$clone()$
-  addExtension(id = "Verlängerung1", contractPeriod = 5, sumInsured = 20000)
-ContractD$Values$basicData
-
-# extension with regular premiums, which are given: sumInsured is calculated from it, reserves start from the existing reserve:
-ContractD = ContractA$clone()$
-  addExtension(id = "Verlängerung1", contractPeriod = 5, premium = 597.8771)
-ContractD$Values$basicData
-```
-
-
-# Handling contracts with increases
-
-While many insurance contracts have a fixed sum insured and constant premium,
-many contracts include some kind of adjustment to account for inflation. There
-are various ways to achieve such an adjustment:
-
-* The initial contract already includes a planned increase in the benefits by a
-  pre-determined factor $(1+s)$ each year, premiums are constant over the whole 
-  duration. 
-* The initial contract has fixed sum insured, but the premiums increase by a 
-  factor $(1+s)$ each year due to salary increases.
-* "Dynamic increases": The initial contract has fixed sum insured with fixed 
-  regular premiums. However, every year (or triggered based on an inflation or 
-  consumer price index) the sum insured is increased by a certain amount (either 
-  fixed or by the same percentage as the index) and the premiums are increased 
-  accordingly. Internally, this is represented by a second, shorter contract
-  covering only the increase in sumInsured, from which the additional premium can 
-  be calculated according to the tariff.
-
-The LifeInsuranceContract package provides functionality for each of these increases. 
-All three increases can in theory be combined in the same contract, although 
-in practice this usually does not happen and at most one kind of increase is 
-included in a contract
-
-## Fixed yearly premium increases
-
-With this kind of increases, the initial contract valuation (i.e. the determination 
-of the premium at contract inception) already takes into account that the premium
-will not stay constant over the whole period,
-but increases by a constant factor each year. The sum insured is calculated by 
-the equivalence principle so that the expected present value of all future 
-benefits and costs equals the expected present value of all future (i.e. 
-increasing) premium payments.
-
-This type of yearly premium increase by a fixed factor can be implemented by 
-the parameter:
-
-* `premiumIncrease` ... The factor, by which the premium increases yearly. Default is 1.0 (no increase in premium).
-
-In the following example, we create a 10-year endowment contract with constant 
-premiums over the whole period and another one with idential parameters except 
-that the premium increases by 4\% each year:
-
-```{r PremiumIncrease.Endowment, results = "hide"}
-# For comparison: Contract with constant premiums
-contract.Endow.Constant = InsuranceContract$new(
-  tarif = Tarif.Endowment,
-  sumInsured = 10000,
-  age = 50, policyPeriod = 10,
-  contractClosing = as.Date("2020-09-01")
-)
-# Contract with 4% yearly premium increase and same sum insured
-contract.Endow.PremInc = InsuranceContract$new(
-  tarif = Tarif.Endowment,
-  sumInsured = 10000,
-  premiumIncrease = 1.04,
-  age = 50, policyPeriod = 10,
-  contractClosing = as.Date("2020-09-01")
-)
-premium.comparison = data.frame(
-  `Sum Insured` = contract.Endow.Constant$Values$basicData[,"SumInsured"],
-  `Constant Premium` = contract.Endow.Constant$Values$basicData[,"Premiums"],
-  `4% Yearly Increase` = contract.Endow.PremInc$Values$basicData[,"Premiums"],
-  check.names = F
-  )
-```
-```{r PremiumIncrease.EndowmentOut, results = "asis"}
-premium.comparison %>% pander
-```
-
-
-## Fixed yearly benefit increases with constant premium
-
-With this kind of increases, the premium will stay constant over the whole 
-contract maturity, but the death and/or survival benefit (or the annuity payment)
-will increase by a fixed factor each year. This is typically to safeguard the
-benefit against inflation, so that the value of the annuity payment or death benefit
-does not diminish due to inflation. The initial contract valuation (i.e. the determination 
-of the constant premium at contract inception) already takes into account that 
-the benefits will not stay constant over the whole period,
-but increases by a constant factor each year. 
-
-This type of yearly benefit increase by a fixed factor can be implemented by 
-the parameters:
-
-* `annuityIncrease` ... The factor, by which potential annuity payments increase yearly. Default is 1.0 (no increase in annuity benefits)
-* `deathBenefit` ... The vector of death benefits (relative to the sum insured, which for endowments describes the survival benefit)
-
-In the following example, we create a 10-year endowment contract with constant 
-premiums over the whole period and another one with idential parameters except 
-that the premium increases by 4\% each year:
-
-```{r FixedSumIncrease.WholeLife, results = "hide"}
-# For comparison: Contract with constant premiums
-contract.TermLife.Constant = InsuranceContract$new(
-  tarif = Tarif.Life,
-  sumInsured = 10000,
-  age = 50, policyPeriod = 10,
-  contractClosing = as.Date("2020-09-01")
-)
-# Contract with 4% yearly increase in sum insured (final survival benefit is 10.000)
-contract.TermLife.SumInc = InsuranceContract$new(
-  tarif = Tarif.Life,
-  sumInsured = 10000,
-  deathBenefit = (1.04)^(0:20),
-  age = 50, policyPeriod = 10,
-  contractClosing = as.Date("2020-09-01")
-)
-premium.comparison = data.frame(
-  `Const S.I.` = contract.TermLife.Constant$Values$absCashFlows[,"death"],
-  `Const. Premium` = contract.TermLife.Constant$Values$absCashFlows[,"premiums_advance"],
-  `4% sum increase` = contract.TermLife.SumInc$Values$absCashFlows[,"death"],
-  `Premium w. sum increase` = contract.TermLife.SumInc$Values$absCashFlows[,"premiums_advance"],
-  check.names = F
-  )
-premium.comparison
-```
-```{r FixedSumIncrease.WholeLifeOut, results = "asis", echo=F}
-premium.comparison %>% pander
-```
-
-For annuities, the benefit increase is not handled through `deathBenefits`, but
-rather through the parameter
-
-* `annuityIncrease` ... yearly increase factor of the annuity payments
-
-In the following example, we create a 10-year endowment contract with constant 
-premiums over the whole period and another one with idential parameters except 
-that the premium increases by 4\% each year:
-
-```{r FixedSumIncrease.Annuity, results = "hide"}
-# For comparison: Contract with constant annuity
-contract.Annuity.Constant = InsuranceContract$new(
-  tarif = Tarif.DefAnnuity,
-  sumInsured = 1200,
-  age = 55, 
-  policyPeriod = 10,
-  deferralPeriod = 5,
-  premiumPeriod = 5,
-  contractClosing = as.Date("2020-09-01")
-)
-# Contract with 4% yearly increase in annuity benefits
-contract.Annuity.Increasing = InsuranceContract$new(
-  tarif = Tarif.DefAnnuity,
-  sumInsured = 1200,
-  annuityIncrease = 1.04,
-  age = 55, 
-  policyPeriod = 10,
-  deferralPeriod = 5,
-  premiumPeriod = 5,
-  contractClosing = as.Date("2020-09-01")
-)
-# Contract with 4% yearly increase in premiums and in annuity payments
-contract.Annuity.IncreasingBoth = InsuranceContract$new(
-  tarif = Tarif.DefAnnuity,
-  sumInsured = 1200,
-  annuityIncrease = 1.04,
-  premiumIncrease = 1.04,
-  age = 55, 
-  policyPeriod = 10,
-  deferralPeriod = 5,
-  premiumPeriod = 5,
-  contractClosing = as.Date("2020-09-01")
-)
-premium.comparison = data.frame(
-  `Const. Annuity` = contract.Annuity.Constant$Values$absCashFlows[,"survival_advance"],
-  `Const. Premium` = contract.Annuity.Constant$Values$absCashFlows[,"premiums_advance"],
-  `4% Annuity Increase` = contract.Annuity.Increasing$Values$absCashFlows[,"survival_advance"],
-  `Premium w. Ann.Increase` = contract.Annuity.Increasing$Values$absCashFlows[,"premiums_advance"],
-  `Inc.Premium w. Ann.Increase` = contract.Annuity.IncreasingBoth$Values$absCashFlows[,"premiums_advance"],
-  check.names = F
-  )
-```
-```{r FixedSumIncrease.AnnuityOut, results = "asis"}
-premium.comparison %>% pander
-```
-
-
-
-## Dynamic Increases
-
-With dynamic increases, the contract initially is written with a fixed sum insured
-and constant premiums over the whole contract period. The future increases are
-not considered at all.
-
-After the initial contract inception, either yearly or when a consumer price 
-index changes by a value larger than a given threshold, the sum insured is 
-increased (either by a fixed amount or by an amount determined by the index change)
-and the premium is adjusted accordingly. Internally, the original contract is
-left untouched and the increase is modelled by a separate contract with the 
-same key parameters, only with shorter duration and a sum insured that represents
-only the increase. The premium for this increase is calculated like a separate
-contract with only the difference in the over-all sum insured as its sum insured.
-
-Each dynamic increase then adds another separate tiny InsuranceContract object 
-and the over-all values are the sums of all those contract blocks (sometimes 
-also called "contract slices").
-
-The `InsuranceContract` class provides a method to add a dynamic increase:
-
-* `InsuranceContract$addDynamics(t, NewSumInsured, SumInsuredDelta, id, ...)`
-
-Only one of `NewSumInsured` (new total sum insured) and `SumInsuredDelta` (only 
-the difference between old and new sum insured) is needed. This method adds a
-new contract block to the given InsuranceContract, starting at time $t$ with 
-`SumInsuredDelta` as its sum insured and its premium calculated from the 
-shorter contract period and the sum insured delta. These blocks for dynamic increases 
-are stored in the contract's `$blocks` list of children. The values stored in the
-contract are then simply the sum of all its children.
-
-Here is an example of a 10-year endowment, which has dynamic increases at times $t=5$, $t=7$ and $t=8$:
-
-
-```{r DynamicIncrease.Endowment}
-# For comparison: Contract with constant annuity
-contract.Endowment.Dynamics = InsuranceContract$new(
-  tarif = Tarif.Endowment,
-  sumInsured = 10000,
-  age = 40, 
-  policyPeriod = 10,
-  contractClosing = as.Date("2020-09-01"),
-  id = "Initial contract"
-)$
-  addDynamics(t = 5, NewSumInsured = 11000, id = "Dynamic at 5")$
-  addDynamics(t = 7, NewSumInsured = 12000, id = "Dynamic at 7")$
-  addDynamics(t = 8, NewSumInsured = 13500, id = "Dynamic at 8")
-
-# Over-all contract sum insured and premiums for all blocks combined
-contract.Endowment.Dynamics$Values$basicData[,c("SumInsured", "Premiums")] %>% pander
-```
-```{r DynamicIncrease.EndowmentOut, results = "asis", echo = F}
-blk = c(list(`Over-all contract` = contract.Endowment.Dynamics), contract.Endowment.Dynamics$blocks)
-
-padArray = function(arr = NULL, pad = 0, len = 0) {
-  padEnd = max(0, len - pad - NROW(arr)) # if len is too short, return an array containing at least the arr
-  nrcols = ifelse(is.null(arr), 0, NCOL(arr))
-  rbind(
-    array(0, dim = c(pad, nrcols)) %>% `colnames<-`(colnames(arr)),
-    arr,
-    array(0, dim = c(padEnd, nrcols)) %>% `colnames<-`(colnames(arr))
-  ) %>% `colnames<-`(colnames(arr))
-}
-
-lapply(blk, function(b) {
-  basic = padArray(b$Values$basicData, pad = b$Parameters$ContractData$blockStart)
-  basic[,"SumInsured"]
-}) %>% 
-  bind_cols() %>% 
-  rowid_to_column("t") %>% 
-  mutate(t = t-1) %>% 
-  pander(caption = "Sum Insured for the over-all contract and each of the blocks")
-
-lapply(blk, function(b) {
-  basic = padArray(b$Values$basicData, pad = b$Parameters$ContractData$blockStart)
-  basic[,"Premiums"]
-}) %>% 
-  bind_cols() %>% 
-  rowid_to_column("t") %>% 
-  mutate(t = t-1) %>% 
-  pander(caption = "Premium time series for the over-all contract and each of the blocks")
-
-```
-
-
-
-# Profit participation
-
-In addition to the above guaranteed values, many contracts also include some 
-kind of profit sharing. The total amount of money to be distributed is usually
-predetermined by law or regulation (in Austria by the
-["Lebensversicherung-Gewinnbeteiligungsverordnung -- LV-GBV"](https://www.ris.bka.gv.at/GeltendeFassung.wxe?Abfrage=Bundesnormen&Gesetzesnummer=20009295), 
-but the actual way they are distributed to individual contracts is up the
-insurance undertaking. The profit participation scheme defines profit participation
-allocations based on certain rates and bases, where the formulas and the types 
-of profit are pre-determined in a formal document (which in this package will 
-be implemented as an object of class `ProfitParticipation`), while the profit 
-rates are determined by the management of the undertaking ("discretionary benefits").
-
-
-Typical Austrian insurance contracts have one of two
-kinds of profit sharing mechanisms:
-
-* "Advance profit participation" or "direct contributions", which is a direct 
-  premium rebate, which can in theory be lowered or revoked at any time.
-* Yearly profit assignments into the reserves based on "total credited interet 
-  rate" and other profit attribution rates.
-
-## Advance profit participation (premium rebate)
-
-To implement advance profit participation, one still needs to create a 
-`ProfitParticipation` object, which can be empty. The contract parameters 
-`advanceProfitParticipation` and `advanceProfitParticipationInclUnitCost` then 
-define the premium rebate. They can be set either in the profit scheme or in
-the tariff definition. The latter is usually the easier way, as one profit 
-scheme might be applicable to multiple different tariffs with different advance 
-profit participation rates.
-
-As an example, we will use our `Tarif.Life` whole life tarif defined above and
-add a $38\%$ advance profit participation on the premium:
-```{r AdvanceProfitExample}
-profit.Advance.V1 = ProfitParticipation$new(
-    name = "Profit Scheme for advance profit participation, V 1.0",
-    advanceProfitParticipation = 0.38
-);
-
-Tarif.Life.withPP = Tarif.Life$createModification(
-  name = "Example Tariff - Whole/Term Life with profit sharing",
-  tarif = "Life1PP",
-  profitParticipationScheme = profit.Advance.V1
-)
-
-contract.LifePP = InsuranceContract$new(
-  tarif = Tarif.Life.withPP,
-  age = 40, policyPeriod = 10,
-  sumInsured = 100000,
-  contractClosing = as.Date("2019-09-01")
-)
-```
-
-The premium composition shows that the profit participation 
-```{r advanceProfitExample.PremiumComposition, eval=F}
-contract.LifePP$Values$premiumComposition
-```
-```{r advanceProfitExample.PremiumCompositionOUT, echo=F}
-contract.LifePP$Values$premiumComposition[,c("charged", "tax", "unitcosts", "profit.advance", "gross", "net")] %>% as.data.frame() %>% rowid_to_column("t") %>% mutate(t = t-1) %>% pander
-```
-
-
-## The ProfitParticiption class
-
-The profit participation scheme of a tarif is represented by an object of the
-`ProfitParticipation` class. While the `InsuranceContract.Parameters` list contains
-elements for the profit rates, the implementation of the calculation of the
-profit parts is done by functions defined in the `ProfitParticipation` 
-constructor.
-
-This scheme is passed to the `InsuranceTarif` or `InsuranceContract` via the 
-`profitParticipationScheme` parameter.
-`
-
-There are different types of profit participation assignments, based on the type
-of risks they are based upon:
-
-* __Interest profit__: total credited rate (minus guarantee) applied to some kind of reserve
-* __Risk profit__: risk profit rate applied to the risk premium, capital or the sum insured
-* __Expense profit__: expense profit rate applied to the sum insured
-* __Sum profit__: rate (depending on sum insured) applied to the sum insured 
-* __Terminal bonus__: yearly attributions are collected and paid out only on contract maturity
-* __Terminal bonus fund__: Part of the ongoing profit allocation is not immediately attributed to the contract, but stored in a special reserve and paid out only on maturity.
-
-Each of these profit components in general depends in some way on a profit rate and a basis to which the rate is applied. So each component has the general functional form:
-$$Profit^{type}_t = Calc\left(Rate^{type}_t, Basis^{type}_t\right)$$
-The most common calculation function is a simple multiplication, i.e.
-$Calc(r, b) = r\cdot b$, but other functions are possible, to
-
-
-The (default) parameters that can be passed to the `ProfitParticipation` constructor
-are:
-
-| | |
-|:-----|:----------|
-|**General profit setup** ||
-| `waitingPeriod`   | During the waiting period at the beginning of a contract, no profit participation is assigned |
-| `profitComponents` | describes the different components of profit participation ("interest", "risk", "expense", "sum", "terminal") |
-| `profitClass`      | a profit ID used to identify the correct profit rates (rates are defined per profit class) |
-| `profitRates`      | a data frame containing company-wide profit rates. Key columns are year and profitClass |
-|**Advance profit participation rates** ||
-| `advanceProfitParticipation`             | premium rebate (percentage discount on the gross premium) |
-| `advanceProfitParticipationInclUnitCost` | premium rebate (percentage discount on the gross premium including unit costs) |
-|**Regular profit participation rates** ||
-| `guaranteedInterest` $i$        | Contract-specific override of the guaranteed intereste rate (only for profit participation purposes) |
-| `interestProfitRate` $ip_t$     | Profit interest rate (added to the guaranteed interest rate to arrive at the total credited rate) |
-| `totalInterest` $tcr_t$         | The total credited interest rate (sum of guaranteed interest and profit participation interest) |
-| `mortalityProfitRate` $rp_t$    | Mortality / risk profit rate |
-| `expenseProfitRate` $ep_t$      | Expenso profit rate |
-| `sumProfitRate` $sp_t$          | Sum profit rate (typically a function, depending on sum insured) |
-| `terminalBonusRate` $tb_t$      | Terminal bonus rate |
-| `terminalBonusFundRate` $tbf_t$ | Terminal bonus fund rate, i.e. which percentage of the assigned profits are withheld in a separate terminal bonus fund and only paid out at maturity. |
-
-
-
-
-
-For the calculation of the profit participation, the `ProfitParticipation` class
-holds a list of function pointers to calculate each component of profit participation, as outlined above.
-For each of interest, risk, expense, sum, terminal and terminal bonus fund the 
-following three functions can be given:
-
-* **Profit rate**: return the profit rate as a function from the values of the contract
-  
-  Function signature: `function(rates, ...)`
-* **Profit base**: The quantity on which to apply the rate. Typically this function 
-  returns either the current reserve, the previous reserve (or some combination), 
-  the sum insured or the current risk premium.
-  
-  Function signature: `function(rates, params, values, ...)`
-* **Calculation**: A function taking the rate and the base and calculate the 
-  profit assigned for the specific profit component. Most common are a simple 
-  multiplication of base and rate, but other formulas are possible, too.
-  
-  Function signature: `function(base, rate, waiting, rates, params, values, ...) `
-  
-
-Thus, the constructor of the `ProfitParticipation` class also takes the following
-parameters:
-
-|Type of profit      |Function for rate          | Function for base         | Function for calculation    |
-|:-------------------|:--------------------------|:--------------------------|:----------------------------|
-|interest on accrued profit |`getInterestOnProfits` |- (existing profit)    |-                            |
-|interest profit     |`getInterestProfitRate`    |`getInterestProfitBase`    |`calculateInterestProfit`    |
-|risk profit         |`getRiskProfitRate`        |`getRiskProfitBase`        |`calculateRiskProfit`        |
-|expense profit      |`getExpenseProfitRate`     |`getExpenseProfitBase`     |`calculateExpenseProfit`     |
-|sum profit          |`getSumProfitRate`         |`getSumProfitBase`         |`calculateSumProfit`         |
-|terminal bonus      |`getTerminalBonusRate`     |`getTerminalBonusBase`     |`calculateTerminalBonus`     |
-|terminal bonus fund |`getTerminalBonusFundRate` |`getTerminalBonusFundBase` |`calculateTerminalBonusFund` |
-
-In addition, the following parameters define functions for reserves:
-
-* `getTerminalBonusReserve` ... Calculate the reserve for the terminal bonus 
-  from the bonus assignments (old tariffs often use some kind of discounting or 
-  conditional reserving for the terminal bonus reserve)
-  
-  Function signature: `function(profits, rates, terminalBonus, terminalBonusAccount, params, values)`
-
-
-To calculate the actual benefits paid out from profit participation, the following 
-parameters take the corresponding functions (signature: `function(profits, rates, params, values, ...)` )
-
-| |        |
-|:---|:---------|
-|`calculateSurvivalBenefit`  |Benefit from profit participation at maturity (in addition to the guaranteed payout) |
-|`calculateDeathBenefitAccrued` |Benefit from profit participation upon death (in addition to the guaranteed payout) |
-|`calculateDeathBenefitTerminal` |Benefit from terminal bonus upon death  (in addition to the guaranteed payout and regular profit participation) |
-|`calculateSurrenderBenefitAccrued` |Benefit from profit participation upon contract surrender (in addition to the surrender value) |
-|`calculateSurrenderBenefitTerminal` |Benefit from terminal bonus upon  contract surrender (in addition to the surrender value and regular profit participation) |
-|`calculatePremiumWaiverBenefitAccrued` |Benefit from profit participation upon premium waiver (in addition to the surrender value) |
-|`calculatePremiumWaiverBenefitTerminal` |Benefit from terminal bonus upon premium waiver surrender (in addition to the surrender value and regular profit participation) |
-
-### Existing functions to use
-
-While the details of a profit participation scheme are very specific and no two 
-profit schemes are exactly alike, the basic functionality to extract rates and 
-bases and the calculation functions are usually not so different. For this 
-reason, the `LifeInsuranceContracts` package provides several little helper functions
-that provide the most common functionality for the definition of rates, bases and
-the profit calculation. See `?ProfitParticipationFunctions` for the full list.
-
-The most common functions are:
-
-* `PP.base.PreviousZillmerReserve(rates, params, values, ...)`
-* `PP.base.contractualReserve(rates, params, values, ...)`
-* `PP.base.previousContractualReserve(rates, params, values, ...)`
-* `PP.base.meanContractualReserve(rates, params, values, ...)`
-* `PP.base.ZillmerRiskPremium(rates, params, values, ...)`
-* `PP.base.sumInsured(rates, params, values, ...)`
-* `PP.base.totalProfitAssignment(res, ...)`
-
-* `PP.rate.interestProfit(rates, ...)`
-* `PP.rate.riskProfit(rates, ...)`
-* `PP.rate.expenseProfit(rates, ...)`
-* `PP.rate.sumProfit(rates, ...)`
-* `PP.rate.terminalBonus(rates, ...)`
-* `PP.rate.terminalBonusFund(rates, ...)`
-* `PP.rate.interestProfitPlusGuarantee(rates, ...)`
-* `PP.rate.totalInterest(rates, ...)`
-
-* `PP.calculate.RateOnBase(base, rate, waiting, rates, params, values, ...)`
-* `PP.calculate.RateOnBaseMin0(base, rate, waiting, rates, params, values, ...)`
-* `PP.calculate.RatePlusGuaranteeOnBase(base, rate, waiting, rates, params, values, ...)`
-
-* `PP.benefit.ProfitPlusTerminalBonusReserve(profits, ...)`
-* `PP.benefit.Profit(profits, ...)`
-* `PP.benefit.ProfitPlusGuaranteedInterest(profits, rates, ...)`
-* `PP.benefit.ProfitPlusTotalInterest(profits, rates, params, values)`
-* `PP.benefit.ProfitPlusHalfTotalInterest(profits, ...)`
-* `PP.benefit.ProfitPlusInterestMinGuaranteeTotal(profits, rates, ...)`
-* `PP.benefit.TerminalBonus5YearsProRata(profits, params, ...)`
-* `PP.benefit.TerminalBonus5Years(profits, params, ...)`
-* `PP.benefit.TerminalBonus(profits, params, ...)`
-
-
-
-
-### Example profit scheme
-
-For example, imagine a tariff's total cumulated assigned profit $G_t$ and the benefits at time $t$ have the formulas:
-$$Prof_t = \left(G_{t-1} + TBF_{t-1}\right) \cdot \left(1 + i + ip_t\right) + ip_t \cdot \frac{\left(Res_{t-1} + Res_{t}\right)}{2} + rp_t \cdot P^r_t + ep_t \cdot SumInsured + sp_t(SI) \cdot SumInsured$$
-$$G_t = G_{t-1} + (1 - tbf_t) \cdot Prof_t$$
-$$TBF_t = TBF_{t-1} + tbf_t \cdot Prof_t$$
-$$Death_t = G_t \cdot \left(1 + i + ip_t\right) + TBF_t$$
-$$Matu_n = G_n + TBF_n$$
-$$Surrender_t = G_t\cdot \left(1+\frac{i + ip_t}{2}\right) + 0.5 \cdot TBF_t$$
-$$Red_t = G_t + 0.5 \cdot TBF_t$$
-
-
-These formulas can be interpreted as following: 
-
-* There are multiple profit components: interest profit, risk profit, expense profit and sum profit.
-* The total profit assignment $Prof_t$ in year $t$ consists of:
-  * Interest (guarantee + interest profit rate) on the accrued profits and the terminal bonus fund
-  * Interest profit on the average reserve
-  * Risk profit as part of the risk premium (similar to advance profit participation, but on a year-by-year basis on the actual risk premium)
-  * Expense profit relative to the sum insured
-  * Sum profit relative to the sum insured. The rate depends on the sum insured, too (e.g. higher SI typically have higher sum profit)
-  * Only a portion $(1-tbf_t)$ is added to the accrued bonus, while the rest ist 
-    stored in the Terminal Bonus Fund.
-* The existing cumulated profit $G_{t-1}$ and the terminal bonus fund $TBF_{t-1}$ yields interest with the guaranteed 
-  interest rate plus potentially the interest profit rate. If the total credited 
-  rate is lower than the guarantee, the guarantee is still applied to the 
-  existing profits. => `PP.rate.interestProfitPlusGuarantee`
-* Additionaly, interest profit is assigned with rate $ip_t$ (=0 if total 
-  credited rate is below guarantee) multiplied with the average of the current
-  and the previous reserve for the guaranteed part. => `PP.base.meanContractualReserve`
-* The risk profit works similar to advance profit participation, only that part 
-  of the (actual) risk premium of the year is returned to the customer after 
-  having paid it. => `PP.base.ZillmerRiskPremium` 
-* Expense profit is based on the sum insured, since most cost structures are 
-  linear in the sum insured and contain certain loadings, which are returned 
-  to the customer via this profit component.
-* A sum profit of $sp_t$ of the sum insured is added, even if no interest profit
-  is distributed. The sum profit rate depends on the sum insured (as a function),
-  since the charges expenses increase linearly in the sum insured while the actual
-  cost do increase only sub-linear. So for higher sums typically more expenses
-  are returned. => The sum profit rate will be a function rather than a single 
-  value each year.
-* Only a part $(1-tbf_t)$ of the profit assignment in year $t$ is added to the 
-  accrued profits $G_t$, while the rest $tbf_t$ is stored in the terminal bonus 
-  fund $TBF_t$, which is partially lost on surrender or premium waiver.
-  
-The values of $Res_t$, $P^r_t$, $SumInsured$ and the guaranteed interest $i^g_t$ are 
-prescribed by the tariff or contract, while the profit participation rates 
-$ip_t$, $rp_t$, $ep_t$ and $sp_t$ are decided on a year-by-year basis by the management boards.
-
-The benefits for death, maturity, surrender and premium waivers are:
-
-* In case of death, the existing cumulated profits yield one additional year of interest => `PP.benefit.ProfitPlusInterestMinGuaranteeTotal`
-* At maturity of the contract, the existing cumulated profits are paid out in 
-  addition to the guaranteed benefits of the contract. => `PP.benefit.Profit`
-* In case of surrender (on average half a year after the contract's anniversary), 
-  half a year of interest is added to the existing cumulated profits from the 
-  last anniversary => `PP.benefit.ProfitPlusHalfInterestMinGuaranteeTotal`
-* When premiums are waived, the existing accrued profits are taken into account
-  without any additional interest. => `PP.benefit.Profit`
-* The terminal bonus fund is paid out fully on death and at maturity, while half 
-  of the TBF is lost on surrender or premium waiver.
-
-This profit scheme can be easily be implemented as a `ProfitParticipation` 
-object, where one can pass the functions for bases and calculation and also 
-provide default profit rates:
-
-```{r Example.ProfitParticipation}
-ProfitScheme.example = ProfitParticipation$new(
-  name = "Example Profit Scheme, V 1.0",
-  profitComponents = c("interest", "risk", "expense", "sum", "TBF"),
-
-  getInterestOnProfits    = PP.rate.interestProfitPlusGuarantee,
-  getInterestProfitBase   = PP.base.meanContractualReserve,
-  getRiskProfitBase       = PP.base.ZillmerRiskPremium,
-  getExpenseProfitBase    = PP.base.sumInsured,
-  getSumProfitBase        = PP.base.sumInsured,
-  getTerminalBonusFundBase = PP.base.totalProfitAssignment,
-  
-  mortalityProfitRate = 0.15,
-  expenseProfitRate = 0.01,
-  sumProfitRate = function(params, ...) {if (params$ContractData$sumInsured > 1000000) 0.005 else 0;},
-  terminalBonusFundRate = 0.3,
-  
-  calculateSurvivalBenefit      = PP.benefit.ProfitPlusTerminalBonusReserve,
-  
-  calculateDeathBenefitAccrued  = PP.benefit.ProfitPlusInterestMinGuaranteeTotal,
-  calculateDeathBenefitTerminal = PP.benefit.TerminalBonus,
-  calculateSurrenderBenefitAccrued = PP.benefit.ProfitPlusHalfInterestMinGuaranteeTotal,
-  calculateSurrenderBenefitTerminal = function(profits, ...) {  profits[, "TBF"] / 2 },
-  calculatePremiumWaiverBenefitAccrued = PP.benefit.Profit,
-  calculatePremiumWaiverBenefitTerminal = function(profits, ...) {  profits[, "TBF"] / 2 },
-  
-  profitClass = NULL
-)
-```
-
-The calculation functions are not given, as they default to the correct
-`PP.calculate.RateOnBase` anyway. The interest profit rates are not given, as
-they will vary over time with no default value. Rathery, they need to be  passed 
-to the call to `InsuranceContract$addProfitScenario()` to calculate one particular
-profit scenario with given rates.
-In contrast, the mortality, expense and sum profit rates are initialized with 
-some default values, which will be used if a profit scenario does not explicitly 
-give those profit rates.
-
-
-### Using the profit scheme in a tariff or contract
-
-The profit scheme defined above can now be used with the `profitParticipationScheme` 
-parameter in a tariff or a contract. Usually, the profit scheme is a property of
-the product, so it should be specified in the tariff, but can be overridden in 
-a contract.
-
-As an example, let us create an endowment contract with 500\% death benefit 
-that uses this profit scheme:
-
-```{r Example.PP.Endowment}
-contract.Endow.PP = InsuranceContract$new(
-  tarif = Tarif.Endowment,
-  sumInsured = 10000,
-  deathBenefit = 5,
-  age = 50, policyPeriod = 15,
-  
-  profitParticipationScheme = ProfitScheme.example,
-  contractClosing = as.Date("2020-09-01")
-)
-```
-
-In contrast to the guaranteed values, which can and will be calculated as soon
-as the contract is created, the profit participation needs to be explicitly 
-called with the desired rates. A contract can store multiple different profit
-scenarios, which can be added with the `addProfitScenario()` method. This method
-can also be chained to add multiple scenarios (e.g. )
-```{r ExamplePP.Endowment.addScenario}
-contract.Endow.PP$
-  addProfitScenario(id = "Current total credited rate", guaranteedInterest = 0.005, interestProfitRate = 0.02, totalInterest = 0.025)$
-  addProfitScenario(id = "Current TCR-1%", guaranteedInterest = 0.005, interestProfitRate = 0.01, totalInterest = 0.015)$
-  addProfitScenario(id = "Current TCR+1%", guaranteedInterest = 0.005, interestProfitRate = 0.03, totalInterest = 0.035)
-  
-```
-All profit scenarios are stored in the `InsuranceContract$Values$profitScenarios`
-list indexed with the id given in the call.
-
-The array containing all values of the profit scenario first holds the calculation 
-basis and the rate for each of the profit components:
-```{r ExamplePP.Endowment.Scenarios}
-contract.Endow.PP$Values$profitScenarios$`Current total credited rate` %>%
-  as.data.frame() %>%
-  select(ends_with("Base"), ends_with("Interest"), ends_with("Rate"), -TBFRate, -TBFBase, -totalInterest) %>%
-  rowid_to_column("t") %>% mutate(t = t - 1) %>% kable()
-```
-
-The base for interest profit is the average of the reserve:
-```{r ExPP.End.reserve, echo = F}
-contract.Endow.PP$Values$reserves %>% as.data.frame() %>% 
-  rownames_to_column("t") %>% 
-  select(t, SumInsured, Zillmer) %>% 
-  mutate(AvgZillmer = rollingmean(c(0,Zillmer))) %>%
-  pander()
-```
-
-From the bases and rates, the calculation function (in our case simply the multiplication of rate and base) is applied to arrive at the yearly profit allocation of each component:
-
-```{r ExamplePP.Endowment.ScenariosAttib}
-contract.Endow.PP$Values$profitScenarios$`Current total credited rate` %>%
-  as.data.frame() %>%
-  select(ends_with("Profit"), totalProfitAssignment, -totalProfit) %>%
-  rowid_to_column("t") %>% mutate(t = t - 1) %>%
-  pander
-
-```
-
-The `totalProfitAssignment` column is the sum of all component allocations in the given year (the $Prof_t$ in the formulas above).
-
-After all components are calculated, the yearly profit assignment is split into the part that is accrued in the regular bonus and the part that is placed in the terminal bonus fund, using the terminal bonus fund rate. Finally, the yearly regular and terminal bonus assignments can be summed up to the regular and the terminal bonus:
-
-```{r ExamplePP.Endowment.ScenariosTBFTotal}
-contract.Endow.PP$Values$profitScenarios$`Current total credited rate` %>%
-  as.data.frame() %>%
-  select(TBFBase, TBFRate, TBFBonusAssignment, regularBonusAssignment, TBF, regularBonus, totalProfit) %>%
-  rowid_to_column("t") %>% mutate(t = t - 1) %>%
-  pander
-```
-
-
-The last step in the calculation of a scenario is to calculate the benefits for 
-each of the possible types of payout:
-
-```{r ExamplePP.Endowment.ScenariosBenefits}
-contract.Endow.PP$Values$profitScenarios$`Current total credited rate` %>%
-  as.data.frame() %>%
-  select(survival, deathAccrued, death, surrenderAccrued, surrender, premiumWaiverAccrued, premiumWaiver) %>%
-  rowid_to_column("t") %>% mutate(t = t - 1) %>%
-  pander
-```
-
-One can add as many profit scenarios as desired. Each of the rates in the 
-`addProfitScenario`-call can also be a vector giving the corresponding rate
-for each year of the contract:
-
-```{r ExamplePP.Endowment.Scenario.Decr}
-contract.Endow.PP$
-  addProfitScenario(id = "decreasing TCR", guaranteedInterest = 0.005, 
-                    interestProfitRate = (15:0)/15 * 0.02, 
-                    expenseProfitRate = c(rep(0.01, 5), rep(0.005, 5), rep(0, 6)))
-
-contract.Endow.PP$Values$profitScenarios$`decreasing TCR` %>%
-  as.data.frame() %>%
-  select(interestBase, expenseBase, interestProfitRate, expenseProfitRate, interestOnProfitRate, interestProfit, expenseProfit, totalProfit) %>%
-  rowid_to_column("t") %>% mutate(t = t - 1) %>%
-  kable
-```
-
-In the Excel export, a separate tab of the Excel file will hold all profit scenarios added to the contract.
-
-
-
-# Modifying the default calculation approach
-
-While the cash-flow approach described above and based on the `type` parameter of the
-`InsuranceTarif` works very well for all standart types of life insurance, sometimes 
-a tariff does not follow the standard behaviour exactly. The valuation approach
-with all-determining cash flows is still correct, but the cash flows might need 
-to be adjusted. For this, some hook functions are provided that allow modification 
-of the contract's internals (e.g. cash flows) before all other calculations commence.
-
-Two hooks are provided, which allow modifications of the cash flow profiles before 
-present values, premiums and reserves are calculated:
-
-|    |      |
-|:---|:-----|
-|`adjustCashFlows` | Adjust the premium and benefit cash flows of the contract |
-|`adjustCashFlowsCosts` | Adjust the cost cash flows |
-|`adjustPremiumCoefficients` | Adjust the coefficients of the premium calculation formulas |
-
-The function signature is `function(x, params, values, ...)`, where `x` is the 
-object holding the standard cash flows determined for the contract. The return 
-value of the hook function will be used instead of `x`.
-
-The \code{adjustPremiumCoefficients} hook has a slightly extended function signature 
-\code{function(coeff, type, premiums, params, values, premiumCalculationTime)}.
-
-An example where the cash-flow-approach solely based on `type` does not immediately
-work is a waiting period of 3 years for the death benefit. In particular,
-if a person dies during the first 3 years of the contract, no death benefit is paid out.
-
-The easiest way to implement such cash flows is to let the `InsuranceTarif` first
-create the standard cash flows (with benefits during the first three years) and then
-provide a hook function that nullifies the benefits in the waiting period, before
-all present values, premiums and reserves are calculated.
-
-```{r WaitingPeriod.Hook}
-contract.Endow.Waiting = InsuranceContract$new(
-  tarif = Tarif.Endowment,
-  sumInsured = 10000,
-  age = 50, policyPeriod = 15,
-  
-  contractClosing = as.Date("2020-09-01"),
-  adjustCashFlows = function(x, ...) { x[1:3, "death_SumInsured"] = 0; x }
-)
-
-contract.Endow.Waiting$Values$cashFlows[,c("premiums_advance", "survival_advance", "death_SumInsured")] %>% pander
-
-contractGridPremium(
-  axes = list(age = seq(20, 80, 10), adjustCashFlows = c(function(x, ...) x, function(x, ...) { x[1:3, "death_SumInsured"] = 0; x })),
-  tarif = Tarif.Endowment,
-  sumInsured = 10000,
-  policyPeriod = 15,
-  
-  contractClosing = as.Date("2020-09-01")
-) %>% `colnames<-`(c("Full benefit", "Waiting period"))
-
-```
-
-Another example are term-fixe insurances where the Zillmer premium also includes the administration (gamma) costs over the whole contract period.
-
-```{r termfix.Zillmeradjust.Hook, eval=FALSE}
-  costs = initializeCosts(alpha = 0.04, Zillmer = 0.035, gamma = 0.0015, gamma.fullcontract = 0.001),
-  adjustPremiumCoefficients = function(coeff, type, premiums, params, values, premiumCalculationTime) {
-    if (type == "Zillmer") {
-      coeff[["SumInsured"]][["costs"]]["gamma", "SumInsured", "guaranteed"] = 1
-    }
-    coeff
-  },
-```
+For the documentation, see https://cran.r-project.org/web/packages/LifeInsureR/vignettes/using-the-lifeinsurer-package.html!