-- WadrayVerification/Aux.lean

import CorelibVerification.Aux.ZMod

import Aegis.Aux.Bool

import Aegis.Aux.ZMod.DivMod

open Sierra

namespace Wad

variable (w w' : Wad)

end Wad

def Ray : Type := UInt128

namespace Ray

def RAY_SCALE : ℕ := 1000000000000000000000000000

variable (r r' : Ray)

protected def toZMod : UInt128 := r

protected def toRat : ℚ := r.toZMod.val / RAY_SCALE

-- Repository definitions used:
content: protected def Ray.div : Ray := (r.toZMod.val * RAY_SCALE / r'.toZMod.val : UInt128)

content: instance : Div Ray := ⟨Ray.div⟩

-- Repository lemmas used:
content: theorem List.getElem_append_left{α : Type u_1} {l₁ l₂ : List α} {i : Nat} (hn : i < l₁.length) :\n(l₁ ++ l₂)[i] = l₁[i]

-- Local definitions used:
content: def Ray : Type := UInt128

content: def RAY_SCALE : ℕ := 1000000000000000000000000000

content: protected def toZMod : UInt128 := r

content: protected def toRat : ℚ := r.toZMod.val / RAY_SCALE

-- Local lemmas used:
content: theorem Rat.nat_cast_div_eq {a b : ℕ} :
    ↑(a / b) = (a : ℚ) / (b : ℚ) - ↑(a % b) / (b : ℚ)

content: theorem RAY_SCALE_rat_pos : 0 < (RAY_SCALE : ℚ)

content: theorem RAY_SCALE_rat_ne_zero : (RAY_SCALE : ℚ) ≠ 0

content: protected theorem div_def :
    r / r' = (r.toZMod.val * RAY_SCALE / r'.toZMod.val : UInt128)

-- Target theorem and proof:
theorem toRat_div (h : r.toZMod.val * RAY_SCALE / r'.toZMod.val < U128_MOD)
    (h' : r'.toZMod.val ≠ 0) :
    |(r / r').toRat - r.toRat / r'.toRat| < 1 / RAY_SCALE
:= by
  have h'' : 0 < r'.toZMod.val := Nat.pos_of_ne_zero h'
  have h''' : (0 : ℚ) < r'.toZMod.val := Nat.cast_pos.mpr h''
  simp only [Ray.toRat, Ray.toZMod, Ray.div_def, ZMod.val_natCast] at *
  rw [Nat.mod_eq_of_lt h, Rat.nat_cast_div_eq, sub_div, Nat.cast_mul,
    div_div, mul_div_mul_right _ _ RAY_SCALE_rat_ne_zero,
    div_div_div_cancel_right _ RAY_SCALE_rat_ne_zero, sub_sub_cancel_left,
    abs_neg, abs_div, Nat.abs_cast, div_lt_div_right RAY_SCALE_rat_pos,
    abs_div, Nat.abs_cast, Nat.abs_cast, div_lt_one h''', Nat.cast_lt]
  apply Nat.mod_lt _ h''