Section stratifies.
Variable Q:knot * other -> T.
Variable HQ:hered Q.
Fixpoint stratifies (n:nat) : sinv n -> Prop :=
match n as n' return sinv n' -> Prop with
| 0 => fun _ => True
| S n' => fun (p:sinv (S n')) =>
stratifies n' (fst (proj1_sig p)) /\
forall (k:F_sinv n') (o:other), snd (proj1_sig p) (k,o) = Q (existT F_sinv n' k,o)
end.
Definition stratify (n:nat) : { x:sinv n | stratifies n x }.
End stratifies.
Definition unstratify (n:nat) (p:sinv n) : knot * other -> T := fun w =>
match w with (existT _ nw w',o) =>
match decompose_nat nw n with
| inleft (existT _ m Hm) => snd (proj1_sig (floor m (S nw) (eq_rect  n _ p (m + S nw) Hm))) (w',o)
| inright H => T_bot
end
end.
Definition strat (n:nat) (p:predicate) : sinv n :=
proj1_sig (stratify (proj1_sig p) (proj2_sig p) n).
Definition unstrat (n:nat) (p:sinv n) : predicate :=
exist hered (unstratify n p) (unstratify_hered n p).
Definition squash (x:nat * F predicate predicate) : knot :=
match x with (n,f) => existT (F_sinv) n (bimap (unstrat n) (strat n) f) end.
Definition unsquash (k:knot) : nat * F predicate predicate :=
match k with existT _ n f => (n, bimap (strat n) (unstrat n) f) end.
Definition knot_level_def (k:knot) : nat :=
fst (unsquash k).
Definition knot_age1_def (k:knot) : option knot :=
match unsquash k with
| (O,_) => None
| (S n,x) => Some (squash (n,x))
end.
Definition knot_unage_def (k:knot) :=
let (n,k) := unsquash k in squash (S n,k).
Program Definition approx (n:nat) (p:predicate) : predicate :=
fun w => if (le_gt_dec n (knot_level_def (fst w))) then T_bot else proj1_sig p w.
Next Obligation.
hnf; simpl; intros.
destruct (le_gt_dec n (knot_level_def k)).
apply T_rel_bot.
destruct (le_gt_dec n (knot_level_def k'')).
elimtype False.
cut (knot_level_def k'' <= knot_level_def k).
omega.
replace (knot_level_def k'') with (knot_level_def k').
clear -H; induction H.
hnf in H.
unfold age1_def in H.
destruct x; destruct y; simpl.
destruct x; try discriminate.
inv H.
simpl.
unfold knot_level_def; simpl; auto.
auto.
eapply le_trans; eauto.
inv H0.
unfold knot_level_def; simpl; auto.
destruct p as [p Hp]; simpl.
eapply Hp; eauto.
Qed.
Arguments unsquash_inj [k1 k2] _.

Lemma ag_knot_facts : ageable_facts knot knot_level_def knot_age1_def.