+
+/** @param A Period which is subtracted from.
+ * @param B Periods to subtract from `A', must be in ascending order of start time and must not overlap.
+ */
+template <class T>
+std::list<TimePeriod<T>> subtract (TimePeriod<T> A, std::list<TimePeriod<T>> const & B)
+{
+ std::list<TimePeriod<T>> result;
+ result.push_back (A);
+
+ for (auto i: B) {
+ std::list<TimePeriod<T>> new_result;
+ for (auto j: result) {
+ auto ov = i.overlap (j);
+ if (ov) {
+ if (*ov == i) {
+ /* A contains all of B */
+ if (i.from != j.from) {
+ new_result.push_back (TimePeriod<T>(j.from, i.from));
+ }
+ if (i.to != j.to) {
+ new_result.push_back (TimePeriod<T>(i.to, j.to));
+ }
+ } else if (*ov == j) {
+ /* B contains all of A */
+ } else if (i.from < j.from) {
+ /* B overlaps start of A */
+ new_result.push_back (TimePeriod<T>(i.to, j.to));
+ } else if (i.to > j.to) {
+ /* B overlaps end of A */
+ new_result.push_back (TimePeriod<T>(j.from, i.from));
+ }
+ } else {
+ new_result.push_back (j);
+ }
+ }
+ result = new_result;
+ }
+
+ return result;
+}
+
+