Section Loop.
Definition Loop := StateWhile Step.
Definition Loop_Rel q : pRel sigSim F 1 :=
fun tin '(yout, tout) =>
forall (T : tapes sig n),
tin[@Fin0] ≃ T ->
let c := {| cstate := q; ctapes := T |} in
exists c' k, loopM c k = Some c' /\
tout[@Fin0] ≃ ctapes c' /\ yout = projT2 pM (cstate c').
Fixpoint Loop_steps q (T : tapes sig n) (k : nat) {struct k} :=
if halt q
then 0
else match k with
| 0 => 0 (* can't happen *)
| S k' =>
let (q', acts) := trans (m := projT1 pM) (q, current_chars T) in
1 + Step_steps q T + Loop_steps q' (doAct_multi T acts) k'
end.

Lemma Loop_steps_eq q T k :
Loop_steps q T k =
if halt q
then 0
else match k with
| 0 => 0
| S k' =>
let (q', acts) := trans (m := projT1 pM) (q, current_chars T) in
1 + Step_steps q T + Loop_steps q' (doAct_multi T acts) k'
end.