(* This program is free software; you can redistribute it and/or      *)
(* modify it under the terms of the GNU Lesser General Public License *)
(* as published by the Free Software Foundation; either version 2.1   *)
(* of the License, or (at your option) any later version.             *)
(*                                                                    *)
(* This program is distributed in the hope that it will be useful,    *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of     *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      *)
(* GNU General Public License for more details.                       *)
(*                                                                    *)
(* You should have received a copy of the GNU Lesser General Public   *)
(* License along with this program; if not, write to the Free         *)
(* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA *)
(* 02110-1301 USA                                                     *)

Require Export Wilson.
Require Export ZdivExp.
Open Scope Z_scope.

Definition sum_of_two_squares :=
   fun p => exists a , exists b , p = a * a + b * b  .

Theorem two_squares_exists_mod:
 forall p a b,
 prime p ->
 ~ Zis_mod (b * b) 0 p ->
 Zis_mod (a * a + b * b) 0 p ->  (exists i , Zis_mod (i * i) (- 1) p ).
intros p a b Hp Hp1 Hp2.
assert (Ha1: 1 < p).
generalize (prime_le_2 p Hp); auto with zarith.
assert (Ha2: rel_prime b p).
apply rel_prime_sym; apply prime_rel_prime; auto with zarith.
intros [x Hx]; case Hp1; exists ((x * x) * p).
subst b; ring.
case (Zis_mod_rel_prime_inverse b p); auto with zarith.
intros b' [Hb1 [Hb2 Hb3]].
exists (a * b').
apply Zis_mod_cancel with b; auto with zarith.
apply Zis_mod_cancel with b; auto with zarith.
apply Zis_mod_trans with ((1 * 1) * (a * a)); auto with zarith.
replace (b * (b * ((a * b') * (a * b')))) with (((b * b') * (b * b')) * (a * a));
 (try ring).
(repeat apply Zis_mod_mult); auto.
apply Zis_mod_ref.
apply Zis_mod_ref.
red.
replace ((1 * 1) * (a * a) - b * (b * - 1)) with ((a * a + b * b) - 0);
 auto with zarith.
ring.
Qed.

Theorem two_squares_interval:
 forall p a b, prime p -> p = a * a + b * b ->  ( 0 < Zabs a < p ).
intros p a b Hp; rewrite (Zabs_square a); rewrite (Zabs_square b); intros Hp1.
assert (Hp2: 1 < p).
generalize (prime_le_2 p Hp); auto with zarith.
case (Zle_lt_or_eq 0 (Zabs a)); auto with zarith; intros Hza1.
assert (Ha1: 0 < Zabs a * Zabs a).
replace 0 with (0 * Zabs a); auto with zarith.
apply Zmult_lt_compat_r; auto with zarith.
case (Zle_lt_or_eq 0 (Zabs b)); auto with zarith; intros Hza2.
assert (Ha2: 0 < Zabs b * Zabs b).
replace 0 with (0 * Zabs b); auto with zarith.
apply Zmult_lt_compat_r; auto with zarith.
split; auto.
replace (Zabs a) with (1 * Zabs a + 0 * 0); auto with zarith.
apply Zle_lt_trans with (Zabs a * Zabs a + 0 * 0); auto with zarith.
contradict Hp; rewrite Hp1; rewrite <- Hza2; simpl.
rewrite Zplus_0_r; apply square_not_prime.
contradict Hp; rewrite Hp1; rewrite <- Hza1; simpl.
apply square_not_prime.
Qed.

Theorem two_squares_sqrt_interval:
 forall p a b, prime p -> p = a * a + b * b ->  ( 0 < Zabs a <= Z.sqrt p ).
intros p a b Hp Hp1; split.
case two_squares_interval with ( 2 := Hp1 ); auto.
rewrite <- (Zsqrt_square_id (Zabs a)); auto with zarith.
apply Zsqrt_le; auto.
split; auto with zarith.
rewrite Hp1; rewrite (Zabs_square a); rewrite (Zabs_square b); auto with zarith.
apply Zle_trans with (Zabs a * Zabs a + 0 * Zabs b); auto with zarith.
Qed.

Theorem two_squares_exists_mod_cor:
 forall p,
 prime p -> sum_of_two_squares p ->  (exists i , Zis_mod (i * i) (- 1) p ).
intros p Hp [a [b Hp1]]; rewrite (Zabs_square a) in Hp1;
 rewrite (Zabs_square b) in Hp1.
assert (Hp2: 1 < p).
generalize (prime_le_2 p Hp); auto with zarith.
apply (two_squares_exists_mod p (Zabs b) (Zabs a)); auto with zarith.
intros Hu; absurd (Zabs a * Zabs a = 0); auto with zarith.
intros Hp3; contradict Hp; rewrite Hp1; rewrite Hp3; simpl;
 apply square_not_prime.
rewrite <- (Zmod_def_small (Zabs a * Zabs a) p); auto with zarith.
rewrite <- (Zmod_def_small 0 p); auto with zarith.
apply Zis_mod_def_inv; auto with zarith.
case (two_squares_interval p a b); auto with zarith.
rewrite Hp1; (repeat rewrite <- Zabs_square); auto.
intros H1 H2; split; auto with zarith.
case (two_squares_interval p b a); auto with zarith.
rewrite Hp1; (repeat rewrite <- Zabs_square); auto with zarith.
intros H3 H4.
apply Zle_lt_trans with (Zabs a * Zabs a + 0 * Zabs b); auto with zarith.
rewrite Hp1; auto with zarith.
apply Zplus_lt_compat_l; auto with zarith.
apply Zmult_lt_compat_r; auto with zarith.
rewrite Hp1; exists 1; auto with zarith.
Qed.

Definition prod2 :=
   fun x1 y1 x2 y2 =>
   list_prod
    (progression Zsucc x1 (Zabs_nat (y1 - x1)))
    (progression Zsucc x2 (Zabs_nat (y2 - x2))).

Theorem in_prod2_inv:
 forall x1 y1 x2 y2 x3 y3,
 x1 <= y1 ->
 x2 <= y2 ->
 In (x3, y3) (prod2 x1 y1 x2 y2) ->  ( x1 <= x3 < y1 ) /\ ( x2 <= y3 < y2 ).
intros x1 y1 x2 y2 x3 y3 H1 H2 H3.
case (in_list_prod_inv _ _ _ _ _ H3); auto.
intros a1 [b1 [H4 [H5 H6]]]; injection H4; clear H4; intros; subst a1; subst b1.
split; split.
apply Zprogression_le_init with ( 1 := H5 ).
rewrite <- (Z_of_nat_abs_le x1 y1); auto;
 apply Zprogression_le_end with ( 1 := H5 ).
apply Zprogression_le_init with ( 1 := H6 ).
rewrite <- (Z_of_nat_abs_le x2 y2); auto;
 apply Zprogression_le_end with ( 1 := H6 ).
Qed.

Theorem prod_Z_surjective:
 forall f x1 y1 x2 y2 x3 y3,
 x1 < y1 ->
 x2 < y2 ->
 x3 < y3 ->
 (forall x y, ( x1 <= x < y1 ) -> ( x2 <= y < y2 ) ->  ( x3 <= f x y < y3 )) ->
 y3 - x3 < (y1 - x1) * (y2 - x2) ->
  (exists x ,
   exists y ,
   exists z ,
   exists t ,
   (( x1 <= x < y1 ) /\ ( x1 <= y < y1 )) /\
   ((( x2 <= z < y2 ) /\ ( x2 <= t < y2 )) /\
    ((x, z) <> (y, t) /\ f x z = f y t))    ).
intros f x1 y1 x2 y2 x3 y3 H1 H2 H3 H4 H5.
case
 (incl_length_repetition
   _ Z_eq_dec (map (fun p => f (fst p) (snd p)) (prod2 x1 y1 x2 y2))
   (progression Zsucc x3 (Zabs_nat (y3 - x3)))).
intros a Ha.
case in_map_inv with ( 1 := Ha ); intros a1; case a1; simpl; clear a1;
 intros a1 b1 [Ha1 Hb1].
case (in_list_prod_inv _ _ _ _ _ Ha1).
intros c1 [d1 [Hd1 [Hd2 Hd3]]].
subst a.
injection Hd1; clear Hd1; intros tmp1 tmp2; subst c1; subst d1.
apply in_Zprogression; auto.
rewrite Z_of_nat_abs_le; auto with zarith.
apply H4; auto.
split.
apply Zprogression_le_init with ( 1 := Hd2 ).
rewrite <- (Z_of_nat_abs_le x1 y1); auto with zarith.
apply Zprogression_le_end with ( 1 := Hd2 ).
split.
apply Zprogression_le_init with ( 1 := Hd3 ).
rewrite <- (Z_of_nat_abs_le x2 y2); auto with zarith.
apply Zprogression_le_end with ( 1 := Hd3 ).
rewrite length_map; unfold prod2; rewrite length_list_prod;
 (repeat rewrite length_progression).
red; apply inj_le_inv.
rewrite inj_mult; rewrite inj_S; (repeat rewrite Z_of_nat_Zabs_nat);
 auto with zarith.
intros a [l1 [l2 [l3 [Hl1 Hl2]]]].
case (same_length_ex _ _ a l1 (app l2 (cons a l3)) (prod2 x1 y1 x2 y2)).
simpl in Hl1 |-; rewrite <- Hl1; apply length_map.
intros l4 [l5 [[a1 b1] [Hg1 [Hg2 Hg3]]]].
generalize Hl1; rewrite Hg3.
intros tmp; (case map_length_decompose with ( 2 := tmp ); clear tmp); auto.
intros Hh1 Hh2.
case (same_length_ex _ _ a l2 l3 l5); auto.
intros l6 [l7 [[c1 d1] [Hj1 [Hj2 Hj3]]]].
simpl in Hh2 |-; injection Hh2; clear Hh2.
intros Hh2 Hh3; subst a.
rewrite Hj3 in Hh2; case map_length_decompose with ( 2 := Hh2 ); clear Hh2; auto.
intros Hl3 Hl4.
exists a1; exists c1; exists b1; exists d1.
case (in_prod2_inv x1 y1 x2 y2 a1 b1); auto with zarith.
rewrite Hg3; auto with datatypes.
intros Hr1 Hr2.
case (in_prod2_inv x1 y1 x2 y2 c1 d1); auto with zarith.
rewrite Hg3; rewrite Hj3; auto with datatypes.
apply in_or_app; right; auto with datatypes.
intros Hr3 Hr4.
assert (ulist (cons (a1, b1) (app l6 (cons (c1, d1) l7)))).
rewrite <- Hj3.
apply ulist_app_inv_r with l4; auto.
rewrite <- Hg3; auto.
unfold prod2; apply ulist_list_prod; apply ulist_Zprogression.
repeat (split; auto).
intros HH; injection HH; clear HH; intros; subst c1; subst d1.
absurd (In (a1, b1) (app l6 (cons (a1, b1) l7))); auto with datatypes.
inversion H; auto.
simpl in Hl4 |-; injection Hl4; auto.
Qed.

Theorem two_squares_mod_exists_sum:
 forall p i, prime p -> Zis_mod (i * i) (- 1) p ->  sum_of_two_squares p.
intros p i H1 H2.
assert (H3: 1 < p).
inversion H1; auto.
assert (H4: 0 <= Z.sqrt p).
apply Zsqrt_is_pos; auto with zarith.
case
 (prod_Z_surjective
   (fun x y => Zmod (x + i * y) p) 0 (Z.sqrt p + 1) 0 (Z.sqrt p + 1) 0
   p); auto with zarith.
intros x y _ _; apply Z_mod_lt; auto with zarith.
repeat rewrite Zminus_0_r.
case (Z.sqrt_spec p); auto with zarith.
intros x1 [x2 [y1 [y2 [[Ha1 Hb1] [[Ha2 Hb2] [Ha3 Ha4]]]]]].
exists (Zabs (x1 - x2)); exists (Zabs (y2 - y1)).
assert (Hc:
 Zis_mod (Zabs (x1 - x2) * Zabs (x1 - x2) + Zabs (y2 - y1) * Zabs (y2 - y1)) 0 p).
repeat rewrite <- Zabs_square.
apply Zis_mod_trans
     with ((x1 - x2) * (x1 - x2) - ((i * i) * (y2 - y1)) * (y2 - y1)).
replace ((x1 - x2) * (x1 - x2) + (y2 - y1) * (y2 - y1))
     with ((x1 - x2) * (x1 - x2) - (- 1 * (y2 - y1)) * (y2 - y1)); (try ring).
apply Zis_mod_minus; auto.
apply Zis_mod_ref; auto.
(repeat (apply Zis_mod_mult || apply Zis_mod_ref)); auto.
apply Zis_mod_sym; auto.
apply Zis_mod_minus_0; auto.
replace (((i * i) * (y2 - y1)) * (y2 - y1))
     with ((i * (y2 - y1)) * (i * (y2 - y1))); (try ring).
assert (Hc: Zis_mod (x1 - x2) (i * (y2 - y1)) p).
replace (x1 - x2) with ((x1 - x2) + - 1 * 0); auto with zarith.
replace (i * (y2 - y1)) with ((x1 - x2) + - 1 * ((x1 + i * y1) - (x2 + i * y2)));
 (try ring).
apply Zis_mod_plus; auto.
apply Zis_mod_ref; auto.
(repeat (apply Zis_mod_mult || apply Zis_mod_ref)); auto.
apply Zis_mod_sym; apply Zis_mod_minus_0.
apply Zis_mod_def; auto with zarith.
apply Zis_mod_mult; auto.
assert (Hc1:
  0 <= Zabs (x1 - x2) * Zabs (x1 - x2) + Zabs (y2 - y1) * Zabs (y2 - y1) < 2 * p
 ).
split; auto with zarith.
replace (2 * p) with (p + p); auto with zarith.
apply Zplus_lt_compat; auto with zarith.
apply Zle_lt_trans with (Z.sqrt p * Z.sqrt p); auto with zarith.
assert (Hc1: Zabs (x1 - x2) <= Z.sqrt p); auto with zarith.
case (Zle_or_lt x1 x2); intros Hc1.
apply Zle_trans with x2; auto with zarith.
rewrite Zabs_non_eq; auto with zarith.
apply Zle_trans with x1; auto with zarith.
rewrite Zabs_eq; auto with zarith.
apply Zmult_le_compat; auto with zarith.
case (Z.sqrt_spec p); auto with zarith.
intros Hc1 Hc2; case Zle_lt_or_eq with ( 1 := Hc1 ); auto.
intros Hc3; contradict H1; rewrite <- Hc3; apply square_not_prime.
apply Zle_lt_trans with (Z.sqrt p * Z.sqrt p); auto with zarith.
assert (Hc1: Zabs (y2 - y1) <= Z.sqrt p); auto with zarith.
case (Zle_or_lt y2 y1); intros Hc1.
rewrite Zabs_non_eq; auto with zarith.
rewrite Zabs_eq; auto with zarith.
apply Zmult_le_compat; auto with zarith.
case (Z.sqrt_spec p); auto with zarith.
intros Hc1 Hc2; case Zle_lt_or_eq with ( 1 := Hc1 ); auto.
intros Hc3; contradict H1; rewrite <- Hc3; apply square_not_prime.
case Hc1; clear Hc1; intros Hc1 Hc2.
case Zle_lt_or_eq with ( 1 := Hc1 ); clear Hc1; intros Hc1.
case Hc.
rewrite Zminus_0_r; intros q Hq; rewrite Hq; rewrite Hq in Hc1;
 rewrite Hq in Hc2; clear Hq.
assert (Hc3:  0 < q < 2 ).
split; intros; apply Zmult_gt_0_lt_reg_r with p; auto with zarith.
case (Zle_lt_or_eq 1 q); auto with zarith.
intros Hc4; rewrite <- Hc4; auto with zarith.
absurd (0 < Zabs (x1 - x2) * Zabs (x1 - x2) + Zabs (y2 - y1) * Zabs (y2 - y1)).
rewrite <- Hc1; auto with zarith.
replace 0 with (0 * Zabs (x1 - x2) + 0 * Zabs (y2 - y1)); auto with zarith.
cut (x1 = x2 \/ 0 < Zabs (x1 - x2)).
intros [Hc3|Hc3].
cut (y1 = y2 \/ 0 < Zabs (y2 - y1)).
intros [Hc4|Hc4].
case Ha3; apply f_equal2 with ( f := @pair Z Z ); auto.
apply Zplus_le_lt_compat; auto with zarith.
apply Zmult_lt_compat_r; auto with zarith.
case (Zle_or_lt y1 y2); intros He.
case Zle_lt_or_eq with ( 1 := He ); intros He1; auto.
rewrite Zabs_eq; auto with zarith.
rewrite Zabs_non_eq; auto with zarith.
apply Zplus_lt_le_compat; auto with zarith.
apply Zmult_lt_compat_r; auto with zarith.
case (Zle_or_lt x1 x2); intros Hd.
case Zle_lt_or_eq with ( 1 := Hd ); intros Hd1; auto.
rewrite Zabs_non_eq; auto with zarith.
rewrite Zabs_eq; auto with zarith.
Qed.

Theorem two_squares_unique:
 forall a b c d p,
 prime p ->
 0 <= a ->
 0 <= b ->
 0 <= c ->
 0 <= d ->
 p = a * a + b * b -> p = c * c + d * d ->  a = c /\ b = d \/ a = d /\ b = c.
intros a b c d p H1 H2 H3 H4 H5 H6 H7.
assert (Hp: 1 < p).
inversion H1; auto.
assert (Hs: Z.sqrt p * Z.sqrt p < p).
case (Z.sqrt_spec p); auto with zarith; intros tmp;
 (case Zle_lt_or_eq with ( 1 := tmp ); auto); intros tmp1 tmp2; contradict H1;
 rewrite <- tmp1; apply square_not_prime.
case Zle_lt_or_eq with ( 1 := H2 ); clear H2; intros H2.
2:contradict H1; rewrite H6; replace (a * a + b * b) with (b * b);
   rewrite <- H2 || apply square_not_prime; auto with zarith.
case Zle_lt_or_eq with ( 1 := H3 ); clear H3; intros H3.
2:contradict H1; rewrite H6; replace (a * a + b * b) with (a * a);
   rewrite <- H3 || apply square_not_prime; auto with zarith.
case Zle_lt_or_eq with ( 1 := H4 ); clear H4; intros H4.
2:contradict H1; rewrite H7; replace (c * c + d * d) with (d * d);
   rewrite <- H4 || apply square_not_prime; auto with zarith.
case Zle_lt_or_eq with ( 1 := H5 ); clear H5; intros H5.
2:contradict H1; rewrite H7; replace (c * c + d * d) with (c * c);
   rewrite <- H5 || apply square_not_prime; auto with zarith.
case (two_squares_sqrt_interval p a b); auto with zarith; rewrite Zabs_eq;
 auto with zarith; intros Hc1 Hc2.
case (two_squares_sqrt_interval p b a); auto with zarith; rewrite Zabs_eq;
 auto with zarith; intros Hc3 Hc4.
case (two_squares_sqrt_interval p c d); auto with zarith; rewrite Zabs_eq;
 auto with zarith; intros Hc5 Hc6.
case (two_squares_sqrt_interval p d c); auto with zarith; rewrite Zabs_eq;
 auto with zarith; intros Hc7 Hc8.
case (prime_mult p H1 (a * d - b * c) (a * d + b * c)); (try intros Ha1).
exists (d * d - b * b).
apply trans_equal with (d * (d * p) - b * (b * p)); (try (ring; fail)).
pattern p at 1; rewrite H6; rewrite H7; ring.
left; assert (Hb1:  - p < a * d - b * c < p ).
split.
apply Zle_lt_trans with (0 * d - b * c); auto with zarith.
replace (0 * d - b * c) with (- (b * c)); auto with zarith.
cut (b * c <= p); auto with zarith.
apply Zle_trans with (Z.sqrt p * Z.sqrt p); auto with zarith.
apply Zmult_le_compat; auto with zarith.
unfold Zminus; apply Zplus_lt_compat_r; auto with zarith.
apply Zmult_lt_compat_r; auto with zarith.
apply Zle_lt_trans with (a * d - 0 * c); auto with zarith.
unfold Zminus; apply Zplus_le_compat; auto with zarith.
cut (0 * c <= b * c); auto with zarith.
replace (a * d - 0 * c) with (a * d); auto with zarith.
apply Zle_lt_trans with (Z.sqrt p * Z.sqrt p); auto with zarith.
apply Zmult_le_compat; auto with zarith.
case Ha1; clear Ha1; intros q Ha1.
assert (Hb2: q = 0).
assert (Hb3:  - 1 < q < 1 ).
split; intros; apply Zmult_gt_0_lt_reg_r with p; auto with zarith.
case (Zle_lt_or_eq 0 q); auto with zarith.
assert (Hb3: a * d = b * c).
apply Zminus_eq; rewrite Ha1; rewrite Hb2; auto with zarith.
clear q Ha1 Hb1 Hb2.
assert (Hb1: Zdivide a c).
apply Gauss with b; auto with zarith.
exists d; auto.
rewrite (Zmult_comm d); auto with zarith.
red.
assert (Zdivide (Zgcd a b) p).
rewrite H6; apply Zdivide_plus_r; auto with zarith.
apply Zdivide_trans with a; auto with zarith.
generalize (Zgcd_is_gcd a b); intros tmp; inversion tmp; auto.
apply Zdivide_trans with b; auto with zarith.
generalize (Zgcd_is_gcd a b); intros tmp; inversion tmp; auto.
case (Zle_lt_or_eq 0 (Zgcd a b)); auto with zarith.
generalize (Zgcd_is_pos a b); auto with zarith.
intros HH1; case (Zle_lt_or_eq 1 (Zgcd a b)); auto with zarith.
intros HH2; contradict H; apply prime_inv_def; auto with zarith.
split; auto.
apply Zle_lt_trans with a; auto with zarith.
apply Zdivide_le; auto with zarith.
generalize (Zgcd_is_gcd a b); intros tmp; inversion tmp; auto.
apply Zle_lt_trans with ( 1 := Hc2 ).
apply Zle_lt_trans with (Z.sqrt p * Z.sqrt p); auto with zarith.
apply Zle_trans with (1 * Z.sqrt p); auto with zarith.
intros tmp; rewrite tmp; apply Zgcd_is_gcd.
intros HH1.
generalize (Zgcd_is_gcd a b); intros tmp; inversion tmp; auto.
case H0; intros q; rewrite <- HH1.
intros HH2; contradict H2; rewrite HH2; auto with zarith.
case Hb1; clear Hb1; intros k Hb1.
assert (Hb2: d = k * b).
apply Zmult_reg_l with a; auto with zarith.
apply trans_equal with ( 1 := Hb3 ).
rewrite Hb1; ring.
assert (Hb4: k * k = 1).
apply Zmult_reg_l with p; auto with zarith.
pattern p at 1; rewrite H6.
apply trans_equal with ((k * a) * (k * a) + (k * b) * (k * b)).
ring.
rewrite <- Hb1; rewrite <- Hb2; auto with zarith.
rewrite Hb1; rewrite Hb2; replace k with 1; auto with zarith.
case (Zmult_1_inversion_l k k); auto.
intros tmp; contradict H4; rewrite Hb1; rewrite tmp; auto with zarith.
right; assert (Hb1: a * c = b * d).
case Ha1; clear Ha1; intros q Ha1.
assert (Hb2: q = 1).
assert (Hb3:  0 < q < 2 ).
split; intros; apply Zmult_gt_0_lt_reg_r with p; auto with zarith.
rewrite <- Ha1; auto with zarith.
replace (0 * p) with (0 * d + 0 * c); auto with zarith.
apply Zplus_lt_compat; apply Zmult_lt_compat_r; auto with zarith.
replace (2 * p) with (p + p); auto with zarith.
rewrite <- Ha1; apply Zplus_lt_compat;
 apply Zle_lt_trans with (Z.sqrt p * Z.sqrt p); auto with zarith.
apply Zle_trans with (Z.sqrt p * d); auto with zarith.
apply Zle_trans with (Z.sqrt p * c); auto with zarith.
case (Zle_lt_or_eq 1 q); auto with zarith.
rewrite Hb2 in Ha1; rewrite Zmult_1_l in Ha1.
apply Zminus_eq; case ((fun x => Zmult_integral x x) (a * c - b * d)); auto.
apply Zplus_reg_l with (p * p); auto with zarith.
pattern p at 1 2; rewrite <- Ha1; pattern p at 1; rewrite H7; rewrite H6; ring.
assert (Hb2: Zdivide a d).
apply Gauss with b; auto with zarith.
exists c; auto.
rewrite (Zmult_comm c); auto with zarith.
red.
assert (Zdivide (Zgcd a b) p).
rewrite H6; apply Zdivide_plus_r; auto with zarith.
apply Zdivide_trans with a; auto with zarith.
generalize (Zgcd_is_gcd a b); intros tmp; inversion tmp; auto.
apply Zdivide_trans with b; auto with zarith.
generalize (Zgcd_is_gcd a b); intros tmp; inversion tmp; auto.
case (Zle_lt_or_eq 0 (Zgcd a b)); auto with zarith.
generalize (Zgcd_is_pos a b); auto with zarith.
intros HH1; case (Zle_lt_or_eq 1 (Zgcd a b)); auto with zarith.
intros HH2; contradict H; apply prime_inv_def; auto with zarith.
split; auto.
apply Zle_lt_trans with a; auto with zarith.
apply Zdivide_le; auto with zarith.
generalize (Zgcd_is_gcd a b); intros tmp; inversion tmp; auto.
apply Zle_lt_trans with ( 1 := Hc2 ).
apply Zle_lt_trans with (Z.sqrt p * Z.sqrt p); auto with zarith.
apply Zle_trans with (1 * Z.sqrt p); auto with zarith.
intros tmp; rewrite tmp; apply Zgcd_is_gcd.
intros HH1.
generalize (Zgcd_is_gcd a b); intros tmp; inversion tmp; auto.
case H0; intros q; rewrite <- HH1.
intros HH2; contradict H2; rewrite HH2; auto with zarith.
case Hb2; clear Hb2; intros k Hb2.
assert (Hb3: c = k * b).
apply Zmult_reg_l with a; auto with zarith.
apply trans_equal with ( 1 := Hb1 ).
rewrite Hb2; ring.
assert (Hb4: k * k = 1).
apply Zmult_reg_l with p; auto with zarith.
pattern p at 1; rewrite H6.
apply trans_equal with ((k * a) * (k * a) + (k * b) * (k * b)).
ring.
rewrite <- Hb2; rewrite <- Hb3; auto with zarith.
rewrite Hb3; rewrite Hb2; replace k with 1; auto with zarith.
case (Zmult_1_inversion_l k k); auto.
intros tmp; contradict H4; rewrite Hb3; rewrite tmp; auto with zarith.
Qed.

Theorem two_square_mod_exists_2: Zis_mod (1 * 1) (- 1) 2.
exists 1; auto with zarith.
Qed.

Theorem two_square_mod_exists_1_mod4:
 forall p,
 prime p ->
 Zis_mod p 1 4 ->
  Zis_mod (Zfact (Zdiv (p - 1) 2) * Zfact (Zdiv (p - 1) 2)) (- 1) p.
intros p Hp Hp1.
case Hp1; clear Hp1; intros q Hp1.
replace ((p - 1) / 2) with (2 * q).
2:rewrite Hp1; replace (q * 4) with ((2 * q) * 2); (try rewrite Z_div_mult);
   auto with zarith.
assert (Hp2: 1 < p).
inversion Hp; auto.
assert (Hp3: 0 < q).
case (Zle_lt_or_eq 0 q); auto with zarith.
apply Zis_mod_trans with ( 2 := wilson p Hp ).
rewrite Hp1.
assert (Hp4: 1 < 2 * q).
apply Zle_lt_trans with (1 * q); auto with zarith.
unfold Zfact; rewrite (Zprod_split_up 1 (2 * q) (q * 4)); auto with zarith.
replace (Zprod (2 * q + 1) (q * 4) (fun (x : Z) => x))
     with (Zprod 1 (2 * q) (fun (x : Z) => 2 * q + x)).
apply Zis_mod_def; auto with zarith.
(repeat rewrite (fun x y z => Zmod_mult (Zprod x y z))); auto with zarith.
apply f_equal2 with ( f := Zmod ); auto.
apply f_equal2 with ( f := Zmult ); auto.
apply trans_equal
     with (Zprod 1 (2 * q) (fun (x : Z) => - 1 * ((2 * q + 1) - x)) mod p).
apply f_equal2 with ( f := Zmod ); auto.
rewrite <- (Zprod_mult 1 (2 * q) (fun x => - 1) (fun x => (2 * q + 1) - x)).
rewrite (Zprod_c (- 1)); auto with zarith.
replace (Zpower (- 1) ((1 + 2 * q) - 1)) with 1.
rewrite Zmult_1_l.
unfold Zprod; rewrite Zle_imp_le_bool; auto with zarith.
rewrite <- (iter_map
             _ _ _ 1 (fun (x : Z) => x) Zmult (fun (x : Z) => (2 * q + 1) - x)).
apply iter_permutation; auto with zarith.
apply permutation_trans
     with (rev (progression Zsucc 1 (Zabs_nat ((1 + 2 * q) - 1)))).
apply permutation_sym; apply permutation_rev.
rewrite Zprogression_opp; auto.
replace ((1 + 2 * q) - 1) with (2 * q); auto with zarith.
replace (1 + Z_of_nat (pred (Zabs_nat (2 * q)))) with (2 * q); auto with zarith.
pattern (2 * q) at 1 3; rewrite <- (Z_of_nat_Zabs_nat (2 * q)).
cut (exists c , c = Zabs_nat (2 * q) ).
intros [c Hc]; pattern (Zabs_nat (2 * q)) at 1 3; rewrite <- Hc.
cut (le (Zabs_nat (2 * q)) c).
generalize c; elim (Zabs_nat (2 * q)); auto; clear c Hc.
intros n Rec c Hc.
repeat rewrite Zprogression_end.
rewrite map_app.
rewrite Zprogression_pred_end.
apply permutation_app_comp; auto with zarith.
replace (Z_of_nat c - Z_of_nat n) with ((Z_of_nat c + 1) - (1 + Z_of_nat n));
 apply permutation_refl || ring.
rewrite Hc; auto with arith.
exists (Zabs_nat (2 * q)); auto.
auto with zarith.
pattern (2 * q) at 2; replace (2 * q) with (Zsucc (Zpred (2 * q)));
 auto with zarith.
rewrite Zabs_nat_Zsucc; auto with zarith.
rewrite <- pred_Sn; rewrite Z_of_nat_Zabs_nat; auto with zarith.
replace ((1 + 2 * q) - 1) with (2 * q); auto with zarith.
replace (2 * q) with (q + q); auto with zarith.
rewrite Zpower_exp; auto with zarith.
rewrite Zabs_square; rewrite Zpower_Zabs; auto with zarith.
replace (Zabs (- 1)) with 1; (repeat rewrite Zpower_1); auto with zarith.
unfold Zprod; (rewrite Zle_imp_le_bool; auto with zarith).
elim (Zabs_nat ((1 + 2 * q) - 1)); auto.
intros n Rec.
(repeat rewrite Zprogression_end); auto with zarith.
(repeat rewrite iter_app); auto with zarith.
rewrite (Zmod_mult
          (iter
            1 (fun (x : Z) => - 1 * ((2 * q + 1) - x)) Zmult
            (progression Zsucc 1 n))); auto with zarith.
rewrite (Zmod_mult
          (iter 1 (fun (x : Z) => 2 * q + x) Zmult (progression Zsucc 1 n)));
 auto with zarith.
apply f_equal2 with ( f := Zmod ); auto.
apply f_equal2 with ( f := Zmult ); auto.
change
 (Zmod ((- 1 * ((2 * q + 1) - (1 + Z_of_nat n))) * 1) p =
  Zmod ((2 * q + (1 + Z_of_nat n)) * 1) p).
apply Zis_mod_def_inv; auto with zarith.
exists (- 1); replace p with (q * 4 + 1); [idtac | rewrite <- Hp1]; ring.
replace (q * 4) with (2 * q + 2 * q); (try ring).
unfold Zprod; ((repeat rewrite Zle_imp_le_bool); auto with zarith).
rewrite <- (iter_map _ _ _ 1 (fun (x : Z) => x) Zmult (fun (x : Z) => 2 * q + x));
 auto.
apply f_equal4 with ( f := @iter Z Z ); auto.
replace ((1 + 2 * q) - 1) with (2 * q); auto with zarith.
replace ((1 + (2 * q + 2 * q)) - (2 * q + 1)) with (2 * q); auto with zarith.
elim (Zabs_nat (2 * q)); auto with zarith.
intros n Rec.
(repeat rewrite Zprogression_end); auto with zarith.
(repeat rewrite map_app); auto with zarith.
apply f_equal2 with ( f := @app Z ); auto.
change
 (cons (2 * q + (1 + Z_of_nat n)) nil = cons ((2 * q + 1) + Z_of_nat n) nil).
apply f_equal2 with ( f := @cons Z ); auto with zarith.
Qed.

Theorem prime_case_4:
 forall p, prime p ->  p = 2 \/ (Zis_mod p 1 4 \/ Zis_mod p 3 4).
intros p Hp.
case (Z_mod_lt p 4); auto with zarith.
intros H2 H3; case Zle_lt_or_eq with ( 1 := H2 ); clear H2; intros H2.
case (Zle_lt_or_eq 1 (p mod 4)); auto with zarith; clear H2; intros H2.
case (Zle_lt_or_eq 2 (p mod 4)); auto with zarith; clear H2; intros H2.
case (Zle_lt_or_eq 3 (p mod 4)); auto with zarith; clear H2; intros H2.
rewrite H2; right; right; apply Zis_mod_mod; auto with zarith.
left; case (Zle_lt_or_eq 2 p); auto with zarith.
inversion Hp; auto with zarith.
intros H4; case (prime_inv_def p 2); auto with zarith.
rewrite (Z_div_mod_eq p 4); auto with zarith.
rewrite <- H2; exists (2 * (p / 4) + 1); ring.
rewrite H2; right; left; apply Zis_mod_mod; auto with zarith.
absurd (Zdivide 4 p).
intros [q Hq].
case (Zle_lt_or_eq 0 q); auto with zarith.
apply Zmult_le_reg_r with 4; auto with zarith.
rewrite <- Hq; inversion Hp; auto with zarith.
intros H4; absurd (Zdivide 2 p).
apply prime_inv_def; auto with zarith.
exists (2 * q); rewrite Hq; auto with zarith.
intros H4; contradict Hp; rewrite Hq; rewrite <- H4.
rewrite Zmult_0_l.
apply not_prime_0.
exists (Zdiv p 4).
pattern p at 1; rewrite (Z_div_mod_eq p 4); auto with zarith.
Qed.

Theorem two_squares_mod_inv:
 forall p i, prime p -> Zis_mod (i * i) (- 1) p ->  p = 2 \/ Zis_mod p 1 4.
intros p i Hp H1.
generalize (prime_case_4 p Hp); intros [H2|[H2|H2]]; auto.
case two_squares_mod_exists_sum with ( 2 := H1 ); auto with zarith.
intros a [b Hab].
absurd (Zmod p 4 = Zmod 3 4).
rewrite Hab.
rewrite Zmod_plus_eq; auto with zarith.
rewrite (Zmod_mult a); (try rewrite (Zmod_mult b)); auto with zarith.
assert (Ha: a mod 4 = 0 \/ (a mod 4 = 1 \/ (a mod 4 = 2 \/ a mod 4 = 3))).
case (Z_mod_lt a 4); auto with zarith; intros Ha Ha1.
case Zle_lt_or_eq with ( 1 := Ha ); clear Ha; intros Ha; auto.
case (Zle_lt_or_eq 1 (a mod 4)); auto with zarith; clear Ha; intros Ha; auto.
case (Zle_lt_or_eq 2 (a mod 4)); auto with zarith; clear Ha; intros Ha; auto.
assert (Hb: b mod 4 = 0 \/ (b mod 4 = 1 \/ (b mod 4 = 2 \/ b mod 4 = 3))).
case (Z_mod_lt b 4); auto with zarith; intros Hb Hb1.
case Zle_lt_or_eq with ( 1 := Hb ); clear Hb; intros Hb; auto.
case (Zle_lt_or_eq 1 (b mod 4)); auto with zarith; clear Hb; intros Hb; auto.
case (Zle_lt_or_eq 2 (b mod 4)); auto with zarith; clear Hb; intros Hb; auto.
generalize Ha Hb; intros [HH1|[HH1|[HH1|HH1]]]; intros [HL1|[HL1|[HL1|HL1]]];
 (repeat rewrite HH1); (repeat rewrite HL1); (intros; (try discriminate)).
apply Zis_mod_def_inv; auto with zarith.
Qed.

Theorem two_squares_case:
 forall p, prime p -> sum_of_two_squares p ->  p = 2 \/ Zis_mod p 1 4.
intros p H1 [a [b H2]].
case (two_squares_exists_mod_cor p); auto.
exists a; exists b; auto.
intros i Hi; apply two_squares_mod_inv with ( 2 := Hi ); auto.
Qed.

Theorem two_squares_exists:
 forall p, prime p -> p = 2 \/ Zis_mod p 1 4 ->  sum_of_two_squares p.
intros p Hp [H1|H1].
apply two_squares_mod_exists_sum with 1; auto.
subst p; apply two_square_mod_exists_2; auto.
apply two_squares_mod_exists_sum with (Zfact (Zdiv (p - 1) 2)); auto.
apply two_square_mod_exists_1_mod4; auto.
Qed.

Theorem two_squares_comp:
 forall n m,
 sum_of_two_squares n -> sum_of_two_squares m ->  sum_of_two_squares (n * m).
intros n m [a [b Hn]] [c [d Hm]].
exists (a * c - b * d); exists (a * d + b * c).
rewrite Hm; rewrite Hn; ring.
Qed.

Theorem not_prime_prime_divide:
 forall n,
 (1 < n)%Z ->
 ~ prime n ->  (exists p , ( 1 < p < n )%Z /\ (prime p /\ Zdivide p n) ).
intros n Hn; generalize Hn; pattern n; apply Zlt_0_ind; auto with zarith;
 clear n Hn.
intros n Rec _ H1 H2.
case (not_prime_divide _ H1 H2); intros m [Hm1 Hm2].
case (prime_dec m); intros Hm3.
exists m; auto.
case (Rec m); auto with zarith.
intros p [Hp [Hp1 Hp2]]; exists p; split; auto with zarith; split;
 auto with zarith.
apply Zdivide_trans with m; auto.
Qed.

Theorem prime_mod_3_4_divide_divide_first:
 forall p a b,
 prime p -> Zis_mod p 3 4 -> Zdivide p (a * a + b * b) ->  Zdivide p a.
intros p a b H1 H2 H3.
assert (Hp: 1 < p).
inversion H1; auto.
case (Z_eq_dec 0 (Zmod a p)); intros H4.
exists (Zdiv a p).
rewrite Zmult_comm; apply Z_div_exact_2; auto with zarith.
case (two_squares_exists_mod p b a); auto with zarith.
contradict H4.
apply sym_equal; replace 0 with (Zmod 0 p); auto with zarith.
apply Zis_mod_def_inv; auto with zarith.
case (Zdivide_dec p a); intros Hd.
case Hd; intros q Hq; exists q; rewrite <- Hq; auto with zarith.
apply Zis_mod_cancel with a; auto with zarith.
apply rel_prime_sym; apply prime_rel_prime; auto with zarith.
rewrite Zmult_0_r; auto.
case H3; intros q Hq; exists q; rewrite <- Hq; auto with zarith.
intros i Hi.
case two_squares_mod_inv with ( 2 := Hi ); auto; intros He.
absurd (Zmod p 4 = Zmod 3 4); auto with zarith.
rewrite He; intros; discriminate.
apply Zis_mod_def_inv; auto with zarith.
absurd (Zmod 1 4 = Zmod 3 4); auto with zarith.
intros; discriminate.
apply Zis_mod_def_inv; auto with zarith.
apply Zis_mod_trans with ( 2 := H2 ); auto.
apply Zis_mod_sym; auto with zarith.
Qed.

Theorem prime_mod_3_4_divide_divide_square:
 forall p a b,
 prime p ->
 Zis_mod p 3 4 -> Zdivide p (a * a + b * b) ->  Zdivide (p * p) (a * a + b * b).
intros p a b H1 H2 H3.
assert (Hp: 1 < p).
inversion H1; auto.
assert (Ha: Zdivide p a).
apply prime_mod_3_4_divide_divide_first with ( b := b ); auto with zarith.
assert (Hb: Zdivide p b).
apply prime_mod_3_4_divide_divide_first with ( b := a ); auto with zarith.
replace (b * b + a * a) with (a * a + b * b); auto with zarith.
exists (Zdiv a p * Zdiv a p + Zdiv b p * Zdiv b p).
pattern a at 1 2; rewrite (Zdivide_Zdiv_eq p a); auto with zarith.
pattern b at 1 2; rewrite (Zdivide_Zdiv_eq p b); auto with zarith; ring.
Qed.

Theorem two_squares_sum:
 forall n,
 0 <= n ->
 (forall p, prime p -> Zis_mod p 3 4 ->  Zeven (Zdiv_exp p n)) ->
  sum_of_two_squares n.
intros n Hn; pattern n; apply Zlt_0_ind; auto with zarith;
 clear n Hn.
intros n Rec H1 H2.
case Zle_lt_or_eq with ( 1 := H1 ); clear H1; intros H1.
2:exists 0; exists 0; rewrite <- H1; ring.
case (Zle_lt_or_eq 1 n); auto with zarith; clear H1; intros H1.
2:exists 1; exists 0; rewrite <- H1; ring.
case (prime_dec n); intros H3.
generalize (prime_case_4 _ H3); intros [H4|[H4|H4]].
apply two_squares_exists; auto.
apply two_squares_exists; auto.
absurd (Zeven (Zdiv_exp n n)); auto.
rewrite Zdiv_exp_id; auto with zarith.
case not_prime_prime_divide with ( 2 := H3 ); auto.
intros p [Hp1 [Hp2 Hp3]].
assert (n = p * Zdiv n p).
apply Zdivide_Zdiv_eq; auto with zarith.
assert (Hpp: 1 < p * p).
apply Zlt_le_trans with (1 * p); auto with zarith.
generalize (prime_case_4 _ Hp2); intros [H4|[H4|H4]].
subst p; rewrite H; apply two_squares_comp; auto with zarith.
apply two_squares_exists; auto with zarith.
apply Rec; auto with zarith.
intros p1 Hm1 Hm2.
rewrite <- Zdiv_exp_prime with ( c := 2 ); auto with zarith.
rewrite Zmult_comm; rewrite <- H; auto with zarith.
intros Hm3; absurd (Zmod p1 4 = Zmod 3 4); auto with zarith.
rewrite (prime_divide_prime_eq p1 2); auto with zarith.
intros; discriminate.
apply Zis_mod_def_inv; auto with zarith.
rewrite H; apply two_squares_comp; auto with zarith.
apply two_squares_exists; auto with zarith.
apply Rec; auto with zarith.
case (Zdivide_Zdiv_lt_pos p n); auto with zarith.
(*case (Zdivide_Zdiv_lt_pos p n); auto with zarith.*)
intros p1 Hm1 Hm2.
rewrite <- Zdiv_exp_prime with ( c := p ); auto with zarith.
rewrite Zmult_comm; rewrite <- H; auto with zarith.
apply Zmult_lt_reg_r with p; auto with zarith.
rewrite (Zmult_comm (Zdiv n p)); rewrite <- H; auto with zarith.
intros Hm3; absurd (Zmod 1 4 = Zmod 3 4); auto with zarith.
intros; discriminate.
apply trans_equal with (Zmod p1 4).
rewrite (prime_divide_prime_eq p1 p); auto with zarith.
apply sym_equal; apply Zis_mod_def_inv; auto with zarith.
apply Zis_mod_def_inv; auto with zarith.
assert (HH: Zdivide (p * p) n).
apply Zdivide_trans with (Zpower p (Zdiv_exp p n)); auto.
replace (p * p) with (Zpower p 2); auto with zarith.
exists (Zpower p (Zdiv_exp p n - 2)).
rewrite <- Zpower_exp; auto with zarith.
apply f_equal2 with ( f := Zpower ); auto with zarith.
case (Zle_lt_or_eq 0 (Zdiv_exp p n)); auto with zarith.
apply Zdiv_exp_pos; auto with zarith.
intros tmp; case (Zle_lt_or_eq 1 (Zdiv_exp p n)); auto with zarith.
intros tmp1; absurd (Zeven (Zdiv_exp p n)); auto with zarith.
rewrite <- tmp1; intros; intros tmp2; case tmp2.
intros tmp; case (Zdiv_exp_not_div p n); auto with zarith.
rewrite <- tmp; auto with zarith.
replace (p ^ (1 + 0)) with p; auto with zarith.
rewrite Zpower_exp_1; auto with zarith.
replace 2 with (1 + 1); auto with zarith.
(repeat (rewrite Zpower_exp || rewrite Zpower_exp_1)); auto with zarith.
apply Zdiv_exp_div; auto with arith.
case Hp1; auto.
apply Zle_trans with p; auto with zarith.
assert (H0: n = (p * p) * Zdiv n (p * p)).
pattern n at 1; rewrite (Z_div_mod_eq n (p * p)); auto with zarith.
rewrite (Zdivide_mod n (p * p)); auto with zarith.
case (Zle_lt_or_eq 1 (n / (p * p))).
case (Zdivide_Zdiv_lt_pos (p * p) n); auto with zarith.
intros Hk; rewrite H0; apply two_squares_comp; auto with zarith.
exists p; exists 0; ring.
apply Rec; auto with zarith.
case (Zdivide_Zdiv_lt_pos (p * p) n); auto with zarith.
intros p1 Hm1 Hm2.
case (Zdivide_dec p1 p); intros Hm3.
rewrite (prime_divide_prime_eq p1 p); auto with zarith.
replace (Zdiv_exp p (n / (p * p))) with (Zpred (Zpred (Zdiv_exp p n)));
 auto with zarith.
apply Zeven_pred; apply Zodd_pred; auto with zarith.
pattern n at 1; rewrite H0.
rewrite <- Zmult_assoc.
rewrite Zdiv_exp_succ; auto with zarith.
rewrite Zdiv_exp_succ; auto with zarith.
apply Zlt_le_trans with (p * 1); auto with zarith.
rewrite <- Zdiv_exp_prime with ( c := p ); auto with zarith.
rewrite <- Zdiv_exp_prime with ( c := p ); auto with zarith.
replace (((n / (p * p)) * p) * p) with n; auto with zarith.
apply trans_equal with ( 1 := H0 ); ring.
apply Zlt_le_trans with (1 * p); auto with zarith.
intros HH1; rewrite H0; rewrite <- HH1; exists p; exists 0; ring.
Qed.

Theorem two_squares_sum_converse:
 forall n,
 0 < n ->
 sum_of_two_squares n ->
 forall p, prime p -> Zis_mod p 3 4 ->  Zeven (Zdiv_exp p n).
intros n Hn Hn1; assert (Hp: 0 <= n); auto with zarith.
generalize Hn Hn1; pattern n; apply Z_lt_induction; auto with zarith;
 clear n Hn Hn1 Hp.
intros n Rec H1 H2 p H3 H4.
case (Zdivide_dec p n); intros Hdec.
case H2; intros a [b Ha1]; rewrite (Zabs_square a) in Ha1;
 rewrite (Zabs_square b) in Ha1; subst n.
assert (Hp: 1 < p).
inversion H3; auto.
assert (Ha: Zdivide p (Zabs a)).
apply prime_mod_3_4_divide_divide_first with ( b := Zabs b ); auto with zarith.
assert (Hb: Zdivide p (Zabs b)).
apply prime_mod_3_4_divide_divide_first with ( b := Zabs a ); auto with zarith.
replace (Zabs b * Zabs b + Zabs a * Zabs a)
     with (Zabs a * Zabs a + Zabs b * Zabs b); auto with zarith.
assert (Ha1: 0 <= Zabs a / p).
apply Zge_le; apply (Z_div_ge0 (Zabs a) p); intros; (try apply Zle_ge);
 auto with zarith.
assert (Hb1: 0 <= Zabs b / p).
apply Zge_le; apply (Z_div_ge0 (Zabs b) p); intros; (try apply Zle_ge);
 auto with zarith.
assert (Hu: 0 < (Zabs a / p) * (Zabs a / p) + (Zabs b / p) * (Zabs b / p)).
case (Zle_lt_or_eq 0 (Zabs a)); auto with zarith; intros Hr1.
case (Zdivide_Zdiv_lt_pos p (Zabs a)); auto with zarith; intros Hr2 Hr3.
apply Zlt_le_trans with ((Zabs a / p) * (Zabs a / p) + 0 * (Zabs b / p));
 auto with zarith.
rewrite Zmult_0_l; rewrite Zplus_0_r; replace 0 with (0 * (Zabs a / p));
 auto with zarith.
apply Zmult_lt_compat_r; auto with zarith.
rewrite <- Hr1; rewrite Zmult_0_l; rewrite Zplus_0_l.
case (Zle_lt_or_eq 0 (Zabs b)); auto with zarith; intros Hs1.
case (Zdivide_Zdiv_lt_pos p (Zabs b)); auto with zarith; intros Hs2 Hs3.
replace 0 with (0 * (Zabs b / p)); auto with zarith.
apply Zmult_lt_compat_r; auto with zarith.
contradict H1; rewrite <- Hs1; rewrite <- Hr1; auto with zarith.
replace (Zdiv_exp p (Zabs a * Zabs a + Zabs b * Zabs b))
     with
      (Zsucc
        (Zsucc
          (Zdiv_exp
            p
            (Zdiv (Zabs a) p * Zdiv (Zabs a) p +
             Zdiv (Zabs b) p * Zdiv (Zabs b) p)))).
apply Zeven_Sn; apply Zodd_Sn; apply Rec; auto with zarith.
split; auto with zarith.
case (Zle_lt_or_eq 0 (Zabs a)); auto with zarith; intros Hr1.
case (Zdivide_Zdiv_lt_pos p (Zabs a)); auto with zarith; intros Hr2 Hr3.
case (Zle_lt_or_eq 0 (Zabs b)); auto with zarith; intros Hs1.
case (Zdivide_Zdiv_lt_pos p (Zabs b)); auto with zarith; intros Hs2 Hs3.
apply Zplus_lt_compat.
apply Zlt_trans with (Zabs a * (Zabs a / p)); auto with zarith.
apply Zmult_lt_compat_r; auto with zarith.
apply Zmult_lt_compat_l; auto with zarith.
apply Zlt_trans with (Zabs b * (Zabs b / p)); auto with zarith.
apply Zmult_lt_compat_r; auto with zarith.
apply Zmult_lt_compat_l; auto with zarith.
rewrite <- Hs1; replace (Zdiv 0 p) with 0.
(repeat rewrite Zmult_0_r); (repeat rewrite Zplus_0_r).
apply Zlt_trans with (Zabs a * (Zabs a / p)); auto with zarith.
apply Zmult_lt_compat_r; auto with zarith.
apply Zmult_lt_compat_l; auto with zarith.
unfold Zdiv; simpl; auto.
rewrite <- Hr1; replace (Zdiv 0 p) with 0.
(repeat rewrite Zmult_0_r); (repeat rewrite Zplus_0_l).
case (Zle_lt_or_eq 0 (Zabs b)); auto with zarith; intros Hs1.
case (Zdivide_Zdiv_lt_pos p (Zabs b)); auto with zarith; intros Hs2 Hs3.
apply Zlt_trans with (Zabs b * (Zabs b / p)); auto with zarith.
apply Zmult_lt_compat_r; auto with zarith.
apply Zmult_lt_compat_l; auto with zarith.
contradict H1; rewrite <- Hs1; rewrite <- Hr1; auto with zarith.
unfold Zdiv; simpl; auto.
exists (Zabs a / p); exists (Zabs b / p); auto.
replace (Zabs a * Zabs a + Zabs b * Zabs b)
     with
      (p * (p * ((Zabs a / p) * (Zabs a / p) + (Zabs b / p) * (Zabs b / p)))).
(repeat rewrite Zdiv_exp_succ); auto with zarith.
apply Zlt_le_trans with (p * 1); auto with zarith.
pattern (Zabs a) at 3 4; rewrite (Zdivide_Zdiv_eq p (Zabs a)); auto with zarith.
pattern (Zabs b) at 3 4; rewrite (Zdivide_Zdiv_eq p (Zabs b)); auto with zarith.
ring.
replace (Zdiv_exp p n) with 0; auto with zarith.
apply Zdiv_exp_inv; auto with zarith.
inversion H3; auto.
rewrite Zplus_0_r; rewrite Zpower_exp_1; auto with zarith.
Qed.


Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.

Generalizable All Variables.

Set Primitive Projections.
Set Universe Polymorphism.

Require Import COC.Base.Main
        COC.Cons.Main
        COC.Adj.Main
        COC.Monad.Main.

Class IsKt (C: Category)(T: C -> C)
      (ret: forall (X: C), C X (T X))
      (bind: forall {X Y: C}, (C X (T Y)) -> (C (T X) (T Y))) :=
  {
    kt_bind_proper:> forall (X Y: C), Proper ((==) ==> (==)) (@bind X Y);
    kt_ret_bind:
      forall (X: C), bind (ret X) == Id (T X);

    kt_bind_ret:
      forall (X Y: C)(f: C X (T Y)),
        bind f \o ret X == f;

    kt_bind_comp:
      forall (X Y Z: C)(f: C X (T Y))(g: C Y (T Z)),
        bind g \o bind f == bind (bind g \o f)
  }.

Class Kt (C: Category)(T: C -> C) :=
  {
    ret: forall {X: C}, C X (T X);
    bind: forall (X Y: C), C X (T Y) -> C (T X) (T Y);

    kt_prf:> IsKt (@ret) bind
  }.
Existing Instance kt_prf.
Notation "[ 'Kt' 'by' ret , bind ]" := (@Build_Kt _ _ ret bind _).

Definition kt_fobj {C: Category}{T: C -> C}(kt: Kt C T) := T.

Program Definition Kt_from_Monad (C: Category)(T: Monad C)
  : Kt C T :=
  [Kt by monad_unit T,
         fun (X Y: C)(f: C X (T Y)) =>
           monad_mult T Y \o fmap T f].
Next Obligation.
  - now intros f g Heq; rewrite Heq.
  - generalize (monad_mult_T_unit (IsMonad:=T) X); simpl.
    now rewrite cat_comp_id_dom.
  - rewrite cat_comp_assoc.
    rewrite <- (natrans_naturality (IsNatrans:=monad_unit T) f); simpl.
    generalize (monad_mult_unit_T (IsMonad:=T) Y); simpl.
    rewrite cat_comp_id_dom, <- cat_comp_assoc; intros H; rewrite H.
    now rewrite cat_comp_id_cod.
  - generalize (monad_mult_mult (IsMonad:=T) Z); simpl; intros Heq.
    rewrite !fmap_comp, <- !cat_comp_assoc.
    rewrite cat_comp_id_dom in Heq; rewrite <- Heq, !cat_comp_assoc.
    rewrite <- (cat_comp_assoc (fmap T f)).
    rewrite <- (natrans_naturality (IsNatrans:=monad_mult T) g).
    now rewrite cat_comp_assoc.
Qed.

Program Definition Monad_from_Kt (C: Category)(T: C -> C)(kt: Kt C T) :=
  [Monad by [Functor by f :-> bind (ret \o f) with X :-> T X],
            [X :=> ret],
            [X :=> bind (Id (T X))]].
Next Obligation.
  - now intros f g Heq; rewrite Heq.
  - now rewrite kt_bind_comp, <- !cat_comp_assoc, kt_bind_ret.
  - now rewrite cat_comp_id_dom, kt_ret_bind.
Qed.
Next Obligation.
  now rewrite kt_bind_ret.
Qed.
Next Obligation.
  rewrite kt_bind_comp.
  rewrite <- cat_comp_assoc, kt_bind_ret, cat_comp_id_cod.
  now rewrite kt_bind_comp, cat_comp_id_dom.
Qed.
Next Obligation.
  - rewrite kt_bind_comp, !cat_comp_id_dom.
    rewrite kt_bind_comp.
    now rewrite <- cat_comp_assoc, kt_bind_ret, cat_comp_id_cod.
  - now rewrite cat_comp_id_dom, kt_bind_ret.
  - rewrite cat_comp_id_dom, kt_bind_comp.
    now rewrite <- cat_comp_assoc, kt_bind_ret, cat_comp_id_cod, kt_ret_bind.
Qed.

(** Equality **)
Program Definition Monad_setoid (C: Category) :=
  [Setoid by (fun (M N: Monad C) =>
                (monad_functor M == monad_functor N)
                /\(forall X: C, monad_unit M X =H monad_unit N X)
                /\(forall X: C, monad_mult M X =H monad_mult N X))].
Next Obligation.
  - intros M N [H [H' H'']]; repeat split; intros.
    + now apply hom_eq_sym, H.
    + now apply hom_eq_sym, H'.
    + now apply hom_eq_sym, H''.
  - intros M N L [Hmn [Hmn' Hmn'']] [Hnl [Hnl' Hnl'']]; repeat split; intros.
    + now apply hom_eq_trans with _ _ (fmap N f).
    + now apply hom_eq_trans with _ _ (monad_unit N X).
    + now apply hom_eq_trans with _ _ (monad_mult N X);
        [apply Hmn'' | apply Hnl''].
Qed.

Program Definition Kt_setoid (C: Category)(T: C -> C) :=
  [Setoid by (fun (k k': Kt C T) =>
                (forall X: C, ret (Kt:=k)(X:=X) == ret (Kt:=k'))
                /\(forall (X Y: C)(f: C X (T Y)),
                      bind (Kt:=k) f == bind (Kt:=k') f))].
Next Obligation.
  intros k k' k'' [Hr Hb] [Hr' Hb']; split; intros.
  - now transitivity (ret (Kt:=k')(X:=X)).
  - now transitivity (bind (Kt:=k') f).
Qed.

Lemma Monad_Kt_Monad_eq:
  forall (C: Category)(T: Monad C),
    T == Monad_from_Kt (Kt_from_Monad T) in Monad_setoid C.
Proof.
  intros; repeat split; simpl; try reflexivity.
  - rewrite fmap_comp, <- cat_comp_assoc.
    generalize (monad_mult_T_unit (IsMonad:=T) Y); simpl.
    rewrite cat_comp_id_dom.
    now intros Heq; rewrite Heq, cat_comp_id_cod.
  - now rewrite fmap_id, cat_comp_id_dom.
Qed.

Lemma Kt_Monad_Kt_eq:
  forall (C: Category)(T: C -> C)(kt: Kt C T),
    kt == Kt_from_Monad (Monad_from_Kt kt) in Kt_setoid C T.
Proof.
  simpl; intros; split; intros; [reflexivity |].
  now rewrite kt_bind_comp, <- cat_comp_assoc, kt_bind_ret, cat_comp_id_cod.
Qed.

(** Special Notation for Kt on Types **)
Notation "m >>= f" := (bind (C:=Types) f m) (at level 53, left associativity).
Notation "[ 'do' M 'in' K ]" := (let _kt := K: Kt Types _ in M).
Notation "[ 'do' M ]" := [do M in _].
Notation "x <- m ; p" := (m >>= (fun x => p)) (at level 60, right associativity).
Notation ":- x ; m" := (_ <- x ; m) (at level 61, right associativity, x at next level).
Notation "x <-: m ; p" := (x <- ret m ; p) (at level 60, right associativity).
Notation "f >> g" := (bind (C:=Types) g \o f) (at level 42, right associativity).

Require Import List.
Import List.ListNotations.
(** Maybe **)
Program Instance Maybe: Kt Types option :=
  {
    ret X x := Some x;
    bind X Y f m := match m with
                    | Some x => f x
                    | None => None
                    end
  }.
Next Obligation.
  - now intros f g Heq [x |].
  - now destruct x as [x |].
  - now destruct x as [x |].
Qed.

Eval compute in
    [do x <-: 0;
       y <- hd_error [1;2];
       ret (x, y) in Maybe].
(* = Some (0, 1) *)
(* : option (product nat nat) *)

Eval compute in
    [do x <-: 0;
       y <- hd_error [];
       ret (x, y) in Maybe].
(* = None *)
(* : option (product nat ?B) *)

(** List **)
Lemma flat_map_app:
  forall (X Y: Type)(f: X -> list Y)(l1 l2: list X),
    flat_map f (l1 ++ l2) = flat_map f l1 ++ flat_map f l2.
Proof.
  induction l1 as [| x l1 IHl1]; simpl; [reflexivity |].
  now intros l2; rewrite IHl1, app_assoc.
Qed.

Program Instance List: Kt Types list :=
  {
    ret X x := [x];
    bind X Y f l := flat_map f l
  }.
Next Obligation.
  - intros f g Heq l.
    now rewrite !flat_map_concat_map, (map_ext _ _ Heq).
  - now induction x as [| x l IHl]; simpl; [| rewrite IHl].
  - now rewrite app_nil_r.
  - induction x as [| x l IHl]; simpl; [reflexivity |].
    now rewrite flat_map_app, IHl.
Qed.

Eval compute in
    [do x <- [3;1;4;1;5];
       y <-: (x + 1);
       ret y in List].
(* = [4; 2; 5; 2; 6] *)
(* : list nat *)

Definition guard {X: Type}(b: X -> bool)(x: X): list X :=
  if b x then [x] else [].

Fixpoint evenb (n: nat): bool :=
  match n with
  | O => true
  | S O => false
  | S (S n') => evenb n'
  end.

Eval compute in
    [do x <- [0;1;2;3] ;
       y <-: (x + 1);
       :- guard evenb y ;
       ret x in List].
(* = [1; 3] *)
(* : list nat *)

Eval compute in
    [do x <-: 0;
       y <- (hd_error
               [do x <- [0;1;2;3] ;
                  y <-: (x + 1);
                  :- guard evenb y ;
                  ret x in List]);
       ret (x, y) in Maybe].
(* = Some (0, 1) *)
(* : option (product nat nat) *)

(** State **)
Module DirectDefinitionOfState.
  Require Import FunctionalExtensionality.
  Definition state (S: Type) := (fun (A: Type) => S -> product A S).
  Program Instance State (S: Type): Kt Types (state S) :=
    {
      ret X x s := (x, s);
      bind X Y f m s := let (x, s') := m s in f x s'
    }.
  Next Obligation.
    - intros f g Heq m.
      extensionality s.
      destruct (m s) as [x s'].
      now rewrite (Heq x).
    - extensionality s.
      now destruct (x s) as [x' s'].
    - extensionality s.
      now destruct (x s) as [x' s'].
  Qed.

  Definition put {S: Type}(s: S): state S unit :=
    (fun _: S => (tt, s)).

  Definition get {S: Type}: state S S :=
    (fun s: S => (s, s)).

  Definition modify {S: Type}(f: S -> S): state S unit :=
    [do s <- get ; put (f s) in State S].

  Definition evalState {S: Type}(X: Type)(m: state S X)(s: S) := m s.

  Eval compute in
      [do x <-: 0;
         y <-: 1;
         ret (x, y) in State nat].
  (* let _kt := State nat in x <-: 0; y <-: 1; ret (x, y) *)
  (*      : state nat (product nat nat) *)

  Eval compute in
      [do x <-: 0;
         y <-: 1;
         ret (x, y) in Maybe].
  (* = Some (0, 1) *)
  (* : option (product nat nat) *)

  Eval compute in
      [do x <-: 2;
         y <-: (evalState [do x <-: 1;
                             modify (plus x) in State nat]
                          x);
         ret (x, y.2) in Maybe].
  (* = Some (2, 3) *)
  (* : option (product nat nat) *)

  Eval compute in
      [do x <-: 2;
         y <-: (evalState [do x <-: 1;
                             modify (plus x) in State nat]
                          x);
         ret (x, y.2) in State bool].
  (* = fun s : bool => ((2, 3), s) *)
  (* : state bool (product nat nat) *)
End DirectDefinitionOfState.

Module StateFromAdjunction.
  Require Import FunctionalExtensionality.

  Program Definition exponential_of_Types (Y Z: Type)
    : Exponential (C:=Types) product_of_Types Y Z :=
    [Exp (Y -> Z)
      by (fun (X: Type) f x y => f (x, y))
     with (fun gy => gy.1 gy.2)].
  Next Obligation.
    - now destruct x.
    - now extensionality y; rewrite H.
  Qed.

  Instance State (S: Type): Kt Types _ :=
    Kt_from_Monad
      (Monad_from_adj
         (prod_exp_adjunction exponential_of_Types S)).

  Definition state (S: Type) := kt_fobj (State S).
  Eval compute in state.
  (* = fun S H : Type => S -> product H S *)
  (* : Type -> Types -> Types *)

  Definition put {S: Type}(s: S): state S unit :=
    (fun _: S => (tt, s)).

  Definition get {S: Type}: state S S :=
    (fun s: S => (s, s)).

  Definition modify {S: Type}(f: S -> S): state S unit :=
    [do s <- get ; put (f s) in State S].

  Definition evalState {S: Type}(X: Type)(m: state S X)(s: S) := m s.

  Eval compute in
      [do x <-: 0;
         y <-: 1;
         ret (x, y) in State nat].
  (* = fun y : nat => ((0, 1), y) *)
  (* : (Monad_from_adj (prod_exp_adjunction exponential_of_Types nat)) *)
  (*     (product nat nat) *)

  Eval compute in
      [do x <-: 0;
         :- modify S;
         s <- get;
         ret (x, s) in State nat].
  (* = fun y : nat => ((0, S y), S y) *)
  (* : (Monad_from_adj (prod_exp_adjunction exponential_of_Types nat)) *)
  (*     (product nat nat) *)

  Eval compute in
      evalState [do x <-: 0;
                   :- modify S;
                   s <- get;
                   ret (x, s) in State nat] 5.
  (*   = ((0, 6), 6) *)
  (* : (Product_2_functor product_of_Types nat) (product nat nat) *)

  Eval compute in
      [do x <-: 2;
         y <-: (evalState [do x <-: 1;
                             modify (plus x) in State nat]
                          x);
         ret (x, y.2) in Maybe].
  (* = Some (2, 3) *)
  (* : option (product nat nat) *)

  Eval compute in
      [do x <-: 2;
         y <-: (evalState [do x <-: 1;
                             modify (plus x) in State nat]
                          x);
         ret (x, y.2) in State bool].
  (* = fun y : bool => ((2, 3), y) *)
  (* : (Monad_from_adj (prod_exp_adjunction exponential_of_Types bool)) *)
  (*     (product nat nat) *)
End StateFromAdjunction.


Require Export Computable.

(** ** Time bounds *)

Fixpoint timeComplexity t (tt: TT t) : Type :=
  match tt with
    ! _ => unit
  | @TyArr t1 t2 tt1 tt2 => t1 -> timeComplexity tt1 -> (nat*timeComplexity tt2)
  end.

Arguments timeComplexity : clear implicits.
Arguments timeComplexity _ {_}.

Fixpoint computesTime {t} (ty : TT t) :  forall (x:t) (xInt :term) (xTime :timeComplexity t), Type :=
  match ty with
    !_ => fun x xInt _=> xInt = enc x
  | @TyArr t1 t2 tt1 tt2 =>
    fun f fInt fTime =>
      proc fInt *
      forall (y : t1) yInt (yTime:timeComplexity t1),
        computesTime y yInt yTime
        -> let fyTime := fTime y yTime in
          {v : term & (redLe (fst fyTime) (fInt yInt) v) * computesTime (f y) v (snd fyTime)}
  end%type.

Arguments computesTime {_} _ _ _ _.

Class computableTime {X : Type} (ty : TT X) (x : X) evalTime: Type :=
  {
    extT : extracted x;
    extTCorrect : computesTime ty x extT evalTime
  }.

Existing Instance extT|4.

Global Arguments computableTime {X} {ty} x.
Global Arguments extT {X} {ty} x {_ computableTime} : simpl never.
Global Arguments extTCorrect {X} ty x {_ computableTime} : simpl never.
Definition evalTime X ty x evalTime (computableTime : @computableTime X ty x evalTime):=evalTime.
Global Arguments evalTime {X} {ty} x {evalTime computableTime}.

Local Fixpoint notHigherOrder t (ty : TT t) :=
  match ty with
    TyArr (TyB _) ty2 => notHigherOrder ty2
  | TyB _ => True
  | _ => False
  end.

Local Lemma computesTime_computes_intern s t (ty: TT t) f evalTime:
  notHigherOrder ty -> computesTime ty f s evalTime -> computes ty f s.
Proof.
  revert s f.
  induction ty;intros s f H int.
  - exact int.
  -destruct ty1; cbn in H. 2:tauto.
   clear IHty1.
   cbn. destruct int as [ps ints]. cbn in ints.
   split. tauto.
   intros. subst.
   edestruct (ints a _ tt eq_refl) as(v&R'&?).
   exists v. split. eapply redLe_star_subrelation. all:eauto.
Defined.

Lemma computableTime_computable X (ty : TT X) (x:X) fT :
  notHigherOrder ty -> computableTime x fT -> computable x.
Proof.
  intros H I. eexists (extT x). destruct I. eapply computesTime_computes_intern. all:eauto.
Defined.

Hint Extern 10 (@computable ?t ?ty ?f) =>
(solve [let H:= fresh "H" in eassert (H : @computableTime t ty f _) by exact _;
                        ( (exact (computableTime_computable (ty:=ty) Logic.I H))|| idtac "Can not derive computable instance from computableTime for higher-order-function" f)]): typeclass_instances.

Lemma computesTimeProc t (ty : TT t) (f : t) fInt fT:
  computesTime ty f fInt fT-> proc fInt.
Proof.
  destruct ty.
  -intros ->. unfold enc. now destruct R.
  -now intros [? _].
Qed.

Lemma proc_extT {X : Type} (ty : TT X) (x : X) fT ( H : computableTime x fT) : proc (extT x).
Proof.
  unfold extT. destruct H as [? H]. now eapply computesTimeProc in H.
Qed.

Instance reg_is_extT ty (R : registered ty) (x : ty): computableTime x tt.
Proof.
  exists (enc x). split;constructor.
Defined.

Lemma computesTimeTyB (t:Type) (x:t) `{registered t}: computesTime (TyB t) x (extT x) tt.
Proof.
  unfold extT. now destruct H.
Qed.

Instance extTApp' t1 t2 {tt1:TT t1} {tt2 : TT t2} (f: t1 -> t2) (x:t1) fT xT (Hf : computableTime f fT) (Hx : computableTime x xT) : computableTime (f x) (snd (fT x xT)).
Proof.
  destruct Hf as [fInt H], Hx as [xInt xInts].
  eexists (projT1 ((snd H) x xInt xT xInts)).
  destruct H as [p fInts]. cbn in *.
  destruct (fInts x xInt xT xInts) as (v&E&fxInts).
  eassumption.
Defined.

Lemma extTApp t1 t2 {tt1:TT t1} {tt2 : TT t2} (f: t1 -> t2) (x:t1) fT xT (Hf : computableTime f fT) (Hx : computableTime x xT) :
  (extT f) (extT x) >(<= fst (evalTime f x (evalTime x))) extT (f x).
Proof.
  unfold extT.
  destruct Hf as [fInt [fP fInts]], Hx as [xInt xInts]. cbn.
  destruct (fInts x xInt xT xInts) as (v&E&fxInts). apply E.
Qed.

Lemma extT_is_enc t1 (R:registered t1) (x: t1) xT (Hf : computableTime x xT) :
  @extT _ _ x xT Hf = enc x.
Proof.
  unfold extT.
  destruct Hf. assumption.
Defined.

Lemma computesTimeTyArr_helper t1 t2 (tt1 : TT t1) (tt2 : TT t2) f fInt time fT:
  proc fInt
  ->
  (forall (y : t1) yT,
      (time y yT<= fst (fT y yT)) *
  forall (yInt : term),
    computesTime tt1 y yInt yT
    -> {v : term & evalLe (time y yT) (fInt yInt) v * (proc v -> computesTime tt2 (f y) v (snd (fT y yT)))})%type
-> computesTime (tt1 ~> tt2) f fInt fT.
Proof.
  intros H0 H. split. tauto.
  intros y yInt yT yInts.
  specialize (H y yT) as (lt&H).
  edestruct H as (v&E&Hv). eassumption.
  exists v.
  split. rewrite <- lt. now apply E.
  apply Hv.
  apply evalLe_eval_subrelation in E. split. rewrite <- E. apply app_closed. apply H0. apply computesTimeProc in yInts. apply yInts. apply E.
Qed.

Definition computesTimeIf {t} (ty : TT t) (f:t) (fInt : term) (P:timeComplexity t-> Prop) : Type :=
  forall fT, P fT -> computesTime ty f fInt fT.
Arguments computesTimeIf {_} _ _ _ _.

Lemma computesTimeIfStart t1 (tt1 : TT t1) (f : t1) (fInt : term) P fT:
  computesTimeIf tt1 f fInt P -> P fT -> computesTime tt1 f fInt fT.
Proof.
  intros ?. cbn. eauto.
Qed.

Definition computesTimeExp {t} (ty : TT t) (f:t) (s:term) (i:nat) (fInt : term) (fT:timeComplexity t) : Type :=
  evalLe i s fInt * computesTime ty f fInt fT.

Arguments computesTimeExp {_} _ _ _ _ _ _.

Lemma computesTimeExpStart t1 (tt1 : TT t1) (f : t1) (fInt : term) fT:
  proc fInt ->
  {v :term & computesTimeExp tt1 f fInt 0 v fT}  -> computesTime tt1 f fInt fT.
Proof.
  intros ? (?&[e lam]&?). decide (fInt=x). subst x. assumption.
  edestruct n. destruct e as ([]&?&?). assumption. inv H0.
Qed.

Lemma computesTimeExpStep t1 t2 (tt1 : TT t1) (tt2 : TT t2) (f : t1 -> t2) (s:term) k k' fInt fT:
  k' = k -> evalIn k' s fInt -> closed s ->
  (forall (y : t1) (yInt : term) yT, computesTime tt1 y yInt yT
                                -> {v : term & computesTimeExp tt2 (f y) (s yInt) (fst (fT y yT) +k) v (snd (fT y yT))}%type) ->
  computesTimeExp (tt1 ~> tt2) f s k fInt fT.

Proof.
  intros -> (R1&p1) ? H. split. split. eexists;split. 2:eassumption. omega. tauto. split. split. 2:tauto. rewrite <- R1. tauto.
  intros y yInt yT yInted.
  edestruct (H y yInt yT yInted) as (v&H2&?).
  eexists v. split.
  edestruct (evalLe_trans_rev) as (H3&R3). exact H2. apply pow_step_congL. eassumption. reflexivity.
  destruct fT. cbn in *. replace (n+k-k) with n in R3 by omega. apply R3. tauto.
Qed.

Lemma computesTimeExt X (tt : TT X) (x x' : X) s fT:
  extEq x x' -> computesTime tt x s fT -> computesTime tt x' s fT.
Proof.
  induction tt in x,x',s,fT |-*;intros eq.
  -inv eq. tauto.
  -cbn in eq|-*. intros [H1 H2]. split. 1:tauto.
   intros y t yT ints.
   specialize (H2 y t yT ints ) as (v&R&H2).
   exists v. split. 1:assumption.
   eapply IHtt2. 2:now eassumption.
   apply eq.
Qed.

Lemma computableTimeExt X (tt : TT X) (x x' : X) fT:
  extEq x x' -> computableTime x fT -> computableTime x' fT.
  intros ? [s ?]. eexists. eauto using computesTimeExt.
Defined.

Fixpoint changeResType_TimeComplexity t1 (tt1 : TT t1) Y {R: registered Y} {struct tt1}:
  forall (fT: timeComplexity t1) , @timeComplexity _ (projT2 (changeResType tt1 (TyB Y))):= (
  match tt1 with
    @TyB t1 tt1 => fun fT => fT
  | TyArr tt11 tt12 => fun fT x xT => (fst (fT x xT),changeResType_TimeComplexity (snd (fT x xT)))
  end).

Lemma cast_registeredAs_TimeComplexity t1 (tt1 : TT t1) Y (R: registered Y) fT (cast : projT1 (resType tt1) -> Y) (f:t1)
      (Hc : injective cast) :
  projT2 (resType tt1) = registerAs cast Hc ->
  computableTime (ty:=projT2 (changeResType tt1 (TyB Y))) (insertCast R cast f) (changeResType_TimeComplexity fT)->
  computableTime f fT.
Proof.
  intros H [s ints].
  eexists s.
  induction tt1 in cast,f,fT,H,s,ints,Hc |- *.
  -cbn in H,ints|-*;unfold enc in *. rewrite H. exact ints.
  -destruct ints as (?&ints). split. assumption.
   intros x s__x int__x T__x.
   specialize (ints x s__x int__x T__x) as (v &?&ints).
   exists v. split. tauto.
   eapply IHtt1_2. all:eassumption.
Qed.

Definition cnst {X} (x:X):nat. exact 0. Qed.

Definition callTime2 {X Y Z} `{registered X} `{registered Y} `{registered Z}
           (fT : timeComplexity (X -> Y -> Z)) x y : nat :=
  let '(k,f):= fT x tt in k + fst (f y tt).
Arguments callTime2 / {_ _ _ _ _ _}.


Require Import Metatheory.
Require Import FJ_Definitions.
Require Import FEV_Definitions.

Lemma rev_nil:
  forall (A:Type) (l:list A), rev l = nil -> l = nil.
Proof.
  intros. destruct l.
  - reflexivity.
  - simpl in H. destruct (rev l).
    + simpl in H. inversion H.
    + simpl in H. inversion H.
Qed.

Lemma rev_involutive:
  forall (A:Type) (l:list A),
    rev (rev l) = l.
Proof.
  intros. induction l.
  - reflexivity.
  - simpl. rewrite rev_app_distr. rewrite IHl. simpl. reflexivity.
Qed.

Lemma rev_eq_f:
  forall (A:Type) (l1 l2:list A),
    l1 = l2 -> rev l1 = rev l2.
Proof.
  intros. rewrite H. reflexivity.
Qed.

Lemma rev_eq_b:
  forall (A:Type) (l1 l2:list A),
    rev l1 = rev l2 -> l1 = l2.
Proof.
  intros. apply rev_eq_f in H. rewrite rev_involutive in H.
  rewrite rev_involutive in H. assumption.
Qed.

Lemma rev_eq:
  forall (A:Type) (l1 l2:list A),
    l1 = l2 <-> rev l1 = rev l2.
Proof.
  split.
  - intros. apply rev_eq_f. assumption.
  - intros. apply rev_eq_b. assumption.
Qed.

Lemma rev_app:
  forall (A:Type) (l1 l2 l3 t:list A) (a:A),
    rev l1 = a :: t ->
      l1 ++ l2 = l3 -> (rev t) ++ a :: nil ++ l2 = l3.
Proof.
  intros. remember (a :: t) as l1'. rewrite app_comm_cons. rewrite app_assoc.
  rewrite <- rev_involutive in H. rewrite Heql1' in H. simpl in H.
  rewrite <- rev_eq in H. rewrite H in H0. assumption.
Qed.

Lemma decomp_no_apply:
  forall (e1 e2 e3 e4:fexp), fst (decomp (f_apply e1 e2)) <> f_apply e3 e4.
Proof.
  intro. induction e1; intros.
  - simpl. discriminate.
  - simpl. discriminate.
  - simpl. discriminate.
  - simpl. discriminate.
  - apply IHe1_1.
Qed.

Lemma apply_rev_args:
  forall (e1 e2 h:fexp) (t:list fexp),
    h::t = rev (snd (decomp (f_apply e1 e2))) -> e2 = h.
Proof.
  intros. simpl in H. rewrite rev_app_distr in H. simpl in H. injection H.
  intros. symmetry. assumption.
Qed.

Lemma decomp_reduce:
  forall (e1 e2 e eb:fexp) (ps:list fexp),
    decomp (f_apply (f_apply e1 e2) e) = (eb, ps ++ e::nil) ->
      e1 <> eb ->
      decomp (f_apply e1 e2) = (eb, ps).
Proof.
  intro. induction e1; intros; simpl in *; injection H; intros.
  - contradiction.
  - contradiction.
  - contradiction.
  - contradiction.
  - apply app_inv_tail in H1. rewrite <- H1. rewrite H2. reflexivity.
Qed.

Lemma decomp_reduce_1:
  forall (e1 e2 e3 e4 eb:fexp) (ps:list fexp),
    decomp (f_apply (f_apply (f_apply e1 e2) e3) e4) = (eb, ps ++ e3::nil ++ e4::nil) ->
      e1 <> eb ->
      decomp (f_apply (f_apply e1 e2) e4) = (eb, ps ++ e4::nil).
Proof.
  intro. induction e1; intros; injection H; intros.
  - contradiction.
  - contradiction.
  - contradiction.
  - contradiction.
  - simpl in *. rewrite H2. rewrite <- app_assoc in H1. simpl in H1.
    apply app_inv_tail in H1. rewrite H1. reflexivity.
Qed.

Lemma decomp_apply_meth:
  forall (e1 e2 eb:fexp) (ps:list fexp) (mn:mname),
    decomp (f_apply e1 e2) = (f_meth eb mn, ps ++ e2::nil) ->
      fexp2exp (f_apply e1 e2) = e_meth (fexp2exp eb) mn (List.map fexp2exp (ps ++ e2::nil)).
Proof.
  intro. induction e1; intros.
  - simpl. discriminate.
  - simpl. discriminate.
  - inversion H. subst. reflexivity.
  - simpl. discriminate.
  - simpl. destruct e1_1 eqn:De1_1.
    + discriminate.
    + discriminate.
    + simpl in *. injection H. intros. subst. injection H. intros.
      rewrite <- H1. simpl. reflexivity.
    + discriminate.
    + injection H. intros. destruct (rev ps) eqn:DRPS.
      * apply rev_nil in DRPS. rewrite DRPS in H0. simpl in H0.
        rewrite <- app_nil_l in H0. apply app_inv_tail in H0.
        destruct (snd (decomp f1) ++ f2 :: nil).
        --  simpl in H0. inversion H0.
        --  simpl in H0. inversion H0.
      * remember (ps ++ e2 :: nil) as pst.
        apply rev_app with (l1:=ps) (l2:=e2 :: nil) (l3:=pst) in DRPS.
        --  rewrite <- DRPS in H. admit.
            (* need to show that f = e1_2 before apply decomp_reduce_1 in H. *)
        --  symmetry. assumption.
Admitted.

Lemma decomp_apply_new:
  forall (e1 e2:fexp) (ps:list fexp) (cn:cname),
    decomp (f_apply e1 e2) = (f_new cn, ps) ->
      fexp2exp (f_apply e1 e2) = e_new cn (List.map fexp2exp ps).
Proof.
  intro. induction e1.
  - simpl. discriminate.
  - simpl. discriminate.
  - simpl. discriminate.
  - intros. inversion H. subst. simpl. reflexivity.
  - intros. admit. (* hopefully similar to the above! *)
Admitted.

Theorem feval_sound:
  forall (e1 e2:fexp) (fct:fctable), feval e1 fct = Some e2 -> eval (fexp2exp e1) (fexp2exp e2).
Proof.
  intro. induction e1; intros.
  - simpl in H. discriminate.
  - destruct (feval e1 fct) eqn : A.
    + apply IHe1 in A as H0. simpl in H. rewrite A in H.
      destruct e1 eqn : D.
       * discriminate.
       * injection H. intro. rewrite <- H1. simpl.
         inversion H0.
          -- admit.
          -- admit.
       * injection H. intros. rewrite <- H1. simpl.
         remember (fun (e:exp) => e::nil) as EE''.
         remember (fun (e:exp) => e_meth (fexp2exp f0) m (EE'' e)) as EE'.
         apply eval_context with (EE:=EE') in H0.
            --  subst. admit.
            --  rewrite HeqEE'. apply ec_meth_args. rewrite HeqEE''. apply esc_head.
       * discriminate.
       * admit.
    + simpl in H. admit.
  - simpl in H. destruct (feval e1 fct) eqn:D.
    + apply IHe1 in D. remember (fun (e:exp) => e_meth e m nil) as EE'.
      apply eval_context with (EE:=EE') in D.
      * rewrite HeqEE' in D. injection H. intro. rewrite <- H0. simpl.
        assumption.
      * rewrite HeqEE'. apply ec_meth_arg0.
    + discriminate.
  - simpl in H. discriminate.
  - destruct (feval e1_2 fct) eqn:Fe1_2.
    + apply IHe1_2 in Fe1_2 as H0. simpl in H. rewrite Fe1_2 in H.
      destruct e1_1 eqn:De1_1.
      * discriminate.
      * discriminate.
      * injection H. intro. rewrite <- H1. simpl.
        remember (fun (e:exp) => e::nil) as EE''.
        remember (fun (e:exp) => e_meth (fexp2exp f0) m (EE'' e)) as EE'.
        apply eval_context with (EE:=EE') in H0.
        --  subst. assumption.
        --  rewrite HeqEE'. apply ec_meth_args. rewrite HeqEE''. apply esc_head.
      * injection H. intro. rewrite <- H1. simpl.
        remember (fun (e:exp) => e::nil) as EE''.
        remember (fun (e:exp) => e_new c (EE'' e)) as EE'.
        apply eval_context with (EE:=EE') in H0.
        --  subst. assumption.
        --  rewrite HeqEE'. apply ec_new_args. rewrite HeqEE''. apply esc_head.
      * destruct (fst (decomp (f_apply f0_1 f0_2))) eqn:DD.
        --  discriminate.
        --  discriminate.
        --  destruct (snd (decomp (f_apply f0_1 f0_2))) eqn:PS.
            ++  simpl in PS. apply app_eq_nil in PS. destruct PS. discriminate.
            ++  remember (rev (snd (decomp (f_apply f0_1 f0_2)))) as RPS.
                destruct RPS.
                **  simpl in HeqRPS. rewrite rev_app_distr in HeqRPS.
                    symmetry in HeqRPS. apply app_eq_nil in HeqRPS.
                    destruct HeqRPS. discriminate.
                **  apply apply_rev_args in HeqRPS as F0_2. admit.
        --  admit.
        --  apply decomp_no_apply in DD. exfalso. assumption.
    + destruct (feval e1_2 fct).
     * discriminate.
     * destruct (snd (decomp (f_apply e1_1 e1_2))) eqn:DD.
        --  simpl in DD. apply app_eq_nil in DD. destruct DD. discriminate.
        --  destruct (f_apply e1_1 e1_2).
          ++  simpl in H. discriminate.
          ++  destruct (feval e1_2 fct) eqn : B.
              **  discriminate.
              **  discriminate.
          ++ discriminate.
          ++ discriminate.
          ++ admit.
Admitted.


(** * Combi.SSRcomplements.sorted : [path] and [sorted] complements *)
(******************************************************************************)
(*      Copyright (C) 2015-2018 Florent Hivert <florent.hivert@lri.fr>        *)
(*                                                                            *)
(*  Distributed under the terms of the GNU General Public License (GPL)       *)
(*                                                                            *)
(*    This code is distributed in the hope that it will be useful,            *)
(*    but WITHOUT ANY WARRANTY; without even the implied warranty of          *)
(*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU       *)
(*    General Public License for more details.                                *)
(*                                                                            *)
(*  The full text of the GPL is available at:                                 *)
(*                                                                            *)
(*                  http://www.gnu.org/licenses/                              *)
(******************************************************************************)
(******************************************************************************)
(** * Various Lemmas about [path] and [sorted] which are missing in MathComp  *)
(**                                                                           *)
(** TODO: these probably should be contributed to path.v                      *)
(******************************************************************************)
Require Import mathcomp.ssreflect.ssreflect.
From mathcomp Require Import ssrbool ssrfun ssrnat eqtype fintype choice seq.
From mathcomp Require Import path.

Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.

Open Scope N.

Module LeqGeqOrder.

Definition geq_refl : reflexive geq :=
  fun x => leqnn x.
Definition geq_total : total geq :=
  fun x y => leq_total y x.
Definition geq_trans : transitive geq :=
  fun x y z H1 H2 => leq_trans H2 H1.
Definition anti_geq : antisymmetric geq :=
  fun x y H => esym (anti_leq H).
Definition ltn_irr : irreflexive ltn :=
  fun x => ltnn x.
Definition gtn_trans : transitive gtn :=
  fun x y z H1 H2 => ltn_trans H2 H1.
Definition gtn_irr : irreflexive gtn :=
  fun x => ltnn x.

#[export] Hint Resolve leq_total leq_trans anti_leq : core.
#[export] Hint Resolve geq_refl geq_total geq_trans anti_geq : core.
#[export] Hint Resolve ltn_trans ltn_irr gtn_trans gtn_irr : core.

End LeqGeqOrder.

Import LeqGeqOrder.

(* TODO: remove me when merged in mathcomp *)
Lemma eq_sorted (T : Type) (e e' : rel T) : e =2 e' -> sorted e =1 sorted e'.
Proof. by move=> ee' [] // ? ?; apply: eq_path. Qed.

Section Sorted.

Variable T : eqType.
Variable Z : T.
Variable R : rel T.

Implicit Type l : T.
Implicit Type r : seq T.

Local Notation sorted r := (sorted R r).
Local Notation "x <=R y" := (R x y) (at level 70, y at next level).

Lemma sorted_consK l r : sorted (cons l r) -> sorted r.
Proof using. by case: r => [//=| r0 r] => /andP []. Qed.

Lemma sorted_rconsK l r : sorted (rcons r l) -> sorted r.
Proof using. by case: r => [//=| r0 r] /=; rewrite rcons_path => /andP []. Qed.

Lemma sorted_take r n : sorted r -> sorted (take n r).
Proof using.
elim: r n => [//= | r0 r IHr] [//=| n] /= H.
case: r r0 H IHr => [//=| r1 r] r0 /= /andP [H Hp] /(_ n Hp).
by case: n => [//=|n] /= ->; rewrite H.
Qed.

Lemma sorted_drop r n : sorted r -> sorted (drop n r).
Proof using.
elim: n r => [//= | n IHn ]; first by case.
case => [//= | r0 r /=] H; apply: IHn.
by case: r H => [//=|r1 r] /andP [].
Qed.

Lemma sorted_catL u v : sorted (u ++ v) -> sorted u.
Proof using. by move/(sorted_take (size u)); rewrite take_size_cat. Qed.

Lemma sorted_catR u v : sorted (u ++ v) -> sorted v.
Proof using. by move/(sorted_drop (size u)); rewrite drop_size_cat. Qed.

Lemma sorted1P r :
  reflect
    (forall (i : nat), i.+1 < (size r) -> (nth Z r i <=R nth Z r i.+1))
    (sorted r).
Proof using.
case: r => [| r0 r] /=; first by apply/(iffP idP).
exact/pathP.
Qed.

Lemma sorted_rcons l r : sorted r -> (last l r <=R l) -> sorted (rcons r l).
Proof using. by case: r => [//=| r0 r] /=; rewrite rcons_path => -> ->. Qed.

Hypothesis Rtrans : transitive R.

Lemma incr_equiv r :
  (forall (i j : nat), i < j < (size r) -> nth Z r i <=R nth Z r j)
  <->
  (forall (i : nat), i.+1 < (size r) -> nth Z r i <=R nth Z r i.+1).
Proof using Rtrans.
split => H.
- by move=> i Hi; apply: H; rewrite Hi ltnSn.
- move=> i j; move Hdiff : (j - i.+1) => diff.
  elim: diff i j Hdiff => [| diff IHdiff] i j /=.
  + move/eqP; rewrite -/(leq j i) => /eqP H1 /andP [H2 Hj].
    have Hij : i.+1 = j by apply/eqP; rewrite eqn_leq H2 /= /leq H1.
    by rewrite -Hij; apply: H; rewrite Hij.
  + move=> Hdiff => /andP [_ Hj].
    have Hij : i < j.-1.
      by move: Hdiff; rewrite subnS -subn1 subnAC subn1 -subn_gt0 => ->.
    apply: (Rtrans (y := nth Z r j.-1)).
    - apply: IHdiff; last by rewrite Hij /=; apply (leq_ltn_trans (leq_pred _)).
      apply/eqP; rewrite -eqSS -Hdiff.
      rewrite -(subSn Hij).
      by move: Hij; case j.
    - by case: j Hj Hij {Hdiff} => [//= | j ] /H /=.
Qed.

Lemma sorted_strictP r :
  reflect
    (forall (i j : nat), i < j < (size r) -> (nth Z r i <=R nth Z r j))
    (sorted r).
Proof using Rtrans. by apply/(iffP idP); rewrite incr_equiv => /sorted1P. Qed.

Hypothesis Rrefl : reflexive R.

Lemma non_decr_equiv r :
  (forall (i j : nat), i <= j < (size r) -> nth Z r i <=R nth Z r j)
  <->
  (forall (i : nat), i.+1 < (size r) -> nth Z r i <=R nth Z r i.+1).
Proof using Rrefl Rtrans.
split => H.
- move=> i Hi.
  have : i <= i.+1 < size r by rewrite Hi andbT.
  exact: H.
- move=> i j; move Hdiff : (j - i) => diff.
  elim: diff i j Hdiff => [| diff IHdiff] i j /=.
  + move/eqP; rewrite -/(leq j i) => H1 /andP [H2 Hj].
    by rewrite (_ : i = j); last by apply/eqP; rewrite eqn_leq H1 H2.
  + move=> Hdiff => /andP [_ Hj].
    have Hiltj : i < j by rewrite -subn_gt0 Hdiff.
    apply: (Rtrans (y := nth Z r i.+1)).
    * by apply: H; exact: (leq_ltn_trans Hiltj).
    * apply: IHdiff => //=; first by rewrite subnS Hdiff.
      by rewrite Hiltj Hj.
Qed.

Lemma sortedP r :
  reflect
    (forall (i j : nat), i <= j < (size r) -> (nth Z r i <=R nth Z r j))
    (sorted r).
Proof using Rrefl Rtrans.
by apply/(iffP idP); rewrite non_decr_equiv => /sorted1P.
Qed.

Lemma sorted_cons l r : sorted (cons l r) -> (l <=R head l r) /\ sorted r.
Proof using Rrefl.
by case: r => [//=| r0 r]; move => /andP [/= ->].
Qed.

Lemma sorted_last l r : sorted (rcons r l) -> (last l r <=R l).
Proof using Rrefl.
by case: r => [//=| r0 r] /=; rewrite rcons_path => /andP [].
Qed.

Lemma head_leq_last_sorted l r : sorted (l :: r) -> (l <=R last l r).
Proof using Rrefl Rtrans.
elim: r l => [//=| t0 r IHr] l /= /andP [Hl {}/IHr].
exact: Rtrans Hl.
Qed.

Hypothesis Hanti : antisymmetric R.

Lemma sorted_lt_by_pos r p q :
  sorted r -> p < size r -> q < size r ->
   (nth Z r p != nth Z r q) && (nth Z r p <=R nth Z r q) -> p < q.
Proof using Hanti Rrefl Rtrans.
move=> /sortedP Hsort Hp Hq /andP [Hneq Hpq].
have H : q <= p -> (nth Z r q <=R nth Z r p).
  by move=> Hqp; apply Hsort; rewrite Hqp Hp.
have:= contra H; rewrite ltnNge; apply.
apply/negP => Hqp.
move: Hneq; suff -> : nth Z r p = nth Z r q by rewrite eq_refl.
by apply Hanti; rewrite Hqp Hpq.
Qed.

End Sorted.

Require Import tools.

Lemma enum_ord_sorted_ltn N :
  sorted (fun i j : 'I_N => i < j) (enum 'I_N).
Proof.
rewrite /sorted; case Henum : (enum 'I_N) => [//= | a l].
rewrite -(map_path (h := val) (e := ltn) (b := pred0)) //.
- rewrite (_ : l = behead (enum 'I_N)); last by rewrite Henum.
  rewrite (_ : val a = head 0 (map val (enum 'I_N))); last by rewrite Henum.
  rewrite -behead_map val_enum_ord.
  case: N {a l Henum} => [//= | N] /=.
  exact: (iota_ltn_sorted 0 N.+1).
- by rewrite (eq_has (a2 := pred0)); first by rewrite has_pred0.
Qed.

Lemma enum_ord_sorted N :
  sorted (fun i j : 'I_N => i <= j) (enum 'I_N).
Proof.
by have:= enum_ord_sorted_ltn N; apply: sub_sorted => i j /=/ltnW.
Qed.

Lemma sorted_ltn_ind s :
  sorted ltn s -> sumn (iota 0 (size s)) <= sumn s /\ last 0 s >= (size s).-1.
Proof.
elim/last_ind: s => [//=| s sn IHs] /= Hsort.
move/(_ (sorted_rconsK Hsort)): IHs => [Hsum Hlast]; split.
- rewrite -{2}(revK (rcons s sn)) rev_rcons sumn_rev /= [sn + _]addnC sumn_rev.
  rewrite size_rcons -addn1 iotaD /= sumn_cat /= add0n addn0.
  apply (leq_add Hsum).
  case/lastP: s Hsort Hlast {Hsum} => [//= | s sn1] /=.
  rewrite !size_rcons !last_rcons /= -!cats1 -catA cat1s => /sorted_catR /=.
  by rewrite andbT => /(leq_ltn_trans _); apply.
- case/lastP: s Hsort Hlast {Hsum} => [//= | s sn1] /=.
  rewrite !size_rcons !last_rcons /= -!cats1 -catA cat1s => /sorted_catR /=.
  by rewrite andbT => /(leq_ltn_trans _); apply.
Qed.

Lemma sorted_sumn_iotaE s :
  sorted ltn s -> sumn s = sumn (iota 0 (size s)) -> s = iota 0 (size s).
Proof.
elim/last_ind: s => [//= | s sn IHs] /= Hsort.
have:= sorted_ltn_ind Hsort.
rewrite -{2 5}(revK (rcons s sn)) rev_rcons sumn_rev /= [sn + _]addnC sumn_rev.
rewrite size_rcons -{1 3 4}addn1 iotaD /= sumn_cat /= add0n addn0 cats1.
rewrite last_rcons => [] [_ Hsn].
have [Hsum _] := sorted_ltn_ind (sorted_rconsK Hsort).
by move=> /esym/(leq_addE Hsum Hsn) [/esym/(IHs (sorted_rconsK Hsort)) <- <-].
Qed.