Section NGramCPS.
Hypothesis Σ:Set.
Hypothesis len_l:nat.
Hypothesis len_r:nat.
Record MidWord:Set := {
l:list Σ;
r:list Σ;
m:Σ;
s:St;
}.
Fixpoint tape_seg(t:Z->Σ)(x:Z)(d:Dir)(n:nat):list Σ :=
match n with
| O => nil
| S n0 => (t x)::(tape_seg t (x+(Dir_to_Z d))%Z d n0)
end.
Definition MidWord_matches(st:ExecState Σ)(mw:MidWord):Prop :=
let (s,t) := st in
let (l0,r0,m0,s0):=mw in
s = s0 /\
m0 = t Z0 /\
l0 = tape_seg t ((-1)%Z) Dneg len_l /\
r0 = tape_seg t (1%Z) Dpos len_r.
Record AbstractES:Type := {
lset: (list Σ)->Prop;
rset: (list Σ)->Prop;
mset: MidWord->Prop;
}.
Definition xset_matches(t:Z->Σ)(xs:(list Σ)->Prop)(d:Dir)(len:nat):Prop :=
forall n:nat,
1<n ->
exists ls,
xs ls /\
ls = tape_seg t ((Z.of_nat n)*(Dir_to_Z d)%Z) d len.
Definition InAES(st:ExecState Σ)(S:AbstractES):Prop :=
let (s,t) := st in
let (ls,rs,ms) := S in
(exists mw, ms mw /\ MidWord_matches st mw) /\
xset_matches t ls Dneg len_l /\
xset_matches t rs Dpos len_r.
Definition AES_isClosed(tm:TM Σ)(S:AbstractES):Prop :=
forall st0,
InAES st0 S ->
exists st1,
step Σ tm st0 = Some st1 /\
InAES st1 S.
Definition AES_CloseAt(tm:TM Σ)(S:AbstractES)(mw:MidWord):Prop :=
let (ls,rs,ms) := S in
let (l0,r0,m0,s0):=mw in
match l0,r0 with
| hl::l1,hr::r1 =>
match tm s0 m0 with
| Some tr =>
let (s1,d,o):=tr in
match d with
| Dpos =>
ls l0 /\
forall x:Σ, rs (r1++(x::nil)) ->
ms {|
l:=o::(pop_back hl l1);
m:=hr;
r:=r1++(x::nil);
s:=s1;
|}
| Dneg =>
rs r0 /\
forall x:Σ, ls (l1++(x::nil)) ->
ms {|
r:=o::(pop_back hr r1);
m:=hl;
l:=l1++(x::nil);
s:=s1;
|}
end
| _ => False
end
| _,_ => False
end.
Definition AES_isClosed'(tm:TM Σ)(S:AbstractES):Prop :=
let (ls,rs,ms) := S in
forall mw,
ms mw ->
AES_CloseAt tm S mw.

Lemma xset_matches_mov_upd_2 t rs d o len:
xset_matches t rs d len ->
rs (tape_seg t (Dir_to_Z d) d len) ->
xset_matches (mov Σ (upd Σ t o) (Dir_rev d)) rs d len.