Theory Integration

theory Integration
imports Derivative
(*  Author:     John Harrison
    Author:     Robert Himmelmann, TU Muenchen (Translation from HOL light); proofs reworked by LCP
*)

section ‹Kurzweil-Henstock Gauge Integration in many dimensions.›

theory Integration
imports
  Derivative
  Uniform_Limit
  "~~/src/HOL/Library/Indicator_Function"
begin

lemma cSup_abs_le: (* TODO: move to Conditionally_Complete_Lattices.thy? *)
  fixes S :: "('a::{linordered_idom,conditionally_complete_linorder}) set"
  shows "S ≠ {} ⟹ (⋀x. x∈S ⟹ ¦x¦ ≤ a) ⟹ ¦Sup S¦ ≤ a"
  apply (auto simp add: abs_le_iff intro: cSup_least)
  by (metis bdd_aboveI cSup_upper neg_le_iff_le order_trans)

lemma cInf_abs_ge:
  fixes S :: "('a::{linordered_idom,conditionally_complete_linorder}) set"
  assumes "S ≠ {}" and bdd: "⋀x. x∈S ⟹ ¦x¦ ≤ a"
  shows "¦Inf S¦ ≤ a"
proof -
  have "Sup (uminus ` S) = - (Inf S)"
  proof (rule antisym)
    show "- (Inf S) ≤ Sup(uminus ` S)"
      apply (subst minus_le_iff)
      apply (rule cInf_greatest [OF ‹S ≠ {}›])
      apply (subst minus_le_iff)
      apply (rule cSup_upper, force)
      using bdd apply (force simp add: abs_le_iff bdd_above_def)
      done
  next
    show "Sup (uminus ` S) ≤ - Inf S"
      apply (rule cSup_least)
       using ‹S ≠ {}› apply (force simp add: )
      apply clarsimp  
      apply (rule cInf_lower)
      apply assumption
      using bdd apply (simp add: bdd_below_def)
      apply (rule_tac x="-a" in exI)
      apply force
      done
  qed
  with cSup_abs_le [of "uminus ` S"] assms show ?thesis by fastforce
qed

lemma cSup_asclose:
  fixes S :: "('a::{linordered_idom,conditionally_complete_linorder}) set"
  assumes S: "S ≠ {}"
    and b: "∀x∈S. ¦x - l¦ ≤ e"
  shows "¦Sup S - l¦ ≤ e"
proof -
  have th: "⋀(x::'a) l e. ¦x - l¦ ≤ e ⟷ l - e ≤ x ∧ x ≤ l + e"
    by arith
  have "bdd_above S"
    using b by (auto intro!: bdd_aboveI[of _ "l + e"])
  with S b show ?thesis
    unfolding th by (auto intro!: cSup_upper2 cSup_least)
qed

lemma cInf_asclose:
  fixes S :: "real set"
  assumes S: "S ≠ {}"
    and b: "∀x∈S. ¦x - l¦ ≤ e"
  shows "¦Inf S - l¦ ≤ e"
proof -
  have "¦- Sup (uminus ` S) - l¦ =  ¦Sup (uminus ` S) - (-l)¦"
    by auto
  also have "… ≤ e"
    apply (rule cSup_asclose)
    using abs_minus_add_cancel b by (auto simp add: S)
  finally have "¦- Sup (uminus ` S) - l¦ ≤ e" .
  then show ?thesis
    by (simp add: Inf_real_def)
qed

lemmas scaleR_simps = scaleR_zero_left scaleR_minus_left scaleR_left_diff_distrib
  scaleR_zero_right scaleR_minus_right scaleR_right_diff_distrib scaleR_eq_0_iff
  scaleR_cancel_left scaleR_cancel_right scaleR_add_right scaleR_add_left real_vector_class.scaleR_one

lemma real_arch_invD:
  "0 < (e::real) ⟹ (∃n::nat. n ≠ 0 ∧ 0 < inverse (real n) ∧ inverse (real n) < e)"
  by (subst(asm) real_arch_inv)


subsection ‹Sundries›

lemma conjunctD2: assumes "a ∧ b" shows a b using assms by auto
lemma conjunctD3: assumes "a ∧ b ∧ c" shows a b c using assms by auto
lemma conjunctD4: assumes "a ∧ b ∧ c ∧ d" shows a b c d using assms by auto

declare norm_triangle_ineq4[intro]

lemma simple_image: "{f x |x . x ∈ s} = f ` s"
  by blast

lemma linear_simps:
  assumes "bounded_linear f"
  shows
    "f (a + b) = f a + f b"
    "f (a - b) = f a - f b"
    "f 0 = 0"
    "f (- a) = - f a"
    "f (s *R v) = s *R (f v)"
proof -
  interpret f: bounded_linear f by fact
  show "f (a + b) = f a + f b" by (rule f.add)
  show "f (a - b) = f a - f b" by (rule f.diff)
  show "f 0 = 0" by (rule f.zero)
  show "f (- a) = - f a" by (rule f.minus)
  show "f (s *R v) = s *R (f v)" by (rule f.scaleR)
qed

lemma bounded_linearI:
  assumes "⋀x y. f (x + y) = f x + f y"
    and "⋀r x. f (r *R x) = r *R f x"
    and "⋀x. norm (f x) ≤ norm x * K"
  shows "bounded_linear f"
  using assms by (rule bounded_linear_intro) (* FIXME: duplicate *)

lemma bounded_linear_component [intro]: "bounded_linear (λx::'a::euclidean_space. x ∙ k)"
  by (rule bounded_linear_inner_left)

lemma transitive_stepwise_lt_eq:
  assumes "(⋀x y z::nat. R x y ⟹ R y z ⟹ R x z)"
  shows "((∀m. ∀n>m. R m n) ⟷ (∀n. R n (Suc n)))"
  (is "?l = ?r")
proof safe
  assume ?r
  fix n m :: nat
  assume "m < n"
  then show "R m n"
  proof (induct n arbitrary: m)
    case 0
    then show ?case by auto
  next
    case (Suc n)
    show ?case
    proof (cases "m < n")
      case True
      show ?thesis
        apply (rule assms[OF Suc(1)[OF True]])
        using ‹?r›
        apply auto
        done
    next
      case False
      then have "m = n"
        using Suc(2) by auto
      then show ?thesis
        using ‹?r› by auto
    qed
  qed
qed auto

lemma transitive_stepwise_gt:
  assumes "⋀x y z. R x y ⟹ R y z ⟹ R x z" "⋀n. R n (Suc n)"
  shows "∀n>m. R m n"
proof -
  have "∀m. ∀n>m. R m n"
    apply (subst transitive_stepwise_lt_eq)
    apply (blast intro: assms)+
    done
  then show ?thesis by auto
qed

lemma transitive_stepwise_le_eq:
  assumes "⋀x. R x x" "⋀x y z. R x y ⟹ R y z ⟹ R x z"
  shows "(∀m. ∀n≥m. R m n) ⟷ (∀n. R n (Suc n))"
  (is "?l = ?r")
proof safe
  assume ?r
  fix m n :: nat
  assume "m ≤ n"
  then show "R m n"
  proof (induct n arbitrary: m)
    case 0
    with assms show ?case by auto
  next
    case (Suc n)
    show ?case
    proof (cases "m ≤ n")
      case True
      with Suc.hyps ‹∀n. R n (Suc n)› assms show ?thesis
        by blast
    next
      case False
      then have "m = Suc n"
        using Suc(2) by auto
      then show ?thesis
        using assms(1) by auto
    qed
  qed
qed auto

lemma transitive_stepwise_le:
  assumes "⋀x. R x x" "⋀x y z. R x y ⟹ R y z ⟹ R x z"
    and "⋀n. R n (Suc n)"
  shows "∀n≥m. R m n"
proof -
  have "∀m. ∀n≥m. R m n"
    apply (subst transitive_stepwise_le_eq)
    apply (blast intro: assms)+
    done
  then show ?thesis by auto
qed


subsection ‹Some useful lemmas about intervals.›

lemma empty_as_interval: "{} = cbox One (0::'a::euclidean_space)"
  using nonempty_Basis
  by (fastforce simp add: set_eq_iff mem_box)

lemma interior_subset_union_intervals:
  assumes "i = cbox a b"
    and "j = cbox c d"
    and "interior j ≠ {}"
    and "i ⊆ j ∪ s"
    and "interior i ∩ interior j = {}"
  shows "interior i ⊆ interior s"
proof -
  have "box a b ∩ cbox c d = {}"
     using inter_interval_mixed_eq_empty[of c d a b] and assms(3,5)
     unfolding assms(1,2) interior_cbox by auto
  moreover
  have "box a b ⊆ cbox c d ∪ s"
    apply (rule order_trans,rule box_subset_cbox)
    using assms(4) unfolding assms(1,2)
    apply auto
    done
  ultimately
  show ?thesis
    unfolding assms interior_cbox
      by auto (metis IntI UnE empty_iff interior_maximal open_box subsetCE subsetI)
qed

lemma inter_interior_unions_intervals:
  fixes f::"('a::euclidean_space) set set"
  assumes "finite f"
    and "open s"
    and "∀t∈f. ∃a b. t = cbox a b"
    and "∀t∈f. s ∩ (interior t) = {}"
  shows "s ∩ interior (⋃f) = {}"
proof (clarsimp simp only: all_not_in_conv [symmetric])
  fix x
  assume x: "x ∈ s" "x ∈ interior (⋃f)"
  have lem1: "⋀x e s U. ball x e ⊆ s ∩ interior U ⟷ ball x e ⊆ s ∩ U"
    using interior_subset
    by auto (meson Topology_Euclidean_Space.open_ball contra_subsetD interior_maximal mem_ball)
  have "∃t∈f. ∃x. ∃e>0. ball x e ⊆ s ∩ t"
    if "finite f" and "∀t∈f. ∃a b. t = cbox a b" and "∃x. x ∈ s ∩ interior (⋃f)" for f
    using that
  proof (induct rule: finite_induct)
    case empty
    obtain x where "x ∈ s ∩ interior (⋃{})"
      using empty(2) ..
    then have False
      unfolding Union_empty interior_empty by auto
    then show ?case by auto
  next
    case (insert i f)
    obtain x where x: "x ∈ s ∩ interior (⋃insert i f)"
      using insert(5) ..
    then obtain e where e: "0 < e ∧ ball x e ⊆ s ∩ interior (⋃insert i f)"
      unfolding open_contains_ball_eq[OF open_Int[OF assms(2) open_interior], rule_format] ..
    obtain a where "∃b. i = cbox a b"
      using insert(4)[rule_format,OF insertI1] ..
    then obtain b where ab: "i = cbox a b" ..
    show ?case
    proof (cases "x ∈ i")
      case False
      then have "x ∈ UNIV - cbox a b"
        unfolding ab by auto
      then obtain d where "0 < d ∧ ball x d ⊆ UNIV - cbox a b"
        unfolding open_contains_ball_eq[OF open_Diff[OF open_UNIV closed_cbox],rule_format] ..
      then have "0 < d" "ball x (min d e) ⊆ UNIV - i"
        unfolding ab ball_min_Int by auto
      then have "ball x (min d e) ⊆ s ∩ interior (⋃f)"
        using e unfolding lem1 unfolding  ball_min_Int by auto
      then have "x ∈ s ∩ interior (⋃f)" using ‹d>0› e by auto
      then have "∃t∈f. ∃x e. 0 < e ∧ ball x e ⊆ s ∩ t"
        using insert.hyps(3) insert.prems(1) by blast
      then show ?thesis by auto
    next
      case True show ?thesis
      proof (cases "x∈box a b")
        case True
        then obtain d where "0 < d ∧ ball x d ⊆ box a b"
          unfolding open_contains_ball_eq[OF open_box,rule_format] ..
        then show ?thesis
          apply (rule_tac x=i in bexI, rule_tac x=x in exI, rule_tac x="min d e" in exI)
          unfolding ab
          using box_subset_cbox[of a b] and e
          apply fastforce+
          done
      next
        case False
        then obtain k where "x∙k ≤ a∙k ∨ x∙k ≥ b∙k" and k: "k ∈ Basis"
          unfolding mem_box by (auto simp add: not_less)
        then have "x∙k = a∙k ∨ x∙k = b∙k"
          using True unfolding ab and mem_box
            apply (erule_tac x = k in ballE)
            apply auto
            done
        then have "∃x. ball x (e/2) ⊆ s ∩ (⋃f)"
        proof (rule disjE)
          let ?z = "x - (e/2) *R k"
          assume as: "x∙k = a∙k"
          have "ball ?z (e / 2) ∩ i = {}"
          proof (clarsimp simp only: all_not_in_conv [symmetric])
            fix y
            assume "y ∈ ball ?z (e / 2)" and yi: "y ∈ i"
            then have "dist ?z y < e/2" by auto
            then have "¦(?z - y) ∙ k¦ < e/2"
              using Basis_le_norm[OF k, of "?z - y"] unfolding dist_norm by auto
            then have "y∙k < a∙k"
              using e k
              by (auto simp add: field_simps abs_less_iff as inner_simps)
            then have "y ∉ i"
              unfolding ab mem_box by (auto intro!: bexI[OF _ k])
            then show False using yi by auto
          qed
          moreover
          have "ball ?z (e/2) ⊆ s ∩ (⋃insert i f)"
            apply (rule order_trans[OF _ e[THEN conjunct2, unfolded lem1]])
          proof
            fix y
            assume as: "y ∈ ball ?z (e/2)"
            have "norm (x - y) ≤ ¦e¦ / 2 + norm (x - y - (e / 2) *R k)"
              apply (rule order_trans,rule norm_triangle_sub[of "x - y" "(e/2) *R k"])
              unfolding norm_scaleR norm_Basis[OF k]
              apply auto
              done
            also have "… < ¦e¦ / 2 + ¦e¦ / 2"
              apply (rule add_strict_left_mono)
              using as e
              apply (auto simp add: field_simps dist_norm)
              done
            finally show "y ∈ ball x e"
              unfolding mem_ball dist_norm using e by (auto simp add:field_simps)
          qed
          ultimately show ?thesis
            apply (rule_tac x="?z" in exI)
            unfolding Union_insert
            apply auto
            done
        next
          let ?z = "x + (e/2) *R k"
          assume as: "x∙k = b∙k"
          have "ball ?z (e / 2) ∩ i = {}"
          proof (clarsimp simp only: all_not_in_conv [symmetric])
            fix y
            assume "y ∈ ball ?z (e / 2)" and yi: "y ∈ i"
            then have "dist ?z y < e/2"
              by auto
            then have "¦(?z - y) ∙ k¦ < e/2"
              using Basis_le_norm[OF k, of "?z - y"]
              unfolding dist_norm by auto
            then have "y∙k > b∙k"
              using e k
              by (auto simp add:field_simps inner_simps inner_Basis as)
            then have "y ∉ i"
              unfolding ab mem_box by (auto intro!: bexI[OF _ k])
            then show False using yi by auto
          qed
          moreover
          have "ball ?z (e/2) ⊆ s ∩ (⋃insert i f)"
            apply (rule order_trans[OF _ e[THEN conjunct2, unfolded lem1]])
          proof
            fix y
            assume as: "y∈ ball ?z (e/2)"
            have "norm (x - y) ≤ ¦e¦ / 2 + norm (x - y + (e / 2) *R k)"
              apply (rule order_trans,rule norm_triangle_sub[of "x - y" "- (e/2) *R k"])
              unfolding norm_scaleR
              apply (auto simp: k)
              done
            also have "… < ¦e¦ / 2 + ¦e¦ / 2"
              apply (rule add_strict_left_mono)
              using as unfolding mem_ball dist_norm
              using e apply (auto simp add: field_simps)
              done
            finally show "y ∈ ball x e"
              unfolding mem_ball dist_norm using e by (auto simp add:field_simps)
          qed
          ultimately show ?thesis
            apply (rule_tac x="?z" in exI)
            unfolding Union_insert
            apply auto
            done
        qed
        then obtain x where "ball x (e / 2) ⊆ s ∩ ⋃f" ..
        then have "x ∈ s ∩ interior (⋃f)"
          unfolding lem1[where U="⋃f", symmetric]
          using centre_in_ball e by auto
        then show ?thesis
          using insert.hyps(3) insert.prems(1) by blast
      qed
    qed
  qed
  from this[OF assms(1,3)] x
  obtain t x e where "t ∈ f" "0 < e" "ball x e ⊆ s ∩ t"
    by blast
  then have "x ∈ s" "x ∈ interior t"
    using open_subset_interior[OF open_ball, of x e t]
    by auto
  then show False
    using ‹t ∈ f› assms(4) by auto
qed

subsection ‹Bounds on intervals where they exist.›

definition interval_upperbound :: "('a::euclidean_space) set ⇒ 'a"
  where "interval_upperbound s = (∑i∈Basis. (SUP x:s. x∙i) *R i)"

definition interval_lowerbound :: "('a::euclidean_space) set ⇒ 'a"
   where "interval_lowerbound s = (∑i∈Basis. (INF x:s. x∙i) *R i)"

lemma interval_upperbound[simp]:
  "∀i∈Basis. a∙i ≤ b∙i ⟹
    interval_upperbound (cbox a b) = (b::'a::euclidean_space)"
  unfolding interval_upperbound_def euclidean_representation_setsum cbox_def SUP_def
  by (safe intro!: cSup_eq) auto

lemma interval_lowerbound[simp]:
  "∀i∈Basis. a∙i ≤ b∙i ⟹
    interval_lowerbound (cbox a b) = (a::'a::euclidean_space)"
  unfolding interval_lowerbound_def euclidean_representation_setsum cbox_def INF_def
  by (safe intro!: cInf_eq) auto

lemmas interval_bounds = interval_upperbound interval_lowerbound

lemma
  fixes X::"real set"
  shows interval_upperbound_real[simp]: "interval_upperbound X = Sup X"
    and interval_lowerbound_real[simp]: "interval_lowerbound X = Inf X"
  by (auto simp: interval_upperbound_def interval_lowerbound_def SUP_def INF_def)

lemma interval_bounds'[simp]:
  assumes "cbox a b ≠ {}"
  shows "interval_upperbound (cbox a b) = b"
    and "interval_lowerbound (cbox a b) = a"
  using assms unfolding box_ne_empty by auto


lemma interval_upperbound_Times:
  assumes "A ≠ {}" and "B ≠ {}"
  shows "interval_upperbound (A × B) = (interval_upperbound A, interval_upperbound B)"
proof-
  from assms have fst_image_times': "A = fst ` (A × B)" by simp
  have "(∑i∈Basis. (SUP x:A × B. x ∙ (i, 0)) *R i) = (∑i∈Basis. (SUP x:A. x ∙ i) *R i)"
      by (subst (2) fst_image_times') (simp del: fst_image_times add: o_def inner_Pair_0)
  moreover from assms have snd_image_times': "B = snd ` (A × B)" by simp
  have "(∑i∈Basis. (SUP x:A × B. x ∙ (0, i)) *R i) = (∑i∈Basis. (SUP x:B. x ∙ i) *R i)"
      by (subst (2) snd_image_times') (simp del: snd_image_times add: o_def inner_Pair_0)
  ultimately show ?thesis unfolding interval_upperbound_def
      by (subst setsum_Basis_prod_eq) (auto simp add: setsum_prod)
qed

lemma interval_lowerbound_Times:
  assumes "A ≠ {}" and "B ≠ {}"
  shows "interval_lowerbound (A × B) = (interval_lowerbound A, interval_lowerbound B)"
proof-
  from assms have fst_image_times': "A = fst ` (A × B)" by simp
  have "(∑i∈Basis. (INF x:A × B. x ∙ (i, 0)) *R i) = (∑i∈Basis. (INF x:A. x ∙ i) *R i)"
      by (subst (2) fst_image_times') (simp del: fst_image_times add: o_def inner_Pair_0)
  moreover from assms have snd_image_times': "B = snd ` (A × B)" by simp
  have "(∑i∈Basis. (INF x:A × B. x ∙ (0, i)) *R i) = (∑i∈Basis. (INF x:B. x ∙ i) *R i)"
      by (subst (2) snd_image_times') (simp del: snd_image_times add: o_def inner_Pair_0)
  ultimately show ?thesis unfolding interval_lowerbound_def
      by (subst setsum_Basis_prod_eq) (auto simp add: setsum_prod)
qed

subsection ‹Content (length, area, volume...) of an interval.›

definition "content (s::('a::euclidean_space) set) =
  (if s = {} then 0 else (∏i∈Basis. (interval_upperbound s)∙i - (interval_lowerbound s)∙i))"

lemma interval_not_empty: "∀i∈Basis. a∙i ≤ b∙i ⟹ cbox a b ≠ {}"
  unfolding box_eq_empty unfolding not_ex not_less by auto

lemma content_cbox:
  fixes a :: "'a::euclidean_space"
  assumes "∀i∈Basis. a∙i ≤ b∙i"
  shows "content (cbox a b) = (∏i∈Basis. b∙i - a∙i)"
  using interval_not_empty[OF assms]
  unfolding content_def
  by auto

lemma content_cbox':
  fixes a :: "'a::euclidean_space"
  assumes "cbox a b ≠ {}"
  shows "content (cbox a b) = (∏i∈Basis. b∙i - a∙i)"
    using assms box_ne_empty(1) content_cbox by blast

lemma content_real: "a ≤ b ⟹ content {a..b} = b - a"
  by (auto simp: interval_upperbound_def interval_lowerbound_def SUP_def INF_def content_def)

lemma abs_eq_content: "¦y - x¦ = (if x≤y then content {x .. y} else content {y..x})"
  by (auto simp: content_real)

lemma content_singleton[simp]: "content {a} = 0"
proof -
  have "content (cbox a a) = 0"
    by (subst content_cbox) (auto simp: ex_in_conv)
  then show ?thesis by (simp add: cbox_sing)
qed

lemma content_unit[iff]: "content(cbox 0 (One::'a::euclidean_space)) = 1"
 proof -
   have *: "∀i∈Basis. (0::'a)∙i ≤ (One::'a)∙i"
    by auto
  have "0 ∈ cbox 0 (One::'a)"
    unfolding mem_box by auto
  then show ?thesis
     unfolding content_def interval_bounds[OF *] using setprod.neutral_const by auto
 qed

lemma content_pos_le[intro]:
  fixes a::"'a::euclidean_space"
  shows "0 ≤ content (cbox a b)"
proof (cases "cbox a b = {}")
  case False
  then have *: "∀i∈Basis. a ∙ i ≤ b ∙ i"
    unfolding box_ne_empty .
  have "0 ≤ (∏i∈Basis. interval_upperbound (cbox a b) ∙ i - interval_lowerbound (cbox a b) ∙ i)"
    apply (rule setprod_nonneg)
    unfolding interval_bounds[OF *]
    using *
    apply auto
    done
  also have "… = content (cbox a b)" using False by (simp add: content_def)
  finally show ?thesis .
qed (simp add: content_def)

corollary content_nonneg [simp]:
  fixes a::"'a::euclidean_space"
  shows "~ content (cbox a b) < 0"
using not_le by blast

lemma content_pos_lt:
  fixes a :: "'a::euclidean_space"
  assumes "∀i∈Basis. a∙i < b∙i"
  shows "0 < content (cbox a b)"
  using assms
  by (auto simp: content_def box_eq_empty intro!: setprod_pos)

lemma content_eq_0:
  "content (cbox a b) = 0 ⟷ (∃i∈Basis. b∙i ≤ a∙i)"
  by (auto simp: content_def box_eq_empty intro!: setprod_pos bexI)

lemma cond_cases: "(P ⟹ Q x) ⟹ (¬ P ⟹ Q y) ⟹ Q (if P then x else y)"
  by auto

lemma content_cbox_cases:
  "content (cbox a (b::'a::euclidean_space)) =
    (if ∀i∈Basis. a∙i ≤ b∙i then setprod (λi. b∙i - a∙i) Basis else 0)"
  by (auto simp: not_le content_eq_0 intro: less_imp_le content_cbox)

lemma content_eq_0_interior: "content (cbox a b) = 0 ⟷ interior(cbox a b) = {}"
  unfolding content_eq_0 interior_cbox box_eq_empty
  by auto

lemma content_pos_lt_eq:
  "0 < content (cbox a (b::'a::euclidean_space)) ⟷ (∀i∈Basis. a∙i < b∙i)"
proof (rule iffI)
  assume "0 < content (cbox a b)"
  then have "content (cbox a b) ≠ 0" by auto
  then show "∀i∈Basis. a∙i < b∙i"
    unfolding content_eq_0 not_ex not_le by fastforce
next
  assume "∀i∈Basis. a ∙ i < b ∙ i"
  then show "0 < content (cbox a b)"
    by (metis content_pos_lt)
qed

lemma content_empty [simp]: "content {} = 0"
  unfolding content_def by auto

lemma content_real_if [simp]: "content {a..b} = (if a ≤ b then b - a else 0)"
  by (simp add: content_real)

lemma content_subset:
  assumes "cbox a b ⊆ cbox c d"
  shows "content (cbox a b) ≤ content (cbox c d)"
proof (cases "cbox a b = {}")
  case True
  then show ?thesis
    using content_pos_le[of c d] by auto
next
  case False
  then have ab_ne: "∀i∈Basis. a ∙ i ≤ b ∙ i"
    unfolding box_ne_empty by auto
  then have ab_ab: "a∈cbox a b" "b∈cbox a b"
    unfolding mem_box by auto
  have "cbox c d ≠ {}" using assms False by auto
  then have cd_ne: "∀i∈Basis. c ∙ i ≤ d ∙ i"
    using assms unfolding box_ne_empty by auto
  have "⋀i. i ∈ Basis ⟹ 0 ≤ b ∙ i - a ∙ i"
    using ab_ne by auto
  moreover
  have "⋀i. i ∈ Basis ⟹ b ∙ i - a ∙ i ≤ d ∙ i - c ∙ i"
    using assms[unfolded subset_eq mem_box,rule_format,OF ab_ab(2)]
          assms[unfolded subset_eq mem_box,rule_format,OF ab_ab(1)]
      by (metis diff_mono)
  ultimately show ?thesis
    unfolding content_def interval_bounds[OF ab_ne] interval_bounds[OF cd_ne]
    by (simp add: setprod_mono if_not_P[OF False] if_not_P[OF ‹cbox c d ≠ {}›])
qed

lemma content_lt_nz: "0 < content (cbox a b) ⟷ content (cbox a b) ≠ 0"
  unfolding content_pos_lt_eq content_eq_0 unfolding not_ex not_le by fastforce

lemma content_times[simp]: "content (A × B) = content A * content B"
proof (cases "A × B = {}")
  let ?ub1 = "interval_upperbound" and ?lb1 = "interval_lowerbound"
  let ?ub2 = "interval_upperbound" and ?lb2 = "interval_lowerbound"
  assume nonempty: "A × B ≠ {}"
  hence "content (A × B) = (∏i∈Basis. (?ub1 A, ?ub2 B) ∙ i - (?lb1 A, ?lb2 B) ∙ i)"
      unfolding content_def by (simp add: interval_upperbound_Times interval_lowerbound_Times)
  also have "... = content A * content B" unfolding content_def using nonempty
    apply (subst Basis_prod_def, subst setprod.union_disjoint, force, force, force, simp)
    apply (subst (1 2) setprod.reindex, auto intro: inj_onI)
    done
  finally show ?thesis .
qed (auto simp: content_def)

lemma content_Pair: "content (cbox (a,c) (b,d)) = content (cbox a b) * content (cbox c d)"
  by (simp add: cbox_Pair_eq)

lemma content_cbox_pair_eq0_D:
   "content (cbox (a,c) (b,d)) = 0 ⟹ content (cbox a b) = 0 ∨ content (cbox c d) = 0"
  by (simp add: content_Pair)

lemma content_eq_0_gen:
  fixes s :: "'a::euclidean_space set"
  assumes "bounded s"
  shows "content s = 0 ⟷ (∃i∈Basis. ∃v. ∀x ∈ s. x ∙ i = v)"  (is "_ = ?rhs")
proof safe
  assume "content s = 0" then show ?rhs
    apply (clarsimp simp: ex_in_conv content_def split: split_if_asm)
    apply (rule_tac x=a in bexI)
    apply (rule_tac x="interval_lowerbound s ∙ a" in exI)
    apply (clarsimp simp: interval_upperbound_def interval_lowerbound_def)
    apply (drule cSUP_eq_cINF_D)
    apply (auto simp: bounded_inner_imp_bdd_above [OF assms]  bounded_inner_imp_bdd_below [OF assms])
    done
next
  fix i a
  assume "i ∈ Basis" "∀x∈s. x ∙ i = a"
  then show "content s = 0"
    apply (clarsimp simp: content_def)
    apply (rule_tac x=i in bexI)
    apply (auto simp: interval_upperbound_def interval_lowerbound_def)
    done
qed

lemma content_0_subset_gen:
  fixes a :: "'a::euclidean_space"
  assumes "content t = 0" "s ⊆ t" "bounded t" shows "content s = 0"
proof -
  have "bounded s"
    using assms by (metis bounded_subset)
  then show ?thesis
    using assms
    by (auto simp: content_eq_0_gen)
qed

lemma content_0_subset: "⟦content(cbox a b) = 0; s ⊆ cbox a b⟧ ⟹ content s = 0"
  by (simp add: content_0_subset_gen bounded_cbox)


subsection ‹The notion of a gauge --- simply an open set containing the point.›

definition "gauge d ⟷ (∀x. x ∈ d x ∧ open (d x))"

lemma gaugeI:
  assumes "⋀x. x ∈ g x"
    and "⋀x. open (g x)"
  shows "gauge g"
  using assms unfolding gauge_def by auto

lemma gaugeD[dest]:
  assumes "gauge d"
  shows "x ∈ d x"
    and "open (d x)"
  using assms unfolding gauge_def by auto

lemma gauge_ball_dependent: "∀x. 0 < e x ⟹ gauge (λx. ball x (e x))"
  unfolding gauge_def by auto

lemma gauge_ball[intro]: "0 < e ⟹ gauge (λx. ball x e)"
  unfolding gauge_def by auto

lemma gauge_trivial[intro!]: "gauge (λx. ball x 1)"
  by (rule gauge_ball) auto

lemma gauge_inter[intro]: "gauge d1 ⟹ gauge d2 ⟹ gauge (λx. d1 x ∩ d2 x)"
  unfolding gauge_def by auto

lemma gauge_inters:
  assumes "finite s"
    and "∀d∈s. gauge (f d)"
  shows "gauge (λx. ⋂{f d x | d. d ∈ s})"
proof -
  have *: "⋀x. {f d x |d. d ∈ s} = (λd. f d x) ` s"
    by auto
  show ?thesis
    unfolding gauge_def unfolding *
    using assms unfolding Ball_def Inter_iff mem_Collect_eq gauge_def by auto
qed

lemma gauge_existence_lemma:
  "(∀x. ∃d :: real. p x ⟶ 0 < d ∧ q d x) ⟷ (∀x. ∃d>0. p x ⟶ q d x)"
  by (metis zero_less_one)


subsection ‹Divisions.›

definition division_of (infixl "division'_of" 40)
where
  "s division_of i ⟷
    finite s ∧
    (∀k∈s. k ⊆ i ∧ k ≠ {} ∧ (∃a b. k = cbox a b)) ∧
    (∀k1∈s. ∀k2∈s. k1 ≠ k2 ⟶ interior(k1) ∩ interior(k2) = {}) ∧
    (⋃s = i)"

lemma division_ofD[dest]:
  assumes "s division_of i"
  shows "finite s"
    and "⋀k. k ∈ s ⟹ k ⊆ i"
    and "⋀k. k ∈ s ⟹ k ≠ {}"
    and "⋀k. k ∈ s ⟹ ∃a b. k = cbox a b"
    and "⋀k1 k2. k1 ∈ s ⟹ k2 ∈ s ⟹ k1 ≠ k2 ⟹ interior(k1) ∩ interior(k2) = {}"
    and "⋃s = i"
  using assms unfolding division_of_def by auto

lemma division_ofI:
  assumes "finite s"
    and "⋀k. k ∈ s ⟹ k ⊆ i"
    and "⋀k. k ∈ s ⟹ k ≠ {}"
    and "⋀k. k ∈ s ⟹ ∃a b. k = cbox a b"
    and "⋀k1 k2. k1 ∈ s ⟹ k2 ∈ s ⟹ k1 ≠ k2 ⟹ interior k1 ∩ interior k2 = {}"
    and "⋃s = i"
  shows "s division_of i"
  using assms unfolding division_of_def by auto

lemma division_of_finite: "s division_of i ⟹ finite s"
  unfolding division_of_def by auto

lemma division_of_self[intro]: "cbox a b ≠ {} ⟹ {cbox a b} division_of (cbox a b)"
  unfolding division_of_def by auto

lemma division_of_trivial[simp]: "s division_of {} ⟷ s = {}"
  unfolding division_of_def by auto

lemma division_of_sing[simp]:
  "s division_of cbox a (a::'a::euclidean_space) ⟷ s = {cbox a a}"
  (is "?l = ?r")
proof
  assume ?r
  moreover
  { fix k
    assume "s = {{a}}" "k∈s"
    then have "∃x y. k = cbox x y"
      apply (rule_tac x=a in exI)+
      apply (force simp: cbox_sing)
      done
  }
  ultimately show ?l
    unfolding division_of_def cbox_sing by auto
next
  assume ?l
  note * = conjunctD4[OF this[unfolded division_of_def cbox_sing]]
  {
    fix x
    assume x: "x ∈ s" have "x = {a}"
      using *(2)[rule_format,OF x] by auto
  }
  moreover have "s ≠ {}"
    using *(4) by auto
  ultimately show ?r
    unfolding cbox_sing by auto
qed

lemma elementary_empty: obtains p where "p division_of {}"
  unfolding division_of_trivial by auto

lemma elementary_interval: obtains p where "p division_of (cbox a b)"
  by (metis division_of_trivial division_of_self)

lemma division_contains: "s division_of i ⟹ ∀x∈i. ∃k∈s. x ∈ k"
  unfolding division_of_def by auto

lemma forall_in_division:
  "d division_of i ⟹ (∀x∈d. P x) ⟷ (∀a b. cbox a b ∈ d ⟶ P (cbox a b))"
  unfolding division_of_def by fastforce

lemma division_of_subset:
  assumes "p division_of (⋃p)"
    and "q ⊆ p"
  shows "q division_of (⋃q)"
proof (rule division_ofI)
  note * = division_ofD[OF assms(1)]
  show "finite q"
    using "*"(1) assms(2) infinite_super by auto
  {
    fix k
    assume "k ∈ q"
    then have kp: "k ∈ p"
      using assms(2) by auto
    show "k ⊆ ⋃q"
      using ‹k ∈ q› by auto
    show "∃a b. k = cbox a b"
      using *(4)[OF kp] by auto
    show "k ≠ {}"
      using *(3)[OF kp] by auto
  }
  fix k1 k2
  assume "k1 ∈ q" "k2 ∈ q" "k1 ≠ k2"
  then have **: "k1 ∈ p" "k2 ∈ p" "k1 ≠ k2"
    using assms(2) by auto
  show "interior k1 ∩ interior k2 = {}"
    using *(5)[OF **] by auto
qed auto

lemma division_of_union_self[intro]: "p division_of s ⟹ p division_of (⋃p)"
  unfolding division_of_def by auto

lemma division_of_content_0:
  assumes "content (cbox a b) = 0" "d division_of (cbox a b)"
  shows "∀k∈d. content k = 0"
  unfolding forall_in_division[OF assms(2)]
  by (metis antisym_conv assms content_pos_le content_subset division_ofD(2))

lemma division_inter:
  fixes s1 s2 :: "'a::euclidean_space set"
  assumes "p1 division_of s1"
    and "p2 division_of s2"
  shows "{k1 ∩ k2 | k1 k2 .k1 ∈ p1 ∧ k2 ∈ p2 ∧ k1 ∩ k2 ≠ {}} division_of (s1 ∩ s2)"
  (is "?A' division_of _")
proof -
  let ?A = "{s. s ∈  (λ(k1,k2). k1 ∩ k2) ` (p1 × p2) ∧ s ≠ {}}"
  have *: "?A' = ?A" by auto
  show ?thesis
    unfolding *
  proof (rule division_ofI)
    have "?A ⊆ (λ(x, y). x ∩ y) ` (p1 × p2)"
      by auto
    moreover have "finite (p1 × p2)"
      using assms unfolding division_of_def by auto
    ultimately show "finite ?A" by auto
    have *: "⋀s. ⋃{x∈s. x ≠ {}} = ⋃s"
      by auto
    show "⋃?A = s1 ∩ s2"
      apply (rule set_eqI)
      unfolding * and Union_image_eq UN_iff
      using division_ofD(6)[OF assms(1)] and division_ofD(6)[OF assms(2)]
      apply auto
      done
    {
      fix k
      assume "k ∈ ?A"
      then obtain k1 k2 where k: "k = k1 ∩ k2" "k1 ∈ p1" "k2 ∈ p2" "k ≠ {}"
        by auto
      then show "k ≠ {}"
        by auto
      show "k ⊆ s1 ∩ s2"
        using division_ofD(2)[OF assms(1) k(2)] and division_ofD(2)[OF assms(2) k(3)]
        unfolding k by auto
      obtain a1 b1 where k1: "k1 = cbox a1 b1"
        using division_ofD(4)[OF assms(1) k(2)] by blast
      obtain a2 b2 where k2: "k2 = cbox a2 b2"
        using division_ofD(4)[OF assms(2) k(3)] by blast
      show "∃a b. k = cbox a b"
        unfolding k k1 k2 unfolding inter_interval by auto
    }
    fix k1 k2
    assume "k1 ∈ ?A"
    then obtain x1 y1 where k1: "k1 = x1 ∩ y1" "x1 ∈ p1" "y1 ∈ p2" "k1 ≠ {}"
      by auto
    assume "k2 ∈ ?A"
    then obtain x2 y2 where k2: "k2 = x2 ∩ y2" "x2 ∈ p1" "y2 ∈ p2" "k2 ≠ {}"
      by auto
    assume "k1 ≠ k2"
    then have th: "x1 ≠ x2 ∨ y1 ≠ y2"
      unfolding k1 k2 by auto
    have *: "interior x1 ∩ interior x2 = {} ∨ interior y1 ∩ interior y2 = {} ⟹
      interior (x1 ∩ y1) ⊆ interior x1 ⟹ interior (x1 ∩ y1) ⊆ interior y1 ⟹
      interior (x2 ∩ y2) ⊆ interior x2 ⟹ interior (x2 ∩ y2) ⊆ interior y2 ⟹
      interior (x1 ∩ y1) ∩ interior (x2 ∩ y2) = {}" by auto
    show "interior k1 ∩ interior k2 = {}"
      unfolding k1 k2
      apply (rule *)
      using assms division_ofD(5) k1 k2(2) k2(3) th apply auto
      done
  qed
qed

lemma division_inter_1:
  assumes "d division_of i"
    and "cbox a (b::'a::euclidean_space) ⊆ i"
  shows "{cbox a b ∩ k | k. k ∈ d ∧ cbox a b ∩ k ≠ {}} division_of (cbox a b)"
proof (cases "cbox a b = {}")
  case True
  show ?thesis
    unfolding True and division_of_trivial by auto
next
  case False
  have *: "cbox a b ∩ i = cbox a b" using assms(2) by auto
  show ?thesis
    using division_inter[OF division_of_self[OF False] assms(1)]
    unfolding * by auto
qed

lemma elementary_inter:
  fixes s t :: "'a::euclidean_space set"
  assumes "p1 division_of s"
    and "p2 division_of t"
  shows "∃p. p division_of (s ∩ t)"
using assms division_inter by blast

lemma elementary_inters:
  assumes "finite f"
    and "f ≠ {}"
    and "∀s∈f. ∃p. p division_of (s::('a::euclidean_space) set)"
  shows "∃p. p division_of (⋂f)"
  using assms
proof (induct f rule: finite_induct)
  case (insert x f)
  show ?case
  proof (cases "f = {}")
    case True
    then show ?thesis
      unfolding True using insert by auto
  next
    case False
    obtain p where "p division_of ⋂f"
      using insert(3)[OF False insert(5)[unfolded ball_simps,THEN conjunct2]] ..
    moreover obtain px where "px division_of x"
      using insert(5)[rule_format,OF insertI1] ..
    ultimately show ?thesis
      by (simp add: elementary_inter Inter_insert)
  qed
qed auto

lemma division_disjoint_union:
  assumes "p1 division_of s1"
    and "p2 division_of s2"
    and "interior s1 ∩ interior s2 = {}"
  shows "(p1 ∪ p2) division_of (s1 ∪ s2)"
proof (rule division_ofI)
  note d1 = division_ofD[OF assms(1)]
  note d2 = division_ofD[OF assms(2)]
  show "finite (p1 ∪ p2)"
    using d1(1) d2(1) by auto
  show "⋃(p1 ∪ p2) = s1 ∪ s2"
    using d1(6) d2(6) by auto
  {
    fix k1 k2
    assume as: "k1 ∈ p1 ∪ p2" "k2 ∈ p1 ∪ p2" "k1 ≠ k2"
    moreover
    let ?g="interior k1 ∩ interior k2 = {}"
    {
      assume as: "k1∈p1" "k2∈p2"
      have ?g
        using interior_mono[OF d1(2)[OF as(1)]] interior_mono[OF d2(2)[OF as(2)]]
        using assms(3) by blast
    }
    moreover
    {
      assume as: "k1∈p2" "k2∈p1"
      have ?g
        using interior_mono[OF d1(2)[OF as(2)]] interior_mono[OF d2(2)[OF as(1)]]
        using assms(3) by blast
    }
    ultimately show ?g
      using d1(5)[OF _ _ as(3)] and d2(5)[OF _ _ as(3)] by auto
  }
  fix k
  assume k: "k ∈ p1 ∪ p2"
  show "k ⊆ s1 ∪ s2"
    using k d1(2) d2(2) by auto
  show "k ≠ {}"
    using k d1(3) d2(3) by auto
  show "∃a b. k = cbox a b"
    using k d1(4) d2(4) by auto
qed

lemma partial_division_extend_1:
  fixes a b c d :: "'a::euclidean_space"
  assumes incl: "cbox c d ⊆ cbox a b"
    and nonempty: "cbox c d ≠ {}"
  obtains p where "p division_of (cbox a b)" "cbox c d ∈ p"
proof
  let ?B = "λf::'a⇒'a × 'a.
    cbox (∑i∈Basis. (fst (f i) ∙ i) *R i) (∑i∈Basis. (snd (f i) ∙ i) *R i)"
  def p  "?B ` (Basis →E {(a, c), (c, d), (d, b)})"

  show "cbox c d ∈ p"
    unfolding p_def
    by (auto simp add: box_eq_empty cbox_def intro!: image_eqI[where x="λ(i::'a)∈Basis. (c, d)"])
  {
    fix i :: 'a
    assume "i ∈ Basis"
    with incl nonempty have "a ∙ i ≤ c ∙ i" "c ∙ i ≤ d ∙ i" "d ∙ i ≤ b ∙ i"
      unfolding box_eq_empty subset_box by (auto simp: not_le)
  }
  note ord = this

  show "p division_of (cbox a b)"
  proof (rule division_ofI)
    show "finite p"
      unfolding p_def by (auto intro!: finite_PiE)
    {
      fix k
      assume "k ∈ p"
      then obtain f where f: "f ∈ Basis →E {(a, c), (c, d), (d, b)}" and k: "k = ?B f"
        by (auto simp: p_def)
      then show "∃a b. k = cbox a b"
        by auto
      have "k ⊆ cbox a b ∧ k ≠ {}"
      proof (simp add: k box_eq_empty subset_box not_less, safe)
        fix i :: 'a
        assume i: "i ∈ Basis"
        with f have "f i = (a, c) ∨ f i = (c, d) ∨ f i = (d, b)"
          by (auto simp: PiE_iff)
        with i ord[of i]
        show "a ∙ i ≤ fst (f i) ∙ i" "snd (f i) ∙ i ≤ b ∙ i" "fst (f i) ∙ i ≤ snd (f i) ∙ i"
          by auto
      qed
      then show "k ≠ {}" "k ⊆ cbox a b"
        by auto
      {
        fix l
        assume "l ∈ p"
        then obtain g where g: "g ∈ Basis →E {(a, c), (c, d), (d, b)}" and l: "l = ?B g"
          by (auto simp: p_def)
        assume "l ≠ k"
        have "∃i∈Basis. f i ≠ g i"
        proof (rule ccontr)
          assume "¬ ?thesis"
          with f g have "f = g"
            by (auto simp: PiE_iff extensional_def intro!: ext)
          with ‹l ≠ k› show False
            by (simp add: l k)
        qed
        then obtain i where *: "i ∈ Basis" "f i ≠ g i" ..
        then have "f i = (a, c) ∨ f i = (c, d) ∨ f i = (d, b)"
                  "g i = (a, c) ∨ g i = (c, d) ∨ g i = (d, b)"
          using f g by (auto simp: PiE_iff)
        with * ord[of i] show "interior l ∩ interior k = {}"
          by (auto simp add: l k interior_cbox disjoint_interval intro!: bexI[of _ i])
      }
      note ‹k ⊆ cbox a b›
    }
    moreover
    {
      fix x assume x: "x ∈ cbox a b"
      have "∀i∈Basis. ∃l. x ∙ i ∈ {fst l ∙ i .. snd l ∙ i} ∧ l ∈ {(a, c), (c, d), (d, b)}"
      proof
        fix i :: 'a
        assume "i ∈ Basis"
        with x ord[of i]
        have "(a ∙ i ≤ x ∙ i ∧ x ∙ i ≤ c ∙ i) ∨ (c ∙ i ≤ x ∙ i ∧ x ∙ i ≤ d ∙ i) ∨
            (d ∙ i ≤ x ∙ i ∧ x ∙ i ≤ b ∙ i)"
          by (auto simp: cbox_def)
        then show "∃l. x ∙ i ∈ {fst l ∙ i .. snd l ∙ i} ∧ l ∈ {(a, c), (c, d), (d, b)}"
          by auto
      qed
      then obtain f where
        f: "∀i∈Basis. x ∙ i ∈ {fst (f i) ∙ i..snd (f i) ∙ i} ∧ f i ∈ {(a, c), (c, d), (d, b)}"
        unfolding bchoice_iff ..
      moreover from f have "restrict f Basis ∈ Basis →E {(a, c), (c, d), (d, b)}"
        by auto
      moreover from f have "x ∈ ?B (restrict f Basis)"
        by (auto simp: mem_box)
      ultimately have "∃k∈p. x ∈ k"
        unfolding p_def by blast
    }
    ultimately show "⋃p = cbox a b"
      by auto
  qed
qed

lemma partial_division_extend_interval:
  assumes "p division_of (⋃p)" "(⋃p) ⊆ cbox a b"
  obtains q where "p ⊆ q" "q division_of cbox a (b::'a::euclidean_space)"
proof (cases "p = {}")
  case True
  obtain q where "q division_of (cbox a b)"
    by (rule elementary_interval)
  then show ?thesis
    using True that by blast
next
  case False
  note p = division_ofD[OF assms(1)]
  have div_cbox: "∀k∈p. ∃q. q division_of cbox a b ∧ k ∈ q"
  proof
    fix k
    assume kp: "k ∈ p"
    obtain c d where k: "k = cbox c d"
      using p(4)[OF kp] by blast
    have *: "cbox c d ⊆ cbox a b" "cbox c d ≠ {}"
      using p(2,3)[OF kp, unfolded k] using assms(2)
      by (blast intro: order.trans)+
    obtain q where "q division_of cbox a b" "cbox c d ∈ q"
      by (rule partial_division_extend_1[OF *])
    then show "∃q. q division_of cbox a b ∧ k ∈ q"
      unfolding k by auto
  qed
  obtain q where q: "⋀x. x ∈ p ⟹ q x division_of cbox a b" "⋀x. x ∈ p ⟹ x ∈ q x"
    using bchoice[OF div_cbox] by blast
  { fix x
    assume x: "x ∈ p"
    have "q x division_of ⋃q x"
      apply (rule division_ofI)
      using division_ofD[OF q(1)[OF x]]
      apply auto
      done }
  then have "⋀x. x ∈ p ⟹ ∃d. d division_of ⋃(q x - {x})"
    by (meson Diff_subset division_of_subset)
  then have "∃d. d division_of ⋂((λi. ⋃(q i - {i})) ` p)"
    apply -
    apply (rule elementary_inters [OF finite_imageI[OF p(1)]])
    apply (auto simp: False elementary_inters [OF finite_imageI[OF p(1)]])
    done
  then obtain d where d: "d division_of ⋂((λi. ⋃(q i - {i})) ` p)" ..
  have "d ∪ p division_of cbox a b"
  proof -
    have te: "⋀s f t. s ≠ {} ⟹ ∀i∈s. f i ∪ i = t ⟹ t = ⋂(f ` s) ∪ ⋃s" by auto
    have cbox_eq: "cbox a b = ⋂((λi. ⋃(q i - {i})) ` p) ∪ ⋃p"
    proof (rule te[OF False], clarify)
      fix i
      assume i: "i ∈ p"
      show "⋃(q i - {i}) ∪ i = cbox a b"
        using division_ofD(6)[OF q(1)[OF i]] using q(2)[OF i] by auto
    qed
    { fix k
      assume k: "k ∈ p"
      have *: "⋀u t s. t ∩ s = {} ⟹ u ⊆ s ⟹ u ∩ t = {}"
        by auto
      have "interior (⋂i∈p. ⋃(q i - {i})) ∩ interior k = {}"
      proof (rule *[OF inter_interior_unions_intervals])
        note qk=division_ofD[OF q(1)[OF k]]
        show "finite (q k - {k})" "open (interior k)" "∀t∈q k - {k}. ∃a b. t = cbox a b"
          using qk by auto
        show "∀t∈q k - {k}. interior k ∩ interior t = {}"
          using qk(5) using q(2)[OF k] by auto
        show "interior (⋂i∈p. ⋃(q i - {i})) ⊆ interior (⋃(q k - {k}))"
          apply (rule interior_mono)+
          using k
          apply auto
          done
      qed } note [simp] = this
    show "d ∪ p division_of (cbox a b)"
      unfolding cbox_eq
      apply (rule division_disjoint_union[OF d assms(1)])
      apply (rule inter_interior_unions_intervals)
      apply (rule p open_interior ballI)+
      apply simp_all
      done
  qed
  then show ?thesis
    by (meson Un_upper2 that)
qed

lemma elementary_bounded[dest]:
  fixes s :: "'a::euclidean_space set"
  shows "p division_of s ⟹ bounded s"
  unfolding division_of_def by (metis bounded_Union bounded_cbox)

lemma elementary_subset_cbox:
  "p division_of s ⟹ ∃a b. s ⊆ cbox a (b::'a::euclidean_space)"
  by (meson elementary_bounded bounded_subset_cbox)

lemma division_union_intervals_exists:
  fixes a b :: "'a::euclidean_space"
  assumes "cbox a b ≠ {}"
  obtains p where "(insert (cbox a b) p) division_of (cbox a b ∪ cbox c d)"
proof (cases "cbox c d = {}")
  case True
  show ?thesis
    apply (rule that[of "{}"])
    unfolding True
    using assms
    apply auto
    done
next
  case False
  show ?thesis
  proof (cases "cbox a b ∩ cbox c d = {}")
    case True
    show ?thesis
      apply (rule that[of "{cbox c d}"])
      apply (subst insert_is_Un)
      apply (rule division_disjoint_union)
      using ‹cbox c d ≠ {}› True assms interior_subset
      apply auto
      done
  next
    case False
    obtain u v where uv: "cbox a b ∩ cbox c d = cbox u v"
      unfolding inter_interval by auto
    have uv_sub: "cbox u v ⊆ cbox c d" using uv by auto
    obtain p where "p division_of cbox c d" "cbox u v ∈ p"
      by (rule partial_division_extend_1[OF uv_sub False[unfolded uv]])
    note p = this division_ofD[OF this(1)]
    have "interior (cbox a b ∩ ⋃(p - {cbox u v})) = interior(cbox u v ∩ ⋃(p - {cbox u v}))"
      apply (rule arg_cong[of _ _ interior])
      using p(8) uv by auto
    also have "… = {}"
      unfolding interior_Int
      apply (rule inter_interior_unions_intervals)
      using p(6) p(7)[OF p(2)] p(3)
      apply auto
      done
    finally have [simp]: "interior (cbox a b) ∩ interior (⋃(p - {cbox u v})) = {}" by simp
    have cbe: "cbox a b ∪ cbox c d = cbox a b ∪ ⋃(p - {cbox u v})"
      using p(8) unfolding uv[symmetric] by auto
    show ?thesis
      apply (rule that[of "p - {cbox u v}"])
      apply (simp add: cbe)
      apply (subst insert_is_Un)
      apply (rule division_disjoint_union)
      apply (simp_all add: assms division_of_self)
      by (metis Diff_subset division_of_subset p(1) p(8))
  qed
qed

lemma division_of_unions:
  assumes "finite f"
    and "⋀p. p ∈ f ⟹ p division_of (⋃p)"
    and "⋀k1 k2. k1 ∈ ⋃f ⟹ k2 ∈ ⋃f ⟹ k1 ≠ k2 ⟹ interior k1 ∩ interior k2 = {}"
  shows "⋃f division_of ⋃⋃f"
  using assms
  by (auto intro!: division_ofI)

lemma elementary_union_interval:
  fixes a b :: "'a::euclidean_space"
  assumes "p division_of ⋃p"
  obtains q where "q division_of (cbox a b ∪ ⋃p)"
proof -
  note assm = division_ofD[OF assms]
  have lem1: "⋀f s. ⋃⋃(f ` s) = ⋃((λx. ⋃(f x)) ` s)"
    by auto
  have lem2: "⋀f s. f ≠ {} ⟹ ⋃{s ∪ t |t. t ∈ f} = s ∪ ⋃f"
    by auto
  {
    presume "p = {} ⟹ thesis"
      "cbox a b = {} ⟹ thesis"
      "cbox a b ≠ {} ⟹ interior (cbox a b) = {} ⟹ thesis"
      "p ≠ {} ⟹ interior (cbox a b)≠{} ⟹ cbox a b ≠ {} ⟹ thesis"
    then show thesis by auto
  next
    assume as: "p = {}"
    obtain p where "p division_of (cbox a b)"
      by (rule elementary_interval)
    then show thesis
      using as that by auto
  next
    assume as: "cbox a b = {}"
    show thesis
      using as assms that by auto
  next
    assume as: "interior (cbox a b) = {}" "cbox a b ≠ {}"
    show thesis
      apply (rule that[of "insert (cbox a b) p"],rule division_ofI)
      unfolding finite_insert
      apply (rule assm(1)) unfolding Union_insert
      using assm(2-4) as
      apply -
      apply (fast dest: assm(5))+
      done
  next
    assume as: "p ≠ {}" "interior (cbox a b) ≠ {}" "cbox a b ≠ {}"
    have "∀k∈p. ∃q. (insert (cbox a b) q) division_of (cbox a b ∪ k)"
    proof
      fix k
      assume kp: "k ∈ p"
      from assm(4)[OF kp] obtain c d where "k = cbox c d" by blast
      then show "∃q. (insert (cbox a b) q) division_of (cbox a b ∪ k)"
        by (meson as(3) division_union_intervals_exists)
    qed
    from bchoice[OF this] obtain q where "∀x∈p. insert (cbox a b) (q x) division_of (cbox a b) ∪ x" ..
    note q = division_ofD[OF this[rule_format]]
    let ?D = "⋃{insert (cbox a b) (q k) | k. k ∈ p}"
    show thesis
    proof (rule that[OF division_ofI])
      have *: "{insert (cbox a b) (q k) |k. k ∈ p} = (λk. insert (cbox a b) (q k)) ` p"
        by auto
      show "finite ?D"
        using "*" assm(1) q(1) by auto
      show "⋃?D = cbox a b ∪ ⋃p"
        unfolding * lem1
        unfolding lem2[OF as(1), of "cbox a b", symmetric]
        using q(6)
        by auto
      fix k
      assume k: "k ∈ ?D"
      then show "k ⊆ cbox a b ∪ ⋃p"
        using q(2) by auto
      show "k ≠ {}"
        using q(3) k by auto
      show "∃a b. k = cbox a b"
        using q(4) k by auto
      fix k'
      assume k': "k' ∈ ?D" "k ≠ k'"
      obtain x where x: "k ∈ insert (cbox a b) (q x)" "x∈p"
        using k by auto
      obtain x' where x': "k'∈insert (cbox a b) (q x')" "x'∈p"
        using k' by auto
      show "interior k ∩ interior k' = {}"
      proof (cases "x = x'")
        case True
        show ?thesis
          using True k' q(5) x' x by auto
      next
        case False
        {
          presume "k = cbox a b ⟹ ?thesis"
            and "k' = cbox a b ⟹ ?thesis"
            and "k ≠ cbox a b ⟹ k' ≠ cbox a b ⟹ ?thesis"
          then show ?thesis by auto
        next
          assume as': "k  = cbox a b"
          show ?thesis
            using as' k' q(5) x' by auto
        next
          assume as': "k' = cbox a b"
          show ?thesis
            using as' k'(2) q(5) x by auto
        }
        assume as': "k ≠ cbox a b" "k' ≠ cbox a b"
        obtain c d where k: "k = cbox c d"
          using q(4)[OF x(2,1)] by blast
        have "interior k ∩ interior (cbox a b) = {}"
          using as' k'(2) q(5) x by auto
        then have "interior k ⊆ interior x"
        using interior_subset_union_intervals
          by (metis as(2) k q(2) x interior_subset_union_intervals)
        moreover
        obtain c d where c_d: "k' = cbox c d"
          using q(4)[OF x'(2,1)] by blast
        have "interior k' ∩ interior (cbox a b) = {}"
          using as'(2) q(5) x' by auto
        then have "interior k' ⊆ interior x'"
          by (metis as(2) c_d interior_subset_union_intervals q(2) x'(1) x'(2))
        ultimately show ?thesis
          using assm(5)[OF x(2) x'(2) False] by auto
      qed
    qed
  }
qed

lemma elementary_unions_intervals:
  assumes fin: "finite f"
    and "⋀s. s ∈ f ⟹ ∃a b. s = cbox a (b::'a::euclidean_space)"
  obtains p where "p division_of (⋃f)"
proof -
  have "∃p. p division_of (⋃f)"
  proof (induct_tac f rule:finite_subset_induct)
    show "∃p. p division_of ⋃{}" using elementary_empty by auto
  next
    fix x F
    assume as: "finite F" "x ∉ F" "∃p. p division_of ⋃F" "x∈f"
    from this(3) obtain p where p: "p division_of ⋃F" ..
    from assms(2)[OF as(4)] obtain a b where x: "x = cbox a b" by blast
    have *: "⋃F = ⋃p"
      using division_ofD[OF p] by auto
    show "∃p. p division_of ⋃insert x F"
      using elementary_union_interval[OF p[unfolded *], of a b]
      unfolding Union_insert x * by metis
  qed (insert assms, auto)
  then show ?thesis
    using that by auto
qed

lemma elementary_union:
  fixes s t :: "'a::euclidean_space set"
  assumes "ps division_of s" "pt division_of t"
  obtains p where "p division_of (s ∪ t)"
proof -
  have *: "s ∪ t = ⋃ps ∪ ⋃pt"
    using assms unfolding division_of_def by auto
  show ?thesis
    apply (rule elementary_unions_intervals[of "ps ∪ pt"])
    using assms apply auto
    by (simp add: * that)
qed

lemma partial_division_extend:
  fixes t :: "'a::euclidean_space set"
  assumes "p division_of s"
    and "q division_of t"
    and "s ⊆ t"
  obtains r where "p ⊆ r" and "r division_of t"
proof -
  note divp = division_ofD[OF assms(1)] and divq = division_ofD[OF assms(2)]
  obtain a b where ab: "t ⊆ cbox a b"
    using elementary_subset_cbox[OF assms(2)] by auto
  obtain r1 where "p ⊆ r1" "r1 division_of (cbox a b)"
    using assms
    by (metis ab dual_order.trans partial_division_extend_interval divp(6))
  note r1 = this division_ofD[OF this(2)]
  obtain p' where "p' division_of ⋃(r1 - p)"
    apply (rule elementary_unions_intervals[of "r1 - p"])
    using r1(3,6)
    apply auto
    done
  then obtain r2 where r2: "r2 division_of (⋃(r1 - p)) ∩ (⋃q)"
    by (metis assms(2) divq(6) elementary_inter)
  {
    fix x
    assume x: "x ∈ t" "x ∉ s"
    then have "x∈⋃r1"
      unfolding r1 using ab by auto
    then obtain r where r: "r ∈ r1" "x ∈ r"
      unfolding Union_iff ..
    moreover
    have "r ∉ p"
    proof
      assume "r ∈ p"
      then have "x ∈ s" using divp(2) r by auto
      then show False using x by auto
    qed
    ultimately have "x∈⋃(r1 - p)" by auto
  }
  then have *: "t = ⋃p ∪ (⋃(r1 - p) ∩ ⋃q)"
    unfolding divp divq using assms(3) by auto
  show ?thesis
    apply (rule that[of "p ∪ r2"])
    unfolding *
    defer
    apply (rule division_disjoint_union)
    unfolding divp(6)
    apply(rule assms r2)+
  proof -
    have "interior s ∩ interior (⋃(r1-p)) = {}"
    proof (rule inter_interior_unions_intervals)
      show "finite (r1 - p)" and "open (interior s)" and "∀t∈r1-p. ∃a b. t = cbox a b"
        using r1 by auto
      have *: "⋀s. (⋀x. x ∈ s ⟹ False) ⟹ s = {}"
        by auto
      show "∀t∈r1-p. interior s ∩ interior t = {}"
      proof
        fix m x
        assume as: "m ∈ r1 - p"
        have "interior m ∩ interior (⋃p) = {}"
        proof (rule inter_interior_unions_intervals)
          show "finite p" and "open (interior m)" and "∀t∈p. ∃a b. t = cbox a b"
            using divp by auto
          show "∀t∈p. interior m ∩ interior t = {}"
            by (metis DiffD1 DiffD2 as r1(1) r1(7) set_rev_mp)
        qed
        then show "interior s ∩ interior m = {}"
          unfolding divp by auto
      qed
    qed
    then show "interior s ∩ interior (⋃(r1-p) ∩ (⋃q)) = {}"
      using interior_subset by auto
  qed auto
qed


subsection ‹Tagged (partial) divisions.›

definition tagged_partial_division_of (infixr "tagged'_partial'_division'_of" 40)
  where "s tagged_partial_division_of i ⟷
    finite s ∧
    (∀x k. (x, k) ∈ s ⟶ x ∈ k ∧ k ⊆ i ∧ (∃a b. k = cbox a b)) ∧
    (∀x1 k1 x2 k2. (x1, k1) ∈ s ∧ (x2, k2) ∈ s ∧ (x1, k1) ≠ (x2, k2) ⟶
      interior k1 ∩ interior k2 = {})"

lemma tagged_partial_division_ofD[dest]:
  assumes "s tagged_partial_division_of i"
  shows "finite s"
    and "⋀x k. (x,k) ∈ s ⟹ x ∈ k"
    and "⋀x k. (x,k) ∈ s ⟹ k ⊆ i"
    and "⋀x k. (x,k) ∈ s ⟹ ∃a b. k = cbox a b"
    and "⋀x1 k1 x2 k2. (x1,k1) ∈ s ⟹
      (x2, k2) ∈ s ⟹ (x1, k1) ≠ (x2, k2) ⟹ interior k1 ∩ interior k2 = {}"
  using assms unfolding tagged_partial_division_of_def by blast+

definition tagged_division_of (infixr "tagged'_division'_of" 40)
  where "s tagged_division_of i ⟷ s tagged_partial_division_of i ∧ (⋃{k. ∃x. (x,k) ∈ s} = i)"

lemma tagged_division_of_finite: "s tagged_division_of i ⟹ finite s"
  unfolding tagged_division_of_def tagged_partial_division_of_def by auto

lemma tagged_division_of:
  "s tagged_division_of i ⟷
    finite s ∧
    (∀x k. (x, k) ∈ s ⟶ x ∈ k ∧ k ⊆ i ∧ (∃a b. k = cbox a b)) ∧
    (∀x1 k1 x2 k2. (x1, k1) ∈ s ∧ (x2, k2) ∈ s ∧ (x1, k1) ≠ (x2, k2) ⟶
      interior k1 ∩ interior k2 = {}) ∧
    (⋃{k. ∃x. (x,k) ∈ s} = i)"
  unfolding tagged_division_of_def tagged_partial_division_of_def by auto

lemma tagged_division_ofI:
  assumes "finite s"
    and "⋀x k. (x,k) ∈ s ⟹ x ∈ k"
    and "⋀x k. (x,k) ∈ s ⟹ k ⊆ i"
    and "⋀x k. (x,k) ∈ s ⟹ ∃a b. k = cbox a b"
    and "⋀x1 k1 x2 k2. (x1,k1) ∈ s ⟹ (x2, k2) ∈ s ⟹ (x1, k1) ≠ (x2, k2) ⟹
      interior k1 ∩ interior k2 = {}"
    and "(⋃{k. ∃x. (x,k) ∈ s} = i)"
  shows "s tagged_division_of i"
  unfolding tagged_division_of
  using assms
  apply auto
  apply fastforce+
  done

lemma tagged_division_ofD[dest]:  (*FIXME USE A LOCALE*)
  assumes "s tagged_division_of i"
  shows "finite s"
    and "⋀x k. (x,k) ∈ s ⟹ x ∈ k"
    and "⋀x k. (x,k) ∈ s ⟹ k ⊆ i"
    and "⋀x k. (x,k) ∈ s ⟹ ∃a b. k = cbox a b"
    and "⋀x1 k1 x2 k2. (x1, k1) ∈ s ⟹ (x2, k2) ∈ s ⟹ (x1, k1) ≠ (x2, k2) ⟹
      interior k1 ∩ interior k2 = {}"
    and "(⋃{k. ∃x. (x,k) ∈ s} = i)"
  using assms unfolding tagged_division_of by blast+

lemma division_of_tagged_division:
  assumes "s tagged_division_of i"
  shows "(snd ` s) division_of i"
proof (rule division_ofI)
  note assm = tagged_division_ofD[OF assms]
  show "⋃(snd ` s) = i" "finite (snd ` s)"
    using assm by auto
  fix k
  assume k: "k ∈ snd ` s"
  then obtain xk where xk: "(xk, k) ∈ s"
    by auto
  then show "k ⊆ i" "k ≠ {}" "∃a b. k = cbox a b"
    using assm by fastforce+
  fix k'
  assume k': "k' ∈ snd ` s" "k ≠ k'"
  from this(1) obtain xk' where xk': "(xk', k') ∈ s"
    by auto
  then show "interior k ∩ interior k' = {}"
    using assm(5) k'(2) xk by blast
qed

lemma partial_division_of_tagged_division:
  assumes "s tagged_partial_division_of i"
  shows "(snd ` s) division_of ⋃(snd ` s)"
proof (rule division_ofI)
  note assm = tagged_partial_division_ofD[OF assms]
  show "finite (snd ` s)" "⋃(snd ` s) = ⋃(snd ` s)"
    using assm by auto
  fix k
  assume k: "k ∈ snd ` s"
  then obtain xk where xk: "(xk, k) ∈ s"
    by auto
  then show "k ≠ {}" "∃a b. k = cbox a b" "k ⊆ ⋃(snd ` s)"
    using assm by auto
  fix k'
  assume k': "k' ∈ snd ` s" "k ≠ k'"
  from this(1) obtain xk' where xk': "(xk', k') ∈ s"
    by auto
  then show "interior k ∩ interior k' = {}"
    using assm(5) k'(2) xk by auto
qed

lemma tagged_partial_division_subset:
  assumes "s tagged_partial_division_of i"
    and "t ⊆ s"
  shows "t tagged_partial_division_of i"
  using assms
  unfolding tagged_partial_division_of_def
  using finite_subset[OF assms(2)]
  by blast

lemma setsum_over_tagged_division_lemma:
  assumes "p tagged_division_of i"
    and "⋀u v. cbox u v ≠ {} ⟹ content (cbox u v) = 0 ⟹ d (cbox u v) = 0"
  shows "setsum (λ(x,k). d k) p = setsum d (snd ` p)"
proof -
  have *: "(λ(x,k). d k) = d ∘ snd"
    unfolding o_def by (rule ext) auto
  note assm = tagged_division_ofD[OF assms(1)]
  show ?thesis
    unfolding *
  proof (rule setsum.reindex_nontrivial[symmetric])
    show "finite p"
      using assm by auto
    fix x y
    assume "x∈p" "y∈p" "x≠y" "snd x = snd y"
    obtain a b where ab: "snd x = cbox a b"
      using assm(4)[of "fst x" "snd x"] ‹x∈p› by auto
    have "(fst x, snd y) ∈ p" "(fst x, snd y) ≠ y"
      by (metis prod.collapse ‹x∈p› ‹snd x = snd y› ‹x ≠ y›)+
    with ‹x∈p› ‹y∈p› have "interior (snd x) ∩ interior (snd y) = {}"
      by (intro assm(5)[of "fst x" _ "fst y"]) auto
    then have "content (cbox a b) = 0"
      unfolding ‹snd x = snd y›[symmetric] ab content_eq_0_interior by auto
    then have "d (cbox a b) = 0"
      using assm(2)[of "fst x" "snd x"] ‹x∈p› ab[symmetric] by (intro assms(2)) auto
    then show "d (snd x) = 0"
      unfolding ab by auto
  qed
qed

lemma tag_in_interval: "p tagged_division_of i ⟹ (x, k) ∈ p ⟹ x ∈ i"
  by auto

lemma tagged_division_of_empty: "{} tagged_division_of {}"
  unfolding tagged_division_of by auto

lemma tagged_partial_division_of_trivial[simp]: "p tagged_partial_division_of {} ⟷ p = {}"
  unfolding tagged_partial_division_of_def by auto

lemma tagged_division_of_trivial[simp]: "p tagged_division_of {} ⟷ p = {}"
  unfolding tagged_division_of by auto

lemma tagged_division_of_self: "x ∈ cbox a b ⟹ {(x,cbox a b)} tagged_division_of (cbox a b)"
  by (rule tagged_division_ofI) auto

lemma tagged_division_of_self_real: "x ∈ {a .. b::real} ⟹ {(x,{a .. b})} tagged_division_of {a .. b}"
  unfolding box_real[symmetric]
  by (rule tagged_division_of_self)

lemma tagged_division_union:
  assumes "p1 tagged_division_of s1"
    and "p2 tagged_division_of s2"
    and "interior s1 ∩ interior s2 = {}"
  shows "(p1 ∪ p2) tagged_division_of (s1 ∪ s2)"
proof (rule tagged_division_ofI)
  note p1 = tagged_division_ofD[OF assms(1)]
  note p2 = tagged_division_ofD[OF assms(2)]
  show "finite (p1 ∪ p2)"
    using p1(1) p2(1) by auto
  show "⋃{k. ∃x. (x, k) ∈ p1 ∪ p2} = s1 ∪ s2"
    using p1(6) p2(6) by blast
  fix x k
  assume xk: "(x, k) ∈ p1 ∪ p2"
  show "x ∈ k" "∃a b. k = cbox a b"
    using xk p1(2,4) p2(2,4) by auto
  show "k ⊆ s1 ∪ s2"
    using xk p1(3) p2(3) by blast
  fix x' k'
  assume xk': "(x', k') ∈ p1 ∪ p2" "(x, k) ≠ (x', k')"
  have *: "⋀a b. a ⊆ s1 ⟹ b ⊆ s2 ⟹ interior a ∩ interior b = {}"
    using assms(3) interior_mono by blast
  show "interior k ∩ interior k' = {}"
    apply (cases "(x, k) ∈ p1")
    apply (meson "*" UnE assms(1) assms(2) p1(5) tagged_division_ofD(3) xk'(1) xk'(2))
    by (metis "*" UnE assms(1) assms(2) inf_sup_aci(1) p2(5) tagged_division_ofD(3) xk xk'(1) xk'(2))
qed

lemma tagged_division_unions:
  assumes "finite iset"
    and "∀i∈iset. pfn i tagged_division_of i"
    and "∀i1∈iset. ∀i2∈iset. i1 ≠ i2 ⟶ interior(i1) ∩ interior(i2) = {}"
  shows "⋃(pfn ` iset) tagged_division_of (⋃iset)"
proof (rule tagged_division_ofI)
  note assm = tagged_division_ofD[OF assms(2)[rule_format]]
  show "finite (⋃(pfn ` iset))"
    apply (rule finite_Union)
    using assms
    apply auto
    done
  have "⋃{k. ∃x. (x, k) ∈ ⋃(pfn ` iset)} = ⋃((λi. ⋃{k. ∃x. (x, k) ∈ pfn i}) ` iset)"
    by blast
  also have "… = ⋃iset"
    using assm(6) by auto
  finally show "⋃{k. ∃x. (x, k) ∈ ⋃(pfn ` iset)} = ⋃iset" .
  fix x k
  assume xk: "(x, k) ∈ ⋃(pfn ` iset)"
  then obtain i where i: "i ∈ iset" "(x, k) ∈ pfn i"
    by auto
  show "x ∈ k" "∃a b. k = cbox a b" "k ⊆ ⋃iset"
    using assm(2-4)[OF i] using i(1) by auto
  fix x' k'
  assume xk': "(x', k') ∈ ⋃(pfn ` iset)" "(x, k) ≠ (x', k')"
  then obtain i' where i': "i' ∈ iset" "(x', k') ∈ pfn i'"
    by auto
  have *: "⋀a b. i ≠ i' ⟹ a ⊆ i ⟹ b ⊆ i' ⟹ interior a ∩ interior b = {}"
    using i(1) i'(1)
    using assms(3)[rule_format] interior_mono
    by blast
  show "interior k ∩ interior k' = {}"
    apply (cases "i = i'")
    using assm(5) i' i(2) xk'(2) apply blast
    using "*" assm(3) i' i by auto
qed

lemma tagged_partial_division_of_union_self:
  assumes "p tagged_partial_division_of s"
  shows "p tagged_division_of (⋃(snd ` p))"
  apply (rule tagged_division_ofI)
  using tagged_partial_division_ofD[OF assms]
  apply auto
  done

lemma tagged_division_of_union_self:
  assumes "p tagged_division_of s"
  shows "p tagged_division_of (⋃(snd ` p))"
  apply (rule tagged_division_ofI)
  using tagged_division_ofD[OF assms]
  apply auto
  done


subsection ‹Fine-ness of a partition w.r.t. a gauge.›

definition fine  (infixr "fine" 46)
  where "d fine s ⟷ (∀(x,k) ∈ s. k ⊆ d x)"

lemma fineI:
  assumes "⋀x k. (x, k) ∈ s ⟹ k ⊆ d x"
  shows "d fine s"
  using assms unfolding fine_def by auto

lemma fineD[dest]:
  assumes "d fine s"
  shows "⋀x k. (x,k) ∈ s ⟹ k ⊆ d x"
  using assms unfolding fine_def by auto

lemma fine_inter: "(λx. d1 x ∩ d2 x) fine p ⟷ d1 fine p ∧ d2 fine p"
  unfolding fine_def by auto

lemma fine_inters:
 "(λx. ⋂{f d x | d.  d ∈ s}) fine p ⟷ (∀d∈s. (f d) fine p)"
  unfolding fine_def by blast

lemma fine_union: "d fine p1 ⟹ d fine p2 ⟹ d fine (p1 ∪ p2)"
  unfolding fine_def by blast

lemma fine_unions: "(⋀p. p ∈ ps ⟹ d fine p) ⟹ d fine (⋃ps)"
  unfolding fine_def by auto

lemma fine_subset: "p ⊆ q ⟹ d fine q ⟹ d fine p"
  unfolding fine_def by blast


subsection ‹Gauge integral. Define on compact intervals first, then use a limit.›

definition has_integral_compact_interval (infixr "has'_integral'_compact'_interval" 46)
  where "(f has_integral_compact_interval y) i ⟷
    (∀e>0. ∃d. gauge d ∧
      (∀p. p tagged_division_of i ∧ d fine p ⟶
        norm (setsum (λ(x,k). content k *R f x) p - y) < e))"

definition has_integral ::
    "('n::euclidean_space ⇒ 'b::real_normed_vector) ⇒ 'b ⇒ 'n set ⇒ bool"
  (infixr "has'_integral" 46)
  where "(f has_integral y) i ⟷
    (if ∃a b. i = cbox a b
     then (f has_integral_compact_interval y) i
     else (∀e>0. ∃B>0. ∀a b. ball 0 B ⊆ cbox a b ⟶
      (∃z. ((λx. if x ∈ i then f x else 0) has_integral_compact_interval z) (cbox a b) ∧
        norm (z - y) < e)))"

lemma has_integral:
  "(f has_integral y) (cbox a b) ⟷
    (∀e>0. ∃d. gauge d ∧
      (∀p. p tagged_division_of (cbox a b) ∧ d fine p ⟶
        norm (setsum (λ(x,k). content(k) *R f x) p - y) < e))"
  unfolding has_integral_def has_integral_compact_interval_def
  by auto

lemma has_integral_real:
  "(f has_integral y) {a .. b::real} ⟷
    (∀e>0. ∃d. gauge d ∧
      (∀p. p tagged_division_of {a .. b} ∧ d fine p ⟶
        norm (setsum (λ(x,k). content(k) *R f x) p - y) < e))"
  unfolding box_real[symmetric]
  by (rule has_integral)

lemma has_integralD[dest]:
  assumes "(f has_integral y) (cbox a b)"
    and "e > 0"
  obtains d where "gauge d"
    and "⋀p. p tagged_division_of (cbox a b) ⟹ d fine p ⟹
      norm (setsum (λ(x,k). content(k) *R f(x)) p - y) < e"
  using assms unfolding has_integral by auto

lemma has_integral_alt:
  "(f has_integral y) i ⟷
    (if ∃a b. i = cbox a b
     then (f has_integral y) i
     else (∀e>0. ∃B>0. ∀a b. ball 0 B ⊆ cbox a b ⟶
      (∃z. ((λx. if x ∈ i then f(x) else 0) has_integral z) (cbox a b) ∧ norm (z - y) < e)))"
  unfolding has_integral
  unfolding has_integral_compact_interval_def has_integral_def
  by auto

lemma has_integral_altD:
  assumes "(f has_integral y) i"
    and "¬ (∃a b. i = cbox a b)"
    and "e>0"
  obtains B where "B > 0"
    and "∀a b. ball 0 B ⊆ cbox a b ⟶
      (∃z. ((λx. if x ∈ i then f(x) else 0) has_integral z) (cbox a b) ∧ norm(z - y) < e)"
  using assms
  unfolding has_integral
  unfolding has_integral_compact_interval_def has_integral_def
  by auto

definition integrable_on (infixr "integrable'_on" 46)
  where "f integrable_on i ⟷ (∃y. (f has_integral y) i)"

definition "integral i f = (SOME y. (f has_integral y) i)"

lemma integrable_integral[dest]: "f integrable_on i ⟹ (f has_integral (integral i f)) i"
  unfolding integrable_on_def integral_def by (rule someI_ex)

lemma has_integral_integrable[intro]: "(f has_integral i) s ⟹ f integrable_on s"
  unfolding integrable_on_def by auto

lemma has_integral_integral: "f integrable_on s ⟷ (f has_integral (integral s f)) s"
  by auto

lemma setsum_content_null:
  assumes "content (cbox a b) = 0"
    and "p tagged_division_of (cbox a b)"
  shows "setsum (λ(x,k). content k *R f x) p = (0::'a::real_normed_vector)"
proof (rule setsum.neutral, rule)
  fix y
  assume y: "y ∈ p"
  obtain x k where xk: "y = (x, k)"
    using surj_pair[of y] by blast
  note assm = tagged_division_ofD(3-4)[OF assms(2) y[unfolded xk]]
  from this(2) obtain c d where k: "k = cbox c d" by blast
  have "(λ(x, k). content k *R f x) y = content k *R f x"
    unfolding xk by auto
  also have "… = 0"
    using content_subset[OF assm(1)[unfolded k]] content_pos_le[of c d]
    unfolding assms(1) k
    by auto
  finally show "(λ(x, k). content k *R f x) y = 0" .
qed


subsection ‹Some basic combining lemmas.›

lemma tagged_division_unions_exists:
  assumes "finite iset"
    and "∀i∈iset. ∃p. p tagged_division_of i ∧ d fine p"
    and "∀i1∈iset. ∀i2∈iset. i1 ≠ i2 ⟶ interior i1 ∩ interior i2 = {}"
    and "⋃iset = i"
   obtains p where "p tagged_division_of i" and "d fine p"
proof -
  obtain pfn where pfn:
    "⋀x. x ∈ iset ⟹ pfn x tagged_division_of x"
    "⋀x. x ∈ iset ⟹ d fine pfn x"
    using bchoice[OF assms(2)] by auto
  show thesis
    apply (rule_tac p="⋃(pfn ` iset)" in that)
    using assms(1) assms(3) assms(4) pfn(1) tagged_division_unions apply force
    by (metis (mono_tags, lifting) fine_unions imageE pfn(2))
qed


subsection ‹The set we're concerned with must be closed.›

lemma division_of_closed:
  fixes i :: "'n::euclidean_space set"
  shows "s division_of i ⟹ closed i"
  unfolding division_of_def by fastforce

subsection ‹General bisection principle for intervals; might be useful elsewhere.›

lemma interval_bisection_step:
  fixes type :: "'a::euclidean_space"
  assumes "P {}"
    and "∀s t. P s ∧ P t ∧ interior(s) ∩ interior(t) = {} ⟶ P (s ∪ t)"
    and "¬ P (cbox a (b::'a))"
  obtains c d where "¬ P (cbox c d)"
    and "∀i∈Basis. a∙i ≤ c∙i ∧ c∙i ≤ d∙i ∧ d∙i ≤ b∙i ∧ 2 * (d∙i - c∙i) ≤ b∙i - a∙i"
proof -
  have "cbox a b ≠ {}"
    using assms(1,3) by metis
  then have ab: "⋀i. i∈Basis ⟹ a ∙ i ≤ b ∙ i"
    by (force simp: mem_box)
  { fix f
    have "⟦finite f;
           ⋀s. s∈f ⟹ P s;
           ⋀s. s∈f ⟹ ∃a b. s = cbox a b;
           ⋀s t. s∈f ⟹ t∈f ⟹ s ≠ t ⟹ interior s ∩ interior t = {}⟧ ⟹ P (⋃f)"
    proof (induct f rule: finite_induct)
      case empty
      show ?case
        using assms(1) by auto
    next
      case (insert x f)
      show ?case
        unfolding Union_insert
        apply (rule assms(2)[rule_format])
        using inter_interior_unions_intervals [of f "interior x"]
        apply (auto simp: insert)
        by (metis IntI empty_iff insert.hyps(2) insert.prems(3) insert_iff)
    qed
  } note UN_cases = this
  let ?A = "{cbox c d | c d::'a. ∀i∈Basis. (c∙i = a∙i) ∧ (d∙i = (a∙i + b∙i) / 2) ∨
    (c∙i = (a∙i + b∙i) / 2) ∧ (d∙i = b∙i)}"
  let ?PP = "λc d. ∀i∈Basis. a∙i ≤ c∙i ∧ c∙i ≤ d∙i ∧ d∙i ≤ b∙i ∧ 2 * (d∙i - c∙i) ≤ b∙i - a∙i"
  {
    presume "∀c d. ?PP c d ⟶ P (cbox c d) ⟹ False"
    then show thesis
      unfolding atomize_not not_all
      by (blast intro: that)
  }
  assume as: "∀c d. ?PP c d ⟶ P (cbox c d)"
  have "P (⋃?A)"
  proof (rule UN_cases)
    let ?B = "(λs. cbox (∑i∈Basis. (if i ∈ s then a∙i else (a∙i + b∙i) / 2) *R i::'a)
      (∑i∈Basis. (if i ∈ s then (a∙i + b∙i) / 2 else b∙i) *R i)) ` {s. s ⊆ Basis}"
    have "?A ⊆ ?B"
    proof
      fix x
      assume "x ∈ ?A"
      then obtain c d
        where x:  "x = cbox c d"
                  "⋀i. i ∈ Basis ⟹
                        c ∙ i = a ∙ i ∧ d ∙ i = (a ∙ i + b ∙ i) / 2 ∨
                        c ∙ i = (a ∙ i + b ∙ i) / 2 ∧ d ∙ i = b ∙ i" by blast
      show "x ∈ ?B"
        unfolding image_iff x
        apply (rule_tac x="{i. i∈Basis ∧ c∙i = a∙i}" in bexI)
        apply (rule arg_cong2 [where f = cbox])
        using x(2) ab
        apply (auto simp add: euclidean_eq_iff[where 'a='a])
        by fastforce
    qed
    then show "finite ?A"
      by (rule finite_subset) auto
  next
    fix s
    assume "s ∈ ?A"
    then obtain c d
      where s: "s = cbox c d"
               "⋀i. i ∈ Basis ⟹
                     c ∙ i = a ∙ i ∧ d ∙ i = (a ∙ i + b ∙ i) / 2 ∨
                     c ∙ i = (a ∙ i + b ∙ i) / 2 ∧ d ∙ i = b ∙ i"
      by blast
    show "P s"
      unfolding s
      apply (rule as[rule_format])
      using ab s(2) by force
    show "∃a b. s = cbox a b"
      unfolding s by auto
    fix t
    assume "t ∈ ?A"
    then obtain e f where t:
      "t = cbox e f"
      "⋀i. i ∈ Basis ⟹
        e ∙ i = a ∙ i ∧ f ∙ i = (a ∙ i + b ∙ i) / 2 ∨
        e ∙ i = (a ∙ i + b ∙ i) / 2 ∧ f ∙ i = b ∙ i"
      by blast
    assume "s ≠ t"
    then have "¬ (c = e ∧ d = f)"
      unfolding s t by auto
    then obtain i where "c∙i ≠ e∙i ∨ d∙i ≠ f∙i" and i': "i ∈ Basis"
      unfolding euclidean_eq_iff[where 'a='a] by auto
    then have i: "c∙i ≠ e∙i" "d∙i ≠ f∙i"
      using s(2) t(2) apply fastforce
      using t(2)[OF i'] ‹c ∙ i ≠ e ∙ i ∨ d ∙ i ≠ f ∙ i› i' s(2) t(2) by fastforce
    have *: "⋀s t. (⋀a. a ∈ s ⟹ a ∈ t ⟹ False) ⟹ s ∩ t = {}"
      by auto
    show "interior s ∩ interior t = {}"
      unfolding s t interior_cbox
    proof (rule *)
      fix x
      assume "x ∈ box c d" "x ∈ box e f"
      then have x: "c∙i < d∙i" "e∙i < f∙i" "c∙i < f∙i" "e∙i < d∙i"
        unfolding mem_box using i'
        by force+
      show False  using s(2)[OF i']
      proof safe
        assume as: "c ∙ i = a ∙ i" "d ∙ i = (a ∙ i + b ∙ i) / 2"
        show False
          using t(2)[OF i'] and i x unfolding as by (fastforce simp add:field_simps)
      next
        assume as: "c ∙ i = (a ∙ i + b ∙ i) / 2" "d ∙ i = b ∙ i"
        show False
          using t(2)[OF i'] and i x unfolding as by(fastforce simp add:field_simps)
      qed
    qed
  qed
  also have "⋃?A = cbox a b"
  proof (rule set_eqI,rule)
    fix x
    assume "x ∈ ⋃?A"
    then obtain c d where x:
      "x ∈ cbox c d"
      "⋀i. i ∈ Basis ⟹
        c ∙ i = a ∙ i ∧ d ∙ i = (a ∙ i + b ∙ i) / 2 ∨
        c ∙ i = (a ∙ i + b ∙ i) / 2 ∧ d ∙ i = b ∙ i"
      by blast
    show "x∈cbox a b"
      unfolding mem_box
    proof safe
      fix i :: 'a
      assume i: "i ∈ Basis"
      then show "a ∙ i ≤ x ∙ i" "x ∙ i ≤ b ∙ i"
        using x(2)[OF i] x(1)[unfolded mem_box,THEN bspec, OF i] by auto
    qed
  next
    fix x
    assume x: "x ∈ cbox a b"
    have "∀i∈Basis.
      ∃c d. (c = a∙i ∧ d = (a∙i + b∙i) / 2 ∨ c = (a∙i + b∙i) / 2 ∧ d = b∙i) ∧ c≤x∙i ∧ x∙i ≤ d"
      (is "∀i∈Basis. ∃c d. ?P i c d")
      unfolding mem_box
    proof
      fix i :: 'a
      assume i: "i ∈ Basis"
      have "?P i (a∙i) ((a ∙ i + b ∙ i) / 2) ∨ ?P i ((a ∙ i + b ∙ i) / 2) (b∙i)"
        using x[unfolded mem_box,THEN bspec, OF i] by auto
      then show "∃c d. ?P i c d"
        by blast
    qed
    then show "x∈⋃?A"
      unfolding Union_iff Bex_def mem_Collect_eq choice_Basis_iff
      apply auto
      apply (rule_tac x="cbox xa xaa" in exI)
      unfolding mem_box
      apply auto
      done
  qed
  finally show False
    using assms by auto
qed

lemma interval_bisection:
  fixes type :: "'a::euclidean_space"
  assumes "P {}"
    and "(∀s t. P s ∧ P t ∧ interior(s) ∩ interior(t) = {} ⟶ P(s ∪ t))"
    and "¬ P (cbox a (b::'a))"
  obtains x where "x ∈ cbox a b"
    and "∀e>0. ∃c d. x ∈ cbox c d ∧ cbox c d ⊆ ball x e ∧ cbox c d ⊆ cbox a b ∧ ¬ P (cbox c d)"
proof -
  have "∀x. ∃y. ¬ P (cbox (fst x) (snd x)) ⟶ (¬ P (cbox (fst y) (snd y)) ∧
    (∀i∈Basis. fst x∙i ≤ fst y∙i ∧ fst y∙i ≤ snd y∙i ∧ snd y∙i ≤ snd x∙i ∧
       2 * (snd y∙i - fst y∙i) ≤ snd x∙i - fst x∙i))" (is "∀x. ?P x")
  proof
    show "?P x" for x
    proof (cases "P (cbox (fst x) (snd x))")
      case True
      then show ?thesis by auto
    next
      case as: False
      obtain c d where "¬ P (cbox c d)"
        "∀i∈Basis.
           fst x ∙ i ≤ c ∙ i ∧
           c ∙ i ≤ d ∙ i ∧
           d ∙ i ≤ snd x ∙ i ∧
           2 * (d ∙ i - c ∙ i) ≤ snd x ∙ i - fst x ∙ i"
        by (rule interval_bisection_step[of P, OF assms(1-2) as])
      then show ?thesis
        apply -
        apply (rule_tac x="(c,d)" in exI)
        apply auto
        done
    qed
  qed
  then obtain f where f:
    "∀x.
      ¬ P (cbox (fst x) (snd x)) ⟶
      ¬ P (cbox (fst (f x)) (snd (f x))) ∧
        (∀i∈Basis.
            fst x ∙ i ≤ fst (f x) ∙ i ∧
            fst (f x) ∙ i ≤ snd (f x) ∙ i ∧
            snd (f x) ∙ i ≤ snd x ∙ i ∧
            2 * (snd (f x) ∙ i - fst (f x) ∙ i) ≤ snd x ∙ i - fst x ∙ i)"
    apply -
    apply (drule choice)
    apply blast
    done
  def AB  "λn. (f ^^ n) (a,b)"
  def A  "λn. fst(AB n)"
  def B  "λn. snd(AB n)"
  note ab_def = A_def B_def AB_def
  have "A 0 = a" "B 0 = b" "⋀n. ¬ P (cbox (A(Suc n)) (B(Suc n))) ∧
    (∀i∈Basis. A(n)∙i ≤ A(Suc n)∙i ∧ A(Suc n)∙i ≤ B(Suc n)∙i ∧ B(Suc n)∙i ≤ B(n)∙i ∧
    2 * (B(Suc n)∙i - A(Suc n)∙i) ≤ B(n)∙i - A(n)∙i)" (is "⋀n. ?P n")
  proof -
    show "A 0 = a" "B 0 = b"
      unfolding ab_def by auto
    note S = ab_def funpow.simps o_def id_apply
    show "?P n" for n
    proof (induct n)
      case 0
      then show ?case
        unfolding S
        apply (rule f[rule_format]) using assms(3)
        apply auto
        done
    next
      case (Suc n)
      show ?case
        unfolding S
        apply (rule f[rule_format])
        using Suc
        unfolding S
        apply auto
        done
    qed
  qed
  note AB = this(1-2) conjunctD2[OF this(3),rule_format]

  have interv: "∃n. ∀x∈cbox (A n) (B n). ∀y∈cbox (A n) (B n). dist x y < e"
    if e: "0 < e" for e
  proof -
    obtain n where n: "(∑i∈Basis. b ∙ i - a ∙ i) / e < 2 ^ n"
      using real_arch_pow2[of "(setsum (λi. b∙i - a∙i) Basis) / e"] ..
    show ?thesis
    proof (rule exI [where x=n], clarify)
      fix x y
      assume xy: "x∈cbox (A n) (B n)" "y∈cbox (A n) (B n)"
      have "dist x y ≤ setsum (λi. ¦(x - y)∙i¦) Basis"
        unfolding dist_norm by(rule norm_le_l1)
      also have "… ≤ setsum (λi. B n∙i - A n∙i) Basis"
      proof (rule setsum_mono)
        fix i :: 'a
        assume i: "i ∈ Basis"
        show "¦(x - y) ∙ i¦ ≤ B n ∙ i - A n ∙ i"
          using xy[unfolded mem_box,THEN bspec, OF i]
          by (auto simp: inner_diff_left)
      qed
      also have "… ≤ setsum (λi. b∙i - a∙i) Basis / 2^n"
        unfolding setsum_divide_distrib
      proof (rule setsum_mono)
        show "B n ∙ i - A n ∙ i ≤ (b ∙ i - a ∙ i) / 2 ^ n" if i: "i ∈ Basis" for i
        proof (induct n)
          case 0
          then show ?case
            unfolding AB by auto
        next
          case (Suc n)
          have "B (Suc n) ∙ i - A (Suc n) ∙ i ≤ (B n ∙ i - A n ∙ i) / 2"
            using AB(4)[of i n] using i by auto
          also have "… ≤ (b ∙ i - a ∙ i) / 2 ^ Suc n"
            using Suc by (auto simp add: field_simps)
          finally show ?case .
        qed
      qed
      also have "… < e"
        using n using e by (auto simp add: field_simps)
      finally show "dist x y < e" .
    qed
  qed
  {
    fix n m :: nat
    assume "m ≤ n" then have "cbox (A n) (B n) ⊆ cbox (A m) (B m)"
    proof (induction rule: inc_induct)
      case (step i)
      show ?case
        using AB(4) by (intro order_trans[OF step.IH] subset_box_imp) auto
    qed simp
  } note ABsubset = this
  have "∃a. ∀n. a∈ cbox (A n) (B n)"
    by (rule decreasing_closed_nest[rule_format,OF closed_cbox _ ABsubset interv])
      (metis nat.exhaust AB(1-3) assms(1,3))
  then obtain x0 where x0: "⋀n. x0 ∈ cbox (A n) (B n)"
    by blast
  show thesis
  proof (rule that[rule_format, of x0])
    show "x0∈cbox a b"
      using x0[of 0] unfolding AB .
    fix e :: real
    assume "e > 0"
    from interv[OF this] obtain n
      where n: "∀x∈cbox (A n) (B n). ∀y∈cbox (A n) (B n). dist x y < e" ..
    have "¬ P (cbox (A n) (B n))"
      apply (cases "0 < n")
      using AB(3)[of "n - 1"] assms(3) AB(1-2)
      apply auto
      done
    moreover have "cbox (A n) (B n) ⊆ ball x0 e"
      using n using x0[of n] by auto
    moreover have "cbox (A n) (B n) ⊆ cbox a b"
      unfolding AB(1-2)[symmetric] by (rule ABsubset) auto
    ultimately show "∃c d. x0 ∈ cbox c d ∧ cbox c d ⊆ ball x0 e ∧ cbox c d ⊆ cbox a b ∧ ¬ P (cbox c d)"
      apply (rule_tac x="A n" in exI)
      apply (rule_tac x="B n" in exI)
      apply (auto simp: x0)
      done
  qed
qed


subsection ‹Cousin's lemma.›

lemma fine_division_exists:
  fixes a b :: "'a::euclidean_space"
  assumes "gauge g"
  obtains p where "p tagged_division_of (cbox a b)" "g fine p"
proof -
  presume "¬ (∃p. p tagged_division_of (cbox a b) ∧ g fine p) ⟹ False"
  then obtain p where "p tagged_division_of (cbox a b)" "g fine p"
    by blast
  then show thesis ..
next
  assume as: "¬ (∃p. p tagged_division_of (cbox a b) ∧ g fine p)"
  obtain x where x:
      "x ∈ (cbox a b)"
      "⋀e. 0 < e ⟹
        ∃c d.
          x ∈ cbox c d ∧
          cbox c d ⊆ ball x e ∧
          cbox c d ⊆ (cbox a b) ∧
          ¬ (∃p. p tagged_division_of cbox c d ∧ g fine p)"
    apply (rule interval_bisection[of "λs. ∃p. p tagged_division_of s ∧ g fine p", OF _ _ as])
    apply (simp add: fine_def)
    apply (metis tagged_division_union fine_union)
    apply (auto simp: )
    done
  obtain e where e: "e > 0" "ball x e ⊆ g x"
    using gaugeD[OF assms, of x] unfolding open_contains_ball by auto
  from x(2)[OF e(1)]
  obtain c d where c_d: "x ∈ cbox c d"
                        "cbox c d ⊆ ball x e"
                        "cbox c d ⊆ cbox a b"
                        "¬ (∃p. p tagged_division_of cbox c d ∧ g fine p)"
    by blast
  have "g fine {(x, cbox c d)}"
    unfolding fine_def using e using c_d(2) by auto
  then show False
    using tagged_division_of_self[OF c_d(1)] using c_d by auto
qed

lemma fine_division_exists_real:
  fixes a b :: real
  assumes "gauge g"
  obtains p where "p tagged_division_of {a .. b}" "g fine p"
  by (metis assms box_real(2) fine_division_exists)

subsection ‹Basic theorems about integrals.›

lemma has_integral_unique:
  fixes f :: "'n::euclidean_space ⇒ 'a::real_normed_vector"
  assumes "(f has_integral k1) i"
    and "(f has_integral k2) i"
  shows "k1 = k2"
proof (rule ccontr)
  let ?e = "norm (k1 - k2) / 2"
  assume as: "k1 ≠ k2"
  then have e: "?e > 0"
    by auto
  have lem: False
    if f_k1: "(f has_integral k1) (cbox a b)"
    and f_k2: "(f has_integral k2) (cbox a b)"
    and "k1 ≠ k2"
    for f :: "'n ⇒ 'a" and a b k1 k2
  proof -
    let ?e = "norm (k1 - k2) / 2"
    from ‹k1 ≠ k2› have e: "?e > 0" by auto
    obtain d1 where d1:
        "gauge d1"
        "⋀p. p tagged_division_of cbox a b ⟹
          d1 fine p ⟹ norm ((∑(x, k)∈p. content k *R f x) - k1) < norm (k1 - k2) / 2"
      by (rule has_integralD[OF f_k1 e]) blast
    obtain d2 where d2:
        "gauge d2"
        "⋀p. p tagged_division_of cbox a b ⟹
          d2 fine p ⟹ norm ((∑(x, k)∈p. content k *R f x) - k2) < norm (k1 - k2) / 2"
      by (rule has_integralD[OF f_k2 e]) blast
    obtain p where p:
        "p tagged_division_of cbox a b"
        "(λx. d1 x ∩ d2 x) fine p"
      by (rule fine_division_exists[OF gauge_inter[OF d1(1) d2(1)]])
    let ?c = "(∑(x, k)∈p. content k *R f x)"
    have "norm (k1 - k2) ≤ norm (?c - k2) + norm (?c - k1)"
      using norm_triangle_ineq4[of "k1 - ?c" "k2 - ?c"]
      by (auto simp add:algebra_simps norm_minus_commute)
    also have "… < norm (k1 - k2) / 2 + norm (k1 - k2) / 2"
      apply (rule add_strict_mono)
      apply (rule_tac[!] d2(2) d1(2))
      using p unfolding fine_def
      apply auto
      done
    finally show False by auto
  qed
  {
    presume "¬ (∃a b. i = cbox a b) ⟹ False"
    then show False
      using as assms lem by blast
  }
  assume as: "¬ (∃a b. i = cbox a b)"
  obtain B1 where B1:
      "0 < B1"
      "⋀a b. ball 0 B1 ⊆ cbox a b ⟹
        ∃z. ((λx. if x ∈ i then f x else 0) has_integral z) (cbox a b) ∧
          norm (z - k1) < norm (k1 - k2) / 2"
    by (rule has_integral_altD[OF assms(1) as,OF e]) blast
  obtain B2 where B2:
      "0 < B2"
      "⋀a b. ball 0 B2 ⊆ cbox a b ⟹
        ∃z. ((λx. if x ∈ i then f x else 0) has_integral z) (cbox a b) ∧
          norm (z - k2) < norm (k1 - k2) / 2"
    by (rule has_integral_altD[OF assms(2) as,OF e]) blast
  have "∃a b::'n. ball 0 B1 ∪ ball 0 B2 ⊆ cbox a b"
    apply (rule bounded_subset_cbox)
    using bounded_Un bounded_ball
    apply auto
    done
  then obtain a b :: 'n where ab: "ball 0 B1 ⊆ cbox a b" "ball 0 B2 ⊆ cbox a b"
    by blast
  obtain w where w:
    "((λx. if x ∈ i then f x else 0) has_integral w) (cbox a b)"
    "norm (w - k1) < norm (k1 - k2) / 2"
    using B1(2)[OF ab(1)] by blast
  obtain z where z:
    "((λx. if x ∈ i then f x else 0) has_integral z) (cbox a b)"
    "norm (z - k2) < norm (k1 - k2) / 2"
    using B2(2)[OF ab(2)] by blast
  have "z = w"
    using lem[OF w(1) z(1)] by auto
  then have "norm (k1 - k2) ≤ norm (z - k2) + norm (w - k1)"
    using norm_triangle_ineq4 [of "k1 - w" "k2 - z"]
    by (auto simp add: norm_minus_commute)
  also have "… < norm (k1 - k2) / 2 + norm (k1 - k2) / 2"
    apply (rule add_strict_mono)
    apply (rule_tac[!] z(2) w(2))
    done
  finally show False by auto
qed

lemma integral_unique [intro]: "(f has_integral y) k ⟹ integral k f = y"
  unfolding integral_def
  by (rule some_equality) (auto intro: has_integral_unique)

lemma has_integral_is_0:
  fixes f :: "'n::euclidean_space ⇒ 'a::real_normed_vector"
  assumes "∀x∈s. f x = 0"
  shows "(f has_integral 0) s"
proof -
  have lem: "⋀a b. ⋀f::'n ⇒ 'a.
    (∀x∈cbox a b. f(x) = 0) ⟹ (f has_integral 0) (cbox a b)"
    unfolding has_integral
  proof clarify
    fix a b e
    fix f :: "'n ⇒ 'a"
    assume as: "∀x∈cbox a b. f x = 0" "0 < (e::real)"
    have "norm ((∑(x, k)∈p. content k *R f x) - 0) < e"
      if p: "p tagged_division_of cbox a b" for p
    proof -
      have "(∑(x, k)∈p. content k *R f x) = 0"
      proof (rule setsum.neutral, rule)
        fix x
        assume x: "x ∈ p"
        have "f (fst x) = 0"
          using tagged_division_ofD(2-3)[OF p, of "fst x" "snd x"] using as x by auto
        then show "(λ(x, k). content k *R f x) x = 0"
          apply (subst surjective_pairing[of x])
          unfolding split_conv
          apply auto
          done
      qed
      then show ?thesis
        using as by auto
    qed
    then show "∃d. gauge d ∧
        (∀p. p tagged_division_of (cbox a b) ∧ d fine p ⟶ norm ((∑(x, k)∈p. content k *R f x) - 0) < e)"
      by auto
  qed
  {
    presume "¬ (∃a b. s = cbox a b) ⟹ ?thesis"
    with assms lem show ?thesis
      by blast
  }
  have *: "(λx. if x ∈ s then f x else 0) = (λx. 0)"
    apply (rule ext)
    using assms
    apply auto
    done
  assume "¬ (∃a b. s = cbox a b)"
  then show ?thesis
    using lem
    by (subst has_integral_alt) (force simp add: *)
qed

lemma has_integral_0[simp]: "((λx::'n::euclidean_space. 0) has_integral 0) s"
  by (rule has_integral_is_0) auto

lemma has_integral_0_eq[simp]: "((λx. 0) has_integral i) s ⟷ i = 0"
  using has_integral_unique[OF has_integral_0] by auto

lemma has_integral_linear:
  fixes f :: "'n::euclidean_space ⇒ 'a::real_normed_vector"
  assumes "(f has_integral y) s"
    and "bounded_linear h"
  shows "((h ∘ f) has_integral ((h y))) s"
proof -
  interpret bounded_linear h
    using assms(2) .
  from pos_bounded obtain B where B: "0 < B" "⋀x. norm (h x) ≤ norm x * B"
    by blast
  have lem: "⋀(f :: 'n ⇒ 'a) y a b.
    (f has_integral y) (cbox a b) ⟹ ((h ∘ f) has_integral h y) (cbox a b)"
    unfolding has_integral
  proof (clarify, goal_cases)
    case prems: (1 f y a b e)
    from pos_bounded
    obtain B where B: "0 < B" "⋀x. norm (h x) ≤ norm x * B"
      by blast
    have "e / B > 0" using prems(2) B by simp
    then obtain g
      where g: "gauge g"
               "⋀p. p tagged_division_of (cbox a b) ⟹ g fine p ⟹
                    norm ((∑(x, k)∈p. content k *R f x) - y) < e / B"
        using prems(1) by auto
    {
      fix p
      assume as: "p tagged_division_of (cbox a b)" "g fine p"
      have hc: "⋀x k. h ((λ(x, k). content k *R f x) x) = (λ(x, k). h (content k *R f x)) x"
        by auto
      then have "(∑(x, k)∈p. content k *R (h ∘ f) x) = setsum (h ∘ (λ(x, k). content k *R f x)) p"
        unfolding o_def unfolding scaleR[symmetric] hc by simp
      also have "… = h (∑(x, k)∈p. content k *R f x)"
        using setsum[of "λ(x,k). content k *R f x" p] using as by auto
      finally have "(∑(x, k)∈p. content k *R (h ∘ f) x) = h (∑(x, k)∈p. content k *R f x)" .
      then have "norm ((∑(x, k)∈p. content k *R (h ∘ f) x) - h y) < e"
        apply (simp add: diff[symmetric])
        apply (rule le_less_trans[OF B(2)])
        using g(2)[OF as] B(1)
        apply (auto simp add: field_simps)
        done
    }
    with g show ?case
      by (rule_tac x=g in exI) auto
  qed
  {
    presume "¬ (∃a b. s = cbox a b) ⟹ ?thesis"
    then show ?thesis
      using assms(1) lem by blast
  }
  assume as: "¬ (∃a b. s = cbox a b)"
  then show ?thesis
  proof (subst has_integral_alt, clarsimp)
    fix e :: real
    assume e: "e > 0"
    have *: "0 < e/B" using e B(1) by simp
    obtain M where M:
      "M > 0"
      "⋀a b. ball 0 M ⊆ cbox a b ⟹
        ∃z. ((λx. if x ∈ s then f x else 0) has_integral z) (cbox a b) ∧ norm (z - y) < e / B"
      using has_integral_altD[OF assms(1) as *] by blast
    show "∃B>0. ∀a b. ball 0 B ⊆ cbox a b ⟶
      (∃z. ((λx. if x ∈ s then (h ∘ f) x else 0) has_integral z) (cbox a b) ∧ norm (z - h y) < e)"
    proof (rule_tac x=M in exI, clarsimp simp add: M, goal_cases)
      case prems: (1 a b)
      obtain z where z:
        "((λx. if x ∈ s then f x else 0) has_integral z) (cbox a b)"
        "norm (z - y) < e / B"
        using M(2)[OF prems(1)] by blast
      have *: "(λx. if x ∈ s then (h ∘ f) x else 0) = h ∘ (λx. if x ∈ s then f x else 0)"
        using zero by auto
      show ?case
        apply (rule_tac x="h z" in exI)
        apply (simp add: * lem z(1))
        apply (metis B diff le_less_trans pos_less_divide_eq z(2))
        done
    qed
  qed
qed

lemma has_integral_scaleR_left:
  "(f has_integral y) s ⟹ ((λx. f x *R c) has_integral (y *R c)) s"
  using has_integral_linear[OF _ bounded_linear_scaleR_left] by (simp add: comp_def)

lemma has_integral_mult_left:
  fixes c :: "_ :: {real_normed_algebra}"
  shows "(f has_integral y) s ⟹ ((λx. f x * c) has_integral (y * c)) s"
  using has_integral_linear[OF _ bounded_linear_mult_left] by (simp add: comp_def)

corollary integral_mult_left:
  fixes c:: "'a::real_normed_algebra"
  shows "f integrable_on s ⟹ integral s (λx. f x * c) = integral s f * c"
  by (blast intro:  has_integral_mult_left)

lemma has_integral_mult_right:
  fixes c :: "'a :: real_normed_algebra"
  shows "(f has_integral y) i ⟹ ((λx. c * f x) has_integral (c * y)) i"
  using has_integral_linear[OF _ bounded_linear_mult_right] by (simp add: comp_def)

lemma has_integral_cmul: "(f has_integral k) s ⟹ ((λx. c *R f x) has_integral (c *R k)) s"
  unfolding o_def[symmetric]
  by (metis has_integral_linear bounded_linear_scaleR_right)

lemma has_integral_cmult_real:
  fixes c :: real
  assumes "c ≠ 0 ⟹ (f has_integral x) A"
  shows "((λx. c * f x) has_integral c * x) A"
proof (cases "c = 0")
  case True
  then show ?thesis by simp
next
  case False
  from has_integral_cmul[OF assms[OF this], of c] show ?thesis
    unfolding real_scaleR_def .
qed

lemma has_integral_neg: "(f has_integral k) s ⟹ ((λx. -(f x)) has_integral (-k)) s"
  by (drule_tac c="-1" in has_integral_cmul) auto

lemma has_integral_add:
  fixes f :: "'n::euclidean_space ⇒ 'a::real_normed_vector"
  assumes "(f has_integral k) s"
    and "(g has_integral l) s"
  shows "((λx. f x + g x) has_integral (k + l)) s"
proof -
  have lem: "((λx. f x + g x) has_integral (k + l)) (cbox a b)"
    if f_k: "(f has_integral k) (cbox a b)"
    and g_l: "(g has_integral l) (cbox a b)"
    for f :: "'n ⇒ 'a" and g a b k l
    unfolding has_integral
  proof clarify
    fix e :: real
    assume e: "e > 0"
    then have *: "e / 2 > 0"
      by auto
    obtain d1 where d1:
      "gauge d1"
      "⋀p. p tagged_division_of (cbox a b) ⟹ d1 fine p ⟹
        norm ((∑(x, k)∈p. content k *R f x) - k) < e / 2"
      using has_integralD[OF f_k *] by blast
    obtain d2 where d2:
      "gauge d2"
      "⋀p. p tagged_division_of (cbox a b) ⟹ d2 fine p ⟹
        norm ((∑(x, k)∈p. content k *R g x) - l) < e / 2"
      using has_integralD[OF g_l *] by blast
    show "∃d. gauge d ∧ (∀p. p tagged_division_of (cbox a b) ∧ d fine p ⟶
              norm ((∑(x, k)∈p. content k *R (f x + g x)) - (k + l)) < e)"
    proof (rule exI [where x="λx. (d1 x) ∩ (d2 x)"], clarsimp simp add: gauge_inter[OF d1(1) d2(1)])
      fix p
      assume as: "p tagged_division_of (cbox a b)" "(λx. d1 x ∩ d2 x) fine p"
      have *: "(∑(x, k)∈p. content k *R (f x + g x)) =
        (∑(x, k)∈p. content k *R f x) + (∑(x, k)∈p. content k *R g x)"
        unfolding scaleR_right_distrib setsum.distrib[of "λ(x,k). content k *R f x" "λ(x,k). content k *R g x" p,symmetric]
        by (rule setsum.cong) auto
      from as have fine: "d1 fine p" "d2 fine p"
        unfolding fine_inter by auto
      have "norm ((∑(x, k)∈p. content k *R (f x + g x)) - (k + l)) =
            norm (((∑(x, k)∈p. content k *R f x) - k) + ((∑(x, k)∈p. content k *R g x) - l))"
        unfolding * by (auto simp add: algebra_simps)
      also have "… < e/2 + e/2"
        apply (rule le_less_trans[OF norm_triangle_ineq])
        using as d1 d2 fine
        apply (blast intro: add_strict_mono)
        done
      finally show "norm ((∑(x, k)∈p. content k *R (f x + g x)) - (k + l)) < e"
        by auto
    qed
  qed
  {
    presume "¬ (∃a b. s = cbox a b) ⟹ ?thesis"
    then show ?thesis
      using assms lem by force
  }
  assume as: "¬ (∃a b. s = cbox a b)"
  then show ?thesis
  proof (subst has_integral_alt, clarsimp, goal_cases)
    case (1 e)
    then have *: "e / 2 > 0"
      by auto
    from has_integral_altD[OF assms(1) as *]
    obtain B1 where B1:
        "0 < B1"
        "⋀a b. ball 0 B1 ⊆ cbox a b ⟹
          ∃z. ((λx. if x ∈ s then f x else 0) has_integral z) (cbox a b) ∧ norm (z - k) < e / 2"
      by blast
    from has_integral_altD[OF assms(2) as *]
    obtain B2 where B2:
        "0 < B2"
        "⋀a b. ball 0 B2 ⊆ (cbox a b) ⟹
          ∃z. ((λx. if x ∈ s then g x else 0) has_integral z) (cbox a b) ∧ norm (z - l) < e / 2"
      by blast
    show ?case
    proof (rule_tac x="max B1 B2" in exI, clarsimp simp add: max.strict_coboundedI1 B1)
      fix a b
      assume "ball 0 (max B1 B2) ⊆ cbox a (b::'n)"
      then have *: "ball 0 B1 ⊆ cbox a (b::'n)" "ball 0 B2 ⊆ cbox a (b::'n)"
        by auto
      obtain w where w:
        "((λx. if x ∈ s then f x else 0) has_integral w) (cbox a b)"
        "norm (w - k) < e / 2"
        using B1(2)[OF *(1)] by blast
      obtain z where z:
        "((λx. if x ∈ s then g x else 0) has_integral z) (cbox a b)"
        "norm (z - l) < e / 2"
        using B2(2)[OF *(2)] by blast
      have *: "⋀x. (if x ∈ s then f x + g x else 0) =
        (if x ∈ s then f x else 0) + (if x ∈ s then g x else 0)"
        by auto
      show "∃z. ((λx. if x ∈ s then f x + g x else 0) has_integral z) (cbox a b) ∧ norm (z - (k + l)) < e"
        apply (rule_tac x="w + z" in exI)
        apply (simp add: lem[OF w(1) z(1), unfolded *[symmetric]])
        using norm_triangle_ineq[of "w - k" "z - l"] w(2) z(2)
        apply (auto simp add: field_simps)
        done
    qed
  qed
qed

lemma has_integral_sub:
  "(f has_integral k) s ⟹ (g has_integral l) s ⟹
    ((λx. f x - g x) has_integral (k - l)) s"
  using has_integral_add[OF _ has_integral_neg, of f k s g l]
  unfolding algebra_simps
  by auto

lemma integral_0:
  "integral s (λx::'n::euclidean_space. 0::'m::real_normed_vector) = 0"
  by (rule integral_unique has_integral_0)+

lemma integral_add: "f integrable_on s ⟹ g integrable_on s ⟹
    integral s (λx. f x + g x) = integral s f + integral s g"
  by (rule integral_unique) (metis integrable_integral has_integral_add)

lemma integral_cmul: "f integrable_on s ⟹ integral s (λx. c *R f x) = c *R integral s f"
  by (rule integral_unique) (metis integrable_integral has_integral_cmul)

lemma integral_neg: "f integrable_on s ⟹ integral s (λx. - f x) = - integral s f"
  by (rule integral_unique) (metis integrable_integral has_integral_neg)

lemma integral_diff: "f integrable_on s ⟹ g integrable_on s ⟹
    integral s (λx. f x - g x) = integral s f - integral s g"
  by (rule integral_unique) (metis integrable_integral has_integral_sub)

lemma integrable_0: "(λx. 0) integrable_on s"
  unfolding integrable_on_def using has_integral_0 by auto

lemma integrable_add: "f integrable_on s ⟹ g integrable_on s ⟹ (λx. f x + g x) integrable_on s"
  unfolding integrable_on_def by(auto intro: has_integral_add)

lemma integrable_cmul: "f integrable_on s ⟹ (λx. c *R f(x)) integrable_on s"
  unfolding integrable_on_def by(auto intro: has_integral_cmul)

lemma integrable_on_cmult_iff:
  fixes c :: real
  assumes "c ≠ 0"
  shows "(λx. c * f x) integrable_on s ⟷ f integrable_on s"
  using integrable_cmul[of "λx. c * f x" s "1 / c"] integrable_cmul[of f s c] ‹c ≠ 0›
  by auto

lemma integrable_neg: "f integrable_on s ⟹ (λx. -f(x)) integrable_on s"
  unfolding integrable_on_def by(auto intro: has_integral_neg)

lemma integrable_diff:
  "f integrable_on s ⟹ g integrable_on s ⟹ (λx. f x - g x) integrable_on s"
  unfolding integrable_on_def by(auto intro: has_integral_sub)

lemma integrable_linear:
  "f integrable_on s ⟹ bounded_linear h ⟹ (h ∘ f) integrable_on s"
  unfolding integrable_on_def by(auto intro: has_integral_linear)

lemma integral_linear:
  "f integrable_on s ⟹ bounded_linear h ⟹ integral s (h ∘ f) = h (integral s f)"
  apply (rule has_integral_unique [where i=s and f = "h ∘ f"])
  apply (simp_all add: integrable_integral integrable_linear has_integral_linear )
  done

lemma integral_component_eq[simp]:
  fixes f :: "'n::euclidean_space ⇒ 'm::euclidean_space"
  assumes "f integrable_on s"
  shows "integral s (λx. f x ∙ k) = integral s f ∙ k"
  unfolding integral_linear[OF assms(1) bounded_linear_component,unfolded o_def] ..

lemma has_integral_setsum:
  assumes "finite t"
    and "∀a∈t. ((f a) has_integral (i a)) s"
  shows "((λx. setsum (λa. f a x) t) has_integral (setsum i t)) s"
  using assms(1) subset_refl[of t]
proof (induct rule: finite_subset_induct)
  case empty
  then show ?case by auto
next
  case (insert x F)
  with assms show ?case
    by (simp add: has_integral_add)
qed

lemma integral_setsum:
  "⟦finite t;  ∀a∈t. (f a) integrable_on s⟧ ⟹
   integral s (λx. setsum (λa. f a x) t) = setsum (λa. integral s (f a)) t"
  by (auto intro: has_integral_setsum integrable_integral)

lemma integrable_setsum:
  "⟦finite t;  ∀a∈t. (f a) integrable_on s⟧ ⟹ (λx. setsum (λa. f a x) t) integrable_on s"
  unfolding integrable_on_def
  apply (drule bchoice)
  using has_integral_setsum[of t]
  apply auto
  done

lemma has_integral_eq:
  assumes "⋀x. x ∈ s ⟹ f x = g x"
    and "(f has_integral k) s"
  shows "(g has_integral k) s"
  using has_integral_sub[OF assms(2), of "λx. f x - g x" 0]
  using has_integral_is_0[of s "λx. f x - g x"]
  using assms(1)
  by auto

lemma integrable_eq: "(⋀x. x ∈ s ⟹ f x = g x) ⟹ f integrable_on s ⟹ g integrable_on s"
  unfolding integrable_on_def
  using has_integral_eq[of s f g] has_integral_eq by blast

lemma has_integral_cong:
  assumes "⋀x. x ∈ s ⟹ f x = g x"
  shows "(f has_integral i) s = (g has_integral i) s"
  using has_integral_eq[of s f g] has_integral_eq[of s g f] assms
  by auto

lemma integral_cong:
  assumes "⋀x. x ∈ s ⟹ f x = g x"
  shows "integral s f = integral s g"
  unfolding integral_def
  by (metis assms has_integral_cong)

lemma has_integral_null [intro]:
  assumes "content(cbox a b) = 0"
  shows "(f has_integral 0) (cbox a b)"
proof -
  have "gauge (λx. ball x 1)"
    by auto
  moreover
  {
    fix e :: real
    fix p
    assume e: "e > 0"
    assume p: "p tagged_division_of (cbox a b)"
    have "norm ((∑(x, k)∈p. content k *R f x) - 0) = 0"
      unfolding norm_eq_zero diff_0_right
      using setsum_content_null[OF assms(1) p, of f] .
    then have "norm ((∑(x, k)∈p. content k *R f x) - 0) < e"
      using e by auto
  }
  ultimately show ?thesis
    by (auto simp: has_integral)
qed

lemma has_integral_null_real [intro]:
  assumes "content {a .. b::real} = 0"
  shows "(f has_integral 0) {a .. b}"
  by (metis assms box_real(2) has_integral_null)

lemma has_integral_null_eq[simp]: "content (cbox a b) = 0 ⟹ (f has_integral i) (cbox a b) ⟷ i = 0"
  by (auto simp add: has_integral_null dest!: integral_unique)

lemma integral_null [simp]: "content (cbox a b) = 0 ⟹ integral (cbox a b) f = 0"
  by (metis has_integral_null integral_unique)

lemma integrable_on_null [intro]: "content (cbox a b) = 0 ⟹ f integrable_on (cbox a b)"
  by (simp add: has_integral_integrable)

lemma has_integral_empty[intro]: "(f has_integral 0) {}"
  by (simp add: has_integral_is_0)

lemma has_integral_empty_eq[simp]: "(f has_integral i) {} ⟷ i = 0"
  by (auto simp add: has_integral_empty has_integral_unique)

lemma integrable_on_empty[intro]: "f integrable_on {}"
  unfolding integrable_on_def by auto

lemma integral_empty[simp]: "integral {} f = 0"
  by (rule integral_unique) (rule has_integral_empty)

lemma has_integral_refl[intro]:
  fixes a :: "'a::euclidean_space"
  shows "(f has_integral 0) (cbox a a)"
    and "(f has_integral 0) {a}"
proof -
  have *: "{a} = cbox a a"
    apply (rule set_eqI)
    unfolding mem_box singleton_iff euclidean_eq_iff[where 'a='a]
    apply safe
    prefer 3
    apply (erule_tac x=b in ballE)
    apply (auto simp add: field_simps)
    done
  show "(f has_integral 0) (cbox a a)" "(f has_integral 0) {a}"
    unfolding *
    apply (rule_tac[!] has_integral_null)
    unfolding content_eq_0_interior
    unfolding interior_cbox
    using box_sing
    apply auto
    done
qed

lemma integrable_on_refl[intro]: "f integrable_on cbox a a"
  unfolding integrable_on_def by auto

lemma integral_refl [simp]: "integral (cbox a a) f = 0"
  by (rule integral_unique) auto

lemma integral_singleton [simp]: "integral {a} f = 0"
  by auto

lemma integral_blinfun_apply:
  assumes "f integrable_on s"
  shows "integral s (λx. blinfun_apply h (f x)) = blinfun_apply h (integral s f)"
  by (subst integral_linear[symmetric, OF assms blinfun.bounded_linear_right]) (simp add: o_def)

lemma blinfun_apply_integral:
  assumes "f integrable_on s"
  shows "blinfun_apply (integral s f) x = integral s (λy. blinfun_apply (f y) x)"
  by (metis (no_types, lifting) assms blinfun.prod_left.rep_eq integral_blinfun_apply integral_cong)


subsection ‹Cauchy-type criterion for integrability.›

(* XXXXXXX *)
lemma integrable_cauchy:
  fixes f :: "'n::euclidean_space ⇒ 'a::{real_normed_vector,complete_space}"
  shows "f integrable_on cbox a b ⟷
    (∀e>0.∃d. gauge d ∧
      (∀p1 p2. p1 tagged_division_of (cbox a b) ∧ d fine p1 ∧
        p2 tagged_division_of (cbox a b) ∧ d fine p2 ⟶
        norm (setsum (λ(x,k). content k *R f x) p1 -
        setsum (λ(x,k). content k *R f x) p2) < e))"
  (is "?l = (∀e>0. ∃d. ?P e d)")
proof
  assume ?l
  then guess y unfolding integrable_on_def has_integral .. note y=this
  show "∀e>0. ∃d. ?P e d"
  proof (clarify, goal_cases)
    case (1 e)
    then have "e/2 > 0" by auto
    then guess d
      apply -
      apply (drule y[rule_format])
      apply (elim exE conjE)
      done
    note d=this[rule_format]
    show ?case
    proof (rule_tac x=d in exI, clarsimp simp: d)
      fix p1 p2
      assume as: "p1 tagged_division_of (cbox a b)" "d fine p1"
                 "p2 tagged_division_of (cbox a b)" "d fine p2"
      show "norm ((∑(x, k)∈p1. content k *R f x) - (∑(x, k)∈p2. content k *R f x)) < e"
        apply (rule dist_triangle_half_l[where y=y,unfolded dist_norm])
        using d(2)[OF conjI[OF as(1-2)]] d(2)[OF conjI[OF as(3-4)]] .
    qed
  qed
next
  assume "∀e>0. ∃d. ?P e d"
  then have "∀n::nat. ∃d. ?P (inverse(of_nat (n + 1))) d"
    by auto
  from choice[OF this] guess d .. note d=conjunctD2[OF this[rule_format],rule_format]
  have "⋀n. gauge (λx. ⋂{d i x |i. i ∈ {0..n}})"
    apply (rule gauge_inters)
    using d(1)
    apply auto
    done
  then have "∀n. ∃p. p tagged_division_of (cbox a b) ∧ (λx. ⋂{d i x |i. i ∈ {0..n}}) fine p"
    by (meson fine_division_exists)
  from choice[OF this] guess p .. note p = conjunctD2[OF this[rule_format]]
  have dp: "⋀i n. i≤n ⟹ d i fine p n"
    using p(2) unfolding fine_inters by auto
  have "Cauchy (λn. setsum (λ(x,k). content k *R (f x)) (p n))"
  proof (rule CauchyI, goal_cases)
    case (1 e)
    then guess N unfolding real_arch_inv[of e] .. note N=this
    show ?case
      apply (rule_tac x=N in exI)
    proof clarify
      fix m n
      assume mn: "N ≤ m" "N ≤ n"
      have *: "N = (N - 1) + 1" using N by auto
      show "norm ((∑(x, k)∈p m. content k *R f x) - (∑(x, k)∈p n. content k *R f x)) < e"
        apply (rule less_trans[OF _ N[THEN conjunct2,THEN conjunct2]])
        apply(subst *)
        using dp p(1) mn d(2) by auto
    qed
  qed
  then guess y unfolding convergent_eq_cauchy[symmetric] .. note y=this[THEN LIMSEQ_D]
  show ?l
    unfolding integrable_on_def has_integral
  proof (rule_tac x=y in exI, clarify)
    fix e :: real
    assume "e>0"
    then have *:"e/2 > 0" by auto
    then guess N1 unfolding real_arch_inv[of "e/2"] .. note N1=this
    then have N1': "N1 = N1 - 1 + 1"
      by auto
    guess N2 using y[OF *] .. note N2=this
    have "gauge (d (N1 + N2))"
      using d by auto
    moreover
    {
      fix q
      assume as: "q tagged_division_of (cbox a b)" "d (N1 + N2) fine q"
      have *: "inverse (of_nat (N1 + N2 + 1)) < e / 2"
        apply (rule less_trans)
        using N1
        apply auto
        done
      have "norm ((∑(x, k)∈q. content k *R f x) - y) < e"
        apply (rule norm_triangle_half_r)
        apply (rule less_trans[OF _ *])
        apply (subst N1', rule d(2)[of "p (N1+N2)"])
        using N1' as(1) as(2) dp
        apply (simp add: ‹∀x. p x tagged_division_of cbox a b ∧ (λxa. ⋂{d i xa |i. i ∈ {0..x}}) fine p x›)
        using N2 le_add2 by blast
    }
    ultimately show "∃d. gauge d ∧
      (∀p. p tagged_division_of (cbox a b) ∧ d fine p ⟶
        norm ((∑(x, k)∈p. content k *R f x) - y) < e)"
      by (rule_tac x="d (N1 + N2)" in exI) auto
  qed
qed


subsection ‹Additivity of integral on abutting intervals.›

lemma interval_split:
  fixes a :: "'a::euclidean_space"
  assumes "k ∈ Basis"
  shows
    "cbox a b ∩ {x. x∙k ≤ c} = cbox a (∑i∈Basis. (if i = k then min (b∙k) c else b∙i) *R i)"
    "cbox a b ∩ {x. x∙k ≥ c} = cbox (∑i∈Basis. (if i = k then max (a∙k) c else a∙i) *R i) b"
  apply (rule_tac[!] set_eqI)
  unfolding Int_iff mem_box mem_Collect_eq
  using assms
  apply auto
  done

lemma content_split:
  fixes a :: "'a::euclidean_space"
  assumes "k ∈ Basis"
  shows "content (cbox a b) = content(cbox a b ∩ {x. x∙k ≤ c}) + content(cbox a b ∩ {x. x∙k ≥ c})"
proof cases
  note simps = interval_split[OF assms] content_cbox_cases
  have *: "Basis = insert k (Basis - {k})" "⋀x. finite (Basis-{x})" "⋀x. x∉Basis-{x}"
    using assms by auto
  have *: "⋀X Y Z. (∏i∈Basis. Z i (if i = k then X else Y i)) = Z k X * (∏i∈Basis-{k}. Z i (Y i))"
    "(∏i∈Basis. b∙i - a∙i) = (∏i∈Basis-{k}. b∙i - a∙i) * (b∙k - a∙k)"
    apply (subst *(1))
    defer
    apply (subst *(1))
    unfolding setprod.insert[OF *(2-)]
    apply auto
    done
  assume as: "∀i∈Basis. a ∙ i ≤ b ∙ i"
  moreover
  have "⋀x. min (b ∙ k) c = max (a ∙ k) c ⟹
    x * (b∙k - a∙k) = x * (max (a ∙ k) c - a ∙ k) + x * (b ∙ k - max (a ∙ k) c)"
    by  (auto simp add: field_simps)
  moreover
  have **: "(∏i∈Basis. ((∑i∈Basis. (if i = k then min (b ∙ k) c else b ∙ i) *R i) ∙ i - a ∙ i)) =
      (∏i∈Basis. (if i = k then min (b ∙ k) c else b ∙ i) - a ∙ i)"
    "(∏i∈Basis. b ∙ i - ((∑i∈Basis. (if i = k then max (a ∙ k) c else a ∙ i) *R i) ∙ i)) =
      (∏i∈Basis. b ∙ i - (if i = k then max (a ∙ k) c else a ∙ i))"
    by (auto intro!: setprod.cong)
  have "¬ a ∙ k ≤ c ⟹ ¬ c ≤ b ∙ k ⟹ False"
    unfolding not_le
    using as[unfolded ,rule_format,of k] assms
    by auto
  ultimately show ?thesis
    using assms
    unfolding simps **
    unfolding *(1)[of "λi x. b∙i - x"] *(1)[of "λi x. x - a∙i"]
    unfolding *(2)
    by auto
next
  assume "¬ (∀i∈Basis. a ∙ i ≤ b ∙ i)"
  then have "cbox a b = {}"
    unfolding box_eq_empty by (auto simp: not_le)
  then show ?thesis
    by (auto simp: not_le)
qed

lemma division_split_left_inj:
  fixes type :: "'a::euclidean_space"
  assumes "d division_of i"
    and "k1 ∈ d"
    and "k2 ∈ d"
    and "k1 ≠ k2"
    and "k1 ∩ {x::'a. x∙k ≤ c} = k2 ∩ {x. x∙k ≤ c}"
    and k: "k∈Basis"
  shows "content(k1 ∩ {x. x∙k ≤ c}) = 0"
proof -
  note d=division_ofD[OF assms(1)]
  have *: "⋀(a::'a) b c. content (cbox a b ∩ {x. x∙k ≤ c}) = 0 ⟷
    interior(cbox a b ∩ {x. x∙k ≤ c}) = {}"
    unfolding  interval_split[OF k] content_eq_0_interior by auto
  guess u1 v1 using d(4)[OF assms(2)] by (elim exE) note uv1=this
  guess u2 v2 using d(4)[OF assms(3)] by (elim exE) note uv2=this
  have **: "⋀s t u. s ∩ t = {} ⟹ u ⊆ s ⟹ u ⊆ t ⟹ u = {}"
    by auto
  show ?thesis
    unfolding uv1 uv2 *
    apply (rule **[OF d(5)[OF assms(2-4)]])
    apply (simp add: uv1)
    using assms(5) uv1 by auto
qed

lemma division_split_right_inj:
  fixes type :: "'a::euclidean_space"
  assumes "d division_of i"
    and "k1 ∈ d"
    and "k2 ∈ d"
    and "k1 ≠ k2"
    and "k1 ∩ {x::'a. x∙k ≥ c} = k2 ∩ {x. x∙k ≥ c}"
    and k: "k ∈ Basis"
  shows "content (k1 ∩ {x. x∙k ≥ c}) = 0"
proof -
  note d=division_ofD[OF assms(1)]
  have *: "⋀a b::'a. ⋀c. content(cbox a b ∩ {x. x∙k ≥ c}) = 0 ⟷
    interior(cbox a b ∩ {x. x∙k ≥ c}) = {}"
    unfolding interval_split[OF k] content_eq_0_interior by auto
  guess u1 v1 using d(4)[OF assms(2)] by (elim exE) note uv1=this
  guess u2 v2 using d(4)[OF assms(3)] by (elim exE) note uv2=this
  have **: "⋀s t u. s ∩ t = {} ⟹ u ⊆ s ⟹ u ⊆ t ⟹ u = {}"
    by auto
  show ?thesis
    unfolding uv1 uv2 *
    apply (rule **[OF d(5)[OF assms(2-4)]])
    apply (simp add: uv1)
    using assms(5) uv1 by auto
qed

lemma tagged_division_split_left_inj:
  fixes x1 :: "'a::euclidean_space"
  assumes d: "d tagged_division_of i"
    and k12: "(x1, k1) ∈ d"
             "(x2, k2) ∈ d"
             "k1 ≠ k2"
             "k1 ∩ {x. x∙k ≤ c} = k2 ∩ {x. x∙k ≤ c}"
             "k ∈ Basis"
  shows "content (k1 ∩ {x. x∙k ≤ c}) = 0"
proof -
  have *: "⋀a b c. (a,b) ∈ c ⟹ b ∈ snd ` c"
    by force
  show ?thesis
    using k12
    by (fastforce intro!:  division_split_left_inj[OF division_of_tagged_division[OF d]] *)
qed

lemma tagged_division_split_right_inj:
  fixes x1 :: "'a::euclidean_space"
  assumes d: "d tagged_division_of i"
    and k12: "(x1, k1) ∈ d"
             "(x2, k2) ∈ d"
             "k1 ≠ k2"
             "k1 ∩ {x. x∙k ≥ c} = k2 ∩ {x. x∙k ≥ c}"
             "k ∈ Basis"
  shows "content (k1 ∩ {x. x∙k ≥ c}) = 0"
proof -
  have *: "⋀a b c. (a,b) ∈ c ⟹ b ∈ snd ` c"
    by force
  show ?thesis
    using k12
    by (fastforce intro!:  division_split_right_inj[OF division_of_tagged_division[OF d]] *)
qed

lemma division_split:
  fixes a :: "'a::euclidean_space"
  assumes "p division_of (cbox a b)"
    and k: "k∈Basis"
  shows "{l ∩ {x. x∙k ≤ c} | l. l ∈ p ∧ l ∩ {x. x∙k ≤ c} ≠ {}} division_of(cbox a b ∩ {x. x∙k ≤ c})"
      (is "?p1 division_of ?I1")
    and "{l ∩ {x. x∙k ≥ c} | l. l ∈ p ∧ l ∩ {x. x∙k ≥ c} ≠ {}} division_of (cbox a b ∩ {x. x∙k ≥ c})"
      (is "?p2 division_of ?I2")
proof (rule_tac[!] division_ofI)
  note p = division_ofD[OF assms(1)]
  show "finite ?p1" "finite ?p2"
    using p(1) by auto
  show "⋃?p1 = ?I1" "⋃?p2 = ?I2"
    unfolding p(6)[symmetric] by auto
  {
    fix k
    assume "k ∈ ?p1"
    then guess l unfolding mem_Collect_eq by (elim exE conjE) note l=this
    guess u v using p(4)[OF l(2)] by (elim exE) note uv=this
    show "k ⊆ ?I1"
      using l p(2) uv by force
    show  "k ≠ {}"
      by (simp add: l)
    show  "∃a b. k = cbox a b"
      apply (simp add: l uv p(2-3)[OF l(2)])
      apply (subst interval_split[OF k])
      apply (auto intro: order.trans)
      done
    fix k'
    assume "k' ∈ ?p1"
    then guess l' unfolding mem_Collect_eq by (elim exE conjE) note l'=this
    assume "k ≠ k'"
    then show "interior k ∩ interior k' = {}"
      unfolding l l' using p(5)[OF l(2) l'(2)] by auto
  }
  {
    fix k
    assume "k ∈ ?p2"
    then guess l unfolding mem_Collect_eq by (elim exE conjE) note l=this
    guess u v using p(4)[OF l(2)] by (elim exE) note uv=this
    show "k ⊆ ?I2"
      using l p(2) uv by force
    show  "k ≠ {}"
      by (simp add: l)
    show  "∃a b. k = cbox a b"
      apply (simp add: l uv p(2-3)[OF l(2)])
      apply (subst interval_split[OF k])
      apply (auto intro: order.trans)
      done
    fix k'
    assume "k' ∈ ?p2"
    then guess l' unfolding mem_Collect_eq by (elim exE conjE) note l'=this
    assume "k ≠ k'"
    then show "interior k ∩ interior k' = {}"
      unfolding l l' using p(5)[OF l(2) l'(2)] by auto
  }
qed

lemma has_integral_split:
  fixes f :: "'a::euclidean_space ⇒ 'b::real_normed_vector"
  assumes fi: "(f has_integral i) (cbox a b ∩ {x. x∙k ≤ c})"
      and fj: "(f has_integral j) (cbox a b ∩ {x. x∙k ≥ c})"
      and k: "k ∈ Basis"
  shows "(f has_integral (i + j)) (cbox a b)"
proof (unfold has_integral, rule, rule, goal_cases)
  case (1 e)
  then have e: "e/2 > 0"
    by auto
    obtain d1
    where d1: "gauge d1"
      and d1norm:
        "⋀p. ⟦p tagged_division_of cbox a b ∩ {x. x ∙ k ≤ c};
               d1 fine p⟧ ⟹ norm ((∑(x, k) ∈ p. content k *R f x) - i) < e / 2"
       apply (rule has_integralD[OF fi[unfolded interval_split[OF k]] e])
       apply (simp add: interval_split[symmetric] k)
       done
    obtain d2
    where d2: "gauge d2"
      and d2norm:
        "⋀p. ⟦p tagged_division_of cbox a b ∩ {x. c ≤ x ∙ k};
               d2 fine p⟧ ⟹ norm ((∑(x, k) ∈ p. content k *R f x) - j) < e / 2"
       apply (rule has_integralD[OF fj[unfolded interval_split[OF k]] e])
       apply (simp add: interval_split[symmetric] k)
       done
  let ?d = "λx. if x∙k = c then (d1 x ∩ d2 x) else ball x ¦x∙k - c¦ ∩ d1 x ∩ d2 x"
  have "gauge ?d"
    using d1 d2 unfolding gauge_def by auto
  then show ?case
  proof (rule_tac x="?d" in exI, safe)
    fix p
    assume "p tagged_division_of (cbox a b)" "?d fine p"
    note p = this tagged_division_ofD[OF this(1)]
    have xk_le_c: "⋀x kk. (x, kk) ∈ p ⟹ kk ∩ {x. x∙k ≤ c} ≠ {} ⟹ x∙k ≤ c"
    proof -
      fix x kk
      assume as: "(x, kk) ∈ p" and kk: "kk ∩ {x. x∙k ≤ c} ≠ {}"
      show "x∙k ≤ c"
      proof (rule ccontr)
        assume **: "¬ ?thesis"
        from this[unfolded not_le]
        have "kk ⊆ ball x ¦x ∙ k - c¦"
          using p(2)[unfolded fine_def, rule_format,OF as] by auto
        with kk obtain y where y: "y ∈ ball x ¦x ∙ k - c¦" "y∙k ≤ c"
          by blast
        then have "¦x ∙ k - y ∙ k¦ < ¦x ∙ k - c¦"
          using Basis_le_norm[OF k, of "x - y"]
          by (auto simp add: dist_norm inner_diff_left intro: le_less_trans)
        with y show False
          using ** by (auto simp add: field_simps)
      qed
    qed
    have xk_ge_c: "⋀x kk. (x, kk) ∈ p ⟹ kk ∩ {x. x∙k ≥ c} ≠ {} ⟹ x∙k ≥ c"
    proof -
      fix x kk
      assume as: "(x, kk) ∈ p" and kk: "kk ∩ {x. x∙k ≥ c} ≠ {}"
      show "x∙k ≥ c"
      proof (rule ccontr)
        assume **: "¬ ?thesis"
        from this[unfolded not_le] have "kk ⊆ ball x ¦x ∙ k - c¦"
          using p(2)[unfolded fine_def,rule_format,OF as,unfolded split_conv] by auto
        with kk obtain y where y: "y ∈ ball x ¦x ∙ k - c¦" "y∙k ≥ c"
          by blast
        then have "¦x ∙ k - y ∙ k¦ < ¦x ∙ k - c¦"
          using Basis_le_norm[OF k, of "x - y"]
          by (auto simp add: dist_norm inner_diff_left intro: le_less_trans)
        with y show False
          using ** by (auto simp add: field_simps)
      qed
    qed

    have lem1: "⋀f P Q. (∀x k. (x, k) ∈ {(x, f k) | x k. P x k} ⟶ Q x k) ⟷
                         (∀x k. P x k ⟶ Q x (f k))"
      by auto
    have fin_finite: "finite {(x,f k) | x k. (x,k) ∈ s ∧ P x k}" if "finite s" for f s P
    proof -
      from that have "finite ((λ(x, k). (x, f k)) ` s)"
        by auto
      then show ?thesis
        by (rule rev_finite_subset) auto
    qed
    { fix g :: "'a set ⇒ 'a set"
      fix i :: "'a × 'a set"
      assume "i ∈ (λ(x, k). (x, g k)) ` p - {(x, g k) |x k. (x, k) ∈ p ∧ g k ≠ {}}"
      then obtain x k where xk:
              "i = (x, g k)"  "(x, k) ∈ p"
              "(x, g k) ∉ {(x, g k) |x k. (x, k) ∈ p ∧ g k ≠ {}}"
          by auto
      have "content (g k) = 0"
        using xk using content_empty by auto
      then have "(λ(x, k). content k *R f x) i = 0"
        unfolding xk split_conv by auto
    } note [simp] = this
    have lem3: "⋀g :: 'a set ⇒ 'a set. finite p ⟹
                  setsum (λ(x, k). content k *R f x) {(x,g k) |x k. (x,k) ∈ p ∧ g k ≠ {}} =
                  setsum (λ(x, k). content k *R f x) ((λ(x, k). (x, g k)) ` p)"
      by (rule setsum.mono_neutral_left) auto
    let ?M1 = "{(x, kk ∩ {x. x∙k ≤ c}) |x kk. (x, kk) ∈ p ∧ kk ∩ {x. x∙k ≤ c} ≠ {}}"
    have d1_fine: "d1 fine ?M1"
      by (force intro: fineI dest: fineD[OF p(2)] simp add: split: split_if_asm)
    have "norm ((∑(x, k)∈?M1. content k *R f x) - i) < e/2"
    proof (rule d1norm [OF tagged_division_ofI d1_fine])
      show "finite ?M1"
        by (rule fin_finite p(3))+
      show "⋃{k. ∃x. (x, k) ∈ ?M1} = cbox a b ∩ {x. x∙k ≤ c}"
        unfolding p(8)[symmetric] by auto
      fix x l
      assume xl: "(x, l) ∈ ?M1"
      then guess x' l' unfolding mem_Collect_eq unfolding prod.inject by (elim exE conjE) note xl'=this
      show "x ∈ l" "l ⊆ cbox a b ∩ {x. x ∙ k ≤ c}"
        unfolding xl'
        using p(4-6)[OF xl'(3)] using xl'(4)
        using xk_le_c[OF xl'(3-4)] by auto
      show "∃a b. l = cbox a b"
        unfolding xl'
        using p(6)[OF xl'(3)]
        by (fastforce simp add: interval_split[OF k,where c=c])
      fix y r
      let ?goal = "interior l ∩ interior r = {}"
      assume yr: "(y, r) ∈ ?M1"
      then guess y' r' unfolding mem_Collect_eq unfolding prod.inject by (elim exE conjE) note yr'=this
      assume as: "(x, l) ≠ (y, r)"
      show "interior l ∩ interior r = {}"
      proof (cases "l' = r' ⟶ x' = y'")
        case False
        then show ?thesis
          using p(7)[OF xl'(3) yr'(3)] using as unfolding xl' yr' by auto
      next
        case True
        then have "l' ≠ r'"
          using as unfolding xl' yr' by auto
        then show ?thesis
          using p(7)[OF xl'(3) yr'(3)] using as unfolding xl' yr' by auto
      qed
    qed
    moreover
    let ?M2 = "{(x,kk ∩ {x. x∙k ≥ c}) |x kk. (x,kk) ∈ p ∧ kk ∩ {x. x∙k ≥ c} ≠ {}}"
    have d2_fine: "d2 fine ?M2"
      by (force intro: fineI dest: fineD[OF p(2)] simp add: split: split_if_asm)
    have "norm ((∑(x, k)∈?M2. content k *R f x) - j) < e/2"
    proof (rule d2norm [OF tagged_division_ofI d2_fine])
      show "finite ?M2"
        by (rule fin_finite p(3))+
      show "⋃{k. ∃x. (x, k) ∈ ?M2} = cbox a b ∩ {x. x∙k ≥ c}"
        unfolding p(8)[symmetric] by auto
      fix x l
      assume xl: "(x, l) ∈ ?M2"
      then guess x' l' unfolding mem_Collect_eq unfolding prod.inject by (elim exE conjE) note xl'=this
      show "x ∈ l" "l ⊆ cbox a b ∩ {x. x ∙ k ≥ c}"
        unfolding xl'
        using p(4-6)[OF xl'(3)] xl'(4) xk_ge_c[OF xl'(3-4)]
        by auto
      show "∃a b. l = cbox a b"
        unfolding xl'
        using p(6)[OF xl'(3)]
        by (fastforce simp add: interval_split[OF k, where c=c])
      fix y r
      let ?goal = "interior l ∩ interior r = {}"
      assume yr: "(y, r) ∈ ?M2"
      then guess y' r' unfolding mem_Collect_eq unfolding prod.inject by (elim exE conjE) note yr'=this
      assume as: "(x, l) ≠ (y, r)"
      show "interior l ∩ interior r = {}"
      proof (cases "l' = r' ⟶ x' = y'")
        case False
        then show ?thesis
          using p(7)[OF xl'(3) yr'(3)] using as unfolding xl' yr' by auto
      next
        case True
        then have "l' ≠ r'"
          using as unfolding xl' yr' by auto
        then show ?thesis
          using p(7)[OF xl'(3) yr'(3)] using as unfolding xl' yr' by auto
      qed
    qed
    ultimately
    have "norm (((∑(x, k)∈?M1. content k *R f x) - i) + ((∑(x, k)∈?M2. content k *R f x) - j)) < e/2 + e/2"
      using norm_add_less by blast
    also {
      have eq0: "⋀x y. x = (0::real) ⟹ x *R (y::'b) = 0"
        using scaleR_zero_left by auto
      have cont_eq: "⋀g. (λ(x,l). content l *R f x) ∘ (λ(x,l). (x,g l)) = (λ(x,l). content (g l) *R f x)"
        by auto
      have "((∑(x, k)∈?M1. content k *R f x) - i) + ((∑(x, k)∈?M2. content k *R f x) - j) =
        (∑(x, k)∈?M1. content k *R f x) + (∑(x, k)∈?M2. content k *R f x) - (i + j)"
        by auto
      also have "… = (∑(x, ka)∈p. content (ka ∩ {x. x ∙ k ≤ c}) *R f x) +
        (∑(x, ka)∈p. content (ka ∩ {x. c ≤ x ∙ k}) *R f x) - (i + j)"
        unfolding lem3[OF p(3)]
        by (subst setsum.reindex_nontrivial[OF p(3)], auto intro!: k eq0 tagged_division_split_left_inj[OF p(1)] tagged_division_split_right_inj[OF p(1)]
              simp: cont_eq)+
      also note setsum.distrib[symmetric]
      also have "⋀x. x ∈ p ⟹
                    (λ(x,ka). content (ka ∩ {x. x ∙ k ≤ c}) *R f x) x +
                    (λ(x,ka). content (ka ∩ {x. c ≤ x ∙ k}) *R f x) x =
                    (λ(x,ka). content ka *R f x) x"
      proof clarify
        fix a b
        assume "(a, b) ∈ p"
        from p(6)[OF this] guess u v by (elim exE) note uv=this
        then show "content (b ∩ {x. x ∙ k ≤ c}) *R f a + content (b ∩ {x. c ≤ x ∙ k}) *R f a =
          content b *R f a"
          unfolding scaleR_left_distrib[symmetric]
          unfolding uv content_split[OF k,of u v c]
          by auto
      qed
      note setsum.cong [OF _ this]
      finally have "(∑(x, k)∈{(x, kk ∩ {x. x ∙ k ≤ c}) |x kk. (x, kk) ∈ p ∧ kk ∩ {x. x ∙ k ≤ c} ≠ {}}. content k *R f x) - i +
        ((∑(x, k)∈{(x, kk ∩ {x. c ≤ x ∙ k}) |x kk. (x, kk) ∈ p ∧ kk ∩ {x. c ≤ x ∙ k} ≠ {}}. content k *R f x) - j) =
        (∑(x, ka)∈p. content ka *R f x) - (i + j)"
        by auto
    }
    finally show "norm ((∑(x, k)∈p. content k *R f x) - (i + j)) < e"
      by auto
  qed
qed


subsection ‹A sort of converse, integrability on subintervals.›

lemma tagged_division_union_interval:
  fixes a :: "'a::euclidean_space"
  assumes "p1 tagged_division_of (cbox a b ∩ {x. x∙k ≤ (c::real)})"
    and "p2 tagged_division_of (cbox a b ∩ {x. x∙k ≥ c})"
    and k: "k ∈ Basis"
  shows "(p1 ∪ p2) tagged_division_of (cbox a b)"
proof -
  have *: "cbox a b = (cbox a b ∩ {x. x∙k ≤ c}) ∪ (cbox a b ∩ {x. x∙k ≥ c})"
    by auto
  show ?thesis
    apply (subst *)
    apply (rule tagged_division_union[OF assms(1-2)])
    unfolding interval_split[OF k] interior_cbox
    using k
    apply (auto simp add: box_def elim!: ballE[where x=k])
    done
qed

lemma tagged_division_union_interval_real:
  fixes a :: real
  assumes "p1 tagged_division_of ({a .. b} ∩ {x. x∙k ≤ (c::real)})"
    and "p2 tagged_division_of ({a .. b} ∩ {x. x∙k ≥ c})"
    and k: "k ∈ Basis"
  shows "(p1 ∪ p2) tagged_division_of {a .. b}"
  using assms
  unfolding box_real[symmetric]
  by (rule tagged_division_union_interval)

lemma has_integral_separate_sides:
  fixes f :: "'a::euclidean_space ⇒ 'b::real_normed_vector"
  assumes "(f has_integral i) (cbox a b)"
    and "e > 0"
    and k: "k ∈ Basis"
  obtains d where "gauge d"
    "∀p1 p2. p1 tagged_division_of (cbox a b ∩ {x. x∙k ≤ c}) ∧ d fine p1 ∧
        p2 tagged_division_of (cbox a b ∩ {x. x∙k ≥ c}) ∧ d fine p2 ⟶
        norm ((setsum (λ(x,k). content k *R f x) p1 + setsum (λ(x,k). content k *R f x) p2) - i) < e"
proof -
  guess d using has_integralD[OF assms(1-2)] . note d=this
  { fix p1 p2
    assume "p1 tagged_division_of (cbox a b) ∩ {x. x ∙ k ≤ c}" "d fine p1"
    note p1=tagged_division_ofD[OF this(1)] this
    assume "p2 tagged_division_of (cbox a b) ∩ {x. c ≤ x ∙ k}" "d fine p2"
    note p2=tagged_division_ofD[OF this(1)] this
    note tagged_division_union_interval[OF p1(7) p2(7)] note p12 = tagged_division_ofD[OF this] this
    { fix a b
      assume ab: "(a, b) ∈ p1 ∩ p2"
      have "(a, b) ∈ p1"
        using ab by auto
      with p1 obtain u v where uv: "b = cbox u v" by auto
      have "b ⊆ {x. x∙k = c}"
        using ab p1(3)[of a b] p2(3)[of a b] by fastforce
      moreover
      have "interior {x::'a. x ∙ k = c} = {}"
      proof (rule ccontr)
        assume "¬ ?thesis"
        then obtain x where x: "x ∈ interior {x::'a. x∙k = c}"
          by auto
        then guess e unfolding mem_interior .. note e=this
        have x: "x∙k = c"
          using x interior_subset by fastforce
        have *: "⋀i. i ∈ Basis ⟹ ¦(x - (x + (e / 2) *R k)) ∙ i¦ = (if i = k then e/2 else 0)"
          using e k by (auto simp: inner_simps inner_not_same_Basis)
        have "(∑i∈Basis. ¦(x - (x + (e / 2 ) *R k)) ∙ i¦) =
              (∑i∈Basis. (if i = k then e / 2 else 0))"
          using "*" by (blast intro: setsum.cong)
        also have "… < e"
          apply (subst setsum.delta)
          using e
          apply auto
          done
        finally have "x + (e/2) *R k ∈ ball x e"
          unfolding mem_ball dist_norm by(rule le_less_trans[OF norm_le_l1])
        then have "x + (e/2) *R k ∈ {x. x∙k = c}"
          using e by auto
        then show False
          unfolding mem_Collect_eq using e x k by (auto simp: inner_simps)
      qed
      ultimately have "content b = 0"
        unfolding uv content_eq_0_interior
        using interior_mono by blast
      then have "content b *R f a = 0"
        by auto
    }
    then have "norm ((∑(x, k)∈p1. content k *R f x) + (∑(x, k)∈p2. content k *R f x) - i) =
               norm ((∑(x, k)∈p1 ∪ p2. content k *R f x) - i)"
      by (subst setsum.union_inter_neutral) (auto simp: p1 p2)
    also have "… < e"
      by (rule k d(2) p12 fine_union p1 p2)+
    finally have "norm ((∑(x, k)∈p1. content k *R f x) + (∑(x, k)∈p2. content k *R f x) - i) < e" .
   }
  then show ?thesis
    by (auto intro: that[of d] d elim: )
qed

lemma integrable_split[intro]:
  fixes f :: "'a::euclidean_space ⇒ 'b::{real_normed_vector,complete_space}"
  assumes "f integrable_on cbox a b"
    and k: "k ∈ Basis"
  shows "f integrable_on (cbox a b ∩ {x. x∙k ≤ c})" (is ?t1)
    and "f integrable_on (cbox a b ∩ {x. x∙k ≥ c})" (is ?t2)
proof -
  guess y using assms(1) unfolding integrable_on_def .. note y=this
  def b'  "∑i∈Basis. (if i = k then min (b∙k) c else b∙i)*R i::'a"
  def a'  "∑i∈Basis. (if i = k then max (a∙k) c else a∙i)*R i::'a"
  show ?t1 ?t2
    unfolding interval_split[OF k] integrable_cauchy
    unfolding interval_split[symmetric,OF k]
  proof (rule_tac[!] allI impI)+
    fix e :: real
    assume "e > 0"
    then have "e/2>0"
      by auto
    from has_integral_separate_sides[OF y this k,of c] guess d . note d=this[rule_format]
    let ?P = "λA. ∃d. gauge d ∧ (∀p1 p2. p1 tagged_division_of (cbox a b) ∩ A ∧ d fine p1 ∧
      p2 tagged_division_of (cbox a b) ∩ A ∧ d fine p2 ⟶
      norm ((∑(x, k)∈p1. content k *R f x) - (∑(x, k)∈p2. content k *R f x)) < e)"
    show "?P {x. x ∙ k ≤ c}"
    proof (rule_tac x=d in exI, clarsimp simp add: d)
      fix p1 p2
      assume as: "p1 tagged_division_of (cbox a b) ∩ {x. x ∙ k ≤ c}" "d fine p1"
                 "p2 tagged_division_of (cbox a b) ∩ {x. x ∙ k ≤ c}" "d fine p2"
      show "norm ((∑(x, k)∈p1. content k *R f x) - (∑(x, k)∈p2. content k *R f x)) < e"
      proof (rule fine_division_exists[OF d(1), of a' b] )
        fix p
        assume "p tagged_division_of cbox a' b" "d fine p"
        then show ?thesis
          using as norm_triangle_half_l[OF d(2)[of p1 p] d(2)[of p2 p]]
          unfolding interval_split[OF k] b'_def[symmetric] a'_def[symmetric]
          by (auto simp add: algebra_simps)
      qed
    qed
    show "?P {x. x ∙ k ≥ c}"
    proof (rule_tac x=d in exI, clarsimp simp add: d)
      fix p1 p2
      assume as: "p1 tagged_division_of (cbox a b) ∩ {x. x ∙ k ≥ c}" "d fine p1"
                 "p2 tagged_division_of (cbox a b) ∩ {x. x ∙ k ≥ c}" "d fine p2"
      show "norm ((∑(x, k)∈p1. content k *R f x) - (∑(x, k)∈p2. content k *R f x)) < e"
      proof (rule fine_division_exists[OF d(1), of a b'] )
        fix p
        assume "p tagged_division_of cbox a b'" "d fine p"
        then show ?thesis
          using as norm_triangle_half_l[OF d(2)[of p p1] d(2)[of p p2]]
          unfolding interval_split[OF k] b'_def[symmetric] a'_def[symmetric]
          by (auto simp add: algebra_simps)
      qed
    qed
  qed
qed


subsection ‹Generalized notion of additivity.›

definition "neutral opp = (SOME x. ∀y. opp x y = y ∧ opp y x = y)"

definition operative :: "('a ⇒ 'a ⇒ 'a) ⇒ (('b::euclidean_space) set ⇒ 'a) ⇒ bool"
  where "operative opp f ⟷
    (∀a b. content (cbox a b) = 0 ⟶ f (cbox a b) = neutral opp) ∧
    (∀a b c. ∀k∈Basis. f (cbox a b) = opp (f(cbox a b ∩ {x. x∙k ≤ c})) (f (cbox a b ∩ {x. x∙k ≥ c})))"

lemma operativeD[dest]:
  fixes type :: "'a::euclidean_space"
  assumes "operative opp f"
  shows "⋀a b::'a. content (cbox a b) = 0 ⟹ f (cbox a b) = neutral opp"
    and "⋀a b c k. k ∈ Basis ⟹ f (cbox a b) =
      opp (f (cbox a b ∩ {x. x∙k ≤ c})) (f (cbox a b ∩ {x. x∙k ≥ c}))"
  using assms unfolding operative_def by auto

lemma property_empty_interval: "∀a b. content (cbox a b) = 0 ⟶ P (cbox a b) ⟹ P {}"
  using content_empty unfolding empty_as_interval by auto

lemma operative_empty: "operative opp f ⟹ f {} = neutral opp"
  unfolding operative_def by (rule property_empty_interval) auto


subsection ‹Using additivity of lifted function to encode definedness.›

fun lifted where
  "lifted (opp :: 'a ⇒ 'a ⇒ 'b) (Some x) (Some y) = Some (opp x y)"
| "lifted opp None _ = (None::'b option)"
| "lifted opp _ None = None"

lemma lifted_simp_1[simp]: "lifted opp v None = None"
  by (induct v) auto

definition "monoidal opp ⟷
  (∀x y. opp x y = opp y x) ∧
  (∀x y z. opp x (opp y z) = opp (opp x y) z) ∧
  (∀x. opp (neutral opp) x = x)"

lemma monoidalI:
  assumes "⋀x y. opp x y = opp y x"
    and "⋀x y z. opp x (opp y z) = opp (opp x y) z"
    and "⋀x. opp (neutral opp) x = x"
  shows "monoidal opp"
  unfolding monoidal_def using assms by fastforce

lemma monoidal_ac:
  assumes "monoidal opp"
  shows [simp]: "opp (neutral opp) a = a"
    and [simp]: "opp a (neutral opp) = a"
    and "opp a b = opp b a"
    and "opp (opp a b) c = opp a (opp b c)"
    and "opp a (opp b c) = opp b (opp a c)"
  using assms unfolding monoidal_def by metis+

lemma neutral_lifted [cong]:
  assumes "monoidal opp"
  shows "neutral (lifted opp) = Some (neutral opp)"
proof -
  { fix x
    assume "∀y. lifted opp x y = y ∧ lifted opp y x = y"
    then have "Some (neutral opp) = x"
      apply (induct x)
      apply force
      by (metis assms lifted.simps(1) monoidal_ac(2) option.inject) }
  note [simp] = this
  show ?thesis
    apply (subst neutral_def)
    apply (intro some_equality allI)
    apply (induct_tac y)
    apply (auto simp add:monoidal_ac[OF assms])
    done
qed

lemma monoidal_lifted[intro]:
  assumes "monoidal opp"
  shows "monoidal (lifted opp)"
  unfolding monoidal_def split_option_all neutral_lifted[OF assms]
  using monoidal_ac[OF assms]
  by auto

definition "support opp f s = {x. x∈s ∧ f x ≠ neutral opp}"
definition "fold' opp e s = (if finite s then Finite_Set.fold opp e s else e)"
definition "iterate opp s f = fold' (λx a. opp (f x) a) (neutral opp) (support opp f s)"

lemma support_subset[intro]: "support opp f s ⊆ s"
  unfolding support_def by auto

lemma support_empty[simp]: "support opp f {} = {}"
  using support_subset[of opp f "{}"] by auto

lemma comp_fun_commute_monoidal[intro]:
  assumes "monoidal opp"
  shows "comp_fun_commute opp"
  unfolding comp_fun_commute_def
  using monoidal_ac[OF assms]
  by auto

lemma support_clauses:
  "⋀f g s. support opp f {} = {}"
  "⋀f g s. support opp f (insert x s) =
    (if f(x) = neutral opp then support opp f s else insert x (support opp f s))"
  "⋀f g s. support opp f (s - {x}) = (support opp f s) - {x}"
  "⋀f g s. support opp f (s ∪ t) = (support opp f s) ∪ (support opp f t)"
  "⋀f g s. support opp f (s ∩ t) = (support opp f s) ∩ (support opp f t)"
  "⋀f g s. support opp f (s - t) = (support opp f s) - (support opp f t)"
  "⋀f g s. support opp g (f ` s) = f ` (support opp (g ∘ f) s)"
  unfolding support_def by auto

lemma finite_support[intro]: "finite s ⟹ finite (support opp f s)"
  unfolding support_def by auto

lemma iterate_empty[simp]: "iterate opp {} f = neutral opp"
  unfolding iterate_def fold'_def by auto

lemma iterate_insert[simp]:
  assumes "monoidal opp"
    and "finite s"
  shows "iterate opp (insert x s) f =
         (if x ∈ s then iterate opp s f else opp (f x) (iterate opp s f))"
proof (cases "x ∈ s")
  case True
  then show ?thesis by (auto simp: insert_absorb iterate_def)
next
  case False
  note * = comp_fun_commute.comp_comp_fun_commute [OF comp_fun_commute_monoidal[OF assms(1)]]
  show ?thesis
  proof (cases "f x = neutral opp")
    case True
    then show ?thesis
      using assms ‹x ∉ s›
      by (auto simp: iterate_def support_clauses)
  next
    case False
    with ‹x ∉ s› ‹finite s› support_subset show ?thesis
      apply (simp add: iterate_def fold'_def support_clauses)
      apply (subst comp_fun_commute.fold_insert[OF * finite_support, simplified comp_def])
      apply (force simp add: )+
      done
  qed
qed

lemma iterate_some:
    "⟦monoidal opp; finite s⟧ ⟹ iterate (lifted opp) s (λx. Some(f x)) = Some (iterate opp s f)"
  by (erule finite_induct) (auto simp: monoidal_lifted)


subsection ‹Two key instances of additivity.›

lemma neutral_add[simp]: "neutral op + = (0::'a::comm_monoid_add)"
  unfolding neutral_def
  by (force elim: allE [where x=0])

lemma operative_content[intro]: "operative (op +) content"
  by (force simp add: operative_def content_split[symmetric])

lemma monoidal_monoid[intro]: "monoidal ((op +)::('a::comm_monoid_add) ⇒ 'a ⇒ 'a)"
  unfolding monoidal_def neutral_add
  by (auto simp add: algebra_simps)

lemma operative_integral:
  fixes f :: "'a::euclidean_space ⇒ 'b::banach"
  shows "operative (lifted(op +)) (λi. if f integrable_on i then Some(integral i f) else None)"
  unfolding operative_def neutral_lifted[OF monoidal_monoid] neutral_add
proof safe
  fix a b c
  fix k :: 'a
  assume k: "k ∈ Basis"
  show "(if f integrable_on cbox a b then Some (integral (cbox a b) f) else None) =
        lifted op + (if f integrable_on cbox a b ∩ {x. x ∙ k ≤ c} then Some (integral (cbox a b ∩ {x. x ∙ k ≤ c}) f) else None)
        (if f integrable_on cbox a b ∩ {x. c ≤ x ∙ k} then Some (integral (cbox a b ∩ {x. c ≤ x ∙ k}) f) else None)"
  proof (cases "f integrable_on cbox a b")
    case True
    with k show ?thesis
      apply (simp add: integrable_split)
      apply (rule integral_unique [OF has_integral_split[OF _ _ k]])
      apply (auto intro: integrable_integral)
      done
  next
    case False
    have "¬ (f integrable_on cbox a b ∩ {x. x ∙ k ≤ c}) ∨ ¬ ( f integrable_on cbox a b ∩ {x. c ≤ x ∙ k})"
    proof (rule ccontr)
      assume "¬ ?thesis"
      then have "f integrable_on cbox a b"
        unfolding integrable_on_def
        apply (rule_tac x="integral (cbox a b ∩ {x. x ∙ k ≤ c}) f + integral (cbox a b ∩ {x. x ∙ k ≥ c}) f" in exI)
        apply (rule has_integral_split[OF _ _ k])
        apply (auto intro: integrable_integral)
        done
      then show False
        using False by auto
    qed
    then show ?thesis
      using False by auto
  qed
next
  fix a b :: 'a
  assume "content (cbox a b) = 0"
  then show "(if f integrable_on cbox a b then Some (integral (cbox a b) f) else None) = Some 0"
    using has_integral_null_eq
    by (auto simp: integrable_on_null)
qed


subsection ‹Points of division of a partition.›

definition "division_points (k::('a::euclidean_space) set) d =
   {(j,x). j ∈ Basis ∧ (interval_lowerbound k)∙j < x ∧ x < (interval_upperbound k)∙j ∧
     (∃i∈d. (interval_lowerbound i)∙j = x ∨ (interval_upperbound i)∙j = x)}"

lemma division_points_finite:
  fixes i :: "'a::euclidean_space set"
  assumes "d division_of i"
  shows "finite (division_points i d)"
proof -
  note assm = division_ofD[OF assms]
  let ?M = "λj. {(j,x)|x. (interval_lowerbound i)∙j < x ∧ x < (interval_upperbound i)∙j ∧
    (∃i∈d. (interval_lowerbound i)∙j = x ∨ (interval_upperbound i)∙j = x)}"
  have *: "division_points i d = ⋃(?M ` Basis)"
    unfolding division_points_def by auto
  show ?thesis
    unfolding * using assm by auto
qed

lemma division_points_subset:
  fixes a :: "'a::euclidean_space"
  assumes "d division_of (cbox a b)"
    and "∀i∈Basis. a∙i < b∙i"  "a∙k < c" "c < b∙k"
    and k: "k ∈ Basis"
  shows "division_points (cbox a b ∩ {x. x∙k ≤ c}) {l ∩ {x. x∙k ≤ c} | l . l ∈ d ∧ l ∩ {x. x∙k ≤ c} ≠ {}} ⊆
      division_points (cbox a b) d" (is ?t1)
    and "division_points (cbox a b ∩ {x. x∙k ≥ c}) {l ∩ {x. x∙k ≥ c} | l . l ∈ d ∧ ~(l ∩ {x. x∙k ≥ c} = {})} ⊆
      division_points (cbox a b) d" (is ?t2)
proof -
  note assm = division_ofD[OF assms(1)]
  have *: "∀i∈Basis. a∙i ≤ b∙i"
    "∀i∈Basis. a∙i ≤ (∑i∈Basis. (if i = k then min (b ∙ k) c else  b ∙ i) *R i) ∙ i"
    "∀i∈Basis. (∑i∈Basis. (if i = k then max (a ∙ k) c else a ∙ i) *R i) ∙ i ≤ b∙i"
    "min (b ∙ k) c = c" "max (a ∙ k) c = c"
    using assms using less_imp_le by auto
  show ?t1 (*FIXME a horrible mess*)
    unfolding division_points_def interval_split[OF k, of a b]
    unfolding interval_bounds[OF *(1)] interval_bounds[OF *(2)] interval_bounds[OF *(3)]
    unfolding *
    apply (rule subsetI)
    unfolding mem_Collect_eq split_beta
    apply (erule bexE conjE)+
    apply (simp add: )
    apply (erule exE conjE)+
  proof
    fix i l x
    assume as:
      "a ∙ fst x < snd x" "snd x < (if fst x = k then c else b ∙ fst x)"
      "interval_lowerbound i ∙ fst x = snd x ∨ interval_upperbound i ∙ fst x = snd x"
      "i = l ∩ {x. x ∙ k ≤ c}" "l ∈ d" "l ∩ {x. x ∙ k ≤ c} ≠ {}"
      and fstx: "fst x ∈ Basis"
    from assm(4)[OF this(5)] guess u v apply-by(erule exE)+ note l=this
    have *: "∀i∈Basis. u ∙ i ≤ (∑i∈Basis. (if i = k then min (v ∙ k) c else v ∙ i) *R i) ∙ i"
      using as(6) unfolding l interval_split[OF k] box_ne_empty as .
    have **: "∀i∈Basis. u∙i ≤ v∙i"
      using l using as(6) unfolding box_ne_empty[symmetric] by auto
    show "∃i∈d. interval_lowerbound i ∙ fst x = snd x ∨ interval_upperbound i ∙ fst x = snd x"
      apply (rule bexI[OF _ ‹l ∈ d›])
      using as(1-3,5) fstx
      unfolding l interval_bounds[OF **] interval_bounds[OF *] interval_split[OF k] as
      apply (auto split: split_if_asm)
      done
    show "snd x < b ∙ fst x"
      using as(2) ‹c < b∙k› by (auto split: split_if_asm)
  qed
  show ?t2
    unfolding division_points_def interval_split[OF k, of a b]
    unfolding interval_bounds[OF *(1)] interval_bounds[OF *(2)] interval_bounds[OF *(3)]
    unfolding *
    unfolding subset_eq
    apply rule
    unfolding mem_Collect_eq split_beta
    apply (erule bexE conjE)+
    apply (simp only: mem_Collect_eq inner_setsum_left_Basis simp_thms)
    apply (erule exE conjE)+
  proof
    fix i l x
    assume as:
      "(if fst x = k then c else a ∙ fst x) < snd x" "snd x < b ∙ fst x"
      "interval_lowerbound i ∙ fst x = snd x ∨ interval_upperbound i ∙ fst x = snd x"
      "i = l ∩ {x. c ≤ x ∙ k}" "l ∈ d" "l ∩ {x. c ≤ x ∙ k} ≠ {}"
      and fstx: "fst x ∈ Basis"
    from assm(4)[OF this(5)] guess u v by (elim exE) note l=this
    have *: "∀i∈Basis. (∑i∈Basis. (if i = k then max (u ∙ k) c else u ∙ i) *R i) ∙ i ≤ v ∙ i"
      using as(6) unfolding l interval_split[OF k] box_ne_empty as .
    have **: "∀i∈Basis. u∙i ≤ v∙i"
      using l using as(6) unfolding box_ne_empty[symmetric] by auto
    show "∃i∈d. interval_lowerbound i ∙ fst x = snd x ∨ interval_upperbound i ∙ fst x = snd x"
      apply (rule bexI[OF _ ‹l ∈ d›])
      using as(1-3,5) fstx
      unfolding l interval_bounds[OF **] interval_bounds[OF *] interval_split[OF k] as
      apply (auto split: split_if_asm)
      done
    show "a ∙ fst x < snd x"
      using as(1) ‹a∙k < c› by (auto split: split_if_asm)
   qed
qed

lemma division_points_psubset:
  fixes a :: "'a::euclidean_space"
  assumes "d division_of (cbox a b)"
      and "∀i∈Basis. a∙i < b∙i"  "a∙k < c" "c < b∙k"
      and "l ∈ d"
      and "interval_lowerbound l∙k = c ∨ interval_upperbound l∙k = c"
      and k: "k ∈ Basis"
  shows "division_points (cbox a b ∩ {x. x∙k ≤ c}) {l ∩ {x. x∙k ≤ c} | l. l∈d ∧ l ∩ {x. x∙k ≤ c} ≠ {}} ⊂
         division_points (cbox a b) d" (is "?D1 ⊂ ?D")
    and "division_points (cbox a b ∩ {x. x∙k ≥ c}) {l ∩ {x. x∙k ≥ c} | l. l∈d ∧ l ∩ {x. x∙k ≥ c} ≠ {}} ⊂
         division_points (cbox a b) d" (is "?D2 ⊂ ?D")
proof -
  have ab: "∀i∈Basis. a∙i ≤ b∙i"
    using assms(2) by (auto intro!:less_imp_le)
  guess u v using division_ofD(4)[OF assms(1,5)] by (elim exE) note l=this
  have uv: "∀i∈Basis. u∙i ≤ v∙i" "∀i∈Basis. a∙i ≤ u∙i ∧ v∙i ≤ b∙i"
    using division_ofD(2,2,3)[OF assms(1,5)] unfolding l box_ne_empty
    using subset_box(1)
    apply auto
    apply blast+
    done
  have *: "interval_upperbound (cbox a b ∩ {x. x ∙ k ≤ interval_upperbound l ∙ k}) ∙ k = interval_upperbound l ∙ k"
          "interval_upperbound (cbox a b ∩ {x. x ∙ k ≤ interval_lowerbound l ∙ k}) ∙ k = interval_lowerbound l ∙ k"
    unfolding l interval_split[OF k] interval_bounds[OF uv(1)]
    using uv[rule_format, of k] ab k
    by auto
  have "∃x. x ∈ ?D - ?D1"
    using assms(3-)
    unfolding division_points_def interval_bounds[OF ab]
    apply -
    apply (erule disjE)
    apply (rule_tac x="(k,(interval_lowerbound l)∙k)" in exI, force simp add: *)
    apply (rule_tac x="(k,(interval_upperbound l)∙k)" in exI, force simp add: *)
    done
  moreover have "?D1 ⊆ ?D"
    by (auto simp add: assms division_points_subset)
  ultimately show "?D1 ⊂ ?D"
    by blast
  have *: "interval_lowerbound (cbox a b ∩ {x. x ∙ k ≥ interval_lowerbound l ∙ k}) ∙ k = interval_lowerbound l ∙ k"
    "interval_lowerbound (cbox a b ∩ {x. x ∙ k ≥ interval_upperbound l ∙ k}) ∙ k = interval_upperbound l ∙ k"
    unfolding l interval_split[OF k] interval_bounds[OF uv(1)]
    using uv[rule_format, of k] ab k
    by auto
  have "∃x. x ∈ ?D - ?D2"
    using assms(3-)
    unfolding division_points_def interval_bounds[OF ab]
    apply -
    apply (erule disjE)
    apply (rule_tac x="(k,(interval_lowerbound l)∙k)" in exI, force simp add: *)
    apply (rule_tac x="(k,(interval_upperbound l)∙k)" in exI, force simp add: *)
    done
  moreover have "?D2 ⊆ ?D"
    by (auto simp add: assms division_points_subset)
  ultimately show "?D2 ⊂ ?D"
    by blast
qed


subsection ‹Preservation by divisions and tagged divisions.›

lemma support_support[simp]:"support opp f (support opp f s) = support opp f s"
  unfolding support_def by auto

lemma iterate_support[simp]: "iterate opp (support opp f s) f = iterate opp s f"
  unfolding iterate_def support_support by auto

lemma iterate_expand_cases:
  "iterate opp s f = (if finite(support opp f s) then iterate opp (support opp f s) f else neutral opp)"
    by (simp add: iterate_def fold'_def)

lemma iterate_image:
  assumes "monoidal opp"
    and "inj_on f s"
  shows "iterate opp (f ` s) g = iterate opp s (g ∘ f)"
proof -
  have *: "iterate opp (f ` s) g = iterate opp s (g ∘ f)"
    if "finite s" "∀x∈s. ∀y∈s. f x = f y ⟶ x = y" for s
    using that
  proof (induct s)
    case empty
    then show ?case by simp
  next
    case insert
    with assms(1) show ?case by auto
  qed
  show ?thesis
    apply (cases "finite (support opp g (f ` s))")
    prefer 2
      apply (metis finite_imageI iterate_expand_cases support_clauses(7))
    apply (subst (1) iterate_support[symmetric], subst (2) iterate_support[symmetric])
    unfolding support_clauses
    apply (rule *)
    apply (meson assms(2) finite_imageD subset_inj_on support_subset)
    apply (meson assms(2) inj_on_contraD rev_subsetD support_subset)
    done
qed


(* This lemma about iterations comes up in a few places. *)
lemma iterate_nonzero_image_lemma:
  assumes "monoidal opp"
    and "finite s" "g(a) = neutral opp"
    and "∀x∈s. ∀y∈s. f x = f y ∧ x ≠ y ⟶ g(f x) = neutral opp"
  shows "iterate opp {f x | x. x ∈ s ∧ f x ≠ a} g = iterate opp s (g ∘ f)"
proof -
  have *: "{f x |x. x ∈ s ∧ f x ≠ a} = f ` {x. x ∈ s ∧ f x ≠ a}"
    by auto
  have **: "support opp (g ∘ f) {x ∈ s. f x ≠ a} = support opp (g ∘ f) s"
    unfolding support_def using assms(3) by auto
  have inj: "inj_on f (support opp (g ∘ f) {x ∈ s. f x ≠ a})"
    apply (simp add: inj_on_def)
    apply (metis (mono_tags, lifting) assms(4) comp_def mem_Collect_eq support_def)
    done
  show ?thesis
    apply (subst iterate_support[symmetric])
    apply (simp add: * support_clauses iterate_image[OF assms(1) inj])
    apply (simp add: iterate_def **)
    done
qed

lemma iterate_eq_neutral:
  assumes "monoidal opp"
      and "⋀x. x ∈ s ⟹ f x = neutral opp"
    shows "iterate opp s f = neutral opp"
proof -
  have [simp]: "support opp f s = {}"
    unfolding support_def using assms(2) by auto
  show ?thesis
    by (subst iterate_support[symmetric]) simp
qed

lemma iterate_op:
   "⟦monoidal opp; finite s⟧
    ⟹ iterate opp s (λx. opp (f x) (g x)) = opp (iterate opp s f) (iterate opp s g)"
by (erule finite_induct) (auto simp: monoidal_ac(4) monoidal_ac(5))

lemma iterate_eq:
  assumes "monoidal opp"
    and "⋀x. x ∈ s ⟹ f x = g x"
  shows "iterate opp s f = iterate opp s g"
proof -
  have *: "support opp g s = support opp f s"
    unfolding support_def using assms(2) by auto
  show ?thesis
  proof (cases "finite (support opp f s)")
    case False
    then show ?thesis
      by (simp add: "*" iterate_expand_cases)
  next
    case True
    def su  "support opp f s"
    have fsu: "finite su"
      using True by (simp add: su_def)
    moreover
    { assume "finite su" "su ⊆ s"
      then have "iterate opp su f = iterate opp su g"
        by (induct su) (auto simp: assms)
    }
    ultimately have "iterate opp (support opp f s) f = iterate opp (support opp g s) g"
      by (simp add: "*" su_def support_subset)
    then show ?thesis
      by simp
  qed
qed

lemma nonempty_witness:
  assumes "s ≠ {}"
  obtains x where "x ∈ s"
  using assms by auto

lemma operative_division:
  fixes f :: "'a::euclidean_space set ⇒ 'b"
  assumes "monoidal opp"
      and "operative opp f"
      and "d division_of (cbox a b)"
    shows "iterate opp d f = f (cbox a b)"
proof -
  def C  "card (division_points (cbox a b) d)"
  then show ?thesis
    using assms
  proof (induct C arbitrary: a b d rule: full_nat_induct)
    case (1 a b d)
    show ?case
    proof (cases "content (cbox a b) = 0")
      case True
      show "iterate opp d f = f (cbox a b)"
        unfolding operativeD(1)[OF assms(2) True]
      proof (rule iterate_eq_neutral[OF ‹monoidal opp›])
        fix x
        assume x: "x ∈ d"
        then show "f x = neutral opp"
          by (metis division_ofD(4) 1(4) division_of_content_0[OF True] operativeD(1)[OF assms(2)] x)
      qed
    next
      case False
      note ab = this[unfolded content_lt_nz[symmetric] content_pos_lt_eq]
      then have ab': "∀i∈Basis. a∙i ≤ b∙i"
        by (auto intro!: less_imp_le)
        show "iterate opp d f = f (cbox a b)"
      proof (cases "division_points (cbox a b) d = {}")
        case True
        { fix u v and j :: 'a
          assume j: "j ∈ Basis" and as: "cbox u v ∈ d"
          then have "cbox u v ≠ {}"
            using "1.prems"(3) by blast
          then have uv: "∀i∈Basis. u∙i ≤ v∙i" "u∙j ≤ v∙j"
            using j unfolding box_ne_empty by auto
          have *: "⋀p r Q. ¬ j∈Basis ∨ p ∨ r ∨ (∀x∈d. Q x) ⟹ p ∨ r ∨ Q (cbox u v)"
            using as j by auto
          have "(j, u∙j) ∉ division_points (cbox a b) d"
               "(j, v∙j) ∉ division_points (cbox a b) d" using True by auto
          note this[unfolded de_Morgan_conj division_points_def mem_Collect_eq split_conv interval_bounds[OF ab'] bex_simps]
          note *[OF this(1)] *[OF this(2)] note this[unfolded interval_bounds[OF uv(1)]]
          moreover
          have "a∙j ≤ u∙j" "v∙j ≤ b∙j"
            using division_ofD(2,2,3)[OF ‹d division_of cbox a b› as]
            apply (metis j subset_box(1) uv(1))
            by (metis ‹cbox u v ⊆ cbox a b› j subset_box(1) uv(1))
          ultimately have "u∙j = a∙j ∧ v∙j = a∙j ∨ u∙j = b∙j ∧ v∙j = b∙j ∨ u∙j = a∙j ∧ v∙j = b∙j"
            unfolding not_less de_Morgan_disj using ab[rule_format,of j] uv(2) j by force }
        then have d': "∀i∈d. ∃u v. i = cbox u v ∧
          (∀j∈Basis. u∙j = a∙j ∧ v∙j = a∙j ∨ u∙j = b∙j ∧ v∙j = b∙j ∨ u∙j = a∙j ∧ v∙j = b∙j)"
          unfolding forall_in_division[OF 1(4)]
          by blast
        have "(1/2) *R (a+b) ∈ cbox a b"
          unfolding mem_box using ab by(auto intro!: less_imp_le simp: inner_simps)
        note this[unfolded division_ofD(6)[OF ‹d division_of cbox a b›,symmetric] Union_iff]
        then guess i .. note i=this
        guess u v using d'[rule_format,OF i(1)] by (elim exE conjE) note uv=this
        have "cbox a b ∈ d"
        proof -
          have "u = a" "v = b"
            unfolding euclidean_eq_iff[where 'a='a]
          proof safe
            fix j :: 'a
            assume j: "j ∈ Basis"
            note i(2)[unfolded uv mem_box,rule_format,of j]
            then show "u ∙ j = a ∙ j" and "v ∙ j = b ∙ j"
              using uv(2)[rule_format,of j] j by (auto simp: inner_simps)
          qed
          then have "i = cbox a b" using uv by auto
          then show ?thesis using i by auto
        qed
        then have deq: "d = insert (cbox a b) (d - {cbox a b})"
          by auto
        have "iterate opp (d - {cbox a b}) f = neutral opp"
        proof (rule iterate_eq_neutral[OF 1(2)])
          fix x
          assume x: "x ∈ d - {cbox a b}"
          then have "x∈d"
            by auto note d'[rule_format,OF this]
          then guess u v by (elim exE conjE) note uv=this
          have "u ≠ a ∨ v ≠ b"
            using x[unfolded uv] by auto
          then obtain j where "u∙j ≠ a∙j ∨ v∙j ≠ b∙j" and j: "j ∈ Basis"
            unfolding euclidean_eq_iff[where 'a='a] by auto
          then have "u∙j = v∙j"
            using uv(2)[rule_format,OF j] by auto
          then have "content (cbox u v) = 0"
            unfolding content_eq_0 using j
            by force
          then show "f x = neutral opp"
            unfolding uv(1) by (rule operativeD(1)[OF 1(3)])
        qed
        then show "iterate opp d f = f (cbox a b)"
          apply (subst deq)
          apply (subst iterate_insert[OF 1(2)])
          using 1
          apply auto
          done
      next
        case False
        then have "∃x. x ∈ division_points (cbox a b) d"
          by auto
        then guess k c
          unfolding split_paired_Ex division_points_def mem_Collect_eq split_conv
          apply (elim exE conjE)
          done
        note this(2-4,1) note kc=this[unfolded interval_bounds[OF ab']]
        from this(3) guess j .. note j=this
        def d1  "{l ∩ {x. x∙k ≤ c} | l. l ∈ d ∧ l ∩ {x. x∙k ≤ c} ≠ {}}"
        def d2  "{l ∩ {x. x∙k ≥ c} | l. l ∈ d ∧ l ∩ {x. x∙k ≥ c} ≠ {}}"
        def cb  "(∑i∈Basis. (if i = k then c else b∙i) *R i)::'a"
        def ca  "(∑i∈Basis. (if i = k then c else a∙i) *R i)::'a"
        note division_points_psubset[OF ‹d division_of cbox a b› ab kc(1-2) j]
        note psubset_card_mono[OF _ this(1)] psubset_card_mono[OF _ this(2)]
        then have *: "(iterate opp d1 f) = f (cbox a b ∩ {x. x∙k ≤ c})"
          "(iterate opp d2 f) = f (cbox a b ∩ {x. x∙k ≥ c})"
          unfolding interval_split[OF kc(4)]
          apply (rule_tac[!] "1.hyps"[rule_format])
          using division_split[OF ‹d division_of cbox a b›, where k=k and c=c]
          apply (simp_all add: interval_split 1 kc d1_def d2_def division_points_finite[OF ‹d division_of cbox a b›])
          done
        { fix l y
          assume as: "l ∈ d" "y ∈ d" "l ∩ {x. x ∙ k ≤ c} = y ∩ {x. x ∙ k ≤ c}" "l ≠ y"
          from division_ofD(4)[OF ‹d division_of cbox a b› this(1)] guess u v by (elim exE) note leq=this
          have "f (l ∩ {x. x ∙ k ≤ c}) = neutral opp"
            unfolding leq interval_split[OF kc(4)]
            apply (rule operativeD(1) 1)+
            unfolding interval_split[symmetric,OF kc(4)]
            using division_split_left_inj 1 as kc leq by blast
        } note fxk_le = this
        { fix l y
          assume as: "l ∈ d" "y ∈ d" "l ∩ {x. c ≤ x ∙ k} = y ∩ {x. c ≤ x ∙ k}" "l ≠ y"
          from division_ofD(4)[OF ‹d division_of cbox a b› this(1)] guess u v by (elim exE) note leq=this
          have "f (l ∩ {x. x ∙ k ≥ c}) = neutral opp"
            unfolding leq interval_split[OF kc(4)]
            apply (rule operativeD(1) 1)+
            unfolding interval_split[symmetric,OF kc(4)]
            using division_split_right_inj 1 leq as kc by blast
        } note fxk_ge = this
        have "f (cbox a b) = opp (iterate opp d1 f) (iterate opp d2 f)" (is "_ = ?prev")
          unfolding *
          using assms(2) kc(4) by blast
        also have "iterate opp d1 f = iterate opp d (λl. f(l ∩ {x. x∙k ≤ c}))"
          unfolding d1_def empty_as_interval
          apply (rule iterate_nonzero_image_lemma[unfolded o_def])
          apply (rule 1 division_of_finite operativeD[OF 1(3)])+
          apply (force simp add: empty_as_interval[symmetric] fxk_le)+
          done
        also have "iterate opp d2 f = iterate opp d (λl. f(l ∩ {x. x∙k ≥ c}))"
          unfolding d2_def empty_as_interval
          apply (rule iterate_nonzero_image_lemma[unfolded o_def])
          apply (rule 1 division_of_finite operativeD[OF 1(3)])+
          apply (force simp add: empty_as_interval[symmetric] fxk_ge)+
          done
        also have *: "∀x∈d. f x = opp (f (x ∩ {x. x ∙ k ≤ c})) (f (x ∩ {x. c ≤ x ∙ k}))"
          unfolding forall_in_division[OF ‹d division_of cbox a b›]
          using assms(2) kc(4) by blast
        have "opp (iterate opp d (λl. f (l ∩ {x. x ∙ k ≤ c}))) (iterate opp d (λl. f (l ∩ {x. c ≤ x ∙ k}))) =
          iterate opp d f"
          apply (subst(3) iterate_eq[OF _ *[rule_format]])
          using 1
          apply (auto simp: iterate_op[symmetric])
          done
        finally show ?thesis by auto
      qed
    qed
  qed
qed

lemma iterate_image_nonzero:
  assumes "monoidal opp"
      and "finite s"
      and "⋀x y. ∀x∈s. ∀y∈s. x ≠ y ∧ f x = f y ⟶ g (f x) = neutral opp"
    shows "iterate opp (f ` s) g = iterate opp s (g ∘ f)"
using assms
by (induct rule: finite_subset_induct[OF assms(2) subset_refl]) auto

lemma operative_tagged_division:
  assumes "monoidal opp"
      and "operative opp f"
      and "d tagged_division_of (cbox a b)"
    shows "iterate opp d (λ(x,l). f l) = f (cbox a b)"
proof -
  have *: "(λ(x,l). f l) = f ∘ snd"
    unfolding o_def by rule auto note tagged = tagged_division_ofD[OF assms(3)]
  { fix a b a'
    assume as: "(a, b) ∈ d" "(a', b) ∈ d" "(a, b) ≠ (a', b)"
    have "f b = neutral opp"
      using tagged(4)[OF as(1)]
      apply clarify
      apply (rule operativeD(1)[OF assms(2)])
      by (metis content_eq_0_interior inf.idem tagged_division_ofD(5)[OF assms(3) as(1-3)])
  }
  then have "iterate opp d (λ(x,l). f l) = iterate opp (snd ` d) f"
    unfolding *
    by (force intro!: assms iterate_image_nonzero[symmetric, OF _ tagged_division_of_finite])