open Graphics ;;
open Images ;;
open Math;;
open Code;;

let img = lire_image "Documents/gauss.png";;


let alpha = 0.95;;
let n = 24;;

let nbreErr () =
	let v = Random.float 1. in
	if (0.<=v && v<0.9) then 0
	else if (0.9<=v && v<0.99) then 1
	else if (0.99<v && v<0.999) then 2
	else 3;;

let rec bruiteur n a = 
	let v = nbreErr () in
	let x = ref a in
	for i=1 to v
	do
		let erreur = 1 lsl (Random.int n) in
		x:=(!x lxor erreur)
	done;
	!x;;

let larg = Array.length img;;
let long = Array.length img.(0);;

let transmet code classes vv =
	try
	let y=CLineaire.encoder code vv in
	let z=bruiteur 7 y in
	let x=CLineaire.decoder code z in
	x
	with CLineaire.IndecodableException -> 0
	| CLineaire.PasDansLeCodeException -> 0
	| NoSuchKeyException -> 0xF;;

let transmettre code classes v =
	let masque = 0b1111 in
	let x0 = masque land v
	and x1 = masque land (v lsr 4)
	and x2 = masque land (v lsr 8)
	and x3 = masque land (v lsr 12)
	and x4 = masque land (v lsr 16)
	and x5 = masque land (v lsr 20) in
	let y0 = masque land (transmet code classes x0)
	and y1 = masque land (transmet code classes x1)
	and y2 = masque land (transmet code classes x2)
	and y3 = masque land (transmet code classes x3)
	and y4 = masque land (transmet code classes x4)
	and y5 = masque land (transmet code classes x5) in
	
	(y0) lor (y1 lsl 4) lor (y2 lsl 8) lor (y3 lsl 12) lor (y4 lsl 16) lor (y5 lsl 20);;
	
let transmetGros code classes v =
	try
	let y=CLineaire.encoder code (v land 0xFFFFFF) in
	let z=bruiteur 31 y in
	let x=CLineaire.decoder code y in
	x land 0xFFFFFF
	with CLineaire.IndecodableException -> 0
	| CLineaire.PasDansLeCodeException -> 0
	| NoSuchKeyException -> 0xF;;

(* classes de Hamming (4,7) *)
let code = CLineaire.systematiqueFromRedondance 4 7 [7; 3; 5; 6];;
let codeG = CLineaire.systematiqueFromRedondance 4 7 (matriceAuPif 3 4);;
let classes = CLineaire.genererClasses code;;
let classesG = CLineaire.genererClasses codeG;;

for i=0 to 177
do
	print_int i;
	print_string "->";
	print_int (transmettre codeG classesG i);
	print_endline ";"
done;;

for i=0 to larg-1 do
for j=0 to long-1 do
img.(i).(j) <- transmettre code classes img.(i).(j)
done
done;;

(*for i=0 to larg-1 do
for j=0 to long-1 do
img.(i).(j) <- transmetGros codeG classesG img.(i).(j)
done
done;;
*)

sauver_image img "gaussV2.png";;
